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
9ba9d8a46b8ac0de44a3fc12ab17388dc7645fb3
buxuele/algo_snippet
/1128_easy.py
2,140
3.78125
4
# https://leetcode-cn.com/problems/number-of-equivalent-domino-pairs/ """ # 乱七八糟的,直接使用集合 set() ,最快捷, 最稳健。 # 字典也行 ,但是复杂度被强行提高了。 另外: 这几句话,写的真好啊!!! https://www.cnblogs.com/kaituorensheng/p/5694555.html 现象:往set对象里add列表、集合对象时,时提示他们是不可hash的,而对于tuple类型就可以。 原因:set里面的对象是hash存储(所以是无序的),对于python万物都是对象,如果存储一个list对象,而后改变了list对象,那set中刚才存储的值的hash就变了。 结论:set是hash存储,必须存储不变的对象,例如字符串、数字、元组等。 [1,2],[1,2] 等价的前提 a==c 且 b==d。 [1,2],[2,1] 等价的前提 a==d 且 b==c。 """ from pprint import pprint # dominoes = [[1,2], # [2,1], # [3,4], # [5,6]] # dominoes = [[1,2],[2,1],[3,4],[5,6]] # dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]] # 对于这个例子,重点考虑一下。 dominoes = [[1,1], [1,1],[1,2],[1,2],[1,1]] def solution(): ret = 0 n = len(dominoes) for i in range(n-1): for j in range(i+1, n): if dominoes[i] == dominoes[j] or dominoes[i] == dominoes[j][::-1]: ret += 1 print(ret) # def solution2(): ret = 0 # 计数 s = set() # 这里, 如果2个都不在,取反的话就是,2个任意一个在 for a, b in dominoes: temp = str(a) + str(b) # 分2部分来检查,查看 "12" 和 "21" if temp not in s and str(b) + str(a) not in s: s.add(temp) else: print(temp) ret += 1 # 这里没有充分的理由的。 除非是 a, b, c 3者是同一类的。 # 那么如果遇到,d,e,f 这3者是同一类的。 那么该怎么办呢。 # 因此,需要使用字典,把每一对合适的计数, 然后再求最终的结果。 # 明天吧。1-27、 ret += ret+1 print(ret) if __name__ == '__main__': solution2()
4932f85f75db65862123ae112b8587e1d10391e7
subii2309/Modify-PPM
/modifyPPM.py
10,694
3.71875
4
#SUBIN LAZAR #10/17/2016 #CS524-02 #Version : Python 3.5.2 #This program illustrates how a ppm image is read and multiple filters are applied to it and stored in a different output file. """Importing randint for generation of random numbers and package sys to invoke exit() to exit from the program.""" from random import randint import sys s=[] """Function enables adding filter invert color on the ppm image. This function reads the image from the input file specified in the parameter 'inputfile' and applies filter invert colors on the image and writes to the file mentioned under parameter 'outputfile'. Input: 1.inputfile--> Name of the input .ppm file which contains the image. 2.outputfile--> Name of file which consists of image after applying filter invert colors""" def invert_ppmimage(inputfile,outputfile): try: ipfile = open(inputfile,'r') invfile = open(outputfile ,'w') except IOError: print ("Error: can\'t find file or read data "+inputfile) print ("Please enter valid file to read data. File doesn't exist!!!") sys.exit() else: for x in range(0, 3): invfile.write(ipfile.readline()) for line in ipfile.readlines(): linesplit=line.split() for word in linesplit: word = 255 - int(word) invfile.write(str(word)) invfile.write(' ') invfile.write('\n') ipfile.close() invfile.close() """Function enables adding filter grayscale on the ppm image. This function reads the image from the input file specified in the parameter 'inputfile' and applies filter grayscale on the image and writes to the file mentioned under parameter 'outputfile'. Input: 1.inputfile--> Name of the input .ppm file which contains the image. 2.outputfile--> Name of file which consists of image after applying filter invert colors""" def gray_ppmimage(inputfile,outputfile): try: ipfile = open(inputfile,'r') grayfile = open(outputfile ,'w') except IOError: print ("Error: can\'t find file or read data "+inputfile) print ("Please enter valid file to read data. File doesn't exist!!!") sys.exit() else: for x in range(0, 3): grayfile.write(ipfile.readline()) for line in ipfile.readlines(): linesplit=line.split() for word in range(0,len(linesplit),3): mean = (int(linesplit[word]) + int(linesplit[word+1]) + int(linesplit[word+2]))/3 for i in range(0, 3): linesplit[word+i] = int(mean) grayfile.write(str(linesplit[word+i])) grayfile.write(' ') grayfile.write('\n') ipfile.close() grayfile.close() """Function enables adding filter flatten image on the ppm image. This function reads the image from the input file specified in the parameter 'inputfile' and applies filter invert colors on the image and writes to the file mentioned under parameter 'outputfile'. Input: 1.inputfile--> Name of the input .ppm file which contains the image. 2.outputfile--> Name of file which consists of image after applying filter invert colors 3.color-->Can hold three values as shown below a. 0 - Flattens red b. 1 - Flattens green c. 2 - Flattens blue""" def flatten_ppmimage(inputfile,outputfile,color): try: ipfile = open(inputfile,'r') flatfile = open(outputfile ,'w') except IOError: print ("Error: can\'t find file or read data "+inputfile) print ("Please enter valid file to read data. File doesn't exist!!!") sys.exit() else: for x in range(0, 3): flatfile.write(ipfile.readline()) for line in ipfile.readlines(): linesplit=line.split() for word in range(0,len(linesplit),3): for i in range(0, 3): linesplit[word+color] = 0 flatfile.write(str(linesplit[word+i])) flatfile.write(' ') flatfile.write('\n') ipfile.close() flatfile.close() """Function enables adding filter extreme contrast on the ppm image. This function reads the image from the input file specified in the parameter 'inputfile' and applies filter extreme contrast on the image and writes to the file mentioned under parameter 'outputfile'. Input: 1.inputfile--> Name of the input .ppm file which contains the image. 2.outputfile--> Name of file which consists of image after applying filter invert colors""" def extreme_contrast_ppmimage(inputfile,outputfile): flag='f' min=0 try: ipfile = open(inputfile,'r') opfile = open(outputfile ,'w') except IOError: print ("Error: can\'t find file or read data "+inputfile) print ("Please enter valid file to read data. File doesn't exist!!!") exit() else: for x in range(0, 3): ipfile.readline() for line in ipfile.readlines(): linesplit=line.split() for word in range(0,len(linesplit)-1): if flag == 'f': min=int(linesplit[word]) flag='t' if int(linesplit[word+1])<min: min=int(linesplit[word+1]) mid=(min+255)/2 ipfile = open(inputfile,'r') for x in range(0, 3): opfile.write(ipfile.readline()) for line in ipfile.readlines(): linesplit=line.split() for word in range(0,len(linesplit)): if int(linesplit[word])<=int(mid): linesplit[word]=int(0) else: linesplit[word]=int(255) opfile.write(str(linesplit[word])) opfile.write(' ') opfile.write('\n') ipfile.close() opfile.close() """Function enables adding filter random noise on the ppm image. This function reads the image from the input file specified in the parameter 'inputfile' and applies filter random noise on the image and writes to the file mentioned under parameter 'outputfile'. Input: 1.inputfile--> Name of the input .ppm file which contains the image. 2.outputfile--> Name of file which consists of image after applying filter invert colors""" def rnoise_ppmimage(inputfile,outputfile): try: ipfile = open(inputfile,'r') noisefile = open(outputfile ,'w') except IOError: print ("Error: can\'t find file or read data "+inputfile) print ("Please enter valid file to read data. File doesn't exist!!!") sys.exit() else: for x in range(0, 3): noisefile.write(ipfile.readline()) for line in ipfile.readlines(): linesplit=line.split() for word in range(0,len(linesplit)): linesplit[word]=int(linesplit[word])+randint(0,50) noisefile.write(str(linesplit[word])) noisefile.write(' ') noisefile.write('\n') ipfile.close() noisefile.close() """Function takes the name of .ppm file as input from the user, which contains the image on which filters need to be applied. User will be able to apply multiple filters one after the other. So each time the program is run the desired filter by the user is applied. So if the user wants to apply 2 filters such as invert colors and flatten red he/she needs to run the program twice firstly selecting the option as 2 which will apply the filter invert colors and secondly with option 3 which will go ahead and apply the filter flatten red on image with inverted colors. If the input file to read mentioned by user is not valid or if it is present in the correct location, the program will terminate raising an appropriate exception displaying the reason to the user""" def main(): inputfile= input('Enter name of image file you need to add filters:') try: ipfile = open(inputfile,'r') except IOError: print ("Error: can\'t find file or read data "+inputfile) print ("Please enter valid file to read data. File doesn't exist!!!") sys.exit() else: c=0 while(True): c=c+1 print ('1.Convert to greyscale') print ('2.Invert image colors') print ('3.Flatten red') print ('4.Flatten green') print ('5.Flatten blue') print ('6.Extreme contrast') print ('7.Random Noise') print ('press 0 to exit') if c>1: inputfile=filterfile filterfile="outputfilter" filterfile=filterfile+str(c) filterfile=filterfile+".ppm" option= input('Enter your option:') if(option=='1'): gray_ppmimage(inputfile,filterfile) print('Your ppm image now is in grayscale.The output is in '+filterfile) elif(option=='2'): invert_ppmimage(inputfile,filterfile) print('Your ppm image now is inverted.The output is in '+filterfile) elif(option=='3'): flatten_ppmimage(inputfile,filterfile,0) print('Your ppm image now is flattened red.The output is in '+filterfile) elif(option=='4'): flatten_ppmimage(inputfile,filterfile,1) print('Your ppm image now is flattened green.The output is in '+filterfile) elif(option=='5'): flatten_ppmimage(inputfile,filterfile,2) print('Your ppm image now is flattened blue.The output is in '+filterfile) elif(option=='6'): extreme_contrast_ppmimage(inputfile,filterfile) print('Your ppm image now has extreme contrast.The output is in '+filterfile) elif(option=='7'): rnoise_ppmimage(inputfile,filterfile) print('Your ppm image now has been exposed some random noise.The output is in '+filterfile) elif(option=='0'): sys.exit() print(" ") input1= input("Press any key to continue!") main()
4214ea9ff223414bf51ad89fe90105bf69111837
jversoza/p4a-spring-16-examples
/p4a-class16/math_server.py
2,354
4.15625
4
""" math server - responds to client requests to add or multiply two numbers request format: OPERATION <OPERAND_1> <OPERAND_2> response format: ANSWER <RESULT> ERROR <ERROR REASON> Examples request: MULTIPLY 5 2 response: ANSWER 10 request: MAKE_SOME_PIZZA pepporni mushroom response: ERROR operation not supported request: aaaa b c d response: ERROR server error or bad request To try out server... 1. start server on the commandline or in PyCharm 2. use netcat to connect: nc localhost 5000 MULTIPLY 5 2 """ import socket HOST, PORT = '', 5000 print('Starting math server on port', PORT) # creates a new socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # bind the socket to a host and port s.bind((HOST, PORT)) # allow server to accept connections... allow 5 connection to queue up s.listen(5) # these are the operations we'll support operator_map = { 'MULTIPLY': lambda a, b: a * b, 'ADD': lambda a, b: a + b } while True: # accept incoming connection; gives back a new socket representing # the client and the address of the client. new socket can be used # to send and receive data client, address = s.accept() print('Got connection from:', address) # get data from client socket data = client.recv(4096) if data: print('Data from incoming request:', data) try: # data is in bytes object... so decode to get a string req = data.decode('utf-8') # get the operation from the request parts = req.split(' ') operator, operand_1, operand_2 = parts[:3] print('operator, operand_1, operand_2:', operator, operand_1, operand_2) # use operation to key into dictionary of operations above result = operator_map[operator](int(operand_1), int(operand_2)) print('result:', result) res = bytes('ANSWER ' + str(result), 'utf-8') except KeyError as e: res = b'ERROR operation not supported' except Exception as e: # there was an error... just send back the exception as a string print('Server error / bad request: {} - {}'.format(e.__class__, e)) res = b'ERROR server error or bad request' print('Sending response\n', res) client.send(res) client.close()
cf6d03ea57bc9733b43a1a701ffdb14ad3bd07d5
juliannepeeling/class-work
/Chapter 6/6-5.py
298
4.15625
4
rivers = { 'seine': 'france', 'rhine': 'germany', 'thames': 'england', } for river, country in rivers.items(): print("The " + river.title() + " runs through " + country.title() + ".") for river in rivers.keys(): print(river.title()) for country in rivers.values(): print(country.title())
a509f7209c4cdfa60d6f1f7693569a007f40204e
rodrigomg/python_basics
/aliens.py
737
3.609375
4
#alien_0 = {'color': 'green', 'points': 5} #alien_1 = {'color': 'yellow', 'points': 10} #alien_2 = {'color': 'red', 'points': 15} #aliens = [alien_0,alien_1,alien_2] #for alien in aliens: # print(alien) aliens = [] for alien_number in range(30): new_alien = {'color':'blue','points':5,'speed':'slow'} aliens.append(new_alien) for alien in aliens[0:3]: if alien['color'] == 'blue': alien['color'] = 'yellow' alien['speed'] = 'medium' alien['points'] = 10 elif alien['color'] == 'yellow': alien['color'] = 'red' alien['speed'] = 'fast' alien['points'] = 15 for alien in aliens[:5]: print(alien) print("...") print("Total number of aliens:" + str(len(aliens)))
d635a36f58ae4b0d501adf9127b486930e16d18a
myemmamy/code_practice
/tree__serialize_and_deserialize_binary_tree__leetcode297.py
2,854
3.921875
4
# https://leetcode.com/problems/serialize-and-deserialize-binary-tree/ # Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. # Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. # Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. # Example 1: # Input: root = [1,2,3,null,null,4,5] # Output: [1,2,3,null,null,4,5] # Example 2: # # Input: root = [] # Output: [] # Example 3: # # Input: root = [1] # Output: [1] # Example 4: # # Input: root = [1,2] # Output: [1,2] # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None #180ms run time, 19.1MB memory class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ q = [] nodes = [] if root == None: return '' q.append(root) while q: node = q.pop(0) if node is None: nodes.append('None') else: nodes.append(str(node.val)) if node.left is not None: q.append(node.left) else: q.append(None) if node.right is not None: q.append(node.right) else: q.append(None) s s= ' '.join(nodes) return ss def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ if data == '': return None ldata = data.split() parent q =[] roo t =None while ldata: if root is None: val = ldata.pop(0) root = TreeNode((val)) parentq.append(root) parentnode = parentq.pop(0) left = ldata.pop(0) right = ldata.pop(0) if left != 'None': parentnode.left = TreeNode((left)) parentq.append(parentnode.left) if right != 'None': parentnode.right = TreeNode((right)) parentq.append(parentnode.right) return root
63a8ec7c23add5aceb8b47267a6bf850c0211a19
JakobBull/gf2
/final/scanner.py
9,795
4.125
4
"""Read the circuit definition file and translate the characters into symbols. Used in the Logic Simulator project to read the characters in the definition file and translate them into symbols that are usable by the parser. Classes ------- Scanner - reads definition file and translates characters into symbols. Symbol - encapsulates a symbol and stores its properties. """ import sys import os class Symbol: """Encapsulate a symbol and store its properties. Parameters ---------- No parameters. Public methods -------------- No public methods. """ def __init__(self): """Initialise symbol properties.""" self.type = None self.id = None # number if symbol is a number # extended to include symbol's line and character number self.number = None self.line_number = None self.start_char_number = None self.end_char_number = None self.string = None class Scanner: """Read circuit definition file and translate the characters into symbols. Once supplied with the path to a valid definition file, the scanner translates the sequence of characters in the definition file into symbols that the parser can use. It also skips over comments and irrelevant formatting characters, such as spaces and line breaks. Parameters ---------- path: path to the circuit definition file. names: instance of the names.Names() class. Public methods ------------- get_symbol(self): Translates the next sequence of characters into a symbol and returns the symbol. """ def __init__(self, path, file, names): """"Open specified file and initialise reserved words and IDs.""" # opens specified file self.path = path # self.file = file # opens specified file self.file = file """ try: # Open and return the file specified by path for reading self.file = open(path, "r", encoding="utf-8") except IOError: print("error, can't find or open file") sys.exit()""" # initialises reserved words and IDs self.names = names # SIMPLE EBNF # self.symbol_type_list = [self.COMMA, self.SEMICOLON, self.EQUALS, # self.KEYWORD, self.NUMBER, self.NAME, self.EOF] = range(7) # self.keywords_list = ["DEVICES", "CONNECT", "MONITOR", "END"] # OUR EBNF self.symbol_type_list = [ self.LEFT_BRACKET, self.RIGHT_BRACKET, self.EQUALS, self.PERIOD, self.DASH, self.SEMICOLON, self.KEYWORD, self.NUMBER, self.NAME, self.EOF ] = range(10) self.keywords_list = [ "NETWORK", "DEVICES", "CLOCK", "SWITCH", "DTYPE", "AND", "NAND", "NOR", "OR", "XOR", "CONNECTIONS", "SIGNALS", "SETSIGNAL", "SETCLOCK", "MONITOR", "starttime", "period", "firstchange", "SIGGEN", "pulse" ] # SIMPLE EBNF # [self.DEVICES_ID, self.CONNECT_ID, self.MONITOR_ID, # self.END_ID] = self.names.lookup(self.keywords_list) # OUR EBNF [ self.NETWORK_ID, self.DEVICES_ID, self.CLOCK_ID, self.SWITCH_ID, self.DTYPE_ID, self.AND_ID, self.NAND_ID, self.NOR_ID, self.OR_ID, self.XOR_ID, self.CONNECTIONS_ID, self.SIGNALS_ID, self.SETSIGNALS_ID, self.SETCLOCK_ID, self.MONITOR_ID, self.starttime_ID, self.period_ID, self.firstchange_ID, self.SIGGEN_ID, self.pulse_ID ] = self.names.lookup(self.keywords_list) # initialise current character to be first character char = self.file.read(1) self.current_character = char # initialise line number and character number counters self.current_line_number = 1 self.current_char_number = 1 if char == '\n': self.current_line_number += 1 def get_symbol(self): """ Translate the next sequence of characters into a symbol. RETURN: Symbol - the next symbol from input file of scanner instance """ symbol = Symbol() self.skip_spaces() # current character now not whitespace while self.current_character == "/": self.skip_comments() self.skip_spaces() self.skip_unused() symbol.line_number = self.current_line_number symbol.start_char_number = self.current_char_number symbol.end_char_number = self.current_char_number if self.current_character.isalpha(): # name name_string = self.get_name() symbol.end_char_number += len(name_string) symbol.string = name_string if name_string in self.keywords_list: symbol.type = self.KEYWORD else: symbol.type = self.NAME [symbol.id] = self.names.lookup([name_string]) elif self.current_character.isdigit(): # number number = self.get_number() symbol.string = number symbol.number = int(number) symbol.type = self.NUMBER elif self.current_character == "{": # punctuation symbol.type = self.LEFT_BRACKET symbol.string = "{" self.advance() elif self.current_character == "}": symbol.type = self.RIGHT_BRACKET symbol.string = "}" self.advance() elif self.current_character == "=": symbol.type = self.EQUALS symbol.string = "=" self.advance() elif self.current_character == ".": symbol.type = self.PERIOD symbol.string = "." self.advance() elif self.current_character == "-": symbol.type = self.DASH symbol.string = "-" self.advance() elif self.current_character == ";": symbol.type = self.SEMICOLON symbol.string = ";" self.advance() elif self.current_character == "": # end of file symbol.type = self.EOF symbol.string = "EOF" else: # not a valid character self.advance() return symbol def advance(self): # Need to advance once to get to fist character of file! """advance: reads the next character from the definition file. Places it in current_character RETURN: None """ char = self.file.read(1) self.current_character = char if (self.current_character == '\n'): self.current_line_number += 1 self.current_char_number = 0 else: self.current_char_number += 1 def skip_spaces(self): """ Skips whitespace until a non-whitespace character is reached. It calls advance until current_character is not whitespace. Only skips to next non-whitespace character if current character is is a space. Then it will skip all whitespace between the current space until the next non whitespace character RETURN: None """ while self.current_character.isspace(): self.advance() def skip_comments(self): """Skip comments defined by //single_line or /* multi_line */ .""" if self.current_character == "/": # comment self.advance() if self.current_character == "/": # single line comment while True: self.advance() if self.current_character == "\n": # self.advance() break elif self.current_character == "*": while True: self.advance() if self.current_character == "*": self.advance() if self.current_character == "/": # self.advance() break def skip_unused(self): """Skip any characters that aren't considered in EBNF.""" used = ('{', '}', '=', '.', '-', ';', '') while True: if self.current_character.isalnum(): break if self.current_character in used: break self.advance() def get_name(self): """ Get next name Assuming current_character is a letter. Returns the word of the following name that begins with current_character. It then stores the next non-alphanumeric character into current_character RETURN: String - the current name """ name = "" name += self.current_character while True: self.advance() if not self.current_character.isalnum(): # self.current_character = char break else: name += self.current_character return name def get_number(self): """Assumes the current_character is a digit, returns next number. Returns the next number that begins with current_character and places the next non-digit character in current_character. Note: get_number will return numbers that begin in 0. ex, if the input file is "0900" it will return "0900" NOT "900" Return: String - the current number """ # should number be able to start with a 0? integernumber = "" integernumber += self.current_character while True: self.advance() if self.current_character.isdigit(): integernumber += self.current_character else: break return integernumber
7fd890647e6de9053a07fdffaa46949853769fba
AaronJiang/ProjectEuler
/py/problem055.py
1,550
4.03125
4
""" If we take 47, reverse and add, 47 + 74 = 121, which is palindromic. Not all numbers produce palindromes so quickly. For example, 349 + 943 = 1292, 1292 + 2921 = 4213 4213 + 3124 = 7337 That is, 349 took three iterations to arrive at a palindrome. Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits). Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994. How many Lychrel numbers are there below ten-thousand? NOTE: Wording was modified slightly on 24 April 2007 to emphasise the theoretical nature of Lychrel number """ from Helper import isPalidrome def isLychrel(n): for i in range(49): n = n + int(str(n)[::-1]) if isPalidrome(n): return False return True count = 0 for i in range(1, 10000): if isLychrel(i): count += 1 print count
76712bb9ba4cf0a1d70f6593fd07f8f2d0a1739a
rafaelperazzo/programacao-web
/moodledata/vpl_data/30/usersdata/97/9220/submittedfiles/atividade.py
179
3.71875
4
# -*- coding: utf-8 -*- from __future__ import division import math n=int(input('digite o valor de n')) while n>0: S=(1/n+2/(n-1)+3/(n-2)+...+n/1 if n<0: n=n*(-1) S=
8faae6f93a7a7ee5bb28e984f2820cf6a4550ef2
fengjiachen/leetcode
/350_399/392_Is_Subsequence.py
630
3.53125
4
class Solution: def isSubsequence(self, s: str, t: str) -> bool: ls = len(s) lt = len(t) indexs = 0 indext = 0 while indexs < ls and indext < lt: while indext < lt and t[indext] != s[indexs]: indext += 1 if indexs < ls and indext < lt and t[indext] == s[indexs]: indexs += 1 indext += 1 if indexs == ls: return True else: return False if __name__ == "__main__": s = Solution() print(s.isSubsequence('abc', 'ahbgdc')) print(s.isSubsequence("aaaaaa", "bbaaaa"))
7e63ff88aa9a1ee87bd8e72cf17813dcfac8c788
JRosadoDiaz/SimplePersistenceProject
/main.py
5,617
3.5
4
#imports import FileReader #main method def main(): display_interface() def display_interface(): # path = input('Please enter path to files:\n') # FileReader.change_file_path(path) sel = '' while sel != '0': # print('1 - View file contents') # print('2 - View employees from files') # print('3 - Add Employee') # print('4 - Delete Employee') # print('5 - Update Employee') print('1 - Serialize Employees') # print('2 - View Employee by ID') print('2 - Find Employee by ID') print('3 - Find Employees by Last Name') print('4 - Print People Details') print('5 - Print Serialized Details') print('6 - Print All Employees') print('0 - Exit') sel = input('Select an option: ') # if sel == '1': # print('Viewing file information:\n') # FileReader.PrintPeopleDetails() # elif sel == '2': # print('Viewing employee data:\n') # FileReader.PrintEmployees() # elif sel == '3': # add_employee() # elif sel == '4': # delete_employee() # elif sel == '5': # update_employee() if sel == '1': FileReader.SerializeAllEmployees() elif sel == '2': find_employee_by_id() elif sel == '3': find_by_last_name() elif sel == '4': print('Viewing file information:\n') FileReader.PrintPeopleDetails() elif sel == '5': print('Viewing Serialized files:\n') FileReader.PrintSerializedDetails("./people/long serialized/") elif sel == '6': FileReader.PrintAllEmployees("./people/long serialized/") elif sel == '0': print('Closing program.') else: print('Instructions unclear.') def view_selected_employee(): idExists = False selectedId = 0 while idExists == False: selectedId = input('Enter ID to view or 0 to exit: ') idExists = FileReader.check_id_exists('./people/long serialized', int(selectedId)) if (selectedId == '0'): idExists = True if (idExists == False): print('Failed to find ID, try another.') if(selectedId == '0'): return else: FileReader.GetSerializedEmployee(int(selectedId)) def find_employee_by_id(): idExists = False selectedId = 0 while idExists == False: selectedId = input('\nEnter ID to view or 0 to exit: ') idExists = FileReader.check_id_exists('./people/long serialized', int(selectedId)) if (selectedId == '0'): idExists = True if (idExists == False): print('Failed to find ID, try another or try serializing first.') if(selectedId == '0'): return else: FileReader.FindEmployeeById(int(selectedId)) def find_by_last_name(): lastName = input("\nEnter last name to search for: ") sel = input("1 for the first employee, 2 for all employees: ") if (sel == '1'): employee = FileReader.FindEmployeeByLastName(lastName.upper()) if (employee == 0): print('No matching employee found.') else: print(employee.toString()) elif (sel == '2'): employees = FileReader.FindAllEmployeesByLastName(lastName.upper()) if (len(employees) == 0): print('No matching employees found.') else: for employee in employees: print(employee.toString()) else: print("Couldn't understand the request.") if __name__ == "__main__": main() # def add_employee(): # idExists = True # selectedId = 0 # while idExists == True: # selectedId = input('Enter ID to add or 0 to exit: ') # if (selectedId == '0'): # idExists = True # idExists = FileReader.check_id_exists('./people/long', int(selectedId)) # if (idExists == True): # print('ID already exists, try another.') # if (selectedId == '0'): # return # firstName = input('Please enter the first name to add:\n') # lastName = input('Please enter the last name to add:\n') # hireDate = input('Please enter the hire year:\n') # FileReader.AddEmployee(selectedId, firstName, lastName, hireDate) # def update_employee(): # idExists = False # selectedId = 0 # while idExists == False: # selectedId = input('Enter ID to update or 0 to exit: ') # idExists = FileReader.check_id_exists('./people/long', int(selectedId)) # if (selectedId == '0'): # idExists = True # if (idExists == False): # print('Failed to find ID, try another.') # if (selectedId == '0'): # return # firstName = input('Please enter updated first name:\n') # lastName = input('Please enter updated last name:\n') # hireDate = input('Please enter updated hire date:\n') # FileReader.UpdateEmployee(selectedId, firstName, lastName, hireDate) # def delete_employee(): # idExists = False # selectedId = 0 # while idExists == False: # selectedId = input('Enter ID to delete or 0 to exit: ') # if (selectedId == '0'): # idExists = True # idExists = FileReader.check_id_exists('./people/long', int(selectedId)) # if (idExists == False): # print('Failed to find ID, try another.') # if(selectedId == '0'): # return # else: # FileReader.DeleteEmployee(selectedId)
77e4e915357d5ea54b8be537a2051478f702ecaa
FunchadelicAD/FUNCHEON_ADRYAN_DSC510
/Learning/wk6 - lists and strings.py
895
4
4
''' shoplist = ['cat', 'dog','ferret'] myIndex = input('enter a index:') myIndex = int(myIndex) myElement = shoplist[myIndex] print('the element at index', myIndex, 'is,', myElement) ''' ''' values = ['cat', 'dog','ferret'] for i in range(len(values)): print(i, values[i]) ''' ''' fruit = 'banana' index = 0 while index < len(fruit): letter = fruit[index] print(letter) index = index + 1 ''' ''' word = 'banana' count = 0 for letter in word: if letter == 'a': count = count + 1 print(count) ''' ''' word = 'banana' if word < 'banana': print('word', word, ' after') elif word > 'banana': print('word', word, ' whatevs') else: print('fuck yeah, bananas!') ''' ''' word = 'banana' new_word = word.upper() print(new_word) ''' ''' camels = 43 '%d' % camels print(camels) ''' cheeses = ['cheddar', 'edam', 'gouda'] for cheese in cheeses: print(cheese)
74d2b11140b60eb8be1b3478c6d0a74197230c9f
SevkavTV/Lab0_Task2
/puzzle.py
2,680
3.921875
4
''' Lab 0, Task 2. Archakov Vsevolod GitHub link: https://github.com/SevkavTV/Lab0_Task2.git ''' def validate_lst(element: list) -> bool: ''' Return True if element is valid and False in other case >>> validate_lst([1, 1]) False ''' for item in range(1, 10): if element.count(item) > 1: return False return True def valid_row_column(board: list) -> bool: ''' Return True if all rows and columns are valid and False in other case >>> valid_row_column([ \ "**** ****", \ "***1 ****", \ "** 3****", \ "* 4 1****", \ " 9 5 ", \ " 6 83 *", \ "3 1 **", \ " 8 2***", \ " 2 ****" \ ]) False ''' for row in range(9): row_lst = [] column_lst = [] # iterate both through all columns and rows for column in range(9): if board[row][column] != '*' and board[row][column] != ' ': row_lst.append(int(board[row][column])) if board[column][row] != '*' and board[column][row] != ' ': column_lst.append(int(board[column][row])) # validate lists (column, row) with values if not validate_lst(row_lst) or not validate_lst(column_lst): return False return True def valid_angle(board: list) -> bool: ''' Return True if all colors are valid and False in other case >>> valid_angle([ \ "**** ****", \ "***1 ****", \ "** 3****", \ "* 4 1****", \ " 9 5 ", \ " 6 83 *", \ "3 1 **", \ " 8 2***", \ " 2 ****" \ ]) True >>> valid_angle([ \ "**** ****", \ "***11****", \ "** 3****", \ "* 4 1****", \ " 9 5 ", \ " 6 83 *", \ "3 1 **", \ " 8 2***", \ " 2 ****" \ ]) False ''' for row in range(4, -1, -1): angle = [] # iterate through each color in a column for column in range(4 - row, 9 - row): if board[column][row] != '*' and board[column][row] != ' ': angle.append(int(board[column][row])) # iterate through each color in a row for column in range(row + 1, row + 5): if board[8 - row][column] != '*' and board[8 - row][column] != ' ': angle.append(int(board[8 - row][column])) if not validate_lst(angle): return False return True def validate_board(board: list) -> bool: ''' Return True if board is valid and False in other case >>> validate_board([ \ "**** ****", \ "***1 ****", \ "** 3****", \ "* 4 1****", \ " 9 5 ", \ " 6 83 *", \ "3 1 **", \ " 8 2***", \ " 2 ****" \ ]) False ''' if not valid_row_column(board) or not valid_angle(board): return False return True
f6d0aadd864bbe88ee1317fb5a7b64a52509e7f2
ayushbhandari02/stringprojects
/Longest_substring1.py
734
4.03125
4
string = input("enter the string") temp_list = [] length = len(string) longest_length = 0 for i in range(length): for j in range(i+1, length): if string[i] == string[j]: if j - i > longest_length: start_index = i last_index = j - 1 longest_length = j - i break else: temp_list.append(string[j]) if j == length - 1: if j - i + 1 > longest_length: longest_length = j - i + 1 start_index = i last_index = j break if j == length - 1: break for x in range(start_index,last_index + 1): print(string[x], end = "") print(" is the longest substring")
99645ce453464c393de08e43a16c5f3864e0d580
dlsrks1218/Algorithm_Study
/DS_Algo/1_7_abstract_data_type/01_reverse_string_with_stack.py
288
3.90625
4
def reverse_string_with_stack(s): stk = [] revStr = '' for c in s: stk.append(c) while stk: revStr += stk.pop() return revStr if __name__ == '__main__': s1 = '버피는 천사다.' print(s1) print(reverse_string_with_stack(s1))
d17b859200f71d00f5ed10abfe897811f3057607
Etyre/chess-timer-project
/MVP_chess_timer.py
3,957
4.40625
4
# Python program to illustrate a stop watch # using tkinter #importing the required libraries import tkinter as tkinter # note to future self: tkinter is capitalized for python 2, but not for python 3. counterR = 4 * 60 * 60 counterL = 4 * 60 * 60 # the counters are both in the units of "seconds" running = False rocker = "L" def make_string_and_show_two_digits(number): if len(str(number)) >= 2: return str(number) else: return "0"+str(number) def convert_seconds_to_time_format(total_seconds): hours = total_seconds // 3600 minutes = (total_seconds%3600) // 60 seconds = (total_seconds%3600)%60 full_timer = make_string_and_show_two_digits(hours)+":"+make_string_and_show_two_digits(minutes)+":"+make_string_and_show_two_digits(seconds) return full_timer def counter_label(label): def count(): if running: global rocker global counterR global counterL global rockerS if counterR <=0: rocker = "L" if counterL <=0: rocker = "R" if counterR <= 0 and counterL <= 0: rocker = 0 display=convert_seconds_to_time_format(counterL)+" "+convert_seconds_to_time_format(counterR) label['text']=display # Or label.config(text=display) # label.after(arg1, arg2) delays by # first argument given in milliseconds # and then calls the function given as second argument. # Generally like here we need to call the # function in which it is present repeatedly. # Delays by 1000ms=1 seconds and call count again. label.after(1000, count) if rocker == "R": counterR -= 1 if rocker == "L": counterL -= 1 # Triggering the start of the counter. count() # start function of the stopwatch def Start(label): global running running=True meta_lable['text']=" work break" counter_label(label) start['state']='disabled' stop['state']='normal' reset['state']='disabled' # Stop function of the stopwatch def Stop(): global running start['state']='normal' stop['state']='disabled' reset['state']='normal' running = False # Switch the rocker def Switch(label): global rocker if rocker == "R": rocker = "L" elif rocker == "L": rocker = "R" # Reset function of the timer def Reset(label): global counter counter=-1 # If reset is pressed after pressing stop. if running==False: reset['state']='disabled' label['text']='Welcome!' # reset the counters global counterR global counterL counterR = 4 * 60 * 60 counterL = 4 * 60 * 60 # If reset is pressed while the stopwatch is running. else: label['text']='Starting...' root = tkinter.Tk() root.title("Stopwatch") # Fixing the window size. root.minsize(width=350, height=200) label = tkinter.Label(root, text="Welcome!", fg="black", font="Verdana 30 bold") meta_lable = tkinter.Label(root, text="", fg="grey", font="Verdana 15 bold") meta_lable.pack() label.pack() #this text defines the buttons that call the functions start = tkinter.Button(root, text='Start', width=15, command=lambda:Start(label)) stop = tkinter.Button(root, text='Pause', width=15, state='disabled', command=Stop) switch = tkinter.Button(root, text='Switch', width=15, command=lambda:Switch(label)) #note that I might like to change this button to be bigger and a different color or something reset = tkinter.Button(root, text='Reset', width=15, state='disabled', command=lambda:Reset(label)) #this text puts the button in the GUI switch.pack() start.pack() stop.pack() reset.pack() root.mainloop()
5b7a8afbef39e550f56ca10e0ae57b58265915d9
r0ckburn/d_r0ck
/The Modern Python 3 Bootcamp/2 - Numbers and Math/math_operators.py
1,032
4.34375
4
# + Addition print(1+1) # - Subtraction print(4-10) # * Multiplication print(6*10) # / Division # This will return a float instead of an int print(40/20) # ** Exponentiation # multiply the number by itself x number of times print(5**3) # 5x5=25, which when multiplied by 5 equals 125 (25*5=125) print(49**0.5) # using 0.5 as an exponent returns the square root of the number # % Modulo # performs devision, then provides the remainder # if modulo is used with with a number that the target number is divisible by it will return '0' print(80%7) # This equation will return 3 - because there is a remainder of 3 after 80 is divided by 7 (11 times) print(80%8) # This equation will return 0 - because there is no remainder after 80 is divided by 8 (10 times) # // Integer Division # provides an int instead of a float print(60//6) # Order of operations # PEMDAS is respected in mathematical equations # Parenthesis # Exponents # Multiplication # Division # Addition # Subtraction
b4e720e5cb6902fb9dd704dbbb6c23c469667a75
shivangi-prog/leetcode
/findKthLargest.py
2,141
3.65625
4
# Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. # 第 k 个最大的元素,而不是第 k 个不同的元素。 import heapq class Solution: def findKthLargest(self, nums, k): a = nums[:k] a.sort() print('a:',a) for i in range(k,len(nums)): print('i:',i) if nums[i] > a[0]: j = 1 while j < k: if nums[i] > a[j]: a[j-1] = a[j] j += 1 else: break print('j:',j) a[j-1] = nums[i] print('a:',a) print('a:',a) return a[0] def findKthLargest_api(self, nums, k): return heapq.nlargest(k,nums)[-1] def findKthLargest(self, nums, k): l = [] for i in range(len(nums)): if len(l) >= k: if nums[i] > l[0]: heapq.heappop(l) heapq.heappush(l,nums[i]) #heapq.heapreplace(l,-nums[i]) else: heapq.heappush(l, nums[i]) return l[0] def findKthSmallest(self, nums, k): l = [] for i in range(len(nums)): if len(l) >= k: if -nums[i] > l[0]: heapq.heappop(l) heapq.heappush(l,-nums[i]) #heapq.heapreplace(l,-nums[i]) else: heapq.heappush(l, -nums[i]) print(l) return -l[0] array = [1,32,23,553,23,55,23] # array = [-1, -1] print(array) # print(array.index(2)) # print(array.index(3)) print(array.count(3)) array2 = [] # array2.sort() k = 2 # a = array[:k] # print('a:',a) # a.sort() # print('a:',a) s1 = Solution() # print('ret:',s1.findKthLargest(array,2)) print('ret:',s1.findKthSmallest(array,6)) # print(s1.removeDuplicates(array2)) print(array) array = [1,32,23,553,23,55,23] heapq.heapify(array) heapq.heappush(array,100) print(array) heapq.heapreplace(array,3) print(array)
3202d68bfbb26104e93394427c1dfa3edfd7c8d6
jtlai0921/MP31601
/CH03/CH0332A.py
260
3.71875
4
# while廻圈將數值累加 sum = 0 #儲存加總結果 count = 1 #計數器 # 進入while廻圈 while count <= 10: #1,3,5 ~ 99 sum += count #將數值累加 count += 1 #累加計數器 print('1+2+3+..+ 10 累加結果', sum) #輸出累加結果
35c418dd7a73ef24cbf2bf10a95dac1022251621
KarenGrigoryan1999/stivenapp
/saves/8.py
535
4.21875
4
''' Грёбанная черепашка ''' import turtle '''for i in range(10,14):''' print("dd") for i in range(1,3): t = turtle.Turtle(10) t.tracing(True) t.setcolor("white") t.right(150) t.setcolor("red") '''t.right(50) t.down(50) t.left(50) t.up(80)''' t.setcolor("white") t.up(40) t.right(100) t.down(150) t.left(50) t.setcolor("green") t.down(100) t.up(50) t.left(50) t.right(50) t.up(30) t.right(80) t.tracing(False) t.right(30)
b7754828a18c8a23042f8b80420384f38b3f9133
hungdodang/cp-code
/30-Day LeetCoding Challenge/Python/stringShift.py
1,114
3.578125
4
class Solution(object): def stringShift(self, s, shift): """ :type s: str :type shift: List[List[int]] :rtype: str """ step = 0 length = len(s) is_left = False for el in shift: if el[0] == 0: step -= el[1] else: step += el[1] if 0 == step: return s elif step > 0: is_left = False else: is_left = True step = abs(step)%length s_after_shift = list(s) for i in range(length): if is_left: if i >= step: s_after_shift[i-step] = s[i] else: s_after_shift[length-step+i] = s[i] else: if i + step > length - 1: s_after_shift[i + step - length] = s[i] else: s_after_shift[i+ step] = s[i] return "".join(s_after_shift) input = [[1,1],[1,1],[0,2],[1,3]] str = "abcdefg" s = Solution() print(s.stringShift(str,input))
a8764ed26e247fec4dc446c72ec29e95f59b9653
NehaTirumalasetti/Competitive-Programming
/hackerrank/python/left_rotate.py
587
4.21875
4
'''A left rotation operation on an array shifts each of the array's elements given units to the left. Given an array and the number of left shifts to be performed, print the resulting array after rotation''' def rotLeft(a, d): b = [i for i in a] leng = len(a) for i in range(leng): b[i] = a[(i+d)%leng] return b nd = input().split() #enter the size of array and number of left rotations to perform eg: 5 4 n = int(nd[0]) d = int(nd[1]) a = list(map(int, input().rstrip().split())) #enter an array of above given size result = rotLeft(a, d) print(result)
37c3eaf71e2839233e9f795018bf036b957d00c8
sharonyeji/Sieve_of_Eratosthenes
/prime.py
1,761
4.375
4
#!/usr/bin/env python3 import eratosthenes def prime_check(Num, primeList): """checking if Num is a prime by divided the element in previous primelist""" for primeNum in primeList: if Num % primeNum == 0: return False return True def gen_eratosthenes(): """ generate prime number """ primeList = [] num = 2 while True: primeList.append(num) yield num num = num + 1 while prime_check(num, primeList) == False: num = num + 1 def main(local_argv): """ local_argv is the argument list, progrom name is first arugment this function prints the fibonacci list calcuated by the command line argument n """ if len(local_argv) != 2: print("must add one and only one command argument, , exit ") return argument_n = int(local_argv[1]) #remember, this is the 2nd argument in command line if argument_n <= 0: print("please input an pistive interger number, exit") return retList =eratosthenes.eratosthenes(argument_n) return retList # After the body of the module, you can optionally create a protected main # section to place executable scripting code. if __name__ == "__main__": # This block only executes if the script is run as a standalone # program from the command line. It is not run when imported as # a module. # It is convention to call a single function here if possible # This function should be defined above and house all code to be # executed. Note that sys.argv will contain all commandline options. # The getopt module may also be helpful for more ambitious programs. import sys main(sys.argv)
94797f1fc950ff2dcea623eb9706a8196d5d6ef0
wmaxclark/final-project
/study.py
6,345
3.796875
4
# Study Module import validation as v import random as r import deckmanager as d import os import csv def getDeck(): easyCards = [] normalCards = [] hardCards = [] deck = [] listOfLines = [] # Loops while reading file readFile = open(d.selectDeck() + ".csv", "r") for line in readFile: #line = readFile.readline() # Strips carriage return line = line.rstrip("\n") # Splits line into a list called a card card = line.split(",") # Adds to easy card list if labeled easy if card[2] == "1": easyCards.append(card) # Adds to normal card list if labeled normal elif card[2] == "2": normalCards.append(card) # Adds to hard card list if labeled hard elif card[2] == "3": hardCards.append(card) # Close the file readFile.close() # Returns the card arrays return(easyCards, normalCards, hardCards) def study(): attempts = 0 deck = [] picker = 0 currentDifficulty = 0 currentCard = [] # Gets the deck of cards from the getDeck function easyCards, normalCards, hardCards = getDeck() print(easyCards, normalCards, hardCards) # User selects how many cards to study # TODO short session medium session or long session instead of user selected userCardNumber = v.getRangedInt("Please enter how many cards you would like to study: ", "Needs to be a number between one and thirty, please. ", 1, 30) # Loops as many times as specified by input for i in range(userCardNumber): # Randomly picks a direction, either giving prompts and recieving answers or vice versa currentDirection = r.randint(0, 1) # Picks a number which will be used to weight how often each type of card will be picked currentRange = r.randint(0, 100) try: # If the range is for easy and easyCards isn't empty if currentRange <= 10 and len(easyCards) != 0: # Picks a random number from the cards picker = r.randint(0, len(easyCards) - 1) currentDifficulty = 1 currentCard = easyCards[picker] # If the range is for normal and normalCards isn't empty elif currentRange <= 50 and len(normalCards) != 0: # Picks a random number from the cards picker = r.randint(0, len(normalCards) - 1) currentDifficulty = 2 currentCard = normalCards[picker] # If the range is for hard and hardCards isn't empty elif len(hardCards) != 0: # Picks a random number from the cards picker = r.randint(0, len(hardCards) - 1) currentDifficulty = 3 currentCard = hardCards[picker] except: break print("No cards") # Repeats as long as you don't have the right answer correct = False # Loops as long as the user hasn't answered correctly while correct == False: # Resets attempts tracker attempts = 0 # Checks direction if currentDirection == 0: # Gets an answer from user userAnswer = v.getStringByLength( "Prompt: " + str(currentCard[0]) + "\nAnswer: ", "That's not even a word.. \n", 0, 30) # Checks user answer against answer cards if userAnswer == str(currentCard[1]): print("Correct!\n") correct = True else: print("Not quite, try again\n") # Adds to attempts attempts += 1 # Hint displays when attempts is over 3 if attempts > 3: print("\nHint: " + currentCard[1][:3]) elif currentDirection == 1: # Gets an answer from user userAnswer = v.getStringByLength( "Answer: " + str(currentCard[1]) + "\nPrompt: ", "That's not even a word.. \n", 0, 30) # Checks user answer against prompt cards as the direction is reversed if userAnswer == str(currentCard[0]): print("Correct!\n") correct = True else: print("Not quite, try again\n") # Adds to attempts attempts += 1 # Hint displays when attempts is over 3 if attempts > 3: print("\nHint: " + currentCard[0][:3]) # Checks the number of attempts if attempts == 0: # Checks how difficult the card was if currentDifficulty == 1: # Replaces the value according to the attempts easyCards[picker][2] = "1" elif currentDifficulty == 2: normalCards[picker][2] = "1" elif currentDifficulty == 3: hardCards[picker][2] = "1" elif attempts <= 2: if currentDifficulty == 1: easyCards[picker][2] = "2" elif currentDifficulty == 2: normalCards[picker][2] = "2" elif currentDifficulty == 3: hardCards[picker][2] = "2" else: if currentDifficulty == 1: easyCards[picker][2] = "3" elif currentDifficulty == 2: normalCards[picker][2] = "3" elif currentDifficulty == 3: hardCards[picker][2] = "3" # Opens file to write and closes when finished with open("../decks/spanish.csv", "w", newline='') as outFile: # Creates object to writer = csv.writer(outFile) for card in easyCards: writer.writerow(card) for card in normalCards: writer.writerow(card) for card in hardCards: writer.writerow(card) print("Good job studying! ")
7f3aec12ebf1055bb0b59c9b4a711c5e0b023fef
v-makarenko/vtoolsmq
/src/main/resources/qtools/lib/helpers/numeric.py
2,073
3.953125
4
""" Helper functions to display numerical values. """ import math, locale locale.setlocale(locale.LC_NUMERIC, '') __all__ = ['sig0','sig1','sig2','sig3', 'format_currency','commafy','isnan'] def sig0(value): if isinstance(value, basestring): return value if isinstance(value, float) and math.isnan(value): return "NaN" elif isinstance(value, float) and math.isinf(value): return "Infinity" #return "%d" % (round(value or 0)) return "%f" % (value or 0) def sig1(value): if isinstance(value, basestring): return value if isinstance(value, float) and math.isnan(value): return "NaN" elif isinstance(value, float) and math.isinf(value): return "Infinity" #return "%.1f" % (value or 0) return "%f" % (value or 0) def sig2(value): if isinstance(value, basestring): return value if isinstance(value, float) and math.isnan(value): return "NaN" elif isinstance(value, float) and math.isinf(value): return "Infinity" #return "%.2f" % (value or 0) return "%f" % (value or 0) def sig3(value): if isinstance(value, basestring): return value if isinstance(value, float) and math.isnan(value): return "NaN" elif isinstance(value, float) and math.isinf(value): return "Infinity" #return "%.3f" % (value or 0) return "%f" % (value or 0) # TODO test def sig_step(value, steps, start=0): if isinstance(value, basestring): return value if isinstance(value, float) and math.isnan(value): return "NaN" elif isinstance(value, float) and math.isinf(value): return "Infinity" for idx, step in enumerate(steps): if value > step: sig = start+idx if sig == 0: return int(round(value)) else: return ("%%.%sf" % sig) % value return value def format_currency(value): return "$%.2f" % value def commafy(val): return locale.format('%d', val, True) def isnan(val): return math.isnan(val)
628818e97be023934374a151799ce0c2e4eec01a
acenelio/curso-algoritmos
/python/cada_linha.py
465
4.21875
4
n: int; maior: int; n = int(input("Qual a ordem da matriz? ")); matriz: [[int]] = [[0 for x in range(n)] for x in range(n)] maiorlinha: int = [] for i in range(n): for j in range(n): matriz[i][j] = int(input(f"Elemento [{i},{j}]: ")) for i in range(n): maior = matriz[i][0] for j in range(1, n): if maior < matriz[i][j]: maior = matriz[i][j] maiorlinha.append(maior) print("MAIOR ELEMENTO DE CADA LINHA:") for i in range(n): print(maiorlinha[i])
f804ef87aa59277dd10359167bf8e496d3357b18
wernersa/kattis
/problems/guessthedatastructure.py
1,690
3.6875
4
import sys # Stack: Last-in, First-out # Queue: First-in, First-out # Priority Queue: Largest element first # Impossible # Not sure def operate(operations): # We assume all data structures could be true to begin with bags = { "stack": [True, []], "queue": [True, []], "priority queue": [True, []]} for operation, item in operations: if operation == 1: # Add operation bags["stack"][1].append(item) bags["queue"][1].insert(0,item) bags["priority queue"][1].append(item) else: # Remove operation try: if bags["stack"][1].pop() != item: bags["stack"][0] = False if bags["queue"][1].pop() != item: bags["queue"][0] = False bags["priority queue"][1].sort() if bags["priority queue"][1].pop() != item: bags["priority queue"][0] = False except: print("impossible") return #Check possible data structures: possible = [bags[x][0] for x in bags.keys()] if sum(possible) > 1: print("not sure") elif sum(possible) == 0: print("impossible") else: for key, val in bags.items(): if val[0] == True: print(key) for i, line in enumerate(sys.stdin): line = line.split() line = list(map(int, line)) if len(line) == 1: i_left = line[0] operations = list() continue else: operations.append(line) i_left -= 1 if i_left == 0: operate(operations)
a67dcbd8cd8023f26d2224597991b99f0ba0efae
jadosfer/clasesYoutube
/funcionesOrdenSuperior.py
408
3.703125
4
class humano: def __init__(self, nombre, edad): self.nombre =nombre self.edad = edad def __str__(self): return "{} tiene {} años".format(self.nombre, self.edad) humanos = [ humano("Diego", 33), humano("Martin", 23), humano("Javier", 39) ] humamos = list(map(lambda Persona: humano(Persona.nombre, Persona.edad + 1), humanos)) for i in humamos: print(i)
1e1ceaa461743ed484879f222411c9a4b504917f
dharness/ctci
/Chapter 2 - Linked Lists/question_1.py
1,173
3.828125
4
from collections import Counter from LinkedList import LinkedList def remove_dupes(list): """ Removes all duplicate data""" n = list.head count = Counter() prev = list.head while n: count[n.data] += 1 if count[n.data] > 1: if n == list.tail: list.tail = prev prev.next_node = n.next_node else: prev = n n = n.next_node return list def remove_dupes2(list): """ Removes all duplicate data without outside data structures""" n = list.head while n: if n: n2 = n.next_node prev2 = n while n2: if n.data == n2.data: prev2.next_node = n2.next_node else: prev = n2 n2 = n2.next_node n = n.next_node return list my_list = LinkedList() my_list.append_left('Rumm1') my_list.append_left('Rumm2') my_list.append_left('Rumm3') my_list.append_left('Rumm4') my_list.append_left('Rumm4') my_list.append_left('Rumm4') my_list.append_left('Rumm4') my_list.append_left('Rumm4') my_list.append_left('Rumm4') my_list.append_left('Rumm4') my_list.append_left('Rumm4') my_list.append_left('Rumm4') print(my_list) my_list = remove_dupes2(my_list) print(my_list)
ff0267bf1aa252999184e30bfc09f337cc05eb12
kakao/pycon2016apac-gawibawibo
/0813/player_orange_b_jung.py
758
4.1875
4
from random import choice HANDS = ['gawi', 'bawi', 'bo'] def show_me_the_hand(records): # list of the appearence of each hand your_hands_record = [records.count(hand) for hand in HANDS] if len(set(your_hands_record)) == 1: # if the apperence counts of the each hand are equal # random hand_to_return = choice(HANDS) else: # the hand that wins the opponent's hand which appears the most hand_to_return = HANDS[(your_hands_record.index(max(your_hands_record)) + 1) % 3] return hand_to_return if __name__ == "__main__": print (show_me_the_hand(['bo', 'gawi', 'bawi', 'bawi'])) print (show_me_the_hand(['bo', 'gawi', 'bawi'])) print (show_me_the_hand(['bo'])) print (show_me_the_hand([]))
5f251c1338aa6e10b12224a3df849d2d807d27e5
JakeMartin99/Lightboard_v2.0
/Python Emulator/HardwareEmulator.py
2,887
3.96875
4
""" Jake Martin Updated 2021 """ # Import the graphical library pygame import pygame # Python-only color adjustment function to make "off" circles still appear on the black background def color_adjust(color): return tuple([round((235/255)*ch+20) for ch in color]) # A class that implements an emulation of the hardware 25x20 lightboard class Lightboard: # Lightboard constructor def __init__(self): # Initialize the pygame engine pygame.init() # Set the font with (size, bold, italics) self.font = pygame.font.SysFont('Calibri', 12, True, False) # Set the height and width of the screen to accomodate 25x20=500 lightboard pixels of # diameter 30px with 5px margin on all sides, and 80x70 for the wood frame self.size = ((30+5)*25+5+80, (30+5)*20+5+70) self.screen = pygame.display.set_mode(self.size) self.background = pygame.image.load("wood.jpg") pygame.display.set_caption("Lightboard Emulator") # Set the FPS rate and frame counter self.FPS = 30 self.FCOUNT = 0 # Set looping variables self.done = False self.clock = pygame.time.Clock() # Set debugging toggle variable self.disp_nums = False def display(self, leds:list): # Clear the screen and set the screen background self.screen.fill((0,0,0)) self.screen.blit(self.background, (0,0)) # Iterates over each of the board pixels to display it i=0 for y in range(20-1,0-1,-1): x_path = (0,25,1) if y%2==1 else (25-1,0-1,-1) for x in range(*x_path): pygame.draw.ellipse(self.screen, color_adjust(leds[i]), [(30+5)*x+5+40,(30+5)*y+5+35,30,30]) if self.disp_nums: text = self.font.render(str(i),True,(255,255,255)) self.screen.blit(text, [(30+5)*x+5+40,(30+5)*y+5+35]) i+=1 # Put updated pixels on the screen pygame.display.flip() # Limit loop to FPS frames per second and count the frame self.clock.tick(self.FPS) self.FCOUNT += 1 def handle_events(self): right, up, timer = False, False, False for event in pygame.event.get(): # If program is quit, end the looping if event.type == pygame.QUIT: self.done = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self.disp_nums = not self.disp_nums elif event.key == pygame.K_UP: up = True elif event.key == pygame.K_RIGHT: right = True if self.FCOUNT >= self.FPS * 30: timer = True self.FCOUNT = 0 return (right, up, timer) def turn_off(self): pygame.quit() del self
8bbe2b9c5772a4e57bfdc85744694ac658f8f96b
abimaell95/2020CodeChallenge
/Challenges/Day7/Karaca.py
412
4.125
4
#code goes here: def encrypt(word): newWord = '' sufix = 'aca' word = word[::-1] #reverse the input for s in word: if(s == 'a'): newWord+='0' elif(s == 'e'): newWord+='1' elif(s == 'o'): newWord+='2' elif(s == 'u'): newWord+='3' else: newWord+=s return newWord+sufix print(encrypt(input()))
9a75177ef546c0d563ee34b552ce635edf18df88
CfSanchezog/SimulacroExamen
/ejercicio1.py
308
3.59375
4
#Escriba el codigo necesario para que al ejecutar #python ejercicio1.py se impriman los enteros del 10 al 1 en cuenta regresiva. import numpy as np import matplotlib.pyplot as plt lista=[] for i in range (11): lista.append(i) num=0 for i in lista: num+=1 print (lista[-num])
adb678cef059fc3ca4cd31cc4a3ccd5f7c8b3d13
nickramos94/DataStructuresAndAlgorithmsInPython
/C04Recursion/Projects/p23.py
570
3.515625
4
import os def find(path, filename): def helper(path): for e in os.listdir(path): new_path = os.path.join(path, e) if e == filename: result.append(new_path) # Not elif because we might look for a dir # Ex : If we have usr/loca/usr/, we want to return both usr/ paths. if os.path.isdir(new_path): helper(new_path) result = [] helper(path) return result if __name__ == "__main__": print(find("../..", "r01.py")) print(find("../..", "Projects"))
787ab85de849ddb79d1c471a1706677d9b4b74b9
HuanbinWu/testgit
/pythonjike/function/fuct_test.py
1,952
4.125
4
#!/usr/bin/env python # _*_ coding:utf-8 _*_ # Author:HuanBing #函数基本操作 # print('abc',end='\n\n') # print('abc') # def func(a,b,c): # print('a=%s'%a) # print('b=%s' %b) # print('c=%s' %c) # func(1.c=3) #取得参数个数 # def howlong(first,*other): # print(1+len(other)) # howlong(123,234,456) #函数作用域 # var1=123 # # def func(): # #定义全局变量var1 # global var1 # var1=1233 # print(var1) # # func() # print(var1) #iter() next() # list1=[1,3,4] # # # it=iter(list1) # # # print(next(it)) # # # print(next(it)) # # # print(next(it)) # # # print(next(it)) # for i in range(10,20,2): # print(i) #生成器,是迭代器的一种,自定义 # def frange(start,stop,step): # x=start # while x<stop: # yield x # x+=step # for i in frange(10,20,0.5): # print(i) #lambda 表达式 # def true():return True # lambda :True # # def add(x,y):return x+y # lambda x,y:x+y # # print(add(3,5)) # lambda x:x<=(month,day) # def func1(x): # return x<(month,day) # lambda item:item[1] # def func2(item): # return item[1] # adict={'a':'aa','b':'bb','c':'cc'} # for i in adict.items(): # print(func2(i)) # filter() map() reduce() zip() # a=[1,2,3,4,5,6,7] # b=list(filter(lambda x:x>2,a)) # print(b) # a=[1,2,3,4,5] # b=[2,3,4,5,6] # c=list(map(lanbda x,y:x+y,a,b) # print(c) # # >>> from functools import reduce # >>> reduce(lambda x,y:x+y,[2,3,4],1) # 10 # >>> 1+2+3+4 # 10 # for i in zip((1, 2, 3), (4, 5, 6)): # print(i) #对调 # dicta={'a':'aa','b':'bb'} # dictb=dict(zip(dicta.values(),dicta.keys())) # print(dictb) # # print((type(num2)))def func(): # # a=1 # # b=2 # # return a+b # # #闭包 # # def sum(a): # # def add(b): # # return a+b # # return add # # # # #add函数名称或函数的引用 # # #add()函数的调用 # # num1=func() # # num2=sum(2) # # print(num2(4)) # # # print(type(num1))
c6f382fef853b2438d6d43938f01e35e3dc801f0
momchilantonov/SoftUni-Python-Fundamentals-September-2020
/Functions/Functions-Lab/03_repeat_string.py
228
3.96875
4
def repeat_string(repeat_text, repeat_time): result = "" for _ in range(repeat_time): result += repeat_text return result text = input() repeats_qty = int(input()) print(repeat_string(text, repeats_qty))
71a6140dd5e4cafdd639ec077c6372c3fbfe112a
sebastiaanver/AdventOfCode2020
/programs/day_8.py
1,214
3.5625
4
def part_1(lines: list) -> (bool, int): acc, line_nr = 0, 0 visited = [] while True: if line_nr in visited: return False, acc visited.append(line_nr) if line_nr >= len(lines): print(f"reached last line: {acc}") return True, acc instruction, number = lines[line_nr].split(" ") if instruction == "acc": acc += int(number) line_nr += 1 elif instruction == "jmp": line_nr += int(number) elif instruction == "nop": line_nr += 1 def part_2(lines: list) -> None: for idx, line in enumerate(lines): instruction, number = line.split(" ") if instruction != "acc": instruction_new = "jmp" if instruction == "nop" else "nop" lines[idx] = f"{instruction_new} {number}" reached_end, acc = part_1(lines) if reached_end: return lines[idx] = f"{instruction} {number}" if __name__ == "__main__": file_name = "../input_files/day_8.txt" file = open(file_name, "r") lines = file.readlines() # Problem 1 part_1(lines) # Problem 2 part_2(lines)
5a1be571fd692a94ef3fd2ff6a28998e53408761
dutcjh/learnpython
/examp5_7.py
243
3.625
4
# -*- coding: utf-8 -*- """ 例5.7 嵌套定义函数,内部函数直接引用外部变量 """ def func(): x,y,m,n = 1,2,3,4 def add(): return x+y def sub(): return m-n return add()*sub() print(func())
a1521219dfcc18a4b4a9f2c5a7de8a56bc2f9090
yoosoobin/codeup
/6070.py
141
3.96875
4
a = int(input()) if 3<=a<=5: print('spring') elif 6<=a<=8: print('summer') elif 9<=a<=11: print('fall') else: print('winter')
5c931f45513b289123ef4587b76c173377ae7b52
elssm/leetcode
/2020年12月/剑指offer54.py
650
3.765625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def kthLargest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int """ #中序遍历之后,逆序res之后,返回res[k-1] res = [] def inorder(node): if node == None: return res inorder(node.left) res.append(node.val) inorder(node.right) inorder(root) res.reverse() return res[k-1]
6f46ab355b1ebfc8f83180aefe67cf5b4cad15b8
fernandavincenzo/exercicios_python
/51-75/067_NegativoFlag.py
199
3.953125
4
while True: num = int(input('Digite o número para ver sua tabuada: ')) if num < 0: break for c in range(1, 11): print(f'{num}x{c}={num * c}') print('Final do programa.')
32a541d615dd2abaf9bf7169e84d1a6da1488cf3
sidneysherrill/hello-python
/src/conditional.py
270
3.703125
4
def main(): isCold = True isUnopened = False if not isUnopened: print('Throw it away') elif not isCold: print('Put in the fridge') elif not isCold & isUnopened: print('Drink it') else: print('Do not drink it') if __name__ == "__main__": main()
6e5385022920fffab14e089599396163ddf3abe0
perryc85/summer_coders
/Change_Calculator.py
1,289
4.09375
4
# read any input file. file = input('Enter the filename: ').strip() # open the file with open(file, 'r')as f: # read it line by line so you can parse the file. f_content1 = f.readline() # parse the data list1 = f_content1.split(" ") # this will automatically choose the seocnd line f_content2 = f.readline() # parse list2 = f_content2.split(" ") # get rid of the garbage data in list list1.pop(0) list1.pop(-1) list2.pop(0) # slice the index that reps the change amount out of list1 # and store the total value in a var, and make it an int change_amount = int(list1[0]) # store the rest of the indexs into a var that reps the change I own coins = list1[1:] my_coins_string = ' '.join(x for x in coins) # total value print(change_amount) # space seperated list of coins print(my_coins_string) # third line is the bound -- sign = list2[1] number = int(list2[2]) num_less = number - 1 num_more = int(number) + 1 if sign == '<': print(f'Program can only accept {num_less} or less coins') elif sign == '>=': print(f'Program can accept {number} or more coins') elif sign == '<=': print(f'Program can accept {number} or less coins') else: print(f'Program can accept {num_more} or more coins')
cb947e79cd579db6d3c5463955dfbf1aad13e570
brianwilfredcraig/pythonCoffeeAndCode
/exercise4_divisors.py
253
3.90625
4
theNumber = int(input("Enter a number to get divisors: ")) testNumber = 1 divisorList = [] while testNumber < theNumber: if ((theNumber % testNumber) == 0): divisorList.append(testNumber) testNumber = testNumber + 1 print(divisorList)
57d727d30e5cdbb8fc214edb790586b9085892c5
appcoreopc/agogosml
/agogosml/agogosml/common/abstract_streaming_client.py
690
3.515625
4
"""Abstract streaming client class""" from abc import ABC, abstractmethod from typing import Dict class AbstractStreamingClient(ABC): @abstractmethod def __init__(self, config: Dict[str, str]): """ Abstract Streaming Client :param config: Dictionary file with all the relevant parameters. """ pass @abstractmethod def send(self, *args, **kwargs): """Send method.""" pass @abstractmethod def stop(self, *args, **kwargs): """Stop method.""" pass @abstractmethod def start_receiving(self, *args, **kwargs): """Start receiving messages from streaming client.""" pass
201aba558b787b17a6459135ec14dd84b1337a6f
aryan-shrivastava09/100DaysofCode
/p19TurtleRace.py
1,098
4.21875
4
from turtle import Turtle, Screen import random screen = Screen() screen.setup(width = 500, height = 400) color = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"] Turtlelist = [] yposition = [150, 100, 50 , 0, -50, -100, -150] for i in range(0,7): a = Turtle() a.shape("turtle") a.color(color[i]) a.penup() a.goto(x = -230, y= yposition[i] ) Turtlelist.append(a) user_bet = screen.textinput(title = "Make your bet", prompt= "Which turtle will win the race? Enter a color: ") while user_bet not in color: user_bet = screen.textinput(title = "Make your bet", prompt= "Enter a valid color: ") race_is_on = False race_is_on = True while race_is_on: for turtle in Turtlelist: if turtle.xcor() > 230: winningturtle = turtle race_is_on = False randomDistance = random.randint(0,10) turtle.forward(randomDistance) c = winningturtle.color() # tupple class if c[0] == user_bet: print(f"You won, {user_bet} is the winner") else: print(f"You lose, {c[0]} is the winner ") screen.exitonclick()
4e4019378a59f2b0eb3668cc4c4fbb0abcfa2139
drashti2210/180_Interview_Questions
/merge_sorted_LL.py
973
4.03125
4
import sys # Day 1 # 4. Merge Sorted Linked List #Example:- #INPUT:- # 2 sorted linked list # 1->2->4, 1->3->4 #OUTPUT:- # Merged Linked List # 1->1->2->3->4->4 class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: if n==0: return elif m == 0: j = 0 for j in range(n): nums1[j] = nums2[j] i, j = m-1, n-1 temp = 0 while i>=0 and j>=0: if nums1[i] >= nums2[j]: nums1[m+n-temp-1] = nums1[i] i-=1 temp+=1 else: nums1[m+n-temp-1] = nums2[j] j-=1 temp+=1 if j < 0: return else: while j>=0: nums1[m+n-temp-1]=nums2[j] j-=1 temp+=1 return
732045a70aa18119b4d614ff457560f4647f7910
HOZH/leetCode
/leetCodePython2020/1213.intersection-of-three-sorted-arrays.py
464
3.734375
4
# # @lc app=leetcode id=1213 lang=python3 # # [1213] Intersection of Three Sorted Arrays # # @lc code=start from collections import Counter class Solution: def arraysIntersection(self, arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]: counter = Counter(arr1+arr2+arr3) ans=[] for item in counter: if counter[item]==3: ans.append(item) return ans # @lc code=end
0a685539dd2ea7093098787e0c0600bf09fbc44e
jesusareyesv/Project-Euler-Problems
/p004.py
684
3.890625
4
def is_palindrome(n: int): n_ = str(n) reversed_ = ''.join(list(reversed(n_))) return n_ == reversed_ largest_palindrome = None b_limit = 0 for i in range(999): largest_palindrome_i = None a, b = 0, 0 for k in range(999): a, b = 999 - i, 999 - k if b < b_limit: break prod = a * b if is_palindrome(prod): largest_palindrome_i = prod break if largest_palindrome_i: if (not largest_palindrome) or largest_palindrome_i >= largest_palindrome: largest_palindrome = largest_palindrome_i b_limit = b else: break print(largest_palindrome)
37b36eb1fc0e1a551dc923835ef16a2011abc2bc
SavinEA/GB_hw
/python/hw_7/hw_7_1.py
5,815
3.859375
4
class Matrix: def __init__(self, matrix): self.matrix = matrix def __str__(self): result_m = '' for el in self.matrix: for num in el: result_m += f'{num}\t' result_m += '\n' return f'{result_m}' def line_matrix(self): # Определяем размер матрицы(строки) line = 0 try: while True: self.matrix[line][0] += 0 line += 1 finally: return line def column_matrix(self): # Определяем размер матрицы(столбцы) column = 0 try: while True: self.matrix[0][column] += 0 column += 1 finally: return column def __add__(self, other): # Суммируем матрицы произвольных размеров line = 0 result = [] if self.line_matrix() < other.line_matrix(): # Если первая матрица имеет меньше строк while line < self.line_matrix(): temp = [] column = 0 if self.column_matrix() < other.column_matrix(): # Если первая матрица имеет меньше столбцов while column < self.column_matrix(): # Проходим по элемнетам первой матрицы el = self.matrix[line][column] + other.matrix[line][column] # Суммируем с элементами второй матрицы temp.append(el) # Добавляем сумму в список column += 1 while column < other.column_matrix(): # Проходим по оставшимся элементам во второй матрице el = other.matrix[line][column] temp.append(el) # Добавляем в список column += 1 result.append(temp) # Список добавляем в качестве первой строк результрующей матрицы else: # Если первая матрица имеет больше столбцов, все с точностью до наоборот column = 0 temp = [] while column < other.column_matrix(): el = self.matrix[line][column] + other.matrix[line][column] temp.append(el) column += 1 while column < self.column_matrix(): el = self.matrix[line][column] temp.append(el) column += 1 result.append(temp) line += 1 while line < other.line_matrix(): # Дописываем оставшиеся элементы второй матрицы в последние столбцы / строки column = 0 temp = [] while column < other.column_matrix(): el = other.matrix[line][column] temp.append(el) column += 1 result.append(temp) line += 1 else: # Если первая матрица имеет больше строк while line < other.line_matrix(): # Сперва идем по строкам второй матрицы temp = [] column = 0 if self.column_matrix() < other.column_matrix(): # Аналогично while column < self.column_matrix(): el = self.matrix[line][column] + other.matrix[line][column] temp.append(el) column += 1 while column < other.column_matrix(): el = other.matrix[line][column] temp.append(el) column += 1 result.append(temp) else: column = 0 temp = [] while column < other.column_matrix(): el = self.matrix[line][column] + other.matrix[line][column] temp.append(el) column += 1 while column < self.column_matrix(): el = self.matrix[line][column] temp.append(el) column += 1 result.append(temp) line += 1 while line < self.line_matrix(): column = 0 temp = [] while column < self.column_matrix(): el = self.matrix[line][column] temp.append(el) column += 1 result.append(temp) while column < other.column_matrix(): # Оставшиеся пустые элементы заменяем на 0 el = 0 temp.append(el) column += 1 line += 1 return Matrix(result) m1 = [[1, 1], [2, 2], [3, 3], [4, 4]] m2 = [[1, 1], [2, 2], [3, 3], [4, 4]] m3 = [[5, 5, 5, 5], [5, 5, 5, 5]] mtr1 = Matrix(m1) mtr2 = Matrix(m2) mtr3 = Matrix(m3) test1 = mtr2 + mtr3 + mtr1 test2 = mtr1 + mtr2 print(test1, type(test1)) print(test2, type(test2))
c78fdcc4d1ba44de5878cede4f17350a8085ad34
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/bob/be94f126a2c74a8984375243594f5ddc.py
670
3.90625
4
import string def hey(what): content = what.strip() if (len(content) == 0): return 'Fine. Be that way!' # If there is at least one alphabetic character, than we need to check the case of the contents. transTable = str.maketrans(dict.fromkeys(string.digits + string.punctuation + string.whitespace)) stripped = content.translate(transTable) if (len(stripped) > 0): # This means that we have at least one alphabetical character if (content == content.upper()): return 'Whoa, chill out!' # Here, we know that the contents are not all upper case (i.e. non-shouting) if (content.endswith('?')): return 'Sure.' return 'Whatever.'
5c6fd4dbb72f727165614e2205fb9b2ce59aeba6
AdamZhouSE/pythonHomework
/Code/CodeRecords/2741/60837/272751.py
369
3.640625
4
def findSub(List): res=[] num=1 for i in range(len(List)-1): if List[i+1]>List[i]: num+=1 else: res.append(num) num=1 res.append(num) return max(res) string=input() string=string.replace('[','') string=string.replace(']','') List=list(map(int,string.split(','))) print(findSub(List))
76244914ec35062d59c7933223920325c2a13593
CourseraK2/ADA1
/week1/PythonTry/inversion/inversion.py
2,905
4.09375
4
# Algorithms: Design and Analysis Part 1, Coursera # Problem 1: Counting the number of inversions in O(nlogn) time # This file contains all of the 100,000 integers between 1 and 100,000 (inclusive) in some random order, with no integer repeated. Your task is to compute the number of inversions in the file given, where the ith row of the file indicates the ith entry of an array. ''' Download the text file here[http://spark-public.s3.amazonaws.com/algo1/programming_prob/IntegerArray.txt]. (Right click and save link as) This file contains all of the 100,000 integers between 1 and 100,000 (inclusive) in some order, with no integer repeated. Your task is to compute the number of inversions in the file given, where the ith row of the file indicates the ith entry of an array. Because of the large size of this array, you should implement the fast divide-and-conquer algorithm covered in the video lectures. The numeric answer for the given input file should be typed in the space below. So if your answer is 1198233847, then just type 1198233847 in the space provided without any space / commas / any other punctuation marks. You can make up to 5 attempts, and we'll use the best one for grading. (We do not require you to submit your code, so feel free to use any programming language you want --- just type the final numeric answer in the following space.) [TIP: before submitting, first test the correctness of your program on some small test files or your own devising. Then post your best test cases to the discussion forums to help your fellow students!] ''' def count_inversion(li, c): """Count the number of inversions in O(nlogn) time li = the original list c = a mutable data struct to store the number of inversions""" length = len(li) if length < 2: return li else: middle = int(length / 2) return count_split_inversion(count_inversion(li[:middle], c), \ count_inversion(li[middle:], c), c) def count_split_inversion(left, right, c): """Count the number of split inversions, i.e. inversions that occur in both halves of the array. left = the left sorted list right = the right sorted list c = a mutable data struct to store the number of inversions""" result = [] while left and right: curr = left if left[0] < right[0] else right result.append(curr.pop(0)) if curr == right: c[0] += len(left) result.extend(left if left else right) return result def main(): count = [0] # a mutable data struct for counting the number of inversions f = open('IntegerArray.txt', 'r') line_list = f.readlines() int_list = [int(line.split()[0]) for line in line_list if line] count_inversion(int_list, count) print(count[0]) if __name__ == '__main__': main()
7781adcb82914fc7840e0575a671591db3378f73
baileybynum5/functions-notes
/main.py
1,032
4.4375
4
#Functions Notes! #custom block in snap! is a function in python #functions have arguments or inputs (inputs to the custom blocks in Snap!) #lines included in a function must be indented #to create a function we use "def" which stands for define #a function must have 2 things EX: def name(): -parenthesis and the colon. arguments or inputs go inside the parenthesis #a function can also have a return value. this gives the function that value when you call it. #this makes the function act like a variable def function_test(input1, input2): ans = input1 + input2 return ans result = function_test(15, -25) #on line 16... 15 gets assigned to input1 and -25 gets assigned to input2. that makes the return value -10. print(result) num1 = int(input("Enter a number\n\t>")) num2 = int(input("Enter a second number\n\t>")) #int() makes whatever is in the parenthesis into an integer result2 = function_test(num1, num2) print(result2) #adding\n\t> at the end of a a prompt creates a nice looking, easy to read prompt. #end notes
46b4c5379474a80ba283f885cd7f8b3ee4f3e143
CppChan/Leetcode
/medium/mediumCode/BinarySearchTree/***BinaryTreeImplementation.py
2,242
3.546875
4
class TreeNode(object): def __init__(self,key,val): self.left = self.right = None self.key = key self.val = val class ImpleBinarySearchTree(object): def __init__(self): self.__root = None def insert(self, key, val): self.__root = self.__insert(self.__root, key, val) def __insert(self, root, key, val): if not root: return TreeNode(key, val) if root.key<key: root.right = self.__insert(root.right, key, val) elif root.key>key: root.left = self.__insert(root.left, key, val) else: root.val = val return root def delete(self, key): self.__root = self.__delete(self.__root, key) def __delete(self, root, key): if root.key<key: root.right = self.__delete(root.right, key) elif root.key >key: root.left = self.__delete(root.left, key) if root.key == key: if not root.left and not root.right: return None elif not root.left: return root.right elif not root.right: return root.left else: new = self.__findMin(root.right) new.right= self.__deleteMin(root.right) new.left = root.left root = new return root return root def __deleteMin(self, root): if not root.left and not root.right: return None elif root.left: root.left = self.__deleteMin(root.left) elif not root.left: return root.right return root def __findMin(self, root): if not root.left: return TreeNode(root.key, root.val) elif root.left: return self.__findMin(root.left) if __name__ == "__main__": s = ImpleBinarySearchTree() # a = TreeNode(5,5) # b = TreeNode(3,3) # c = TreeNode(8,8) # d = TreeNode(1,1) # e = TreeNode(4,4) # f = TreeNode(6,6) # g = TreeNode(9,9) s.insert(5,5) s.insert(3,3) s.insert(8,8) s.insert(1,1) s.insert(4,4) s.insert(6,6) s.insert(9,9) s.delete(3) s.delete(6) s.delete(9)
133964c363c9bfc1510a099cad7ec32190f9caf9
katetsoutour/iek-assignments
/Programming/Python/prog02.py
223
4.09375
4
x = int (input ("Please enter an intiger: ")) if x < 0: print ('Negative number, transforming into positive') x = -x elif x == 0: print ('Zero') elif x == 1: print ('One') else : print ('Great than 1')
acaa3689a4e8367e767d42f6c51270c640b63f10
manav999m/golden-dawn
/height_converter.py
1,428
3.5
4
from tkinter import Tk, Button, Label, DoubleVar, Entry window = Tk() window.title("feet to meter") window.configure(background="red") window.geometry("320x220") window.resizable(height=False, width=False) def convert(): if mt_entry.get() == "": value1 = float(ft_entry.get()) meter = value1*0.3048 mt_value.set("%.4f" % meter) else : #pass #if ft_entry == None: value2 = float(mt_entry.get()) feet = value2/0.3048 ft_value.set("%.4f" % feet) def clear(): ft_value.set("") mt_value.set("") ft_lbl = Label(window, text="feet", bg="purple", fg="white", width=14) ft_lbl.grid(row=0, column=0, padx=30, pady=30) ft_value = DoubleVar() ft_entry = Entry(window, textvariable=ft_value, width=14) ft_entry.grid(row=0, column=1) ft_entry.delete(0, 'end') mt_lbl = Label(window, text="meter", bg="green", fg="white", width=14) mt_lbl.grid(row=1, column=0, pady=30) mt_value = DoubleVar() mt_entry = Entry(window, textvariable=mt_value, width=14) mt_entry.grid(row=1, column=1, pady=0) mt_entry.delete(0, 'end') convert_btn = Button(window, text="convert", bg="blue", fg="black", width=14, command=convert) convert_btn.grid(row=3, column=0, padx=30) clear_btn = Button(window, text="clear", bg="blue", fg="black", width=14, command=clear) clear_btn.grid(row=3, column=1, padx=30) window.mainloop()
97dd5c4eb91276768c7512ebea038df3aa8d903e
asrinutku/Codewars-Solutions
/Square Every Digit.py
260
3.703125
4
# -*- coding: utf-8 -*- """ Created on Sat Jan 9 22:33:18 2021 @author: asrinutku """ def square_digits(num): if(str(num).isdigit()): z = ''.join(str(int(i)**2) for i in str(num)) return int(z) else: return 0
ff8de4591748ec2427caeac05330a92dbdb0a536
querneu/udf_pro_i_listas
/lista2.py
11,830
3.953125
4
''' @Lucas Soares Leite - 22955658 https://www.github.com/querneu ''' import os import math def questao(numero): if(numero == 1): clear_terminal() print("Questão 1 - Elabore um programa que solicite ao usuário um número real e ao final imprima na tela se o número informado é maior que 10 (dez)") valor_1 = int(input("Digite um número: ")) print("O valor é maior que 10" if valor_1 > 10 else "Valor menor ou igual a 10") os.system('pause') elif(numero == 2): clear_terminal() print("Questão 2 - Escreva um programa que solicite ao usuário um número real e ao final imprima na tela se o número informado é maior ou igual a dez ou menor que 10 (dez)") valor_1 = int(input("Digite um número: ")) if(valor_1 < 10): print("O valor é menor que 10") elif(valor_1 > 10): print("O valor é maior que 10") else: print("O valor é igual a {}".format(valor_1)) os.system('pause') elif(numero == 3): clear_terminal() print("Questão 3 - Elabore um algoritmo que solicite ao usuário um número real e ao final imprima na tela se o número informado é maior que dez, se é menor que dez, ou se é igual a dez") valor_1 = int(input("Digite um número: ")) if(valor_1 < 10): print("O valor é menor que 10") elif(valor_1 > 10): print("O valor é maior que 10") else: print("O valor é igual a {}".format(valor_1)) os.system('pause') elif(numero == 4): clear_terminal() print("Questão 4 - Elabore um algoritmo que solicite ao usuário um número real e ao final imprima na tela se o número informado é positivo, negativo ou nulo (zero)") valor_1 = int(input("Digite um número: ")) if(valor_1 < 0): print("O valor é negativo") elif(valor_1 > 0): print("O valor é positivo") else: print("O valor é nulo") os.system('pause') elif(numero == 5): clear_terminal() print("Questão 5 - Elabore um algoritmo que leia um número inteiro e imprima uma das mensagens: é múltiplo de 3, ou, não é múltiplo de 3") numero_1 = int(input("Digite um número inteiro: ")) mod = numero_1 % 3 print("O número {} é multiplo de 3".format(numero_1) if(mod == 0) else "O número {} Não é multiplo de 3".format(numero_1)) os.system('pause') return 0 # Correção alternativa de escape de valor na memória "Valor inválido" elif(numero == 6): clear_terminal() print( "Questão 6 - Refazer o exercício 5, solicitando antes o múltiplo a ser testado") numero_1 = int(input("Digite um número inteiro: ")) multiplo_de = int(input("Digite o valor que deve ser multiplo de: ")) mod = numero_1 % multiplo_de print("O numero {} é multiplo de {}".format(numero_1, multiplo_de) if( mod == 0) else "O número {} não é multiplo de {}".format(numero_1, multiplo_de)) os.system('pause') elif(numero == 7): clear_terminal() print("Questão 7 - Desenvolva um algoritmo que classifique um número inteiro fornecido pelo usuário como par ou ímpar") numero_1 = int(input("Digite um número inteiro: ")) mod = numero_1 % 2 print("O numero {} é par".format(numero_1) if(mod == 0) else "O número {} é impar".format(numero_1)) os.system('pause') elif(numero == 8): clear_terminal() print("Questão 8 - Elabore um algoritmo que leia um número, e se ele for maior do que 20, imprimir a metade desse número, caso contrário, imprimir o dobro do número") numero_1 = float(input("Digite um número: ")) print("Metade: {}".format(numero_1/2) if(numero_1 > 20) else "Dobro: {}".format(numero_1*2)) os.system('pause') elif(numero == 9): clear_terminal() print("Questão 9 - Elabore um algoritmo que leia dois números inteiros e realize a adição; caso o resultado seja maior que 10, imprima o quadrado do resultado, caso contrário, imprima a metade dele") numero_1 = float(input("Digite o primeiro número: ")) numero_2 = float(input("Digite o segundo número: ")) soma = numero_1+numero_2 print("Quadrado do reultado: {}".format(math.pow(soma, 2)) if (soma > 10) else "Metade: {}".format(soma/2)) os.system('pause') elif(numero == 10): clear_terminal() print("""Questão 10 - O sistema de avaliação de determinada disciplina é composto por três provas. A primeira prova tem peso 2, a segunda tem peso 3 e a terceira tem peso 5. Considerando que a média para aprovação é 6.0, faça um algoritmo para calcular a média final de um aluno desta disciplina e dizer se o aluno foi aprovado ou não""") nota_1 = float(input("Digite a primeira nota: ")) nota_2 = float(input("Digite a segunda nota: ")) nota_3 = float(input("Digite a terceira nota:")) media = (nota_1 * 2 + nota_2 * 3 + nota_3 * 5)/10 print("Nota {}, aprovado!".format(media) if ( media >= 6) else "Reprovado: {}".format(media)) os.system('pause') elif(numero == 11): clear_terminal() print("Questão 11 - Elabore um algoritmo que leia o nome e o peso de duas pessoas e imprima o nome da pessoa mais pesada") nome_1 = input("Digite o nome da primeira pessoa: ") peso_1 = input("Digite o peso da primeira pessoa: ") nome_2 = input("Digite o nome da segunda pessoa: ") peso_2 = input("Digite o peso da segunda pessoa: ") print("{} é mais pesado, com {}Kg".format(nome_1, peso_1) if ( peso_1 > peso_2) else "{} é mais pesado, com {}Kg".format(nome_2, peso_2)) os.system('pause') elif(numero == 12): clear_terminal() print("Questão 12 - Elabore um algoritmo que indique se um número digitado está compreendido entre 20 e 90, ou não") numero_1 = int(input("Digite um numero: ")) print("{} está entre 20 e 90".format(numero_1) if (20 <= numero_1 <= 90) else "O numero {} não está entre 20 e 90".format(numero_1)) os.system('pause') elif(numero == 13): clear_terminal() print("Questão 13 - Elabore um algoritmo que leia dois números e imprima qual é maior, qual é menor, ou se são iguais") primeiro = int(input("Primeiro numero: ")) segundo = int(input("Segundo numero : ")) #maior if (segundo > primeiro): print("Menor: {}".format(primeiro)) print("Maior: {}".format(segundo)) elif (primeiro > segundo): print("Maior: {}".format(primeiro)) print("Menor: {}".format(segundo)) #menor elif (segundo < primeiro): print("Maior: {}".format(primeiro)) print("Menor: {}".format(segundo)) elif (primeiro < segundo): print("Menor: {}".format(primeiro)) print("Maior: {}".format(segundo)) #igual else: print("{} e {} são iguais.".format(primeiro, segundo)) os.system('pause') elif(numero == 14): clear_terminal() print("""Questão 14 - Escreva um programa em linguagem C que solicite ao usuário a média para aprovação em um curso e em seguida solicite ao usuário o nome, sexo e as 03 notas do aluno e ao final imprima a frase: "O aluno XXXXX foi aprovado com media YY" considerando o gênero do(a) aluno(a) e se foi aprovado(a) ou reprovado(a)""") media = float(input("Digite a média para aprovação: ")) nome = input("Digite seu nome: ") sexo = input("Digite seu sexo; M para masculino, F para feminino.\n") nota1 = float(input("Digite a primeira nota: ")) nota2 = float(input("Digite a segunda nota: ")) nota3 = float(input("Digite a terceira nota: ")) total = (nota1+nota2+nota3)/3 if(sexo == 'M'): if(total < media): print("O aluno {}, foi reprovado com media {}".format(nome, total)) if(total >= media): print("O aluno {}, foi aprovado com media {}".format(nome,total)) elif(sexo == 'F'): if(total < media): print("A aluna {}, foi reprovada com media {}".format(nome, total)) if(total >= media): print("A aluna {}, foi aprovada com media {}".format(nome,total)) os.system('pause') else: clear_terminal() print("Digito invalido!") os.system('pause') def clear_terminal(): os.system('cls' if os.name == 'nt' else 'clear') def main(): clear_terminal() print("Questão 1 - Elabore um programa que solicite ao usuário um número real e ao final imprima na tela se o número informado é maior que 10 (dez)") print("Questão 2 - Escreva um programa que solicite ao usuário um número real e ao final imprima na tela se o número informado é maior ou igual a dez ou menor que 10 (dez)") print("Questão 3 - Elabore um algoritmo que solicite ao usuário um número real e ao final imprima na tela se o número informado é maior que dez, se é menor que dez, ou se é igual a dez") print("Questão 4 - Elabore um algoritmo que solicite ao usuário um número real e ao final imprima na tela se o número informado é positivo, negativo ou nulo (zero)") print("Questão 5 - Elabore um algoritmo que leia um número inteiro e imprima uma das mensagens: é múltiplo de 3, ou, não é múltiplo de 3") print("Questão 6 - Refazer o exercício 5, solicitando antes o múltiplo a ser testado") print("Questão 7 - Desenvolva um algoritmo que classifique um número inteiro fornecido pelo usuário como par ou ímpar") print("Questão 8 - Elabore um algoritmo que leia um número, e se ele for maior do que 20, imprimir a metade desse número, caso contrário, imprimir o dobro do número") print("Questão 9 - Elabore um algoritmo que leia dois números inteiros e realize a adição; caso o resultado seja maior que 10, imprima o quadrado do resultado, caso contrário, imprima a metade dele") print("""Questão 10 - O sistema de avaliação de determinada disciplina é composto por três provas. A primeira prova tem peso 2, a segunda tem peso 3 e a terceira tem peso 5. Considerando que a média para aprovação é 6.0, faça um algoritmo para calcular a média final de um aluno desta disciplina e dizer se o aluno foi aprovado ou não""") print("Questão 11 - Elabore um algoritmo que leia o nome e o peso de duas pessoas e imprima o nome da pessoa mais pesada") print("Questão 12 - Elabore um algoritmo que indique se um número digitado está compreendido entre 20 e 90, ou não") print("Questão 13 - Elabore um algoritmo que leia dois números e imprima qual é maior, qual é menor, ou se são iguais") print("""Questão 14 - Escreva um programa que solicite ao usuário a média para aprovação em um curso e em seguida solicite ao usuário o nome, sexo e as 03 notas do aluno e ao final imprima a frase: "O aluno XXXXX foi aprovado com media YY" considerando o gênero do(a) aluno(a) e se foi aprovado(a) ou reprovado(a)""") questao(int(input("Digite o número da questão: "))) while True: main()
8e47cfd787246a28d53c9f1e13ec78bdd9ba3046
carlosaugus1o/Python-Exercicios
/ex081 - Extraindo dados de uma lista.py
944
3.90625
4
listaNumeros = [] contNumero = 0 while True: listaNumeros.append(int(input(f'Informe o {contNumero + 1}º número: '))) contNumero += 1 print('-' * 35) continuar = input('Outro número? [S/N]: ').strip().upper() while continuar not in ('S', 'N'): print('\nInforme a opção corretamente...') continuar = input('Outro número? [S/N]: ').strip().upper() print('-' * 35) if continuar == 'N': print(f'\nVocê digitou {contNumero} valores') listaNumeros.sort(reverse=True) print(f'Lista de valores em ordem decrescente: {listaNumeros}') if 5 in listaNumeros: for idx, valor in enumerate(listaNumeros): if valor == 5: print(f'O valor 5 foi encontrado na lista na posição {idx}') break else: print('O valor 5 não foi encontrado na lista') break
2b9ffce27bae71ee8eddf493b1e602ea331a12c5
ktyagi12/LeetCode
/AllPalindromicPartitions.py
981
4
4
# Problem available at: https://www.geeksforgeeks.org/given-a-string-print-all-possible-palindromic-partition/ def check_palindrome(str_, left, right): while(left < right): if str_[left] != str_[right]: return False left += 1 right -= 1 return True def check_palindrome_partition(final_list, curr_list, start, end, input_str): if start >= end: final_list.append(curr_list.copy()) return for i in range(start, end): if check_palindrome(input_str,start,i): curr_list.append(input_str[start: i+1]) check_palindrome_partition(final_list, curr_list, i+1, end, input_str) curr_list.pop() def all_palindrome(input_str): start = 0 end = len(input_str) final_list = [] curr_list = [] check_palindrome_partition(final_list, curr_list, start, end, input_str) for i in range(len(final_list)): for j in range(len(final_list[i])): print(final_list[i][j], end = " ") if __name__ == "__main__": input_str = input() all_palindrome(input_str)
399229af753d2ec90ae8bfe23bc7f2fb8a783fbb
nixondcoutho/Python
/Problem12/DivisibleTriangleNumber.py
580
4.0625
4
# Following Primality Test algorithm to check if a number is prime or not def sumTillNth(n): res = sum(range(1,n)) return res; IncrementNumber = 2 flag = True while flag: incrementCount = 0; sumValue = sumTillNth(IncrementNumber); for val in range(1,IncrementNumber): if(sumValue% val == 0): incrementCount+= 1 IncrementNumber+= 1 print("The increment Number is {0} and the count is {1}".format(IncrementNumber,incrementCount)) if(incrementCount == 500): print("The increment Number is {0} and the sum is {1}".format(IncrementNumber,sumValue)) break
ae97721d9f45b7399d873b44351e384e4320d5cf
Grayer123/agr
/Tree/Medium/144-Binary-Tree-Preorder-Traversal/solution_recursive_noHelper.py
658
3.828125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # version 2: no adding a helper method class Solution: def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: # recursive # tc:O(n); sc:O(h) if not root: return [] res = [root.val] left = self.preorderTraversal(root.left) right = self.preorderTraversal(root.right) res.extend(left) res.extend(right) return res
c0efe80f3f2a6bfd6f7654c42ac13252cd07f03f
aveldma2/ITAO-Coding-Journal
/QuestionMark.py
88
4.0625
4
q = input('question') if q[-1] != '?': q = str(q) + '?' else: q = q print(q)
156f5b5173e6cbc5f65a38d2b9aa81e0966592b9
OseiasBeu/CursoDePython3
/My_Codes/MD1/lambda.py
471
3.96875
4
#encoding: utf-8 #Funçẽos onde conseguimos definir com apenas uma linha e sua existência será temporária def square(num): return num ** 2 # result = num**2 # return result # return num ** 2 squ = lambda num: num ** 2 par = lambda x: x % 2 ==0 primeiroChar = lambda letra: letra[0] invertString = lambda strin: strin[::-1] print(invertString('olá mundo!!!')) print(primeiroChar('Olá mundo!!!')) print(par(10)) print(squ(4)) print(square(2))
6e031075cb1c4b30bb6346146ccf8c27fdd4574b
Arun-07/python_100_exercises
/Question_49.py
535
4.3125
4
# Define a class named Shape and its subclass Square. The Square class has # an init function which takes a length as argument. Both classes have # a area function which can print the area of the shape where Shape's area is 0 by default. class Shape: def __init__(self): pass def area(self): return 0 class Square(Shape): def __init__(self, a=0): self.a = a def area(self): sq_area = self.a**2 return sq_area sqr_1 = Square(4) print(sqr_1.area()) print(Square().area())
fafc0f712687b9d85516a01cf5a6096af45c8a18
NumEconCopenhagen/projects-2019-hyggerbare
/dataproject/dataProject.py
4,335
3.609375
4
# Importing packages: import numpy as np import pandas as pd import matplotlib.pyplot as plt import pandas_datareader import datetime import ipywidgets as widgets from ipywidgets import interact start = datetime.datetime(2005, 1, 1) end = datetime.datetime(2017, 1, 1) # Fetching data from the Federal Reserve's API cons = pandas_datareader.data.DataReader('PCEC', 'fred', start, end) # Private consumption inv = pandas_datareader.data.DataReader('GPDI', 'fred', start, end) # Investments publ = pandas_datareader.data.DataReader('FGEXPND', 'fred', start, end) # Government expenditures exp = pandas_datareader.data.DataReader('NETEXP', 'fred', start, end) # Net exports # Merging data from FED to dataframe data_merged = pd.merge(cons, inv, how = 'left', on = ['DATE']) for i in exp, publ: # i. merging remaining variables to dataframe data_merged = pd.merge(data_merged, i, how = 'left', on = ['DATE']) # Defining names for columns variable = {} variable['PCEC'] = 'Private Consumption' variable['FGEXPND'] = 'Government Expenditures' variable['GPDI'] = 'Investment' variable['NETEXP'] = 'Net Exports' # Renaming columns and calculating GDP as the sum of the former variables data_merged.rename(columns = variable, inplace=True) data_merged['Gross Domestic Product'] = data_merged.sum(axis = 1) data_merged.describe() # Creating an interactive figure with all time series figure = plt.figure() ax0 = data_merged.plot(grid = True) plt.xlabel('Year') plt.ylabel('Bil. $US (Current prices, seasonally adjusted)') def draw(x): """ Function used in the interactive plot, showing either all series og chosen series. Args: x: series to plot Returns: plot: depending on chosen series, function returns a plot """ if x == 'All': return figure else: figure1 = plt.figure() ax0 = data_merged[x].plot(grid = True) plt.xlabel('Year') plt.ylabel('Bil. $US (Current prices, seasonally adjusted)') return plt.show() # Options for drop-down menu Series = ['All', 'Gross Domestic Product', 'Private Consumption', 'Government Expenditures', 'Investment', 'Net Exports'] interact(draw, x = Series) # Creating shares of total GDP ratios = data_merged.copy() choose = ('Private Consumption', 'Investment','Net Exports', 'Government Expenditures') for var in choose: # i. calculating ratios of total GDP for each variable ratios[var] = ratios[var]/ratios['Gross Domestic Product']*100 # Plotting shares of GDP at different points in time objects = ('Private Consumption', 'Investment', 'Net Exports', 'Government Expenditures') y_pos = np.arange(len(objects)) for i in 0, 17, 36: # i. defining the input to the bar chart performance = [ratios['Private Consumption'][i], ratios['Investment'][i], ratios['Net Exports'][i], ratios['Government Expenditures'][i]] # ii. plotting the bar chart, naming labels and title plt.figure() plt.bar(y_pos, performance, align = 'center', color = 'lightblue') plt.xticks(y_pos, objects) plt.ylabel('Percentage share of GDP') plt.title('Shares of total GDP '+str(ratios.index[i])) data_merged_copy = data_merged.copy() Liste = ['Gross Domestic Product', 'Private Consumption', 'Government Expenditures', 'Investment', 'Neat Exports'] for i in Liste: # i. percentage change of each variable data_merged_copy[i+'_Growth'] = data_merged_copy[i].pct_change() # Multiplying 'Net Exports_Growth' column by -1 as we have learned that df.pct_change() # finds the right value but reversed (possibly due to the fact that Net Exports are negative). data_merged_copy['Net Exports_Growth'] = data_merged_copy['Net Exports_Growth'].mul(-1) for i in Liste: # i. mean of each variable data_merged_copy[i+' Mean'] = np.mean(data_merged_copy[i+'_Growth']) # Plotting the quarterly growth rates seperately along with their mean for i in Liste: plt.figure() plt.xlabel('Date') plt.ylabel('Quarterly Growth') ax1 = data_merged_copy[i+'_Growth'].plot(color='blue', grid = True, label = 'Quarterly growth') ax2 = data_merged_copy[i+' Mean'].plot(color='red', grid = True, label = 'Mean') plt.title(i+' (growth rate)') plt.show()
ec5ae073c5cabe4549be9c58a44fb7064c6fff40
dagangge/myPythonCode
/3第三周天天向上的力量/字符串分段组合.py
70
3.703125
4
a=input() res=str(a).split('-') print("{}+{}".format(res[0],res[-1]))
f527abe327e3a1dc1a700d1ee6b0fb0313b20639
stephenoken/udacity-intro-to-machine-learning-projects
/svm/svm_author_id.py
1,519
3.515625
4
""" This is the code to accompany the Lesson 2 (SVM) mini-project. Use a SVM to identify emails from the Enron corpus by their authors: Sara has label 0 Chris has label 1 """ import sys from time import time sys.path.append("../tools/") from email_preprocess import preprocess ### features_train and features_test are the features for the training ### and testing datasets, respectively ### labels_train and labels_test are the corresponding item labels features_train, features_test, labels_train, labels_test = preprocess() # SVM is SUPER slow # features_train = features_train[:len(features_train)/100] # labels_train = labels_train[:len(labels_train)/100] ######################################################### ### your code goes here ### from sklearn.svm import SVC from sklearn.metrics import accuracy_score def classify(): clf = SVC(kernel='rbf', C=10000.0) t0 = time() clf.fit(features_train,labels_train) print "training time:", round(time()-t0, 3), "s" return clf def accuracy(): t1 = time() pred = classify().predict(features_test) print "training time:", round(time()-t1, 3), "s" print "Element 10: {}".format(pred[10]) print "Element 26: {}".format(pred[26]) print "Element 50: {}".format(pred[50]) print "Number of Chris emails: {}".format(len(filter(lambda x: x == 1, pred))) return accuracy_score(labels_test,pred) print "Accuracy scrore: {}".format(accuracy()) #########################################################
907cccd7e3e34d8ce8961187c2dc9bd6d46662b2
bmiltz/cascade-at
/src/cascade_at/dismod/constants.py
4,514
3.796875
4
from enum import Enum import pandas as pd import numpy as np def enum_to_dataframe(enum_name): """Given an enum, return a dataframe with two columns, name and value.""" return pd.DataFrame.from_records( np.array( [(measure, enum_value.value) for (measure, enum_value) in enum_name.__members__.items()], dtype=np.dtype([("name", object), ("value", np.int)]), ) ) class DensityEnum(Enum): """The distributions supported by Dismod-AT. They always have these ids.""" uniform = 0 "Uniform Distribution" gaussian = 1 "Gaussian Distribution" laplace = 2 "Laplace Distribution" students = 3 "Students-t Distribution" log_gaussian = 4 "Log-Gaussian Distribution" log_laplace = 5 "Log-Laplace Distribution" log_students = 6 "Log-Students-t Distribution" class RateEnum(Enum): """These are the five underlying rates. """ pini = 0 """Initial prevalence of the condition at birth, as a fraction of one.""" iota = 1 """Incidence rate for leaving susceptible to become diseased.""" rho = 2 """Remission from disease to susceptible.""" chi = 3 """Excess mortality rate.""" omega = 4 """Other-cause mortality rate.""" class MulCovEnum(Enum): """These are the mulcov kinds listed in the mulcov table.""" alpha = "rate_value" beta = "meas_value" gamma = "meas_noise" class IntegrandEnum(Enum): """These are all of the integrands Dismod-AT supports, and they will have exactly these IDs when serialized.""" Sincidence = 0 """Susceptible incidence, where the denominator is the number of susceptibles. Corresponds to iota.""" remission = 1 """Remission rate, corresponds to rho.""" mtexcess = 2 """Excess mortality rate, corresponds to chi.""" mtother = 3 """Other-cause mortality, corresponds to omega.""" mtwith = 4 """Mortality rate for those with condition.""" susceptible = 5 """Fraction of susceptibles out of total population.""" withC = 6 """Fraction of population with the disease. Total pop is the denominator.""" prevalence = 7 """Fraction of those alive with the disease, so S+C is denominator.""" Tincidence = 8 """Total-incidence, where denominator is susceptibles and with-condition.""" mtspecific = 9 """Cause-specific mortality rate, so mx_c.""" mtall = 10 """All-cause mortality rate, mx.""" mtstandard = 11 """Standardized mortality ratio.""" relrisk = 12 """Relative risk.""" incidence = -99 """This integrand should never be used, but we need it when we are converting from the epi database measures initially""" class WeightEnum(Enum): """Dismod-AT allows arbitrary weights, which are functions of space and time, defined by bilinear interpolations on grids. These weights are used to average rates over age and time intervals. Given this problem, there are three kinds of weights that are relevant.""" constant = 0 """This weight is constant everywhere at 1. This is the no-weight weight.""" susceptible = 1 """For measures that are integrals over population without the condition.""" with_condition = 2 """For measures that are integrals over those with the disease.""" total = 3 """For measures where the denominator is the whole population.""" class PriorKindEnum(Enum): """The three kinds of priors.""" value = 0 dage = 1 dtime = 2 INTEGRAND_TO_WEIGHT = dict( Sincidence=WeightEnum.susceptible, remission=WeightEnum.with_condition, mtexcess=WeightEnum.with_condition, mtother=WeightEnum.total, susceptible=WeightEnum.constant, withC=WeightEnum.constant, mtwith=WeightEnum.with_condition, prevalence=WeightEnum.total, Tincidence=WeightEnum.total, mtspecific=WeightEnum.total, mtall=WeightEnum.total, mtstandard=WeightEnum.constant, relrisk=WeightEnum.constant, ) RateToIntegrand = { "iota": "Sincidence", "rho": "remission", "chi": "mtexcess", "omega": "mtother", "pini": "prevalence" } IntegrandToRate = { v: k for k, v in RateToIntegrand.items() } """Each integrand has a natural association with a particular weight because it is a count of events with one of four denominators: constant, susceptibles, with-condition, or the total population. For instance, if you supply mtspecific data, it will always use the weight called "total." """
19e0f52313621411fb302d873f6240b06f093a3d
sunetro123/lc_array
/src/lcarray/second_try_88_merge_sorted_array_2018_09_05.py
1,613
4.15625
4
""" The mistake I was doing: Not understanding what in-place means """ """ Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. Example: Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] """ class Solution: def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead. """ idx1 = m -1 idx2 = n -1 lastidx = m+n -1 # This is which will shrink as we move # Now the loop shall only compare (m-1) elements with (n-1) elements while (idx2 >= 0): # we start with last element #possibility 1. Last element of nums1 is bigger than last element of nums2 print("entering loop nums1 {}".format(nums1)) if idx2 >=0: if nums2[idx2] > nums1[idx1]: nums1[lastidx] = nums2[idx2] idx2 -= 1 print("small array value greater than big array {}".format(nums1)) else: nums1[lastidx] = nums1[idx1] idx1 -= 1 print("else {}".format(nums1)) lastidx -= 1 if __name__ == "__main__": nums1 = [1,2,3,0,0,0] Solution().merge(nums1, 3, [2,5,6], 3) print(nums1)
e9eedc60e6f355ea49b67589977a398fbfe0936d
Abhishek-khoya/Python-projects
/TMRangeIterator.py
1,749
3.640625
4
class TMMissing: pass class TMRange: def __init__(self,start,end=TMMissing(),step=1): if (type(end) is TMMissing)==True: end=start start=1 if isinstance(start,int)==False: raise TypeError(f"Value of start should be of type {type(33)}, found {type(start)}") if isinstance(end,int)==False: raise TypeError(f"Value of end should be of type {type(33)}, found {type(end)}") if isinstance(step,int)==False: raise TypeError(f"Value of step should be of type {type(33)}, found {type(step)}") if step==0: raise ValueError(f"start is {start},end is {end} and step is {step} this leads to infinite range") if start<end and step<0: raise ValueError(f"starts is {start}, end is {end} and step is {step},this leads to infinite range") if start>end and step>0: raise ValueError(f"starts is {start}, end is {end} and step is {step},this leads to infinite range") self.start=start self.end=end self.step=step def __str__(self): return f"TMRange({self.start},{self.end})" def __iter__(self): iterator=TMRangeIterator(self) return iterator class TMRangeIterator: def __init__(self,obj): self.start=obj.start self.end=obj.end self.step=obj.step self.current=self.start def __next__(self): if self.step>0: if self.current>self.end: raise StopIteration else: if self.current>self.end: raise StopIteration data=self.current self.current+=self.step return data def __str__(self): return f"TMRangeIterator({self.start},{self.end})"
8778a86e5c9c18ca10af27239d00976de9c7cd17
GitPistachio/Competitive-programming
/SPOJ/OVGDEL - Good Elements/Good Elements.py
1,314
3.515625
4
# Project name : SPOJ: OVGDEL - Good Elements # Author : Wojciech Raszka # E-mail : gitpistachio@gmail.com # Date created : 2019-04-27 # Description : # Status : Accepted (23692744) # Tags : python, binary search # Comment : import sys def isInArray(a, A, l, r): while l <= r: m = l + (r - l)//2 if A[m] == a: return True elif A[m] > a: r = m - 1 else: l = m + 1 return False T = int(sys.stdin.readline()) for t in range(1, T + 1): n = int(sys.stdin.readline()) A = [int(x) for x in sys.stdin.readline().split()] A.sort() max_a = A[-1] no_of_good_a = 0 b = None for i in range(n): a = A[i] if a == b: no_of_good_a += 1 elif a > 1: b = a while a <= max_a: if isInArray(a, A, i + 1, n - 1): no_of_good_a += 1 break a *= A[i] else: # a is equal to 1 if 1 < n and A[1] == 1: #if in sorted array A is 1 then it must by at index 0 and if there is another 1 then all numbers are good no_of_good_a = n else: no_of_good_a = n - 1 break sys.stdout.write("Case %d: %d\n" % (t, no_of_good_a))
261cdfe592889331d6a5587e065c10886c9eb62b
davis-lin/Python-Practices
/6.4.py
729
3.859375
4
# Define class class Car(): def exclaim(self): print("I'm a Car!") class Yugo(Car): def exclaim(self): print("I'm a Yugo! Much like a Car, but more Yugo-ish") # Create an object for class give_me_a_car = Car() give_me_a_yugo = Yugo() # Print the object of class print(give_me_a_car.exclaim()) print(give_me_a_yugo.exclaim()) class Person(): def __init__(self, name): self.name = name class MDPerson(Person): def __init__(self, name): self.name = "Doctor " + name class JDPerson(Person): def __init__(self, name): self.name = name + ", Esquire" person = Person('Fudd') doctor = MDPerson('Fudd') lawyer = JDPerson('Fudd') print(person) print(doctor) print(lawyer)
20173cef800851987c2cb6cd989093f9c0215882
masaponto/project-euler
/p004/p004.py
712
3.828125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def is_palindrome(n: int) -> bool: """ >>> is_palindrome(1001) True >>> is_palindrome(1221) True >>> is_palindrome(1234) False >>> is_palindrome(9234) False """ s = str(n) for i in range(int(len(s)/2)): if s[i] != s[-(i+1)]: return False return True def solve() -> int: pal_list = [] for i in range(100, 999 + 1): for j in range(100, 999 + 1): m = i*j if is_palindrome(m): pal_list.append(m) return max(pal_list) def main(): print(solve()) if __name__ == "__main__": import doctest doctest.testmod() main()
4c4f630d43c5fa5e10fc9274d9f6c8a9cb9c72b0
welhefna/donation-data-processing
/insight_testsuite/temp/src/Donor/Donor.py
567
3.578125
4
class Contributor: def __init__(self,name,zip_code,amount_contributed,transaction_data,recipient_ID): self.name=name self.zip_code=zip_code self.amount_contributed=amount_contributed self.transaction_data=transaction_data self.recipient_ID=recipient_ID def identification(self): ''' itype:None rtype: tuple name, ans zip_code help: this method return contributor identification as tuple conatin his name and zip code ''' return (self.name,self.zip_code) if __name__=="__main__": print "hello"
9f51ee7aff334e3611bf49141dd27e7ce9c5ded3
victorsemenov1980/Coding-challenges
/decode.py
2,208
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 28 11:07:02 2020 @author: user """ ''' Given a string s formed by digits ('0' - '9') and '#' . We want to map s to English lowercase characters as follows: Characters ('a' to 'i') are represented by ('1' to '9') respectively. Characters ('j' to 'z') are represented by ('10#' to '26#') respectively. Return the string formed after mapping. It's guaranteed that a unique mapping will always exist. Example 1: Input: s = "10#11#12" Output: "jkab" Explanation: "j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2". Example 2: Input: s = "1326#" Output: "acz" Example 3: Input: s = "25#" Output: "y" Example 4: Input: s = "12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#" Output: "abcdefghijklmnopqrstuvwxyz" Constraints: 1 <= s.length <= 1000 s[i] only contains digits letters ('0'-'9') and '#' letter. s will be valid string such that mapping is always possible ''' import re class Solution(object): def freqAlphabets(self, s): """ :type s: str :rtype: str """ decode={'1':'a','2':'b','3':'c','4': 'd', '5':'e','6': 'f', '7':'g', '8':'h','9': 'i', '10':'j','11': 'k','12': 'l', '13':'m', '14':'n','15': 'o','16': 'p','17': 'q','18': 'r','19': 's','20': 't','21': 'u','22': 'v','23': 'w','24': 'x','25': 'y','26': 'z'} answer='' indices=[] for x in re.finditer('#',s): indices.append(x.start()-2) # print(indices) i=0 while i in range(len(s)): if i in indices: x=(s[i]+s[i+1]) answer+=decode[x] i+=3 else: answer+=decode[s[i]] i+=1 return answer y=Solution() s = "10#11#12" if y.freqAlphabets(s)=="jkab": print ('True') else: print('False') s = "1326#" if y.freqAlphabets(s)=="acz": print ('True') else: print('False') s = "25#" if y.freqAlphabets(s)=="y": print ('True') else: print('False') s = "12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#" if y.freqAlphabets(s)=="abcdefghijklmnopqrstuvwxyz": print ('True') else: print('False')
fdabdc8fa04d19c5c5528a525bc72990213510db
tnakaicode/jburkardt-python
/geometry/circles_intersect_points_2d.py
4,890
4.1875
4
#! /usr/bin/env python # def circles_intersect_points_2d ( r1, center1, r2, center2 ): #*****************************************************************************80 # ## CIRCLES_INTERSECT_POINTS_2D: intersection points of two circles in 2D. # # Discussion: # # Two circles can intersect in 0, 1, 2 or infinitely many points. # # The 0 and 2 intersection cases are numerically robust the 1 and # infinite intersection cases are numerically fragile. The routine # uses a tolerance to try to detect the 1 and infinite cases. # # An implicit circle in 2D satisfies the equation: # # ( X - CENTER(1) )^2 + ( Y - CENTER(2) )^2 = R^2 # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 15 January 2018 # # Author: # # John Burkardt # # Parameters: # # Input, real R1, the radius of the first circle. # # Input, real CENTER1(2), the center of the first circle. # # Input, real R2, the radius of the second circle. # # Input, real CENTER2(2), the center of the second circle. # # Output, integer NUM_INT, the number of intersecting points found. # NUM_INT will be 0, 1, 2 or 3. 3 indicates that there are an infinite # number of intersection points. # # Output, real P(2,2), if NUM_INT is 1 or 2, # the coordinates of the intersecting points. # import numpy as np tol = np.finfo ( float ).eps p = np.zeros ( [ 2, 2 ] ) # # Take care of the case in which the circles have the same center. # t1 = ( abs ( center1[0] - center2[0] ) \ + abs ( center1[1] - center2[1] ) ) / 2.0 t2 = ( abs ( center1[0] ) + abs ( center2[0] ) \ + abs ( center1[1] ) + abs ( center2[1] ) + 1.0 ) / 5.0 if ( t1 <= tol * t2 ): t1 = abs ( r1 - r2 ) t2 = ( abs ( r1 ) + abs ( r2 ) + 1.0 ) / 3.0 if ( t1 <= tol * t2 ): num_int = 3 else: num_int = 0 return num_int, p distsq = ( center1[0] - center2[0] ) ** 2 + ( center1[1] - center2[1] ) ** 2 root = 2.0 * ( r1 * r1 + r2 * r2 ) * distsq - distsq * distsq \ - ( r1 - r2 ) * ( r1 - r2 ) * ( r1 + r2 ) * ( r1 + r2 ) if ( root < -tol ): num_int = 0 return num_int, p sc1 = ( distsq - ( r2 * r2 - r1 * r1 ) ) / distsq if ( root < tol ): num_int = 1 for i in range ( 0, 2 ): p[i,0] = center1[i] + 0.5 * sc1 * ( center2[i] - center1[i] ) return num_int, p sc2 = np.sqrt ( root ) / distsq num_int = 2 p[0,0] = center1[0] + 0.5 * sc1 * ( center2[0] - center1[0] ) \ - 0.5 * sc2 * ( center2[1] - center1[1] ) p[1,0] = center1[1] + 0.5 * sc1 * ( center2[1] - center1[1] ) \ + 0.5 * sc2 * ( center2[0] - center1[0] ) p[0,1] = center1[0] + 0.5 * sc1 * ( center2[0] - center1[0] ) \ + 0.5 * sc2 * ( center2[1] - center1[1] ) p[1,1] = center1[1] + 0.5 * sc1 * ( center2[1] - center1[1] ) \ - 0.5 * sc2 * ( center2[0] - center1[0] ) return num_int, p def circles_intersect_points_2d_test ( ): #*****************************************************************************80 # ## CIRCLES_INTERSECT_POINTS_2D_TEST tests CIRCLES_INTERSECT_POINTS_2D # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 15 January 2018 # # Author: # # John Burkardt # import numpy as np from circle_imp_print_2d import circle_imp_print_2d ntest = 5 center1 = np.array ( [ 0.0, 0.0 ] ) r1 = 5.0 r2_test = np.array ( [ 0.5, 5.0, 3.0, 3.0, 5.0 ] ) xc2_test = np.array ( [ 5.0, 7.0710678, 4.0, 6.0, 0.0 ] ) yc2_test = np.array ( [ 5.0, 7.0710678, 0.0, 0.0, 0.0 ] ) print ( '' ) print ( 'CIRCLES_INTERSECT_POINTS_2D_TEST' ) print ( ' CIRCLES_INTERSECT_POINTS_2D determines the intersections of' ) print ( ' two circles in 2D.' ) circle_imp_print_2d ( r1, center1, ' The first circle:' ) for i in range ( 0, ntest ): r2 = r2_test[i] center2 = np.array ( [ xc2_test[i], yc2_test[i] ] ) circle_imp_print_2d ( r2, center2, ' The second circle:' ) num_int, x = circles_intersect_points_2d ( r1, center1, r2, center2 ) if ( num_int == 0 ): print ( '' ) print ( ' The circles do not intersect.' ) elif ( num_int == 1 ): print ( '' ) print ( ' The circles intersect at one point:' ) print ( '' ) print ( ' X Y' ) print ( '' ) print ( ' %6f %6f' % ( x[0,0], x[1,0] ) ) elif ( num_int == 2 ): print ( '' ) print ( ' The circles intersect at two points:' ) print ( '' ) print ( ' X Y' ) print ( '' ) print ( ' %6f %6f' % ( x[0,0], x[1,0] ) ) print ( ' %6f %6f' % ( x[0,1], x[1,1] ) ) elif ( num_int == 3 ): print ( '' ) print ( ' The circles coincide (infinite intersection).' ) return if ( __name__ == '__main__' ): circles_intersect_points_2d_test ( )
049713e8928c92ea4650fb4394bfadd67fb8cdd8
arnabs542/BigO-Coding-material
/BigO_Algorithm/algorithmreview/CPTTRN1.py
338
3.5
4
#CPTTRN1 - Character Patterns 1 testcase = int(input()) for case in range(testcase): col, row = map(int,input().split()) for c in range(col): for r in range(row): if (r + c) % 2 == 0: print('*',end='') else: print('.',end='') print() print()
3b9f95154ee903c214aa0fb5ebf833b6bf32563f
adammann52/catan
/visualize.py
36,541
3.796875
4
from tkinter import * import math from game import Game from seven import Seven import board import player import random from seven import Seven class Visualize: def __init__(self): self.game = None self.freeze = False self.robber_move = False self.rolled = True self.setUp() #initializes game self.playGame() self.hand = None self.devs = None self.c = None self.point_counter = 0 self.current_robber = None """Creates a small window to obtain user input of the names of players and their desired colors""" def setUp(self): root = Tk() root.title('Settlers of Catan') n_players = 0 players = [] colors = [] def addInput(): players.append(e1.get()) colors.append(e2.get()) e1.delete(0,END) e2.delete(0,END) def destroy(): n_name = e1.get() color = e2.get() if len(n_name) > 0: players.append(n_name) colors.append(color) root.destroy() Label(root, text="Name").grid(row=0) Label(root, text="Color").grid(row=1) e1 = Entry(root) e2 = Entry(root) e1.grid(row=0, column=1) e2.grid(row=1, column=1) Button(root,text='Enter',command=addInput)\ .grid(row=2,column=0,sticky=W) Button(root, text='Start Game', command=destroy).grid(row=2, column=1, sticky=W) root.mainloop() if len(players) > 2: self.game = Game(players,colors) else: self.game = Game() def playGame(self): #creatig the board root = Tk() root.title('Settlers of Catan') #creating the tiles w = 70 #tile sizes spots = [self.game.board.spots[i].resource for i in range(1,20)] colors = {'Ore':'grey','Wheat':'yellow','Brick':'red', 'Wood':'#228B22','Desert':'tan','Sheep':'#90EE90'} c = Canvas(root,width=w*15, height=w*15, background ='#ADD8E6') self.c = c c.pack() center = [w*7.5,w*6] #center of board #positioning of tiles in spiral order tiles = [[2,-2*math.sqrt(3)],[0,-2*math.sqrt(3)],[-2,-2*math.sqrt(3)], [-3,-math.sqrt(3)],[-4,0],[-3,math.sqrt(3)], [-2,2*math.sqrt(3)], [0,2*math.sqrt(3)],[2,2*math.sqrt(3)],[3,math.sqrt(3)],[4,0], [3,-math.sqrt(3)],[1,-math.sqrt(3)],[-1,-math.sqrt(3)],[-2,0], [-1,math.sqrt(3)],[1,math.sqrt(3)],[2,0],[0,0]] #padded width of each tile to create space in between for roads pw = math.sqrt(w**2 - (w/2)**2) + 4 #creates the tan area around the board points = [] for i in range(0,360,60): points.append(math.cos(i*(math.pi/180))*pw*6.5 + center[0]) points.append(math.sin(i*(math.pi/180))*pw*6.5 + center[1]) c.create_polygon(points,fill = '#ffdf80') #create the black underlay points = [] for i in range(0,360,60): points.append(math.cos(i*(math.pi/180))*pw*4.62 + center[0]) points.append(math.sin(i*(math.pi/180))*pw*4.62 + center[1]) c.create_polygon(points,fill = 'black') tile_to_knight = {} #creates each tile as specified in the board class for tile,spot,q in zip(tiles,spots,range(1,20)): points = [] shiftx = (center[0]+(tile[0]*pw)) shifty = (center[1]+(tile[1]*pw)) for i in range(30,390,60): points.append(math.cos(i*(math.pi/180))*w+shiftx) points.append(math.sin(i*(math.pi/180))*w+shifty) t = c.create_polygon(points, outline=colors[spot], fill=colors[spot]) if spot != 'Desert': c.create_text(shiftx,shifty,fill='black', font="Times 25 bold", text=str(self.game.board.rollDic[q])) #used to move the knight tmp = c.create_oval(shiftx+15,shifty+15, shiftx-15,shifty-15,fill = '',outline='') tile_to_knight[t] = [tmp,self.game.board.spots[q]] if spot == 'Desert': self.current_robber = t c.itemconfigure(tile_to_knight[t][0],fill = 'black') c.tag_bind(t,"<Enter>", lambda event, tag = t: enterTile(tag)) c.tag_bind(t,"<Leave>", lambda event, tag = t: leaveTile(tag)) c.tag_bind(t,'<Button-1>',lambda event, tag = t: clickTile(tag)) c.tag_bind(tile_to_knight[t][0],"<Enter>", lambda event, tag = t: enterTile(tag)) c.tag_bind(tile_to_knight[t][0],"<Leave>", lambda event, tag = t: leaveTile(tag)) c.tag_bind(tile_to_knight[t][0],'<Button-1>',lambda event, tag = t: clickTile(tag)) def enterTile(tag): if self.freeze and self.robber_move: c.itemconfigure(tile_to_knight[tag][0],fill='black') def leaveTile(tag): if self.freeze and self.robber_move and \ tag != self.current_robber: c.itemconfigure(tile_to_knight[tag][0],fill = '') def clickTile(tag): if self.freeze and self.game.round > 1 and \ self.robber_move: c.itemconfigure(tile_to_knight[tag][0],fill='black') c.itemconfigure(tile_to_knight[self.current_robber][0], fill = '') tile_to_knight[self.current_robber][1].blocked=False self.current_robber = tag tile_to_knight[self.current_robber][1].blocked=True self.robber_move = False self.freeze = False self.takeCard(tile_to_knight[self.current_robber][1]) threeOnes = [[-2.8,-2.8*math.sqrt(3)],[-2.8,2.8*math.sqrt(3)], [5.75,0],[4,-3]] for port in threeOnes: x = center[0] + port[0]*pw y = center[1] + port[1]*pw c.create_text(x,y,fill='black',font='Times 25 italic bold', text='3:1') #positioning of ports ports = {'Sheep':[.7,-5],'Wood':[.7,5],'Ore':[-4.8,-1.7], 'Wheat':[-4.8,1.7],'Brick':[4,3]} for port in ports.keys(): x = center[0] + ports[port][0]*pw y = center[1] + ports[port][1]*pw c.create_text(x,y,fill='black',font='Times 25 italic bold', text=port) #Top left tells you which players turn turn_label = c.create_text(100,50,fill='black', font = 'Times 30', text = self.game.current_player.name+"'s Turn") #Top right tell you the current players point tally point_counter = c.create_text(950,50,fill='black', font = 'Times 30', text = 'Points: '+ \ str(self.game.current_player.points)) self.point_counter = point_counter """Player's hand""" c.create_polygon([[140,1050],[910,1050],[910,800],[140,800]], fill = 'white') self.hand = {} self.devs = {} #resource cards c.create_text(210,825,fill='black',font='Times 30 bold', text='HAND') self.hand['brick'] = c.create_text(255,875,fill='black', font='Times 25',text='Brick: '+ \ str(self.game.current_player.hand['brick']), anchor='e') self.hand['ore'] = c.create_text(255,910,fill='black', font='Times 25',text='Ore: '+ \ str(self.game.current_player.hand['ore']), anchor='e') self.hand['sheep'] = c.create_text(255,945,fill='black', font='Times 25',text='Sheep: '+ \ str(self.game.current_player.hand['sheep']), anchor='e') self.hand['wheat'] = c.create_text(255,980,fill='black', font='Times 25', text='Wheat: '+ \ str(self.game.current_player.hand['wheat']), anchor='e') self.hand['wood'] = c.create_text(255,1015,fill='black', font='Times 25', text='Wood: '+ \ str(self.game.current_player.hand['wood']), anchor='e') #development cards c.create_text(900,82e5,fill='black',font='Times 30 bold', text='DEV CARDS',anchor = 'e') self.devs['knight'] = c.create_text(900,875,fill='black', font='Times 25',text='Knight x '+ \ str(self.game.current_player.knight), anchor='e') def clickKnight(tag): if self.game.current_player.knight > 0 and not self.game.playedDev: self.game.current_player.knight -= 1 self.game.playedDev = True self.updateDevs() self.robber_move = True self.freeze = True self.game.playedKnight() c.tag_bind(self.devs['knight'],'<Button-1>',lambda event, tag = self.devs['knight']: clickKnight(tag)) self.devs['monopoly'] = c.create_text(900,910,fill='black', font='Times 25', text='Monopoly x '+ \ str(self.game.current_player.monopoly), anchor='e') def clickMonopoly(tag): if self.game.current_player.monopoly > 0 and not self.game.playedDev: self.game.current_player.monopoly -= 1 self.game.playedDev = True self.updateDevs() self.freeze = True self.monopolize() c.tag_bind(self.devs['monopoly'],'<Button-1>',lambda event, tag = self.devs['monopoly']: clickMonopoly(tag)) self.devs['road_builder'] = c.create_text(900,945,fill='black', font='Times 25',text='Road Builder x '+ \ str(self.game.current_player.road_builder), anchor='e') def clickRB(tag): if self.game.current_player.road_builder > 0 and not self.game.playedDev: self.game.current_player.road_builder -= 1 self.game.playedDev = True self.updateDevs() self.game.building_roads = 2 self.game.availableMoves() c.tag_bind(self.devs['road_builder'],'<Button-1>',lambda event, tag = self.devs['road_builder']: clickRB(tag)) self.devs['year_of_plenty'] = c.create_text(900,980,fill='black', font='Times 25',text='Year of Plenty x '+ \ str(self.game.current_player.year_of_plenty), anchor='e') def clickYP(tag): if self.game.current_player.year_of_plenty > 0 and\ not self.game.playedDev: self.game.current_player.year_of_plenty -= 1 self.game.playedDev = True self.updateDevs() self.freeze = True self.plentiful(2) c.tag_bind(self.devs['year_of_plenty'],'<Button-1>',lambda event, tag = self.devs['year_of_plenty']: clickYP(tag)) self.devs['point_cards'] = c.create_text(900,1015,fill='black', font='Times 25', text='Point Card x '+ \ str(self.game.current_player.point_cards), anchor='e') #Keeps track of the current rolled number roll_label = c.create_text(525,825,fill='black', font = 'Times 30 bold', text = 'Roll: '+ str(self.game.dieRoll)) def nextTurn(): if self.game.round > 1: self.game.rollDice() c.itemconfigure(roll_label, text = 'Roll: ' + str(self.game.dieRoll)) self.rolled = True else: self.rolled = True self.game.playerUpdate() self.updateDevs() c.itemconfigure(turn_label, text = self.game.current_player.name+"'s Turn") self.game.availableMoves() self.updateHand() if self.game.dieRoll == 7: Seven.rolled(self,self.game.players) self.updateHand() self.game.availableMoves() def enterRoll(event,tag): if not self.freeze and not self.rolled: c.itemconfigure(roll_box,fill = 'white') def leaveRoll(event,tag): if not self.freeze: c.itemconfigure(roll_box,fill = 'red') def clickRoll(event,tag): if not self.freeze and not self.rolled: if self.game.round > 1: nextTurn() roll_box = c.create_rectangle(5,1020,135,970,fill = 'red') tmp = c.create_text(70,995,fill='black',font = 'Times 25 bold', text = 'ROLL') c.tag_bind(tmp,"<Enter>", lambda event, tag = tmp: enterRoll(event,tag)) c.tag_bind(tmp,"<Leave>", lambda event, tag = tmp: leaveRoll(event,tag)) c.tag_bind(tmp,'<Button-1>',lambda event, tag = tmp: clickRoll(event,tag)) c.tag_bind(roll_box,'<Button-1>',lambda event, tag = roll_box: clickRoll(event,tag)) def enterEnd(event,tag): if not self.freeze: c.itemconfigure(end_box,fill = 'white') def leaveEnd(event,tag): if not self.freeze: c.itemconfigure(end_box,fill = '#808080') def clickEnd(event,tag): if not self.freeze and self.rolled: c.itemconfigure(roll_label, text = 'Roll: ') self.game.turn += 1 self.game.round = self.game.turn//len(self.game.players) self.game.playerUpdate() self.updateDevs() c.itemconfigure(turn_label, text = self.game.current_player.name+"'s Turn") self.game.availableMoves() self.updateHand() self.rolled = False end_box = c.create_rectangle(915,1020,1045,970,fill = '#808080') tmp = c.create_text(980,995,fill='black',font = 'Times 23 bold', text = 'END TURN') c.tag_bind(tmp,"<Enter>", lambda event, tag = tmp: enterEnd(event,tag)) c.tag_bind(tmp,"<Leave>", lambda event, tag = tmp: leaveEnd(event,tag)) c.tag_bind(tmp,'<Button-1>',lambda event, tag = tmp: clickEnd(event,tag)) c.tag_bind(end_box,'<Button-1>',lambda event, tag = end_box: clickEnd(event,tag)) def enterBDev(event,tag): if not self.freeze and self.rolled: c.itemconfigure(dev_box,fill = 'white') def leaveBDev(event,tag): if not self.freeze: c.itemconfigure(dev_box,fill = '#A9A9A9') def clickBDev(event,tag): if not self.freeze and self.game.round > 1 and \ self.game.moves['dev_card'] and self.rolled: self.game.buyDev() self.updateHand() self.updateDevs() self.game.availableMoves() dev_box = c.create_rectangle(915,965,1045,915, fill = '#A9A9A9') tmp = c.create_text(980,940,fill='black',font = 'Times 23 bold', text = 'BUY DEV-C') c.tag_bind(tmp,"<Enter>", lambda event, tag = tmp: enterBDev(event,tag)) c.tag_bind(tmp,"<Leave>", lambda event, tag = tmp: leaveBDev(event,tag)) c.tag_bind(tmp,'<Button-1>',lambda event, tag = tmp: clickBDev(event,tag)) c.tag_bind(dev_box,'<Button-1>',lambda event, tag = dev_box: clickBDev(event,tag)) def enterTrade(event,tag): if not self.freeze and self.rolled: c.itemconfigure(tradeIn_box,fill = 'white') def leaveTrade(event,tag): if not self.freeze: c.itemconfigure(tradeIn_box,fill = '#C8C8C8') def clickTrade(event,tag): if not self.freeze and self.rolled and self.game.round > 1: #self.freeze = True self.tradeWindow() tradeIn_box = c.create_rectangle(915,910,1045,860, fill = '#C8C8C8', activefill='white') tmp = c.create_text(980,885,fill='black',font = 'Times 23 bold', text = 'TRADE IN') c.tag_bind(tmp,"<Enter>", lambda event, tag = tmp: enterTrade(event,tag)) c.tag_bind(tmp,"<Leave>", lambda event, tag = tmp: leaveTrade(event,tag)) c.tag_bind(tmp,'<Button-1>',lambda event, tag = tmp: clickTrade(event,tag)) c.tag_bind(tradeIn_box,'<Button-1>',lambda event, tag = tradeIn_box: clickTrade(event,tag)) def enterTradeOther(event,tag): if not self.freeze and self.rolled: c.itemconfigure(tradeOther_box,fill = 'white') def leaveTradeOther(event,tag): if not self.freeze: c.itemconfigure(tradeOther_box,fill = '#E0E0E0') def clickTradeOther(event,tag): if not self.freeze and self.rolled and self.game.round > 1: #self.freeze = True self.tradeOtherWindow() tradeOther_box = c.create_rectangle(915,855,1045,805, fill = '#E0E0E0', activefill='white') tmp = c.create_text(980,830,fill='black',font = 'Times 19 bold', text = ' TRADE \nPLAYERS') c.tag_bind(tmp,"<Enter>", lambda event, tag = tmp: enterTradeOther(event,tag)) c.tag_bind(tmp,"<Leave>", lambda event, tag = tmp: leaveTradeOther(event,tag)) c.tag_bind(tmp,'<Button-1>',lambda event, tag = tmp: clickTradeOther(event,tag)) c.tag_bind(tradeIn_box,'<Button-1>',lambda event, tag = tradeOther_box: clickTradeOther(event,tag)) """Create houses and cities""" houses = [] house_positions = [] settlements_to_vertices = {} boughtHomes = set() cities = [] city_positions = [] cities_to_vertices = {} boughtCities = set() house_to_city = {} #centers house around cooridinates def houseShape(x,y): points = [[15,0],[0,-10],[-15,0],[-15,20],[15,20]] return [[el[0]+x+center[0],el[1]+y+center[1]] for el in points] def cityShape(x,y): points = [[35,0],[15,0],[0,-10],[-15,0],[-15,20],[35,20]] return [[el[0]+x+center[0],el[1]+y+center[1]] for el in points] def buyHouse(event,tag): index = settlements_to_vertices[tag] if self.game.moves['settlements'][index[0]][index[1]] and \ not self.freeze and self.rolled: c.itemconfigure(tag,fill=self.game.current_player.color, outline='black') boughtHomes.add(tag) self.game.buySettlement(self.game.current_player.name, index) self.game.availableMoves() self.updateHand() c.tag_raise(house_to_city[tag]) def enterHouse(event,tag): index = settlements_to_vertices[tag] if self.game.moves['settlements'][index[0]][index[1]] and\ not self.freeze and self.rolled: c.itemconfigure(tag,fill='#D3D3D3') def leaveHouse(event,tag): if tag not in boughtHomes: c.itemconfigure(tag,fill='') def buyCity(event,tag): index = cities_to_vertices[tag] if self.game.round > 1 and \ self.game.moves['cities'][index[0]][index[1]] and \ not self.freeze and self.rolled: c.itemconfigure(tag,fill=self.game.current_player.color, outline='black') boughtCities.add(tag) self.game.buyCity(self.game.current_player.name, index) self.game.availableMoves() self.updateHand() def enterCity(event,tag): index = cities_to_vertices[tag] if self.game.round > 1 and self.game.moves['cities'][index[0]][index[1]] and\ not self.freeze and self.rolled: c.itemconfigure(tag,fill='#D3D3D3') def leaveCity(event,tag): if tag not in boughtCities: c.itemconfigure(tag,fill='') startPoints = [[-3*pw+2,-4.1*pw],[-4*pw+2,-2.4*pw], [-5*pw+2,-.7*pw],[-5*pw+2,.5*pw],[-4*pw+2,2.2*pw], [-3*pw+2,3.9*pw]] for i in range(len(self.game.board.vertices)): row = [] c_row = [] position_row = [] x = startPoints[i][0] y = startPoints[i][1] for q in range(len(self.game.board.vertices[0])): if self.game.board.vertices[i][q]: home = c.create_polygon(houseShape(x,y),fill = '') city = c.create_polygon(cityShape(x,y), fill = '') c.tag_bind(home,"<Button-1>", lambda event, tag = home: buyHouse(event,tag)) c.tag_bind(home,"<Enter>", lambda event, tag = home: enterHouse(event,tag)) c.tag_bind(home,"<Leave>", lambda event, tag = home: leaveHouse(event,tag)) c.tag_bind(city,"<Button-1>", lambda event, tag = city: buyCity(event,tag)) c.tag_bind(city,"<Enter>", lambda event, tag = city: enterCity(event,tag)) c.tag_bind(city,"<Leave>", lambda event, tag = city: leaveCity(event,tag)) house_to_city[home] = city row.append(home) c_row.append(city) position_row.append((x+center[0],y+center[1]+6)) settlements_to_vertices[home] = (i,q) cities_to_vertices[city] = (i,q) x += math.sqrt(.75*w**2) + 3.5 if i%2==0: if q%2==0: y -= .5*w else: y += .5*w else: if q%2==0: y += .5*w else: y -= .5*w else: row.append(None) position_row.append(None) houses.append(row) house_positions.append(position_row) cities.append(row) city_positions.append(position_row) """Create roads""" boughtRoads = set() def buyRoad(event,tag): index = roads_to_edges[tag] if index in self.game.moves['roads'] and not self.freeze: c.itemconfigure(tag,fill=self.game.current_player.color) boughtRoads.add(tag) self.game.buyRoad(self.game.current_player.name,index) self.game.availableMoves() if self.game.round < 2: self.rolled = False self.game.turn += 1 self.game.round = self.game.turn//len(self.game.players) nextTurn() self.updateHand() def enterRoad(event,tag): index = roads_to_edges[tag] if index in self.game.moves['roads'] and not self.freeze: c.itemconfigure(tag,fill='#D3D3D3') def leaveRoad(event,tag): if tag not in boughtRoads: c.itemconfigure(tag,fill='') roads_to_edges = {} for edge in self.game.board.availableEdges: house_1 = edge[0] house_2 = edge[1] road = c.create_line(house_positions[house_1[0]][house_1[1]], house_positions[house_2[0]][house_2[1]], fill='',width=8) c.tag_bind(road,"<Button-1>", lambda event, tag = road: buyRoad(event,tag)) c.tag_bind(road,"<Enter>", lambda event, tag = road: enterRoad(event,tag)) c.tag_bind(road,"<Leave>", lambda event, tag = road: leaveRoad(event,tag)) roads_to_edges[road] = edge for key in settlements_to_vertices.keys(): c.tag_raise(key) root.mainloop() #Reflects changes in hand after any transaction or at beginning of turn def updateHand(self): for key in self.hand.keys(): self.c.itemconfigure(self.hand[key], text = key.capitalize()+': '+ \ str(self.game.current_player.hand[key])) self.c.itemconfigure(self.point_counter, text = 'Points: '+ \ str(self.game.current_player.points)) #Updates development cards at new turn/ after pruchase/ after use def updateDevs(self): self.c.itemconfigure(self.devs['knight'], text = 'Knight x '+str(self.game.current_player.knight)) self.c.itemconfigure(self.devs['monopoly'], text = 'Monopoly x '+ \ str(self.game.current_player.monopoly)) self.c.itemconfigure(self.devs['year_of_plenty'], text = 'Year of Plenty x '+ \ str(self.game.current_player.year_of_plenty)) self.c.itemconfigure(self.devs['road_builder'], text = 'Road Builder x '+ \ str(self.game.current_player.road_builder)) self.c.itemconfigure(self.devs['point_cards'], text = 'Point Card x '+ \ str(self.game.current_player.point_cards)) def takeCard(self,tile): players = set() for vertex in tile.vertices: if self.game.board.vertices[vertex[0]][vertex[1]].owner: players.add(self.game.board.\ vertices[vertex[0]][vertex[1]].owner) players = list(players) takeable = [] for player in players: if player != self.game.current_player and \ sum(list(player.hand.values()))>0: takeable.append(player) if len(takeable)>0: root = Tk() b1 = Button(root,text=takeable[0].name, command=lambda p = takeable[0]:takeOne(p)) b1.grid(row=0,column=0) if len(takeable)>1: b2 = Button(root,text=takeable[1].name, command=lambda p = takeable[1]:takeOne(p)) b2.grid(row=1,column=0) if len(takeable)>2: b3 = Button(root,text=takeable[2].name, command=lambda p = takeable[2]:takeOne(p)) b3.grid(row=2,column=0) def takeOne(p): l = [[resource]*amount for resource, amount in \ zip(p.hand.keys(),p.hand.values())] cards = [] for element in l: cards += element taken = cards[random.randint(0,len(cards)-1)] p.hand[taken] -= 1 self.game.current_player.hand[taken] += 1 self.updateHand() self.game.availableMoves() root.destroy() root.mainloop() def monopolize(self): root = Tk() brick = Button(root,text='Brick',command = lambda r = 'brick': takeResource(r)) brick.grid(row=0) brick = Button(root,text='Ore',command = lambda r = 'ore': takeResource(r)) brick.grid(row=1) brick = Button(root,text='Sheep',command = lambda r = 'sheep': takeResource(r)) brick.grid(row=2) brick = Button(root,text='Wheat',command = lambda r = 'wheat': takeResource(r)) brick.grid(row=3) brick = Button(root,text='Wood',command = lambda r = 'wood': takeResource(r)) brick.grid(row=4) def takeResource(resource): total = 0 for player in self.game.players: if player != self.game.current_player: total += player.hand[resource] player.hand[resource] = 0 self.game.current_player.hand[resource] += total self.updateHand() self.game.availableMoves() self.freeze = False root.destroy() def plentiful(self, count): root = Tk() brick = Button(root,text='Brick',command = lambda r = 'brick': takeResource(r)) brick.grid(row=0) brick = Button(root,text='Ore',command = lambda r = 'ore': takeResource(r)) brick.grid(row=1) brick = Button(root,text='Sheep',command = lambda r = 'sheep': takeResource(r)) brick.grid(row=2) brick = Button(root,text='Wheat',command = lambda r = 'wheat': takeResource(r)) brick.grid(row=3) brick = Button(root,text='Wood',command = lambda r = 'wood': takeResource(r)) brick.grid(row=4) def takeResource(resource): nonlocal count self.game.current_player.hand[resource] += 1 self.updateHand() count -= 1 if count == 0: self.freeze = False self.game.availableMoves() root.destroy() def tradeWindow(self): root = Tk() Label(root,text = 'What to Trade In').grid(row=0) Button(root, text = 'Brick',command = lambda resource='brick':trade(resource)).grid(row=1) Button(root, text = 'Ore',command = lambda resource='ore':trade(resource)).grid(row=2) Button(root, text = 'Sheep',command = lambda resource='sheep':trade(resource)).grid(row=3) Button(root, text = 'Wheat',command = lambda resource='wheat':trade(resource)).grid(row=4) Button(root, text = 'Wood',command = lambda resource='wood':trade(resource)).grid(row=5) def trade(r): if self.game.current_player.ports[r] and self.game.current_player.hand[r] > 1: self.game.current_player.hand[r] -= 2 self.plentiful(1) root.destroy() elif self.game.current_player.ports['3:1'] and self.game.current_player.hand[r] > 2: self.game.current_player.hand[r] -= 3 self.plentiful(1) root.destroy() elif self.game.current_player.hand[r] > 3: self.game.current_player.hand[r] -= 4 self.plentiful(1) root.destroy() root.mainloop() def tradeOtherWindow(self): root = Tk() n_give = [] n_take = [] def addInput(): n_give = list(map(int,[e1.get(),e2.get(),e3.get(),e4.get(),e5.get()])) n_take = list(map(int,[e6.get(),e7.get(),e8.get(),e9.get(),e10.get()])) root.destroy() self.offerTrade(n_give,n_take) Label(root,text="Want I want to give").grid(row=0,column=0, columnspan = 2) Label(root,text="Want I want to give").grid(row=0, column = 2, columnspan=2) Label(root, text="Brick").grid(row=1) Label(root, text="Ore").grid(row=2) Label(root, text="Sheep").grid(row=3) Label(root, text="Wheat").grid(row=4) Label(root, text="Wood").grid(row=5) e1 = Entry(root) e2 = Entry(root) e3 = Entry(root) e4 = Entry(root) e5 = Entry(root) e1.grid(row=1, column=1) e1.insert(0,0) e2.grid(row=2, column=1) e2.insert(0,0) e3.grid(row=3, column=1) e3.insert(0,0) e4.grid(row=4, column=1) e4.insert(0,0) e5.grid(row=5, column=1) e5.insert(0,0) Label(root, text="Brick").grid(row=1,column=2) Label(root, text="Ore").grid(row=2,column=2) Label(root, text="Sheep").grid(row=3,column=2) Label(root, text="Wheat").grid(row=4,column=2) Label(root, text="Wood").grid(row=5,column=2) e6 = Entry(root) e7 = Entry(root) e8 = Entry(root) e9 = Entry(root) e10 = Entry(root) e6.grid(row=1, column=3) e6.insert(0,0) e7.grid(row=2, column=3) e7.insert(0,0) e8.grid(row=3, column=3) e8.insert(0,0) e9.grid(row=4, column=3) e9.insert(0,0) e10.grid(row=5, column=3) e10.insert(0,0) Button(root, text='Offer Trade', command=addInput).grid(row=6, sticky=W) root.mainloop() def offerTrade(self,n_give,n_take): root = Tk() res = ['brick','ore','sheep','wheat','wood'] offering = 'Offering: ' + ' ,'.join([str(n)+ ' '+ r for n,r in zip(n_give,res) if n != 0]) wants = 'For: ' + ' ,'.join([str(n)+ ' '+ r for n,r in zip(n_take,res) if n != 0]) for n,r in zip(n_give,res): if self.game.current_player.hand[r] < n: root.destroy() takers = [] for player in self.game.players: lacking = False for n,r in zip(n_take,res): if player.hand[r] < n: lacking = True if not lacking: takers.append(player) Label(root,text = offering).grid(row = 0) Label(root,text = wants).grid(row = 1) Label(root,text = 'Who wants to take it? (Enter Name)').grid(row=2) e1 = Entry(root) e1.grid(row=3) def takeTrade(): name = e1.get() if name not in self.game.player_dic: root.destroy() elif self.game.player_dic[name] in takers: for n,r in zip(n_take,res): self.game.current_player.hand[r] += n self.game.player_dic[name].hand[r] -= n for n,r in zip(n_give,res): self.game.player_dic[name].hand[r] += n self.game.current_player.hand[r] -= n self.updateHand() self.game.availableMoves() root.destroy() Button(root, text = 'Take Trade', command= takeTrade).grid(row=4,column=0) Button(root, text = 'None One Wants It', command = root.destroy).grid(row=4,column=1) if len(takers) == 0: root.destroy()
5754235c912ab975dc3c4206f1e0636933639025
wangz0314/Python
/class/class2.py
1,287
3.84375
4
# -*- coding: utf-8 -*- ######################################################################## # File Name: class2.py # Author: wangzhao # mail:wangzhao314@126.com # Created Time: 2015-06-12 17:58:13 ######################################################################## #!/usr/bin/python '类的继承与使用;当使用多超类继承时,先继承的类中的方法会重写后继承类中的方法' class Counter: def count(self, expression): self.value = eval(expression) print 'Counter类的count()方法!' def user(self): print "Hi, Counter's value is", self.value print "Counter类的user()方法!" class User: def user(self): print "Hi, User's value is", self.value print "User类的user()方法!" class New1(Counter, User): pass #先继承Counter类 class New2(User, Counter): pass #先继承User类 print 'uc1=New1(Counter, User)的结果:' print uc1 = New1() #将使用Counter类的user()方法 uc1.count('1+2*3') uc1.user() print print '------------------------------' print 'uc2=New2(User, Counter)的结果:' print uc2 = New2() #将使用User类的user()方法 uc2.count('2+3*6') uc2.user() print
d3bfcc3fda68f944b64961b0ef0f936e58ff011a
Argentum462/Coursera-python
/week5/solution16.py
635
3.703125
4
# Найдите наибольшее значение в списке и индекс последнего элемента, # который имеет данное значение за один проход по списку, # не модифицируя этот список и не используя дополнительного списка. NumList = list(map(int, input().split())) MaxNum = 0 IndexNum = 0 for i in range(len(NumList)): if NumList[i] >= MaxNum: MaxNum = NumList[i] IndexNum = i print(MaxNum, IndexNum) # или print(max(NumList), len(NumList) - NumList[::-1].index(max(NumList)) - 1)
cc9318efbcc5b93c2f0a6fb3fe7772f24d00c774
StaroKep/Python
/Простые задачи/p10.py
1,593
4.15625
4
# Дана строка. # Определите, какой символ в ней встречается раньше: 'x' или 'w'. # Если какого-то из символов нет, вывести сообщение об этом. # Для проверки: "qwerty", "zxcvb", "qwertyzxcvb", "zxcvbqwerty" # Решить с использованием цикла (нужно написать функцию поиска символа в строке) # code... def my_finder(s, p): k = 0 for i in s: if (i == p): return k k += 1 return -1 def y(s): x = my_finder(s, 'x') w = my_finder(s, 'w') if (x == -1): return 'x в строке не встречается' elif (w == -1): return 'w в строке не встречается' elif (x > w): return 'w встречается раньше' else: return 'x встречается раньше' print(y("qwerty")) print(y("zxcvb")) print(y("qwertyzxcvb")) print(y("zxcvbqwerty")) print("---") # Решить с использованием метода string.find(string) # code... def f(s): x = s.find('x') w = s.find('w') if (x == -1): return 'x в строке не встречается' elif (w == -1): return 'w в строке не встречается' elif (x > w): return 'w встречается раньше' else: return 'x встречается раньше' print(f("qwerty")) print(f("zxcvb")) print(f("qwertyzxcvb")) print(f("zxcvbqwerty"))
c3f6034996deb8fa1cdee32b9cb9ef1d01489f32
angeloevangelista/fiap-on-python
/Dictionaries/users/UserHandlers.py
977
3.640625
4
from DictionaryFunctions import ( find, insert, remove, update ) def requestOption(): selectedOption = input( 'O que deseja fazer?\n' + '<I> - Inserir um usuário.\n' + '<P> - Pesquisar um usuário.\n' + '<E> - Excluir um usuário.\n' + '<L> - Listar usuários.\n' ).upper() return selectedOption # def handleUserInsertion(users): login = input('Digite o login: ').upper() name = input('Digite o nome: ').upper() lastAccessDate = input('Digite a data do último acesso: ') station = input('Digite a última estação acessada: ').upper() insert(users, login, [name, lastAccessDate, station]) # def handleUserSearch(users): login = input('Digite o login: ').upper() foundUser = find(users, login) print(foundUser) # def handleUserRemotion(users): login = input('Digite o login do usuário a ser removido: ').upper() remove(users, login) # def handleUserList(users): for login in users: print(users[login]) #
f4b4164886e036299d858474d57cf8018cd810be
yash3110/Python-Codewayy
/Python Task-2/Dictionary.py
519
4.21875
4
#TASK 2 #Program for 7 different methods of dictionary #Initialize the dictionary voc = ('Name': 'Yash', 'Age': 19 'Course': 'B-Tech CSE') print (voc) #Printing elemnts using key print("Name: ", voc['Name']) #Add a new key voc['college'] = "Amity University" print (voc) #Printing (keys,values) pair of dictionary items voc.item() print("key, value pair of dictionary: ", voc.items()) #Remove Entry using key del voc['Course'] print(voc) #legnth of a dictionary print ("legnth of the dictionary is: ", len(voc))
5eaba6716712c140c8a732d7547f7351d3cd875b
Elite2017/17B01A0231
/problem44.py
343
3.90625
4
#find the pair of pentagonal numbers for which their sum and difference is pentagonal find the difference of that pair of numbers? def pent(): ps = set() i = 1000 while True: i += 1 s = (3 * i* i - i)//2 for pj in ps: if s - pj in ps and s - 2*pj in ps: return s - 2*pj ps.add(s) print(pent())
b42a0b0b83550002be848ed9f74777013fb7e872
ruizsugliani/Algoritmos-1-Essaya
/Unidad 14/14_7.py
641
3.84375
4
''' Escribir una función llamada tail que recibe un archivo y un número N e imprime las últimas N líneas del archivo. Durante el transcurso de la función no puede haber más de N líneas en memoria. ''' from cola import Cola def tail(ruta_archivo, n): ultimas_lineas = Cola() with open(ruta_archivo) as archivo: cantidad_lineas = 0 for linea in archivo: ultimas_lineas.encolar(linea) cantidad_lineas += 1 if cantidad_lineas > n: ultimas_lineas.desencolar() while not ultimas_lineas.esta_vacia(): print(ultimas_lineas.desencolar())
23be7f01cca7b9d64f832beae316b1b10bb891b4
YingTing04/Neural-Networks
/a2/Assignment 2.py
7,127
3.84375
4
#implementing a backpropagation algorithm in a multilayer perceptron from sklearn.datasets import load_digits, fetch_openml from sklearn.model_selection import train_test_split import numpy as np #obtain flattened data for dense neural network X, Y = fetch_openml('mnist_784', version = 1, return_X_y = True) X_train, X_test, Y_train, Y_test = train_test_split(X, Y, train_size = 60000, test_size = 10000, shuffle = False) #performing normalisation X_train = X_train.astype('float32') X_train/= 255 X_test = X_test.astype('float32') X_test /= 255 #generation of one-hot labels for output def one_hot(arr): all_labels = [] for item in arr: label_arr = np.full((10), 0) label = int(item) label_arr[label] = 1 all_labels.append(label_arr) all_labels = np.array(all_labels) return all_labels #sigmoid activation function def sigmoid(x): y = 1 / (1 + np.exp(-x)) return y #derivative of sigmoid function def sigmoid_derivative(x): return sigmoid(x) * (1 - sigmoid(x)) sigmoid_vfunc = np.vectorize(sigmoid_derivative) #converting labels to one-hot vectors all_train_labels = one_hot(Y_train) print(all_train_labels.shape) #parameters batch_size = 64 input_dim = 784 hidden_nodes_1 = 64 data_size = 60000 output_dim = 10 lr = 0.1 momentum = 0.1 epoch = 0 iteration = 3 X_train_edit = X_train[:data_size] all_train_labels_edit = all_train_labels[:data_size] #generate random weights & bias for hidden nodes np.random.seed(2) #range of hidden weights: [0, 0.01] weights_hidden = np.random.rand(input_dim, hidden_nodes_1)/100 bias_hidden = np.random.rand(1, hidden_nodes_1)/100 #keeping track of previous weight changes for momentum prev_weights_hidden = np.zeros((input_dim, hidden_nodes_1)) #generate random weights & bias for output nodes np.random.seed(2) #range of output weights: [0, 0.1] weights_output = np.random.rand(hidden_nodes_1, output_dim)/10 bias_output = np.random.rand(1, output_dim)/10 #keeping track of previous weight changes for momentum prev_weights_output = np.zeros((hidden_nodes_1, output_dim)) #confusion matrix confusion_matrix_train = np.zeros((10,10)) for j in range(iteration): for i in range(0, data_size, batch_size): total_error = 0 epoch += 1 print(epoch) #split input into batches batch_input = X_train_edit[i:i+batch_size] batch_actual_output = all_train_labels_edit[i:i+batch_size] #calculation of activation at hidden node a_hidden = np.matmul(batch_input, weights_hidden) + bias_hidden #applying activation function to a hidden node y_hidden = np.zeros((a_hidden.shape[0], a_hidden.shape[1])) for i in range(a_hidden.shape[0]): for j in range(a_hidden.shape[1]): y_hidden[i][j] = sigmoid(a_hidden[i][j]) #note that y_hidden is input to output layer #calculation of activation at output node a_output = np.matmul(y_hidden, weights_output) + bias_output #applying activation function to a output node y_output = np.zeros((a_output.shape[0], a_output.shape[1])) for i in range(a_output.shape[0]): for j in range(a_output.shape[1]): y_output[i][j] = sigmoid(a_output[i][j]) #deriving predicted class using argmax for i in range(y_output.shape[0]): predict_class = np.argmax(y_output[i]) actual_class= np.argmax(batch_actual_output[i]) confusion_matrix_train[predict_class][actual_class] += 1 #calculating (d-y) for output node error_arr = batch_actual_output - y_output for i in range(error_arr.shape[0]): for j in range(error_arr.shape[1]): #epsilon = 0.1 if (abs(error_arr[i][j]) <= 0.1): error_arr[i][j] = 0 total_error += error_arr[i][j] **2 #calculation of errors and deltas output_delta = np.multiply(error_arr, sigmoid_vfunc(a_output)) hidden_error = np.matmul(output_delta, np.transpose(weights_output)) hidden_delta = np.multiply(hidden_error, sigmoid_vfunc(a_hidden)) #calculation of changes for weights and bias weights_output_change = lr * np.matmul(np.transpose(y_hidden), output_delta) weights_hidden_change = lr * np.matmul(np.transpose(batch_input), hidden_delta) bias_output_change = lr * np.sum(output_delta, axis = 0) bias_hidden_change = lr * np.sum(hidden_delta, axis = 0) #performing weights and bias changes weights_output += weights_output_change + momentum * prev_weights_output weights_hidden += weights_hidden_change + momentum * prev_weights_hidden bias_output += bias_output_change bias_hidden += bias_hidden_change prev_weights_output = weights_output_change prev_weights_hidden = weights_hidden_change print(total_error) print(confusion_matrix_train) #calculation of precision and recall for i in range(10): precision = confusion_matrix_train[i][i]/confusion_matrix_train.sum(axis = 1)[i] recall = confusion_matrix_train[i][i]/confusion_matrix_train.sum(axis = 0)[i] print('Class %d precision: %.4f recall: %.4f' % (i, precision, recall)) #converting labels to one-hot vectors all_test_labels = one_hot(Y_test) print(all_test_labels.shape) #testing of data data_size = 10000 #confusion matrix confusion_matrix_test = np.zeros((10,10)) for i in range(0, data_size, batch_size): total_error = 0 epoch += 1 print(epoch) #split input into batches batch_input = X_test[i:i+batch_size] batch_actual_output = all_test_labels[i:i+batch_size] #calculation of activation at hidden node a_hidden = np.matmul(batch_input, weights_hidden) + bias_hidden #applying activation function to a hidden node y_hidden = np.zeros((a_hidden.shape[0], a_hidden.shape[1])) for i in range(a_hidden.shape[0]): for j in range(a_hidden.shape[1]): y_hidden[i][j] = sigmoid(a_hidden[i][j]) #print(y_hidden) #note that y_hidden is input to output layer #calculation of activation at output node a_output = np.matmul(y_hidden, weights_output) + bias_output #applying activation function to a output node y_output = np.zeros((a_output.shape[0], a_output.shape[1])) for i in range(a_output.shape[0]): for j in range(a_output.shape[1]): y_output[i][j] = sigmoid(a_output[i][j]) #deriving predicted class using argmax for i in range(y_output.shape[0]): predict_class = np.argmax(y_output[i]) actual_class= np.argmax(batch_actual_output[i]) confusion_matrix_test[predict_class][actual_class] += 1 print(confusion_matrix_test) #calculation of precision and recall for i in range(10): precision = confusion_matrix_test[i][i]/confusion_matrix_test.sum(axis = 1)[i] recall = confusion_matrix_test[i][i]/confusion_matrix_test.sum(axis = 0)[i] print('Class %d precision: %.4f recall: %.4f' % (i, precision, recall))
a81ee00636c7d38f2a449553b96f42531e66cc80
SGCI-Coding-Institute/skyandsea
/number_test.py
168
3.796875
4
#This is a test file to print a list of numbers def printList(num): count = num while (count > 0): print(count) count = count - 1 printList(10)
f9b2518bf1167ff663a4d30d0e750d5d60e917eb
gaylonalfano/Python-3-Bootcamp
/dictionaries.py
4,380
3.6875
4
artist = { 'first': 'Neil', 'last': 'Young', } #full_name = artist['first'] + ' ' + artist['last'] # Format() solution: # full_name = "{} {}".format(artist['first'], artist['last']) # F-String solution: full_name = f"{artist['first']} {artist['last']}" print(full_name) # Iterating over dictionaries .values() instructor = { 'name': 'Colt', 'owns_dog': True, 'num_courses': 4, 'favorite_language': 'Python', 'is_hilarious': False, 44: 'my favorite number!' } for value in instructor.values(): print(value) # .keys() for key in instructor.keys(): print(key) # .items() instructor.items() print(instructor.items()) for key, value in instructor.items(): print(f"Key is: {key}. Value is: {value}.") # Donations Exercise donations = {'sam': 25.0, 'lena': 88.99, 'chuck': 13.0, 'linus': 99.5, 'stan': 150.0, 'lisa': 50.25, 'harrison': 10.0} total_donations = 0 for value in donations.values(): total_donations += value print(total_donations) # Another option using .sum() total_donations2 = sum(donation for donation in donations.values()) print(total_donations2) # Another advanced option using .sum() print(sum(donations.values())) # 'in' only checks keys in dictionaries if 'phone' in instructor.values(): print('There is a phone') else: print('No phone!') # Dictionary Methods # clear # instructor.clear() # setdefault(key to check for, value to set if key DOES NOT EXIST) # Good for ensuring that a key exists. spam = {'name': 'Pooka', 'age': 5} spam.setdefault('color', 'black') print(f'Here is spam: {spam}') spam.setdefault('color', 'white') # Still will be 'black' since key 'color' already exists ''' Program that counts the number of occurrences of each letter in a string ''' message = 'It was a bright cold day in April, and the clocks were striking thirteen.' def count_dict(string): count = {letter: string.count(letter) for letter in string} return count print(count_dict(message)) # count = {} # # for character in message: # count.setdefault(character, 0) # count[character] += 1 # # print(count) # pprint.pprint(count) - Nice print out view for Dictionaries # Copy() d = dict(a=1, b=2, c=3) c = d.copy() print(d, c) c is d # False c == d # True # dict.fromkeys() -- Creates key-value pairs from comma separated values {}.fromkeys('a', 'b') # {'a': 'b'} {}.fromkeys(['email'], 'unknown') # {'email': 'unknown'} {}.fromkeys('a', [1, 2, 3, 4, 5]) # {'a': [1, 2, 3, 4, 5]} {}.fromkeys(range(10), 'unknown') # .get() instructor.get('name') # 'Colt' from random import choice #DON'T CHANGE! food = choice(["cheese pizza", "quiche","morning bun","gummy bear","tea cake"]) #DON'T CHANGE! #DON'T CHANGE THIS DICTIONARY EITHER! bakery_stock = { "almond croissant" : 12, "toffee cookie": 3, "morning bun": 1, "chocolate chunk cookie": 9, "tea cake": 25 } [print(f'{bakery_stock[food]} left') if food in bakery_stock else print("We don't have that") for item in bakery_stock.keys()] # [print(f'{bakery_stock[food]} left') if food in bakery_stock.keys() else print("We don't have that")] # for key in bakery_stock.keys()] print(f'Food: {food}') print(food in bakery_stock.keys()) # Solution #1 my version: if food in bakery_stock.keys(): print(f'{bakery_stock[food]} left') else: print("We don't have that") # Solution #2 using .format() if food in bakery_stock: print("{} left".format(bakery_stock[food])) else: print("We don't make that") # Solution #3 using .get() quantity = bakery_stock.get(food) if quantity: print("{} left".format(quantity)) else: print("we don't make that") # dict.fromkeys Exercise Section 14, Coding Exercise 30 game_properties = ["current_score", "high_score", "number_of_lives", "items_in_inventory", "power_ups", "ammo", "enemies_on_screen", "enemy_kills", "enemy_kill_streaks", "minutes_played", "notications", "achievements"] initial_game_state = dict.fromkeys(game_properties, 0) print(initial_game_state) # .pop('key') -- Removes the specified key item from dict # .popitem() -- Removes a random key item from dict # .update() -- dictname.update() Update keys and values in a dict with another set of key-value pairs first = dict(a=1, b=2, c=3, d=4, e=5) second = {} second.update(first) print(second) second['a'] = 'AMAZING' second.update(first) second['f'] = 6 print(second)
af60ccc8024307938ab7e048f5dae479b6e00047
gilbutITbook/006936
/Unit 38/try_except_raise.py
376
3.890625
4
try: x = int(input('3의 배수를 입력하세요: ')) if x % 3 != 0: # x가 3의 배수가 아니면 raise Exception('3의 배수가 아닙니다.') # 예외를 발생시킴 print(x) except Exception as e: # 예외가 발생했을 때 실행됨 print('예외가 발생했습니다.', e)
d5ff8b3540cba3ba96aee1d687af1cf0caa7fb11
jmmoore/AdventOfCode2015
/Day05Solution/Day05SolutionPart2.py
931
3.65625
4
#!/usr/local/bin/python3 import os def checkForDuplicatePattern(string): i = 0 while i < len(string): a, b = 0, 2 checkString = string[(a+i):(b+i)] if string.count(checkString) > 1 and len(checkString) > 1: i += 1 return True return False def checkForSeparatedRepeats(string): for char in string: if char*2 in string[::2] or char*2 in string[1::2]: return True else: continue return False def countNiceStrings(inputFile): inputList = list(open(inputFile).readlines()) niceCounter = 0 for string in inputList: if checkForDuplicatePattern(string) and checkForSeparatedRepeats(string): niceCounter += 1 else: continue return niceCounter # Execution inputFile = os.path.abspath("./Day05Input") niceStringsCount = countNiceStrings(inputFile) print(niceStringsCount)
dbbccc58b29acb9aa9877f6c1654469a1bfccbd6
dennis2030/HumanAttributeOnDepth
/processGT/genRandom.py
552
3.640625
4
#!/usr/bin/env python import sys import random import collections def Usage(): print './genRandom.py num' print 'It would generate a random set in range 0 ~ num' print 'Total number of generate int is num/5' def __main__(): # if no argument, print usage for user if len(sys.argv) < 2: Usage() return num = int(sys.argv[1]) randomSet = set() for i in range(0,num/5): randomSet.add(random.randint(0,num)) for r in randomSet: print r if __name__ == '__main__': __main__()
f609000fa504e22e6b6be84112511812422bbb1b
Mrliuyuchao/Interview
/面试题整合/分离指针/合并两个有序数组.py
496
3.734375
4
def mergeTwo(nums1,m,nums2,n): i = m - 1 j = n - 1 k = m + n -1 while i >= 0 and j >= 0: if nums1[i] >= nums2[j]: nums1[k] = nums1[i] i -= 1 else: nums1[k] = nums2[j] j -= 1 k -= 1 while i >= 0: nums1[k] = nums1[i] i -= 1 k -= 1 while j >= 0 : nums1[k] = nums2[j] j -= 1 k -= 1 return nums1 n = mergeTwo([1,2,3,0,0,0],3,[-5,-4,-3],3) print(n)
cebeff183e38caa73bc67d3f68858494beee378b
FancyYan123/LeetcodeExercises
/414_thirdMaxNum.py
516
4.0625
4
from typing import * from queue import PriorityQueue class Solution: def thirdMax(self, nums: List[int]) -> int: nums, maxV = list(set(nums)), 0 q = PriorityQueue() for each in nums: maxV = each if each > maxV else maxV q.put(-each) rtn = 0 for i in range(3): if q.empty(): return maxV rtn = -q.get() return rtn if __name__ == '__main__': s = Solution() print(s.thirdMax([1,2,2,5,3,5]))
8ad227868eeb2819c1870beff43052fc61ce7052
singhavdeshk/python
/graphShortestPath/graphShortPath.py
3,713
3.984375
4
################################################### # Shortest path problem using Dijkistra Algorithm, # -- By Avdesh kr Singh, singh.avdesh.k@gmail.com ################################################### import math from collections import namedtuple from collections import defaultdict constants = namedtuple('constants', 'radius') CONST = constants(radius=4000) class CloudTravel: def __init__(self): self.nodes = set() self.edges = defaultdict(list) self.distances = {} def addNodes(self, count): for i in range(count): self.nodes.add(i) def addEdge(self, from_node, to_node, distance): self.edges[from_node].append(to_node) # self.edges[to_node].append(from_node) self.distances[(from_node, to_node)] = distance # self.distances[(from_node, to_node)] = distance def latLonArc(self, latLong1=(), latLong2=()): lat1 = math.radians(float(latLong1[0])) lon1 = math.radians(float(latLong1[1])) lat2 = math.radians(float(latLong2[0])) lon2 = math.radians(float(latLong2[1])) arc = CONST.radius * \ math.acos(math.sin(lat1) * math.sin(lat2) + math.cos(lat1) * math.cos(lat2) * \ math.cos(lon1 - lon2)) return int(arc) ## Dijkistra Algorithm ## def getDist(self, initial, dest): visited = {initial: 0} nodes = set(self.nodes) while nodes: min_node = None for node in nodes: if node in visited: if min_node is None: min_node = node elif visited[node] < visited[min_node]: min_node = node if min_node is None: break nodes.remove(min_node) current_weight = visited[min_node] if min_node == dest: break for edge in self.edges[min_node]: try: weight = current_weight + self.distances[(min_node, edge)] except: continue if edge not in visited or weight < visited[edge]: visited[edge] = weight return visited def shortestTrip(self, latitude, longitude, canTravel, origin, destination): canTravel = [ i.split(' ') for i in canTravel ] canTravel = [ list(map(int, j)) for j in canTravel ] latitude = list(latitude) longitude = list(longitude) self.makeNetwork(canTravel, latitude, longitude) d = self.getDist(origin, destination) if destination in d: return d[destination] else: return -1 def makeNetwork(self, canTravel, latitude, longitude): self.addNodes(len(canTravel)+1) for nodeFrom in range(len(canTravel)): for nodeTo in canTravel[nodeFrom]: dis = self.latLonArc((latitude[nodeFrom], longitude[nodeFrom]), \ (latitude[nodeTo], longitude[nodeTo])) self.addEdge(nodeFrom, nodeTo, dis) if __name__ == "__main__": c = CloudTravel() ###### Change the inputs of line below ######### #dist = c.shortestTrip(lat,lon,canTravel,origin,destination) dist = c.shortestTrip([0, 0, 70], [90, 0, 45], ["2", "0 2", "0 1"], 0, 1) #dist = c.shortestTrip([0, 30, 60], [25, -130, 78], ["1 2", "0 2", "1 2"], 0, 0) #dist = c.shortestTrip([0, 20, 55], [-20, 85, 42], ["1", "0", "0"], 0, 2) if dist != -1: print("The distance from origin to destination is: %d"% dist) else: print("No available routes.")
3e259f5d61ab3e3ef621ae116944312935442f75
rshekhovtsov/py-intro
/week2/2_38 second max.py
273
3.65625
4
# 2_38 second max max = 0 secmax = 0 n = -1 while not (n == 0): n = int(input()) if n == 0: continue if n > max: secmax = max max = n continue if n <= max and n > secmax: secmax = n print(secmax)
8147f9f8341dafa3b4d618b6d31f264331048bb7
inJAJA/Study
/homework/딥러닝 교과서/numpy/np15_arr_calculate.py
435
3.5625
4
import numpy as np ''' # 행렬 계산 ''' arr = np.arange(9).reshape(3, 3) # np.dot(a ,b) : 두 행렬의 행렬 곱을 반환 dot = np.dot(arr, arr) print(dot) # [[ 15 18 21][ 42 54 66][ 69 90 111]] print(dot.shape) # (3, 3) # np.linalg.norm(a) : norm을 반환 vector = arr.reshape(9) norm = np.linalg.norm(arr) print(norm) # 14.2828568570857
94049b66d8543296a5b9bf6e89069b5639bcef65
santiagoom/leetcode
/solution/python/270_ClosestBinarySearchTreeValue_3.py
650
3.578125
4
from typing import List from utils import * import collections class Solution_270_ClosestBinarySearchTreeValue_3: def closestValue(self, root: TreeNode, target: float) -> int: closest = root.val while root: closest = min(root.val, closest, key = lambda x: abs(target - x)) root = root.left if target < root.val else root.right return closest if __name__ == "__main__": nums = [2, 7, 11, 15] target = 26 so = Solution_270_ClosestBinarySearchTreeValue_3() s = "aa" arrays = [[1, 2, 3], [4, 5, 6]] print(arrays)
de45368f4ab77dd0a8601a3a7f62909cb26713e6
JayedHoshen/python-practic
/laptop/fRevesion/mojarProgram/prime_number-3.py
447
4.375
4
def is_prime3(n): if n == 2: return True #2 is prime if n % 2 ==0: print(n,"is divisible by 2") return False #all even numbers except 2 are not prime if n < 2: return False #numbers less than 2 are not prime prime = True m = n//2+1 for x in range(3,m,2): if n % x ==0: print(n,"is divisible by",x) prime = False return prime return prime