blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
c892b0004d36908c0fca32091c2261d700f1251a
Eashan123/Laposte_
/packages/le_poste/le_poste/config/logging_config.py
940
4.03125
4
# refer: https://docs.python.org/3/howto/logging.html#logging-advanced-tutorial import logging import sys # Multiple calls to logging.getLogger('someLogger') return a # reference to the same logger object. This is true not only # within the same module, but also across modules as long as # it is in the same Python interpreter process. FORMATTER = logging.Formatter( "%(asctime)s — %(name)s — %(levelname)s —" "%(funcName)s:%(lineno)d — %(message)s" #datetime stamp , name of the logger , levelname , name of the function from which the log was generated , line number within the function , the actual message that we logged. ) def get_console_handler(): console_handler = logging.StreamHandler(sys.stdout) # logs will be shown on the terminal, alternatively we could have assigned a file handler where the logs would have been sent to a file. console_handler.setFormatter(FORMATTER) return console_handler
3c7b2e44ad8bf4f0160f4b8da1a7792a3dbdc597
lees9/ftp-with-socket-programming
/server/ftserver.py
11,556
4.375
4
#!/usr/bin/env python # # Programming assignment 1 for cs372 online by Kamal Chaya # # simple implementation of FTP server in python # USAGE: # 1. In order to run the script w/o typing "python" give yourself # execute permissions. Run the following command in the shell: # chmod +x ftserver.py # # 2. Then you have to run the script with the following command # (omit the square brackets) # ./ftserver.py -c [port number for control connection] # import socket import sys import errno import os import getopt import signal #functions def sigIntHandler(signal, frame): """ Function: sigIntHandler() Input Parameters: signal: the signal to write the handler for frame: the function which is the signal handler Output: Prints a message saying the server is exiting when the signal is received Description: A signal handler for the SIGINT signal. When the user presses CTRL-C while the server is listening for commands from the client, the server will print a message saying it is exiting and invoke the exit function to exit the program. Invoking the exit function ensures that the kernel closes all the sockets Internal Dependencies: None External Dependencies: python sys API """ print 'Server exiting... the kernel will close the sockets\n' sys.exit(0) def getPort(): """ Function: getPort() Input Parameters: None Output: None, unless the arguments are entered incorrectly, then a message is printed showing how the arguments should be entered properly Description: parses the command line input for the control port number using getopt and returns it. Handles any exceptions from incorrect input Internal Dependencies: none External Dependencies: python getopt library """ try: opts, args = getopt.getopt(sys.argv[1:], "c:") except getopt.GetoptError as err: print "USAGE: ./ftserver.py -c [controlport] \n" ctrlPort = None for o, a in opts: if o == "-c": ctrlPort = a return ctrlPort def createSocket(): """ Function: createSocket() Input Parameters: None Output: returns a TCP IPv4 socket, but if the creation of the socket fails, an error message is printed Description: Creates a TCP IPv4 socket, and handles any exceptions that occur by exiting Internal Dependencies: None External Dependencies: python socket API python sys API """ try: return socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create the socket except socket.error: print "Error in socket creation" sys.exit(1) def connectDataSocket(dataSocket, hostName, dataPort): """ Function: connectDataSocket() Input Parameters: the socket to connect to a particular hostname and port number (dataSocket) the hostname to connect the socket to (hostName) the port number to connect the socket to (dataPort) Output: error messages are printed if the socket connection is refused or if any other error happens Description: This function connects the socket used for the TCP data connection to the appropriate host name and port number for the data connection. Internal Dependencies: None External Dependencies: python socket API python error library python sys API """ try: dataSocket.connect((hostName, int(dataPort))) except socket.error as e: if e.errno == errno.ECONNREFUSED: #Handling the exception of the socket connection being refused print "error: socket connection refused" sys.exit(1) else: print "Error: a socket exception occured" sys.exit(1) print 'Sucessfully established TCP data connection\n' def checkCmd(connectionSocket, cmd): """ Function: checkCmd() Input Parameters: the socket used to send data over the TCP control connection (connectionSocket) the command sent to the server by the client (cmd) Output: None, nothing is returned Description: This function simply checks if the command sent by the client is a valid list or get command. For checking a get command, it is necessary to check if the command contains the string 'get ' and that it is longer than 4 characters, to ensure that the command contains the word 'get' and the name of a file which is at least 1 character long. An appropriate message is sent to the client depending on whether the command is valid or not. Internal Dependencies: None External Dependencies: python socket API """ validCmd = False if 'list' == cmd: validCmd = True elif 'get ' in cmd and len(cmd) > 4: validCmd = True if validCmd == False: connectionSocket.send('Invalid command entered; Valid commands are \'list\', and \'get <filename>\'') else: connectionSocket.send('valid command sent: ' + cmd) return validCmd def execListCmd(dataSocket): """ Function: execListCmd() Input Parameters: the socket used to send data over the TCP data connection (dataSocket) Output: Nothing is returned, the function simply prints to the server's screen a message indicating that it is executing a list command Description: This function gets in list format all the files in the current directory of the server, and then it iterates through this list, and adds each filename on to a string, adding a newline character after each. After the list has been completely iterated through, the string contains the names of all the files in the servers current directory, with a newline after each. Then, this string is sent to the client. Interal Dependencies: None External Dependencies: python socket API python os API """ print 'Executing \'list\' command...\n' files = os.listdir(os.curdir) fileStr = '' for i in files: fileStr = fileStr + i + '\n' dataSocket.send(fileStr+"end") def execGetCmd(connectionSocket, dataSocket, cmd): """ Function: execGetCmd() Input Parameters: the socket used to send data over the TCP control connection (connectionSocket) the socket used to send data over the TCP data connection (dataSocket) the command sent to the client from the server (cmd) Output: Nothing is returned, various messages are printed depicting the progress towards completing the get command, how many bytes have been sent, what file the client is requesting, and an error message is printed if the socket connection becomes broken. Description: This function executes the get command, and it is called by the listenForCmd() function. It extracts the name of the file from the get command sent by the user, and then sees if the file exists on the servers current directory. If it doesn't, an error message is sent to the client. If it does, the client is sent the name of the file and its size. Once the client receives this information it sends back a message saying "transfer". When the server receives this message, the file is opened in read mode on the server and sent to the client in the while loop. Internal Dependencies: None External Dependencies: python socket API python os API python sys API """ fileName = cmd.split()[1] print 'Executing \'get ' + fileName + '\' command...\n' fileSize = 0 try: fileSize = os.path.getsize(fileName) except os.error: connectionSocket.send('error: the file was not found') else: connectionSocket.send(fileName + ":" + str(fileSize)) received = connectionSocket.recv(1024) if received == "transfer": #Start sending the file to the client here fileStr = open(fileName, 'r').read() totalBytesSent = 0 while totalBytesSent < fileSize: sent = dataSocket.send(fileStr[totalBytesSent:]) print "Bytes sent: " + str(sent) + " out of " + str(fileSize) + " \n" if sent == 0: print 'Socket connection broken\n' sys.exit(1) totalBytesSent = totalBytesSent + sent def listenForCmd(controlSocket,portNum): """ Function: listenForCmd() Input parameters: the Socket for the TCP control connection (controlSocket) the port number the TCP control socket should bind to (portNum) Output: This function doesn't output anything except when there is an invalid command given by the client, then it prints 'invalid command' on the screen Description: Waits for the command, data connection port, and client hostname to be sent from the client, then checks if it is a valid command or not (using the checkCmd() function). If the command is valid, and the command was a list command, the execListCmd() function is invoked in order to list the contents of the current directory on the server and send them to the client. However if the user sent a get command, the execGetCmd() function is invoked to send the requested file to the client if it exists on the server. Internal Dependencies: validCmd() execListCmd() execGetCmd() External Dependencies: python socket API python os API python sys API python signal API """ controlSocket.bind(('',int(portNum))) controlSocket.listen(1) print 'Server is ready to recieve commands\n' #Register the signal handler signal.signal(signal.SIGINT, sigIntHandler) while 1: connectionSocket, addr = controlSocket.accept() received = connectionSocket.recv(1024) receivedArray = received.split(":") dataPort = receivedArray[0] cmd = receivedArray[1] clientHostName = receivedArray[2] validCmd = checkCmd(connectionSocket, cmd) #Check if the command sent was valid if validCmd == False: print 'Invalid command\n' connectionSocket.close() sys.exit(1) else: dataSocket = createSocket() received = connectionSocket.recv(1024) if received == 'valid cmd received': connectDataSocket(dataSocket, clientHostName, dataPort) if cmd == 'list': execListCmd(dataSocket) elif 'get ' in cmd and len(cmd) > 4: execGetCmd(connectionSocket, dataSocket, cmd) dataSocket.close() connectionSocket.close() #main program ctrlPort = getPort() #get host and port numbers controlSocket = createSocket() #create the socket for the TCP control connection listenForCmd(controlSocket, ctrlPort) # Await user commands from the server
c0f82a228074325413677ec4ea24c65fe63a73d9
alpaka99/algorithm
/algorithm_class/완전검색_그리디/p_연습3/s1.py
453
4.125
4
""" 연습 문제3. 2의 거듭제곱 2의 거듭 제곱을 반복과 재귀버전으로 구현하시오. """ my_list = [5, 2, 7, 1, 3, 8, 9, 3, 5, 2] # 반복 def power_of_two_iteration(k): answer = 1 for _ in range(4): answer *= 2 return answer print(power_of_two_iteration(4)) # 재귀 def power_of_two_recursion(k): if k == 0: return 1 return power_of_two_recursion(k-1)*2 print(power_of_two_recursion(4))
bc4d675149f418e5ac29813c6da17335aa30a0de
Dami-o72/mini-project
/incomplete-week-4.py
2,588
4.3125
4
# user input 1 - print """def print_list_or_dict(op): #change name '''Print courier list, products list or orders dictionary''' print(op) print_list_or_dict()""" # user input 2 - create -- rename to new_product/courier """def create(num:str): '''Create new product or new courier''' # product if num == '1': get_name = input('Enter name ') get_price = float(input('Enter price ')) # new product product = {} product['name']= get_name.title() product['price'] = get_price # print (product) product_list.append(product) # courier elif num == '2': get_name = input('Enter name ') get_phone_number = input('Enter phone number ') # new courier courier = {} courier['name']= get_name.title() courier['price'] = get_phone_number # print (courier) courier_list.append(courier) print(courier_list) create()""" """def create_order(): '''Create new order''' print('You\'re about to create a new order') get_name = input('Enter full name ') get_customer_address = input('Enter customer address ') get_phone_number = input('Enter phone number ') for i, item in enumerate(products_list): print('\n',i,item) #this become the items product_index_val = input('Enter index(es) of product with commas') list_of_int = list(map(int,product_index_val.split(','))) for i, item in enumerate(courier_list): print('\n',i,item) select_courier = input('Enter index of courier ') order_status = 'PREPARING' orders_dict["customer_name"] = get_name orders_dict["customer_address"] = get_customer_address orders_dict["customer_phone"] = get_phone_number orders_dict["courier"] = select_courier orders_dict["status"] = order_status orders_dict["items"] = list_of_int print(orders_dict) orders_list.append(orders_dict) create_order() """ # user input 4 - delete """def delete_list(menu_list): '''Delete product, courier or orders list''' for i, item in enumerate(menu_list): print('\n',i,item) delete_product = input('would you like to delete product? y/n\n ') if delete_product == 'y': index_2 = int(input('Enter index\n')) remove = menu_list.pop(index_2) print(menu_list) # make robust by ensuring user has entered right index list and right value into input delete_list(product_list)"""
c361b9aeb879c9e2652d1e1b78b3daf825dd8de2
justAnotherMathmo/CrypticConstructor
/assembler.py
6,275
3.90625
4
import numpy as np import re # flag that indicates when we should backtrack class BacktrackException(Exception): pass def backtrack_search(answers, size, symmetric): BLANK = ' ' VOID = '#' # all letters in the completed grid board = np.array([[BLANK for j in range(size + 2)] for i in range(size + 2)]) # all numbers labelling where answers start labels = np.array([[None for j in range(size + 2)] for i in range(size + 2)]) for i in range(size + 2): board[0, i] = VOID board[size + 1, i] = VOID board[i, 0] = VOID board[i, size + 1] = VOID # separate across and down answers and sandwich with VOIDs across = {} down = {} for i, o in answers: ans = re.sub('[^A-Z]', '', answers[(i, o)]) ans = VOID + ans + VOID if o == 'A': across[i] = ans else: down[i] = ans max_number = max(answers)[0] placements = [] # stack of placements, so we can backtrack as necessary # Undo the last placement def backtrack(): if len(placements) > 0: label_placement, board_placement = placements.pop() for row, col in label_placement: labels[row, col] = None for row, col in board_placement: board[row, col] = BLANK # Try to write in the answer(s) numbered n (down or across or both) at position pos # Raises a BacktrackException if this fails because we try to overwrite non-BLANK squares def place(n, row, col): label_placement = [] board_placement = [] placements.append((label_placement, board_placement)) try: assert labels[row, col] is None labels[row, col] = n label_placement.append((row, col)) if n in across: ans = across[n] assert col + len(ans) <= size + 3 # word must fit for i, letter in enumerate(ans): assert board[row, col - 1 + i] in [BLANK, letter] # can't overwrite if board[row, col - 1 + i] == BLANK: board[row, col - 1 + i] = letter board_placement.append((row, col - 1 + i)) down_special_logic(row, col - 1 + i) if n in down: ans = down[n] assert row + len(ans) <= size + 3 # word must fit for j, letter in enumerate(ans): assert board[row - 1 + j, col] in [BLANK, letter] # can't overwrite if board[row - 1 + j, col] == BLANK: board[row - 1 + j, col] = letter board_placement.append((row - 1 + j, col)) except AssertionError: raise BacktrackException # check the current board for symmetry def check_symmetry(): for row in range(1, size + 1): for col in range(1, size + 1): first = board[row, col] in [BLANK, VOID] second = board[size + 1 - row, size + 1 - col] in [BLANK, VOID] if first != second: raise BacktrackException # Down special logic: While writing in a new letter from an across, if we # write in a new letter immediately below another letter, this would imply # a down that we don't already have: this can't happen def down_special_logic(row, col): if board[row - 1, col] not in [BLANK, VOID]: raise BacktrackException # Across special logic: If board[row,col-1:col+2] looks like _XX, then we # must have an across answer starting at (row, col) def across_special_logic(row, col): if board[row, col - 1] in [BLANK, VOID]: if board[row, col] not in [BLANK, VOID]: if board[row, col + 1] not in [BLANK, VOID]: if labels[row, col] not in across: raise BacktrackException def publish(): board_copy = board[1:-1, 1:-1] labels_copy = labels[1:-1, 1:-1] board_copy[board_copy == VOID] = BLANK return board_copy, labels_copy # recursive backtracker def backtracker(current_number, current_pos): for pos in range(current_pos, size ** 2): row, col = pos // size + 1, pos % size + 1 if col >= 3: across_special_logic(row, col - 2) try: place(current_number, row, col) if current_number == max_number: if symmetric: check_symmetry() yield publish() else: yield from backtracker(current_number + 1, pos + 1) except BacktrackException: backtrack() # got to end of loop, so we must have gone wrong somewhere raise BacktrackException # start search yield from backtracker(1, 0) def assemble(answers, size, symmetric=True, hide_answers=False): try: for board, labels in backtrack_search(answers, size, symmetric): if hide_answers: board[board != ' '] = '?' return board, labels except BacktrackException: raise BacktrackException('No solutions found. Check your answers or try increasing size') def pretty_string(board, labels=None, hide_answers=False): size = board.shape[0] pretty_board = np.array([[None] * size] * size) for i in range(size): for j in range(size): if labels is not None and labels[i, j] is not None: pretty_board[i, j] = '{}:{}'.format(labels[i, j], board[i, j]) else: pretty_board[i, j] = board[i, j] if hide_answers: pretty_board[i, j] = re.sub('[A-Z]', '?', pretty_board[i, j]) lines = [''] for row in pretty_board: row = ('{:>4} ' * len(row)).format(*row) if hide_answers: row = re.sub('[A-Z]', '?', row) lines.append(row) lines.append('') return '\n'.join(lines) def flatten(board, hide_answers=False): flat = ''.join([''.join(row) for row in board]) if hide_answers: flat = re.sub('[A-Z]', '?', flat) return flat
fd18fed3f2b6c8adfa54ce9e5c3d705ad0d6e063
skumartd/PythonIntro
/Day2/Dictionaries.py
1,814
4.5
4
# Example: jobs = {"David": "Professor", "Sahan": "Postdoc", "Shawn": "Grad student"} print(jobs["Sahan"]) # output : Postdoc # Can change in place jobs["Shawn"] = "Postdoc" print(jobs["Shawn"]) # Oupup : Postdoc # Lists of keys and values print(jobs.keys()) # Output : ['Sahan', 'Shawn', 'David'] # note order is diff print(jobs.values()) # Output : ['Postdoc', 'Postdoc', 'Professor’] print(jobs.items()) # Output : [('Sahan', 'Postdoc'), ('Shawn', 'Postdoc'), ('David', 'Professor')] # A dictionary works with keys and values phonebook = {} phonebook["John"] = 938477566 phonebook["Jack"] = 938377264 phonebook["Jill"] = 947662781 phonebook[1]=78 print(phonebook) # another way to implement Dictionary is phonebook1 = {"John": 938477566, "Jack": 938377264, "Jill": 947662781} print(phonebook1) # Iterating over dictionaries for name, number in phonebook.items(): print("Phone number of %s is %d" % (name, number)) # Removing a value one can use del or pop del phonebook["John"] print(phonebook) phonebook1.pop("John") print(phonebook1) #Add an entry phonebook['Johny']=938477567 print(phonebook) #See if a key is in dictionary print("tested" in phonebook) #To fech a value print(phonebook.get("tested")) print(phonebook.get("tested","defaultVal")) # defaultdict means that if a key is not found in the dictionary, # then instead of a KeyError being thrown, a new entry is created. # The type of this new entry is given by the argument of defaultdict. # somedict = {} # print(somedict[3]) # KeyError from collections import defaultdict someddict = defaultdict(int) someddict[0]=1 someddict[2]=3 print(someddict[0]) print(someddict[3]) # print int(), thus 0 print(someddict[8]) print(someddict[6]) #Update Map print(jobs) print(phonebook) phonebook.update(jobs) print(phonebook)
e808ed4773414a5f8f068fa8a4ae7da5cb4eb225
monaj07/ml
/rl/sumtree.py
4,154
3.75
4
""" This code implements a sumTree data structure, to be used in Prioritized Experience Replay (PER) sampling algorithm. It has O(log(n)) complexity for samplings, insertions, and updates. Great explanation in: https://adventuresinmachinelearning.com/sumtree-introduction-python/ This method is an alternative for straightforward inverse probabilistic sampling, where we compute the CDF of the array probabilities, and then take a uniform sample and map it to the CDF to retrieve our sample. This easy method, despite having O(1) complexity for insertion and update, has a complexity of O(n) for sampling, which is not desirable, given that sampling is very frequent in the learning process. That is why we take a refuge in the sumTree approach. Basically the main idea is that we mimic the CDF in form of a Binary Tree, where the sum of each two nodes is assigned to their parent node. """ import numpy as np import random class SumTree: def __init__(self, capacity): # Capacity is the maximum size of the experience replay memory self.capacity = capacity # The filled size of the memory so far self.size = 0 # Experience memory data self.replay_memory = np.empty(capacity, dtype=object) # The sumTree tree array self.priority_tree = np.zeros(2 * capacity - 1) def __len__(self): return self.size def add(self, transition, priority): """ If the memory still has vacancy, append the new experience to it; otherwise compare its priority with the minimum priority, and if it is greater than that minimum value, replace it. """ if self.size >= self.capacity: # If the replay memory is out of capacity, start filling it from the begining self.size = 0 self.replay_memory[self.size] = transition # Filling the last row (leaf nodes) of the binary tree starting from (capacity - 1) index tree_index = self.size + self.capacity - 1 self.priority_tree[tree_index] = priority # Add the new priority to all upstream nodes up to the root self._update_upstream_priority_tree(tree_index, priority) self.size += 1 def _update_upstream_priority_tree(self, idx, change): self.priority_tree[idx] += change while idx > 0: parent_index = (idx - 1) // 2 self.priority_tree[parent_index] += change idx = parent_index def _search_downstream_priority_tree(self): z = random.uniform(0, self.priority_tree[0]) # Start the search from the root node idx = 0 while 1: # Move to the left or right child depending on the random value # If we have to go to the right direction, # then subtract the value of the left child if z <= self.priority_tree[2 * idx + 1]: child_idx = 2 * idx + 1 else: z -= self.priority_tree[2 * idx + 1] child_idx = 2 * idx + 2 # If we are at a leaf node, return the index of the item and its priority # Otherwise go one level deeper. if child_idx >= len(self.priority_tree): # child_idx is beyond the size of the tree, # Hence 'idx' is a leaf node, so stop and return the current value # We return the normalised indices of the last row that refers to the indices of the memory array return (idx - (self.capacity - 1)), self.priority_tree[idx] else: idx = child_idx def sample(self, n): samples_indices = [] mini_batch_priorities = [] for _ in range(n): # Retrieve a sample given the current tree structure sample_idx, sample_priority = self._search_downstream_priority_tree() samples_indices.append(sample_idx) mini_batch_priorities.append(sample_priority) mini_batch_data = self.replay_memory[samples_indices] return mini_batch_data, mini_batch_priorities if __name__ == "__main__": st = SumTree(4) print()
5b52c3470834a83fff234c73b2fdc017b2d15493
EvanJamesMG/Leetcode
/python/Binary Search/033.Search in Rotated Sorted Array.py
2,295
3.640625
4
# coding=utf-8 import collections ''' Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. ''' class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class ListNode(object): def __init__(self, x): self.val = x self.next = None ''' 由于旋转前数组有序,故旋转后,数组被分为两个有序的子区间(无旋转时为一个有序区间)。 算法同样采用折半查找的思想进行搜索,但上下界first、last的更新相比常规的折半查找略微复杂。 关键点在于确定mid位于旋转点之前,还是之后: 若mid在旋转点之前left和mid之间的元素都有序(在一个有序子区间中)。例如 [4 5 6 7 8 9 || 1 2 3] 若mid在旋转点之后mid和right之间的元素都有序(在一个有序子区间中)。例如 [7 8 || 1 2 3 4 5 6] 参考 http://zhangxc.com/2013/11/leetcode-search-in-rotated-sorted-array ''' class Solution(object): def search(self, A, target): """ :type nums: List[int] :type target: int :rtype: int """ left = 0; right = len(A) - 1 while left <= right: mid = (left + right) / 2 if target == A[mid]: return mid if A[left] <= A[mid]: #此时mid处于旋转点之前,left和mid之间的元素都有序(在一个有序子区间中)。例如 [4 5 6 7 8 9 || 1 2 3] if A[left] <= target and target < A[mid]:#若if成立,则target在[left,mid)之间,否则在[mid+1,right)之间 right = mid - 1 else: left = mid + 1 else: #此时mid处于旋转点之后,mid和right之间的元素有序, 例如[7 8 || 1 2 3 4 5 6] if A[mid] < target and target <= A[right]:#若if成立,则target在(mid,right]之间,否则在[left,mid)之间 left = mid + 1 else: right = mid - 1 return -1
2e7210a960e852010a07e22221ea2c8351e715d2
seocobe/Python_oefeningen_sbm
/donderdag/oefening_collecties.py
1,216
4.03125
4
# lees 3 waarden in van stdin # maak er een tuple van # maak ook de tuple in omgekeerde volgorde # toon beide tuples # geef weer of de omgekeerde tuple groter is dan de oorspronkelijke a = input('geef eerste element in: ') b = input('geef tweede element in: ') c = input('geef derde element in: ') tup = a,b,c print(tup) omgekeerd = tuple(reversed(tup)) print(tup) print(f"omgekeerd > tup ? {omgekeerd > tup}") a = input('geef eerste element in: ') b = input('geef tweede element in: ') c = input('geef derde element in: ') if a.startswith('toon ') or b.startswith("toon ")\ or c.startswith('toon'): tp = (a,b,c) print(tp) print(dir(tp)) # lees 3 waarden in van stdin # maak er een lijst van # maak ook de lijst in omgekeerde volgorde # toon beide lijsten # geef weer of de omgekeerde lijst groter is dan de oorspronkelijke # # set = {1,2,3} # lijstVanKarakters = list('dit is een lijst van karakters') # str(lijstVanKarakters) # ''.join(lijstVanKarakters) # Lees 2 strings in van de console # Geef weer welke karakters # - in beide strings voorkomen # - enkel in de eerste voorkomen # - enkel in de tweede voorkomen # - in minstens 1 van de 2 strings voorkomen
c5c9501e6c18fe2d00019fe4c3c024f83ead8ca1
Hector-hedb12/HackTheNorth2018Challenge
/main.py
256
4.0625
4
import itertools def rotate(m): while m: yield m[0] m = list(reversed(zip(*m[1:]))) def main(): m = [[1,2,3], [8,9,4], [7,6,5]] print list(itertools.chain(*rotate(m))) if __name__ == "__main__": main()
96b000cfffb76131818b45ac62ec301115713dab
yingliufengpeng/algorithm
/zhengwei/extra_python/cmpobject.py
847
3.859375
4
# -*- coding: utf-8 -*- import functools class Student(object): def __init__(self, name, score): self.name = name self.score = score def __str__(self): return '(%s: %s)' % (self.name, self.score) __repr__ = __str__ def __gt__(self, other): # > print('__ge__') print(self.score > other.score) def __le__(self, other): # <= print('__le__') print(self.score < other.score) def __cmp__(self, s): if self.name < s.name: return -1 elif self.name > s.name: return 1 else: return 0 s1 = Student('wang', 20) s2 = Student('peng', 38) # s = [s2, s1] # # print(s) # # s3 = sorted(s, reverse=True) # print(s3) s1 >= s2 s1 <= s2 s1 < s2 s1 > s2
6dafb78d3fea822988dc95f8fff1b18061145c70
loristissino/oopython
/lessons/21/custom_widget.pyw
4,072
3.53125
4
#!/usr/bin/env python3.1 from tkinter import * from tkinter import messagebox import fractions class FractionWidget(object): def __init__(self, parent, height=10, width=10, background=None): self.parent=parent self.height=height self.width=width self.NumeratorValue=IntVar() self.NumeratorValue.set(1) self.DenominatorValue=IntVar() self.DenominatorValue.set(1) vcmd=(self.parent.register(self.doValidation), '%P') self.MainFrame=Frame(self.parent, width=self.width, height=self.height) self.Numerator=Entry(self.MainFrame, textvariable=self.NumeratorValue, width=self.width, justify="right", validate="key", validatecommand=vcmd) self.FractionLine=Label(self.MainFrame, text="------") self.Denominator=Entry(self.MainFrame, textvariable=self.DenominatorValue, width=self.width, justify="right", validate="key", validatecommand=vcmd) self.Numerator.pack(side="top", padx=5, pady=5) self.FractionLine.pack(side="top") self.Denominator.pack(side="top", padx=5, pady=5) if background: self.MainFrame['background']=background def doValidation(self, P): try: k=int(P) except ValueError as Err: return False return True def getNumerator(self): return self.NumeratorValue.get() def getDenominator(self): return self.DenominatorValue.get() def setNumerator(self, value): self.NumeratorValue.set(value) def setDenominator(self, value): self.DenominatorValue.set(value) def __setitem__(self, key, value): if key in ('background', 'bg', 'borderwidth', 'bd', 'relief'): self.MainFrame[key]=value if key=='numerator': self.setNumerator(value) if key=='denominator': self.setDenominator(value) def __getitem__(self, key): if key in ('background', 'bg', 'borderwidth', 'bd', 'relief'): return self.MainFrame[key] if key=='numerator': return self.getNumerator() if key=='denominator': return self.getDenominator() def pack(self, *args, **kwargs): self.MainFrame.pack(*args, **kwargs) def grid(self, *args, **kwargs): self.MainFrame.grid(*args, **kwargs) def place(self, *args, **kwargs): self.MainFrame.place(*args, **kwargs) class Application(object): def __init__(self, parent): self.parent = parent self.Fraction=FractionWidget(self.parent, background='red') self.Fraction['borderwidth']=10 self.Fraction['relief']='ridge' # i valori possibili per relief sono # 'sunken', 'raised', 'groove', 'ridge' self.Fraction['numerator']=12 self.Fraction['denominator']=24 self.Fraction.pack({'side':'top', 'padx':10, 'pady':10}) self.SimplifyButton=Button( self.parent, text="Semplifica", command=self.SimplifyButton_Click ) self.SimplifyButton.pack({'side':'top', 'padx':10, 'pady':10}) def SimplifyButton_Click(self): if self.Fraction.getDenominator()==0: messagebox.showinfo(message='Non è ammesso il denominatore zero.') f=fractions.Fraction(self.Fraction['numerator'], self.Fraction.getDenominator()) # si può accedere ai valori sia con le parentesi quadre sia con il metodo specifico self.Fraction.setNumerator(f.numerator) self.Fraction.setDenominator(f.denominator) def main(): root = Tk() myapp = Application(root) root.mainloop() if __name__=='__main__': main()
22c14efc86b486131f8245160634370641a71609
SergeiLSL/PYTHON-cribe
/Глава 3. Списки, кортежи и словари/Раздел 1. Списки/7.1 Знакомство со списками (массивами)/Задача 3.py
916
3.890625
4
""" Задача №3 Напишите программу, которая считает среднее арифметическое первых трёх элементов массива. Найденное значение округляется, то есть печатается только целая часть, дробная часть отбрасывается. Массив уже задан в программе. Надо обратиться по индексам к указанным элементам и организовать вычисления в формуле. """ A = [2345, 3455, 6789, 2343, 234, 1232] print((A[0] + A[1] + A[2]) // 3) # =============================================== A = [2345, 3455, 6789, 2343, 234, 1232] print(int(sum(A[:3])/3)) # =============================================== A = [2345, 3455, 6789, 2343, 234, 1232] print(int((A[0] + A[1] + A[2]) / 3))
43b0c6aeab42d8937cb26de89c86b5d53afdb469
alexsieusahai/dim
/src/dataStructures/lineLinkedList.py
2,098
4.09375
4
from dataStructures.lineNode import LineNode class LineLinkedList: """ doubly linked list created with lineNode objects each value contains a string (could contain other objects) constructor takes in a list of values, usually strings, to creat the linked list """ def __init__(self,lineList): """ lineList is a list object containing either objects generally should be strings """ self.length = 0 self.start = None self.end = None lastNode = None for line in lineList: node = LineNode(line,lastNode) if self.start == None: self.start = node node.lastNode = lastNode if lastNode != None: lastNode.nextNode = node lastNode = node self.length += 1 self.end = lastNode def remake_list(self,headNode): """ taking a head node, remakes the linked list object using it """ # set our start to the new head node self.start = headNode self.length = 0 pointer_node = headNode # go through the linked list from the head node # thi is to get the size of the list, as well as find the very last list while pointer_node != None: pointer_node = pointer_node.nextNode self.length += 1 self.end = pointer_node def toList(self): """ takes its own linked list and constructs a list based off of it """ walk = self.start alist = [] while walk is not None: alist.append(walk.value) walk = walk.nextNode return alist def print_LL(self): """ print linked list as list """ LL_as_list = self.toList() print(' '.join(LL_as_list)) if __name__ == '__main__': ll = LineLinkedList([x for x in 'dog']) walkNode = ll.start while walkNode.nextNode != None: print(walkNode.value) walkNode = walkNode.nextNode print(walkNode.value)
98953b09c12beaafd98a34a0cb76c1d44e8f52ba
chefmohima/DS_Algo
/quick_sort.py
778
3.8125
4
import random def quicksort(A,start,end): # pick random pivot index if start < 0 or end >= len(A) or start>=end: return pivot_index = random.randint(start,end) (p1,p2) = dnf(A,start,end,pivot_index) quicksort(A,start,p1) quicksort(A,p2,end) def dnf(A,start,end,pivot_index): pivot = A[pivot_index] low = start-1 mid = start-1 high = end+1 while mid+1 < high: if A[mid+1] > pivot: A[mid+1],A[high-1] = A[high-1],A[mid+1] high -= 1 elif A[mid+1] < pivot: A[mid+1],A[low+1] = A[low+1],A[mid+1] low += 1 mid += 1 else: mid += 1 return (low,high) l = [10,2,3,9,6,5] quicksort(l,0,len(l)-1)
368fdcb904663352b71f3d7af00e9684c88a84d0
Tele-Pet/informaticsPython
/Homework/Week 5/bookExercise5.2_viaList_v1.py
540
4.3125
4
# Exercise 5.2 Write another program that prompts for a list of numbers as above and at the end prints out both the maximum and minimum of the numbers instead of the average. import numpy as np usrInput = None usrList = [] while usrInput != 'done': usrInput = raw_input('Enter a number: ') try: usrInput = float(usrInput) usrList.append(usrInput) print 'Your current list: ', usrList except: if usrInput == 'done': print 'List min is: ', min(usrList) print 'List max is: ', max(usrList) else: print 'Invalid input'
64c375227ea2d1b6759b868cffee983aebabd482
inyong37/Study
/V. Algorithm/i. Book/모두의 알고리즘 with 파이썬/Chapter 11.py
944
3.765625
4
# -*- coding: utf-8 -*- # Modified Author: Inyong Hwang ([email protected]) # Date: *-*-*-* # 모두의 알고리즘 with 파이썬 # Chapter 11. 퀵 정렬 def quick_sort_1(a): n = len(a) if n <= 1: return a pivot = a[-1] g1 = [] g2 = [] for i in range(0, n - 1): if a[i] < pivot: g1.append(a[i]) else: g2.append(a[i]) return quick_sort_1(g1) + [pivot] + quick_sort_1(g2) d = [6, 8, 3, 9, 10, 1, 2, 4, 7, 5] print(quick_sort_1(d)) def quick_sort_sub(a, start, end): if end - start <= 0: return pivot = a[end] i = start for j in range(start, end): if a[j] <= pivot: a[i], a[j] = a[j], a[i] i += 1 a[i], a[end] = a[end], a[i] quick_sort_sub(a, start, i - 1) quick_sort_sub(a, i + 1, end) def quick_sort_2(a): quick_sort_sub(a, 0, len(a) - 1) d = [6, 8, 3, 9, 10, 1, 2, 4, 7, 5] quick_sort_2(d) print(d)
ac374c68621cd0d30ebde38dadcd1e85841dbf1b
Kartavya-verma/Python-Programming
/16.py
173
4.34375
4
#16.Write a python program to display table of a number taken from user input. num=int(input("Enter the number ")) for i in range(1,11,1): print(num ,"*", i,"=",num*i )
7de1d60ead2b8ef15c8d7977f1f3a8cd7da4abaf
sheng1993/datastructures_algorithms
/_4_algorithms_on_strings/Week1/Programming-Assignment-1/trie/trie.py
1,815
3.75
4
#Uses python3 import sys from typing import List, Dict # Return the trie built from patterns # in the form of a dictionary of dictionaries, # e.g. {0:{'A':1,'T':2},1:{'C':3}} # where the key of the external dictionary is # the node ID (integer), and the internal dictionary # contains all the trie edges outgoing from the corresponding # node, and the keys are the letters on those edges, and the # values are the node IDs to which these edges lead. def build_trie(patterns: List[str]): tree = dict() # type: Dict[int, Dict[str, int]] # write your code here cont = 0 node = 0 for pattern in patterns: for x in pattern: if node not in tree: tree[node] = dict() if x in tree[node]: node = tree[node][x] else: cont += 1 tree[node][x] = cont node = cont node = 0 return tree def build_trie_2(patterns: List[str]): tree = dict() # type: Dict[int, Dict[str, int]] root = 0 nodeCount = 0 for pattern in patterns: currentNode = root for i in range(0, len(pattern)): if currentNode not in tree: tree[currentNode] = dict() currentSymbol = pattern[i] if currentSymbol in tree[currentNode]: currentNode = tree[currentNode][currentSymbol] else: nodeCount += 1 tree[nodeCount] = dict() tree[currentNode][currentSymbol] = nodeCount currentNode = nodeCount return tree if __name__ == '__main__': patterns = sys.stdin.read().split()[1:] tree = build_trie_2(patterns) for node in tree: for c in tree[node]: print("{}->{}:{}".format(node, tree[node][c], c))
80a46493f9d50ae5c04ba512d3bc9432a691c65d
Saccha/Exercicios_Python
/secao05/ex05.py
287
4.0625
4
""" 5. Faça um programa que receba um número inteiro e verifique se este número é par ou ímpar. """ x = int(input("Digite o valor de x: ")) if (x % 2 == 0): # Resto da divisão print(f'O valor que foi digitado ele é PAR') else: print(f'O valor que foi digitado ele é IMPAR')
84c74294624bd0625c8f63e73c4fa40e40e83f72
LeTurtleBoy/General-Algorithms
/Python_general_purpose/Generators.py
1,008
3.625
4
#generators from time import sleep #top level syntax or function -> underscore method def add(x,y): return x+y class adder: def __init__(self): self.z = 0 def __call__(self,x,y): self.z +=1 return x+y+self.z def compute(): rv = [] for i in range(10): sleep(0.5) rv.append(i) return rv class compute2(): ''' def __call__(self): rv = [] for i in range(10): sleep(0.5) rv.append(i) return rv ''' def __iter__(self): self.last = 0 return self def __next__(self): rv = self.last self.last += 1 if self.last > 10: raise StopIteration() sleep(.5) #Proceso return rv def computegen(): for i in range(10): sleep(0.5) yield i for val in computegen(): print(val) #Los generadores estan pensados para subrutinas que se corren una vez y sale para pintura def first(): print(1) def second(): print(2) def last(): print('n') class Api: def run_this_first(self): first() def run_this_second(self): second() def run_this_last(self): last()
b56a0a4d3bd12f19c4954af109e6c7533da86f4c
bloy/adventofcode
/2016/day13.py
2,158
3.859375
4
#!/usr/bin/env python3 import collections def is_space(input_number, x, y): if x < 0 or y < 0: return False num = x*x + 3*x + 2*x*y + y + y*y + input_number num_ones = len([c for c in "{0:b}".format(num) if c == "1"]) return ((num_ones % 2) == 0) def print_map(input_number, size): map_chars = { True: '.', False: '#' } for y in range(size): for x in range(size): if is_space(input_number, x, y): c = '.' else: c = '#' print(c, end='') print() def find_path(input_number, start, goal): seen = set() queue = collections.deque() queue.append((start, tuple())) while queue: step = queue.popleft() position = step[0] path = step[1] if position == goal: return path if position not in seen: seen.add(position) x = position[0] y = position[1] for p in ((x-1, y), (x, y-1), (x+1, y), (x, y+1)): if p not in seen and is_space(input_number, p[0], p[1]): queue.append((p, path + (position,))) def find_locations(input_number, start, num_steps): seen = set() queue = collections.deque() queue.append((start, 0)) while queue: step = queue.popleft() position = step[0] length = step[1] if position not in seen: seen.add(position) if length < num_steps: x = position[0] y = position[1] for p in ((x-1, y), (x, y-1), (x+1, y), (x, y+1)): if p not in seen and is_space(input_number, p[0], p[1]): queue.append((p, length + 1)) return seen if __name__ == '__main__': start = (1, 1) input_number = 1358 goal = (31, 39) # input_number = 10 # goal = (7, 4) print_map(input_number, max(goal) + 1) path = find_path(input_number, start, goal) print(path) print(len(path)) seen = find_locations(input_number, start, 50) print() print(seen) print(len(seen))
267082575179466d13ce7d3a3f4fd051f7f256a9
cho-stat/coding-exercises
/intersection.py
515
3.796875
4
class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: if len(nums1) < len(nums2): num_set = {num for num in nums1} compare_list = nums2 else: num_set = {num for num in nums2} compare_list = nums1 result = set() for num in compare_list: if num in num_set and num not in result: result.add(num) return [num for num in result]
bddc63619cdf56c8c702c93ff94cc44599a19db4
akimi-yano/algorithm-practice
/lc/978.LongestTurbulentSubarray.py
2,816
3.515625
4
# 978. Longest Turbulent Subarray # Medium # 964 # 154 # Add to List # Share # Given an integer array arr, return the length of a maximum size turbulent subarray of arr. # A subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray. # More formally, a subarray [arr[i], arr[i + 1], ..., arr[j]] of arr is said to be turbulent if and only if: # For i <= k < j: # arr[k] > arr[k + 1] when k is odd, and # arr[k] < arr[k + 1] when k is even. # Or, for i <= k < j: # arr[k] > arr[k + 1] when k is even, and # arr[k] < arr[k + 1] when k is odd. # Example 1: # Input: arr = [9,4,2,10,7,8,8,1,9] # Output: 5 # Explanation: arr[1] > arr[2] < arr[3] > arr[4] < arr[5] # Example 2: # Input: arr = [4,8,12,16] # Output: 2 # Example 3: # Input: arr = [100] # Output: 1 # Constraints: # 1 <= arr.length <= 4 * 104 # 0 <= arr[i] <= 109 # This solution works: ''' Here we need shortest distances, so Dijkstra algorithm is good idea. First of all, let us forgot about split points, and deal with graph as weighted graph, where weight of each node is number of split points on it plus one. On this graph we perform Dijkstra algorithm. Now at each point we have distance for it from origin. We can find total number of reachable points as: All original nodes with distance less or equal to M. For every edge we need to check what we have as distances for it ends: if both of distances more than M, than we can not reach any split points on this node. If both of them less or equal to M, we can reach some point starting with one end and some points, starting with another end, these two sets can intersect, so we need to remove then number of points in intersection. Also if for one end distance is more than M and for another is less or equal than M, we have only one set of points that can be reached. Complexity Time complexity is O(E log N), space complexity is O(N) as for classical Dijkstra algorithm. ''' class Solution: def reachableNodes(self, edges, M, N): G = defaultdict(set) dist = [float('inf')] * N dist[0] = 0 for i, j, w in edges: G[i].add((j, w + 1)) G[j].add((i, w + 1)) heap = [(0, 0)] while heap: min_dist, idx = heappop(heap) for neibh, weight in G[idx]: cand = min_dist + weight if cand < dist[neibh]: dist[neibh] = cand heappush(heap, (cand, neibh)) ans = sum(dist[i] <= M for i in range(N)) for i, j, w in edges: w1, w2 = M - dist[i], M - dist[j] ans += (max(0, w1) + max(0, w2)) if w1 >= 0 and w2 >= 0: ans -= max(w1 + w2 - w, 0) return ans
8c1365f56e26fe97f5f383b6836683dd8c579c08
Jyllove/Python
/DataStructures&Algorithms/Sort/heapsort.py
821
4.21875
4
def heap(array,start,end): root = start child = root*2+1 while child<=end: if child+1<=end and array[child]<array[child+1]: child += 1 if array[root]<array[child]: array[root],array[child] = array[child],array[root] root = child child = root*2+1 else: break def heap_sort(array): first = len(array)//2-1 for start in range(first,-1,-1): heap(array,start,len(array)-1) for end in range(len(array)-1,0,-1): array[0],array[end] = array[end],array[0] heap(array,0,end-1) if __name__ == "__main__": array = [1,4,6,7,3,8,9,2,5,10] print("raw array is: ",end="") print(array) heap_sort(array) print("sorted array is: ",end="") print(array)
366393da267bfdc9e3558dd8276c6738e92e34d1
jr09/DojoAssignments
/Python/Multiples,Sum,Average/allin1.py
367
3.703125
4
# Multiple Par 1 for idx in range(1,100,2): print idx # Multiples Part 2 for idx in range(5,1000000,1): if(idx%5==0): print idx # Sum List a = [1, 2, 5, 10, 255, 3] sum = 0 for item in a: sum += item print sum # Average a = [1, 2, 5, 10, 255, 3] sum_a = 0 for item in a: sum_a += item print "Average of a = {}".format(sum_a/float(len(a)))
8f5d302380ad4e16c44bf769b750018b506b344d
polonkaipal/Szkriptnyelvek
/hazi feladatok/09.15/20120815e.py
1,724
4.03125
4
#!/usr/bin/env python3 """ Palindróm Írjunk függvényt, mely egy sztringről eldönti, hogy palindróm-e. Egy karaktersorozatot akkor nevezünk palindrómnak, ha visszafelé olvasva megegyezik az eredeti karaktersorozattal, pl.: görög. A feladatot többféleképpen is oldjuk meg: (1) Triviális módszer (Pythonban egy szekvencia nagyon egyszerűen megfordítható). (2) Iteratív módszer. A sztringről nem készíthetünk másolatot. Tipp: használhatunk egy while ciklust is. Hasonlóan működik a C nyelvben megismertekkel: i = 0 while i < 5: print(i) i += 1 (3) Rekurzív módszer. Csak hogy szokjuk a rekurziót is. """ TEXT = "görög" TEXT2 = "török" # 1. módszer def palindrom1(s): return s == s[::-1] # 2. módszer def palindrom2(s): hossz = len(s) - 1 for i in range(0, hossz + 1): if s[i] != s[hossz - i]: return False return True # 3. módszer def palindrom3(s): if len(s) < 2: return True elif s[0] == s[-1]: return palindrom3(s[1:-1]) else: return False def main(): print("'{}' {}palindróm".format(TEXT, "" if palindrom1(TEXT) else "nem ")) print("'{}' {}palindróm".format(TEXT2, "" if palindrom1(TEXT2) else "nem ")) print("") print("'{}' {}palindróm".format(TEXT, "" if palindrom2(TEXT) else "nem ")) print("'{}' {}palindróm".format(TEXT2, "" if palindrom2(TEXT2) else "nem ")) print("") print("'{}' {}palindróm".format(TEXT, "" if palindrom3(TEXT) else "nem ")) print("'{}' {}palindróm".format(TEXT2, "" if palindrom3(TEXT2) else "nem ")) ############################################################################## if __name__ == "__main__": main()
5a2248958f79e79b325df87dea72cae262cd0a02
jamsidedown/euler_py
/problems/0XX/00X/002/solution.py
294
3.5625
4
def run() -> int: total, first, second = 0, 1, 2 while second < 4_000_000: if second % 2 == 0: total += second first, second = second, first + second return total if __name__ == '__main__': print(f'Sum of even fibonacci numbers under 4M: {run()}')
df6fa5bf6a8ccac896eb39298dc350143e5949a9
taekyunlee/SNU_FIRA_Business-Analytics
/1st semester/파이썬을 이용한 빅데이터 분석 개론/hw5-1 score100.py
1,689
4.09375
4
# Assignment Number... : 5 # Student Name........ : 이택윤 # File Name........... : hw5_이택윤 # Program Description. : 이것은 if_else 문과 while, for 문을 활용하여 원하는 결과를 출력하는 과제입니다. a = int(input('Enter a: ')) # int() 와 input()을 활용하여 각각의 변수 a,b,c에 정수를 선언합니다. b = int(input('Enter b: ')) c = int(input('Enter c: ')) if a>b and a>c : # if_else 문을 이용하여 입력된 a,b,c의 값을 비교하여 작은 값 두개의 합을 출력합니다. print(b+c) elif b>a and b>c : print(a+c) else : print(a+b) city = input('Enter the name of the city: ') # input()을 활용하여 도시의 이름을 입력 받습니다. if city == 'Seoul' : # if_else 문을 활용하여 입력받은 도시의 이름과 그 도시의 면적을 문자열 서식을 통해서 출력합니다. size = 605 elif city =='New York' : size = 789 elif city =='Beijing' : size = 16808 else : size ='Unknown' print('The size of {} is {}'.format(city , size)) import math # math 라이브러리를 import를 이용해서 불러옵니다. for i in range(10) : # 0부터 9까지의 10개의 정수의 계승 값을 구하기 위해서 for문을 이용하고 그 안에서 math.factorial()을 적용합니다. print(math.factorial(i)) j=0 while j< 10 : # 마찬가지로 while 문을 이용하고 그 안에서 math.factorial()을 이용하여 계승 값을 구합니다. print(math.factorial(j)) j+=1
ff4bf1df1d5e76f43c53579358ddf35438896488
xiaohaier66/python_study
/map.py
153
3.53125
4
alien_0 = {'color':'green'} print("The alien is "+alien_0['color'] + ".") alien_0['color'] = 'yellow' print("The alien is now "+alien_0['color'] + ".")
c5ad6d92040373117ea4a33465aa26f0f53975ee
manojnaidu15498/manset8
/p1.py
70
3.609375
4
s=input() ns=s[::-1] if s==ns: print('yes') else: print('no')
39b770c6cd5d262efc4c887a4a388765a969167b
oscarDelgadillo/AT05_API_Test_Python_Behave
/GermanQuinonez/sessions/session1_examples.py
887
3.703125
4
# Values and types print(type(1)) print(type("Somthing")) print(type(0.2)) # Variables Message = "hi" n = 1000 pi = 3.04e500 print(type(Message)) print(type(n)) print(type(pi)) # Membership operators a = 1 b = 2 list = [1, 2, 3, 4, 5]; if (a in list): print("a exists list") else: print("a does not exist list") if (b not in list): print("b does not exist list") else: print("b exists list") # Identity operators value_1 = 20 value_2 = 20 if value_1 is value_2: print("Line 1 - a and b have same identity") else: print('Line 1 - a and b do not have same identity') if id(value_1) == id(value_2): print("Line 2 - a and b have same identity") else: print("Line 2 - a and b do not have same identity") # Functions def print_lyrics(): print("I'm a tester, and I'm okay.") print("I sleep all night and I work all day.") print_lyrics()
c090ccd81e1c69ef0cf819397821efb710385eb9
hilariusperdana/praxis-academy
/novice/01-01/latihan/shellsort.py
547
3.828125
4
def shellsort (arr): n = len(arr)//2 while n > 0: for mulai in range(n): gapInsertionSort(arr,mulai,n) print("setelah",n,"listnya",arr) n = n // 2 def gapInsertionSort(arr,start,gapP: for i in range(start+gap,len(arr),gap): value = arr[i] position = i while position >= gap and arr[position-gap]>value: arr[position] = arr[position-gap] position = position-gap arr[position] = value arr = [54,26,93,17,77,31,44,55,20] shellsort(arr) print(arr)
08c2942c26d0c382b7ce410f434f638f1fad0704
yukiko1929/python_scripts
/function_basic.py
978
4.125
4
# 関数に関する基本的な知識 # def sentence(name, department, years): # print('%s is at %s for %s years' % (name, department, years)) # print(sentence()) #TypeError: sentence() missing 3 required positional arguments: 'name', 'department', and 'years' # print(sentence('yuki')) # print(sentence('yuki', 'MP', '5')) # print(sentence('yuki', 'mass production', '5', 'yukiko')) # print(sentence('miho', name='yuki', years='5', department='RD')) # got multiple values # # print(sentence(years='5', department='RD', name='yuki')) # print(sentence(years='5', 'RD', name='yuiko')) # # def func1(*args): # print(args) # # def func2(**kwargs): # print(kwargs) # # if __name__ == '__main__': # print(func1('yuki',23,'tokyo')) # print(func2(name = 'tom', age = 39, city = 'tokyo')) # print(func1()) # print(func2()) def info(name, age): print('%s : %s' % (name, age)) print(info(**{'name':'yuki', 'age':25})) print(info(name='yuki', age=25))
10ee7a231767d1583053ee7970753cce97a0fda5
MoritzSchwerer/Maze
/src/algorithms/generators/backtracker.py
935
3.796875
4
from src.algorithms.generators.generator import Generator class Backtracker(Generator): def __init__(self, board): self.board = board self.current = self.choose_start(board) self.initial = self.current self.stack = [] def choose_start(self, board): tiles = self.board.get_tiles() return tiles[0][0] def make_step(self): self.current.make_visited() neighbour = self.current.choose_next(self.board.get_tiles()) if neighbour: neighbour.make_visited() self.stack.append(self.current) self.board.remove_walls(self.current, neighbour) self.current = neighbour elif len(self.stack) > 0: self.current = self.stack.pop() self.current.highlight() def is_done(self): return len(self.current.get_neighbours(self.board.get_tiles())) == 0 and len(self.stack) == 0
2ee75810b80ede9ca2d099190baf2a5157f3a1c4
wangminli/codes
/python/defaultdict.py
225
3.609375
4
#! /usr/bin/env python # -*-coding:utf-8 -*- 'defaultdict,对dict添加一个默认值' from collections import defaultdict dd = defaultdict(lambda: '==> :no this value') dd['key1'] = 'abc' print dd['key1'] print dd['key2']
9266397b9bdd7e11e1047ff431a060fe789a5694
adqz/interview_practice
/algo_expert/p26_reverse_linked_list.py
608
3.875
4
# O(n) time | O(1) space def reverse(head): node = head if node.next == None: return head prev_node = None # 1. Reverse links until last element while node.next != None and node.next.next != None: next_node = node.next next_next_node = node.next.next # Reverse next_node.next = node node.next = prev_node node = next_next_node prev_node = next_node # 2. Reverse last link if node.next != None: next_node = node.next node.next = prev_node next_node.next = node return next_node
9191dc53a92190dc08fdd2c79a6e5b22dce8d750
lotabout/leetcode-solutions
/617-merge-two-binary-tree.py
824
3.921875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # https://leetcode.com/problems/merge-two-binary-trees/description/ from util import TreeNode class Solution(object): def mergeTrees(self, t1, t2): """ :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode """ if t1 is None and t2 is None: return None root = TreeNode(0) if t1: root.val += t1.val if t2: root.val += t2.val root.left = self.mergeTrees(t1.left if t1 else None, t2.left if t2 else None) root.right = self.mergeTrees(t1.right if t1 else None, t2.right if t2 else None) return root solution = Solution() assert solution.mergeTrees(TreeNode.of([1,3,2,5]), TreeNode.of([2,1,3,None,4,None,7])) == [3,4,5,5,4,None,7]
44bcadcde07d95f6d112b5a939b7f4305db0da91
lorodin/py-lesson8
/task7.py
1,387
4.0625
4
# 7. Реализовать проект «Операции с комплексными числами». # Создайте класс «Комплексное число», реализуйте перегрузку методов сложения и умножения комплексных чисел. # Проверьте работу проекта, создав экземпляры класса (комплексные числа) и выполнив сложение и # умножение созданных экземпляров. Проверьте корректность полученного результата. # class Complex: d: float i: float def __init__(self, d = 0, i = 0): self.d = d self.i = i def __add__(self, other): return Complex(self.d + other.d, self.i + other.i) def __mul__(self, other): return Complex( self.d * other.d - self.i * other.i, self.d * other.i + self.i * other.d ) def __str__(self): return f'{self.d}+{self.i}i' if __name__ == '__main__': c1 = Complex(2, 1) c2 = Complex(3, 4) s = c1 + c2 print(f'({c1}) + ({c2}) = {s}') if s.d != 5 or s.i != 5: print('Error. Sum is incorrect') m = c1 * c2 print(f'({c1}) * ({c2}) = {m}') if m.d != 2 or m.i != 11: print('Error. Mul is incorrect')
a4fa1006b6923c940032476160f26b4a2e4ef50d
tranxuanduc1501/Homework-23-7-2019
/Bài 2 ngày 23-7-2019 ( Cách ngu).py
425
3.859375
4
listnumber= [129,2,182,41,439] a= int(input('Enter a number: ')) if a!=129 and a!=2 and a!=182 and a!=41 and a!=439: print('Number not found in the list') elif a==129: print('Number found. Position 1') elif a==2: print('Number found. Position 2') elif a==182: print('Number found. Position 3') elif a==41: print('Number found. Position 4') elif a==439: print('Number found. Position 5')
058350f37a2143994fef846169735b8826fea047
DK333D/AGH_Algorithms
/SEM_1/python/Ex 2018/can_create_0_sum/main.py
777
3.734375
4
def find(array, curr_line=0, curr_sum=0) -> (bool, []): result = [] if curr_sum == 0 and curr_line >= len(array): return True, result if curr_line >= len(array): return False, result for i in range(len(array[curr_line]) + 1): if i == len(array[curr_line]): return False, result element = array[curr_line][i] res, arr = find(array, curr_line + 1, curr_sum + element) result.extend(arr) if res is True: result.append("{} from line {}".format(element, curr_line)) return True, result if __name__ == '__main__': array = [[3, 4, 5], [1, 2, 3, 4, -5], [1, 2, 3, 4, 5]] result, nums = find(array) for i in nums: print(i) print() print(result)
9da3bd19daaa7a02153c4373cd1844f01d6ad250
hasnatosman/sum_cube
/cube_sum.py
225
4.25
4
def cube_sum(num): sum = 0 for n in range(num + 1): sum = sum + n ** 3 return sum user_num = int(input('Enter a number: ')) result = cube_sum(user_num) print('Your sum of cubes are: ', result)
948453d9e75087f16c4785803892a1d1ffa9df13
afaubion/Python-Tutorials
/Code_Introspection.py
1,245
3.578125
4
# Code introspection is the ability to examine classes, functions and keywords # to know what they are, what they do and what they know. # Python provides several functions and utilities for code introspection. """ help() dir() hasattr() id() type() repr() callable() issubclass() isinstance() __doc__ __name__ """ # Often the most important one is the help function, since you can use it to find what other functions do. # EXERCISE # Print a list of all attributes of the given Vehicle object. # ----- # Define the Vehicle class class Vehicle: name = "" kind = "car" color = "" value = 100.00 def description(self): desc_str = "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value) return desc_str # Print a list of all attributes of the Vehicle class. print(dir(Vehicle)) # ----- # Output: """ ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'color', 'description', 'kind', 'name', 'value'] """
6bfd0499452e9064f200fe1d382f366c2ef2cc91
ThomArm/snips-skill-sonos
/snipssonos/provider/provider_player_template.py
4,276
3.515625
4
import abc from abc import ABCMeta, abstractmethod import sys if sys.version_info >= (3, 4): ABC = abc.ABC else: ABC = abc.ABCMeta('ABC', (), {}) class A_ProviderPlayerTemplate(ABC): """ Abstract Class to create a music provider as Spotify, Soundclound you have to create at least one of the play method and the __init__ method """ __metaclass__ = ABCMeta @abstractmethod def __init__(self): pass @classmethod def play_artist(self, device, name, shuffle=False): """ Play a music from a artist :param self: self :param device: the sonos speaker the skill is connected to :param name: artist name :param shuffle: do we need to shuffle the list of music :type device: soco.core.Soco :type name: string :type shuffle: Boolean :return: Did we succed to play a music :rtype: Boolean """ return False @classmethod def play_track(self, device, name, shuffle=False): """ Play a track with its name :param self: self :param device: the sonos speaker the skill is connected to :param name: track name :param shuffle: do we need to shuffle the list of music :type device: soco.core.Soco :type name: string :type shuffle: Boolean :return: Did we succed to play a music :rtype: Boolean """ return False @classmethod def play_album(self, device, name, shuffle=False): """ Play an album :param self: self :param device: the sonos speaker the skill is connected to :param name: album name :param shuffle: do we need to shuffle the list of music :type device: soco.core.Soco :type name: string :type shuffle: Boolean :return: Did we succed to play a music :rtype: Boolean """ return False @classmethod def play_playlist(self, device, name, shuffle=False): """ Play a playlist :param self: self :param device: the sonos speaker the skill is connected to :param name: playlist name :param shuffle: do we need to shuffle the list of music :type device: soco.core.Soco :type name: string :type shuffle: Boolean :return: Did we succed to play a music :rtype: Boolean """ return False @classmethod def play_station(self, device, name, shuffle=False): """ Play a radio station :param self: self :param device: the sonos speaker the skill is connected to :param name: radio station name :param shuffle: do we need to shuffle the list of music :type device: soco.core.Soco :type name: string :type shuffle: Boolean :return: Did we succed to play a music :rtype: Boolean """ return False @classmethod def play_genre(self, device, name, shuffle=False): """ Play a music genre :param self: self :param device: the sonos speaker the skill is connected to :param name: genre name :param shuffle: do we need to shuffle the list of music :type device: soco.core.Soco :type name: string :type shuffle: Boolean :return: Did we succed to play a music :rtype: Boolean """ return False @classmethod def play_tag(self, device, name, shuffle=False): """ Play music from its tag :param self: self :param device: the sonos speaker the skill is connected to :param name: tag name :param shuffle: do we need to shuffle the list of music :type device: soco.core.Soco :type name: string :type shuffle: Boolean :return: Did we succed to play a music :rtype: Boolean """ return False
76bc06baf83941444925155cc2fd668f4ba1c6d5
sagarnikam123/learnNPractice
/hackerEarth/practice/dataStructures/arrays/1D/theAmazingRace.py
1,588
3.703125
4
# The Amazing Race ####################################################################################################################### # # As the Formula One Grand Prix was approaching, the officials decided to make the races a little more interesting # with a new set of rules. According to the new set of rules, each driver will be given a vehicle with different # height and the driver with maximum SIGHT would win the race. # Now, SIGHT of a driver is defined by (X∗P), where # # X = number of drivers he can see in front of him + number of drivers he can see behind him # P = position of the driver in a given scenario ( index of the driver array is 1 - N indexed ) # # As all the drivers are moving in a straight line, a driver i # cannot see beyond another driver j if height of j >= height of driver i # # INPUT # First line of the input contains t, the number of test cases. The 1st line of each test case consists of a single # integer n, the number of drivers. Second line contains n space separated integers H[1], H[2], H[3]...H[n] denoting # the heights of the drivers 1,2,3....n # # OUTPUT # Output for each test case should be a single line displaying the index of the winning driver. In case of ties, # display the driver with minimum index. # # CONSTRAINTS # 0 <= t <= 50 # 1 <= n <= 105 # 0 <= H[i] <= 106 # # SAMPLE INPUT # 2 # 5 # 4 1 2 1 4 # 5 # 5 1 2 4 1 # # SAMPLE OUTPUT # 5 # 4 # #######################################################################################################################
c464a63272bf7a280e5baca41cc0f5386f205bfc
zaid-sayyed602/Python-Basics
/if else_2.py
116
3.703125
4
number1=input("enter no 1") number2=input("enter no 2") print("number1 is",number1) print("number2 is",number2)
4575352727f3905c627aa642b11231da4f55ad55
othLah/Email_Sender
/emailSender.pyw
10,246
3.5625
4
''' This code present a simple application to send text mails from a gmail,live,yahoo and gmx accounts to any other email address, gmail and yahoo ask for the "Less Secure App" option to be actived but don't worry, the app will guide you to the right place. Enjoy and Leave your comments ;) ''' import tkinter as tk from tkinter import ttk import os from webbrowser import open_new_tab import smtplib as smtp from tkinter import messagebox ALL_FONT = ("Verdana", 15) serverType = "" email = "" password = "" smtpObj = smtp.SMTP() def exitApp(): reallyTk = tk.Tk() lab = tk.Label(reallyTk, text="Do You Wanna Really Exit The App?", font=ALL_FONT) yesButt = ttk.Button(reallyTk, text="Yes", command=lambda: os._exit(0)) noButt = ttk.Button(reallyTk, text="No", command=reallyTk.destroy) lab.grid(row=0, column=0, columnspan=2) yesButt.grid(row=1, column=0) noButt.grid(row=1, column=1) tk.Tk.wm_title(reallyTk, "Exit...") reallyTk.mainloop() def exitApp2(contTk): reallyTk = tk.Tk() def exitIt(): reallyTk.destroy() contTk.destroy() lab = tk.Label(reallyTk, text="Do You Wanna Really Exit?", font=ALL_FONT) yesButt = ttk.Button(reallyTk, text="Yes", command=exitIt) noButt = ttk.Button(reallyTk, text="No", command=reallyTk.destroy) lab.grid(row=0, column=0, columnspan=2) yesButt.grid(row=1, column=0) noButt.grid(row=1, column=1) tk.Tk.wm_title(reallyTk, "Exit...") reallyTk.mainloop() def connectToServer(server): global smtpObj try: if server == "gmail": smtpObj = smtp.SMTP("smtp.gmail.com", 587) elif server == "live": smtpObj = smtp.SMTP("smtp.live.com", 587) elif server == "yahoo": smtpObj = smtp.SMTP("smtp.mail.yahoo.com", 465) elif server == "gmx": smtpObj = smtp.SMTP("smtp.gmx.com", 25) else: raise smtp.SMTPConnectError smtpObj.starttls() return True except: msg = messagebox.showerror("SMTPConnectError", "Error occurred during establishment of a connection with the server") return False def goToGmail(contTk): global serverType global smtpObj serverType="gmail" if connectToServer(serverType): open_new_tab("https://accounts.google.com/ServiceLogin/signinchooser?service=accountsettings&passive=1209600&osid=1&continue=https%3A%2F%2Fmyaccount.google.com%2Flesssecureapps&followup=https%3A%2F%2Fmyaccount.google.com%2Flesssecureapps&emr=1&mrp=security&flowName=GlifWebSignIn&flowEntry=ServiceLogin") ConnectSendClass() def goToLive(contTk): global serverType global smtpObj serverType="live" if connectToServer(serverType): ConnectSendClass() def goToYahoo(contTk): global serverType global smtpObj serverType="yahoo" if connectToServer(serverType): open_new_tab("https://help.yahoo.com/kb/SLN27791.html") ConnectSendClass() def goToGMX(contTk): global serverType global smtpObj serverType="gmx" if connectToServer(serverType): ConnectSendClass() class EmailClass(tk.Tk): def __init__(self): tk.Tk.__init__(self) globalP = tk.Frame(self) globalP.pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.allPages = {} for P in (EntryPage, LessSecurePage): self.allPages[P] = P(globalP, self) self.raisePage(EntryPage) tk.Tk.iconbitmap(self, default=r"email_icon.ico") tk.Tk.wm_title(self, "Email Sender") tk.Tk.resizable(self, False, False) tk.Tk.protocol(self, "WM_DELETE_WINDOW", exitApp) self.mainloop() def raisePage(self, page): self.allPages[page].grid(row=0, column=0) self.allPages[page].tkraise() class EntryPage(tk.Frame): def __init__(self, contP, contTk): tk.Frame.__init__(self, contP) message = tk.Message(self, text=""" This App build just for educationnal purposes, it's source code is available for all users. If you do anything wrong with it, we aren't the ones who will pay your fault. Feel safe and use it. """, font=ALL_FONT) agreeButt = ttk.Button(self, text="Agree", command=lambda: contTk.raisePage(LessSecurePage)) disagreeButt = ttk.Button(self, text="Disagree", command=lambda: os._exit(0)) message.pack() agreeButt.pack() disagreeButt.pack() class LessSecurePage(tk.Frame): def __init__(self, contP, contTk): tk.Frame.__init__(self, contP) var = tk.StringVar() var.set("L") message = tk.Message(self, text=""" You must TURN ON the \"less secure apps\" mode for you email account. Please select your account type. NOTE: not every account has the above mode!!! """, font=ALL_FONT) gmailChoice = tk.Radiobutton(self, text="gmail(should TURN it ON)", activebackground="black", activeforeground="yellow", variable=var, value="varG", font=ALL_FONT, command=lambda: goToGmail(contTk)) liveChoice = tk.Radiobutton(self, text="hotmail/live(shouldn't TURN it ON)", activebackground="black", activeforeground="yellow",variable=var, value="varL", font=ALL_FONT, command=lambda: goToLive(ConnectPage)) yahooChoice = tk.Radiobutton(self, text="yahoo(should TURN it ON)", activebackground="black", activeforeground="yellow",variable=var, value="varY", font=ALL_FONT, command=lambda: goToYahoo(contTk)) gmxChoice = tk.Radiobutton(self, text="gmx(shouldn't TURN it ON)", activebackground="black", activeforeground="yellow",variable=var, value="varGMX", font=ALL_FONT, command=lambda: goToGMX(ConnectPage)) gmailChoice.deselect() liveChoice.deselect() yahooChoice.deselect() gmxChoice.deselect() message.pack() gmailChoice.pack() liveChoice.pack() yahooChoice.pack() gmxChoice.pack() class ConnectSendClass(tk.Tk): def __init__(self): tk.Tk.__init__(self) globalP = tk.Frame(self) globalP.pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.allPages = {} for P in (ConnectPage, SendPage): self.allPages[P] = P(globalP, self) self.raisePage(ConnectPage) tk.Tk.iconbitmap(self, default=r"email_icon.ico") tk.Tk.wm_title(self, "Email Sender") tk.Tk.resizable(self, False, False) tk.Tk.protocol(self, "WM_DELETE_WINDOW", lambda: exitApp2(self)) self.mainloop() def raisePage(self, page): self.allPages[page].grid(row=0, column=0) self.allPages[page].tkraise() class ConnectPage(tk.Frame): def __init__(self, contP, contTk): tk.Frame.__init__(self, contP) emailL = tk.Label(self, text="Email: ") self.emailF = tk.Entry(self, width=40) passwordL = tk.Label(self, text="Password: ") self.passwordF = tk.Entry(self, width=40, show="*") exitButt = ttk.Button(self, text="Exit", command=lambda: exitApp2(contTk)) loginButt = ttk.Button(self, text="Log In", command=lambda: self.checkLogIn(contTk)) emailL.grid(row=0, column=0, sticky=tk.W) self.emailF.grid(row=0, column=1) passwordL.grid(row=1, column=0, sticky=tk.W) self.passwordF.grid(row=1, column=1) exitButt.grid(row=2, column=0, sticky=tk.W) loginButt.grid(row=2, column=1, sticky=tk.E) def checkLogIn(self, contTk): global email global password e = self.emailF.get() p = self.passwordF.get() try: smtpObj.login(e, p) email = e password = p contTk.raisePage(SendPage) except smtp.SMTPHeloError: msg = messagebox.showerror("ERROR...", "The server didn’t reply properly to the HELO greeting") except smtp.SMTPAuthenticationError: msg = messagebox.showerror("ERROR...", "The server didn’t accept the username/password combination") except smtp.SMTPNotSupportedError: msg = messagebox.showerror("ERROR...", "The AUTH command is not supported by the server") except smtp.SMTPException: msg = messagebox.showerror("ERROR...", "No suitable authentication method was found") class SendPage(tk.Frame): def __init__(self, contP, contTk): tk.Frame.__init__(self, contP) toL = tk.Label(self, text="To: ") self.toF = tk.Entry(self, width=40) msgL = tk.Label(self, text="Msg: ") self.msgF = tk.Text(self, height=10, width=70) sendButt = ttk.Button(self, text="Send", command=self.sendIt) toL.grid(row=0, column=0, sticky=tk.W) self.toF.grid(row=0, column=1) msgL.grid(row=1, column=0, sticky=tk.W) self.msgF.grid(row=1, column=1) sendButt.grid(row=2, column=0, columnspan=2) def sendIt(self): try: t = self.toF.get() m = self.msgF.get(1.0, tk.END) smtpObj.sendmail(email, t, m) msg = messagebox.showinfo("Mission Completed!!!", "Your Mail Has Been Successfully Sended") except smtp.SMTPRecipientsRefused: msg = messagebox.showerror("ERROR...", "All recipients were refused. Nobody got the mail. The recipients attribute of the exception object is a dictionary with information about the refused recipients (like the one returned when at least one recipient was accepted)") except smtp.SMTPHeloError: msg = messagebox.showerror("ERROR...", "The server didn’t reply properly to the HELO greeting") except smtp.SMTPSenderRefused: msg = messagebox.showerror("ERROR...", "The server didn’t accept the from_addr") except smtp.SMTPDataError: msg = messagebox.showerror("ERROR...", "The server replied with an unexpected error code (other than a refusal of a recipient)") except smtp.SMTPNotSupportedError: msg = messagebox.showerror("ERROR...", "SMTPUTF8 was given in the mail_options but is not supported by the server") ec = EmailClass()
dc5b5ccd096855e87a3ae3777d5e9677126fb3b4
elveera0491/SimpleSockets
/server.py
2,202
3.546875
4
import socket import threading PORT = 5000 HEADER = 64 SERVER = socket.gethostbyname(socket.gethostname()) FORMAT = 'utf-8' ADDR = (SERVER, PORT) DISCONNECT_MESSAGE = "Client Disconnected" server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(ADDR) def handle_client(conn, addr): ''' Handle individual connection between client-server Will be running concurrently for each client ''' # displays all the new connections to the server print(f"[NEW CONNECTIONS] {addr} connected.") connected = True while connected: # conn.recv() is a blocking line of code and hence you need threads for simultaneous connections # from other clients. The messages received are encoded and hence it has to be decoded at the server. msg_length = conn.recv(HEADER).decode(FORMAT) # Check if you're getting a valid message if msg_length: msg_length = int(msg_length) msg = conn.recv(msg_length).decode(FORMAT) if msg == DISCONNECT_MESSAGE: connected = False print(f"[{addr}] {msg}") conn.send("Message received".encode(FORMAT)) # Gracefully close the connection conn.close() def start_socket(): ''' Listen and handles connections with clients ''' # listen for new client connections server.listen() print(f"[LISTENING] server is listening on {SERVER}") # Infinite loop so that the server is always listening while True: # Waits for a new connection to the server. # Server accepts the address of a client connection conn, addr = server.accept() #Checks the number of active connections thread = threading.Thread(target=handle_client, args=(conn, addr)) thread.start() #Displays new thread for each of the new clients # (threading.activeCount()-1 means there is always a thread running to listen to new connections) print(f"[ACTIVE CONNECTIONS] {threading.activeCount()-1}") print("[STARTING] server is starting...") start_socket()
637a4afd8df595740820901f6f92175bcf0b6d61
mbassale/computer-science
/book2-algorithms-sedgewick/ch2/03_shell_sort.py
1,597
3.671875
4
from math import floor import sys import random import time class ShellSort: def sort(self, items) -> None: h = 1 while h < len(items) // 3: h = 3 * h + 1 # 1, 4, 13, 40, 121, 364, 1093, ... while h >= 1: for i in range(h, len(items)): j = i while j >= h and items[j] < items[j - h]: self.swap(items, j, j - h) j -= h h = h // 3 def swap(self, items, i, j) -> None: items[i], items[j] = items[j], items[i] def main(): print('Shell Sort') if len(sys.argv) < 2: print('Missing number of items.') exit(1) number_items = int(sys.argv[1]) print('Number of Items: ', number_items) print('Generating numbers... ', end='', flush=True) numbers = [random.randint(0, 1000000) for _ in range(number_items)] print('Done.') if number_items <= 100: print('Numbers: ', ', '.join((str(n) for n in numbers))) print('Sorting... ', end='', flush=True) shell_sort = ShellSort() t1 = time.time() shell_sort.sort(numbers) t2 = time.time() print('Done.') print('Running time: ', (t2 - t1), 'secs.') if number_items <= 100: print('Numbers: ', ', '.join((str(n) for n in numbers))) print('Checking... ', end='', flush=True) for i in range(len(numbers) - 1): if numbers[i] > numbers[i + 1]: print('\nBad ordering: ', numbers[i], ', ', numbers[i + 1]) exit(1) print('Done.') if __name__ == '__main__': main()
c7726ea73793143b840221ffe03d8762b3442f51
marsied107/CS0008-f2016
/Ch3-Ex/Ch3-Ex8.py
289
4.15625
4
#Prompts the user to enter the number of people attending the party and how many hot dogs they will be given people = int(input('Enter the number of people attending the party: ')) hotdogs = int(input('Enter the number of hot dogs each person will be served: ')) total = people * hotdogs
6e3660f6ea66e0baf14dbe45b7a4c59062cbf656
dante092/Password
/password.py
1,426
3.796875
4
import re def digitRegex(testpassword, digit_list): 'Returns a list of Digits in password.' digitRegex = re.compile(r'\d') digit_list = digitRegex.findall(testpassword) return digit_list def characterRegex(testpassword, character_list): 'Returns a list of characters in password.' characterRegex = re.compile(r'\w') character_list = characterRegex.findall(testpassword) return character_list def AlphaRegex(testpassword, alpha_list): 'Returns a list of CAPITALIZED characters in password' AlphaRegex = re.compile(r'[A-Z]') alpha_list =AlphaRegex.findall(testpassword) return alpha_list def test(character_list, digit_list, alpha_list, number_of_tests_passed =0): 'Checks the strength of the password' if len(character_list) >= 8: print('MINIMUN CHARACTER TEST: PASSED') number_of_tests_passed = number_of_tests_passed +1 else: print('MINIMUM CHARACTER TEST: FAILED') if digit_list != []: print('NUMERICAL TEST: PASSED') number_of_tests_passed = number_of_tests_passed +1 else: print('NUMERICAL TEST: FAILED ') if len(alpha_list) >= 1: print('ALPHA TEST: PASSED') number_of_tests_passed=number_of_tests_passed +1 else: print('ALPHA TEST: FAILED') if number_of_tests_passed == 3: print('\nPASSWORD SECURED') else: print('\nPASSWORD WEAK') #End
5279912fcad3e1a8e145784ae46cfd3743e541b7
SeffuCodeIT/pythoncrashcourse
/functions.py
552
3.890625
4
# name = input() # print("Nice to meet you" + name) # def greeting(): # print('Hello there my friend') # print('what is your name') # name = input() # print("my name is" + name) # greeting() # greeting() def greeting(name): print('Hello there' + name) # greeting('Seffu') def multiply_by_10(number): # print(20 * number) return 10 * number def add(number, by=1): return number + by added_number = add(10) print(added_number) # multiply_by_10(50) # multipied_number = multiply_by_10(20) # print(multipied_number)
475b6ca8dc219c3259c81efae79e07886921bee9
sidhumeher/PyPractice
/LeetCode/Arrays/twoSum.py
1,275
3.5625
4
''' Created on Apr 20, 2020 @author: sidteegela ''' def twoSum(nums,target): result = [] ''' for i in range(len(nums)-1): for j in range(1,len(nums)-1): if nums[i] + nums[j] == target: result.append(i) result.append(j) ''' ''' for i in range(len(nums)): reminder = target - nums[i] if reminder in nums[:i-1]: #print(i) #print(nums.index(reminder,0,i-1)) result.append(i) result.append(nums.index(reminder,0,i-1)) elif reminder in nums[i+1:]: #print(i) #print(nums.index(reminder,i+1,len(nums)-1)) result.append(i) result.append(reminder,i+1,len(nums)-1) ''' my_dict = dict() for item in range(len(nums)): reminder = target - nums[item] if reminder in my_dict: result.append(item) #print(item) result.append(my_dict[reminder]) #print(my_dict[reminder]) break return result if __name__ == '__main__': #nums = [2,7,11,15] #target = 9 nums = [3,2,4] target = 6 result = twoSum(nums, target) print(result)
836bb4d2fc506e0e9a6916ffd5c186229532ed50
carolana/learning-area
/projects/scripts/nome-completo.py
318
3.9375
4
nome = str(input('Digite seu nome completo: ')).split print('Seu nome com todas as letras maiusculas é {}'.format(nome.upper())) print('Seu nome em minusculo é {}'.format(nome.lower())) print('Seu nome tem {} letras'.format(len(nome)- nome.count(' '))) print('Seu primeiro nome tem {} letras'.format(nome.find(' ')))
7579c07e26aa0645a96eb7d0118096f58573e607
Amithmg6/ipl_data_analysis_python
/test folder/spark.py
4,519
4.15625
4
# Verify SparkContext # print(sc) # Print Spark version # print(sc.version) # Import SparkSession from pyspark.sql from pyspark.sql import SparkSession # Create my_spark my_spark = SparkSession.builder.getOrCreate() # Print my_spark print(my_spark) # Print the tables in the catalog print(spark.catalog.listTables()) # Don't change this query query = "FROM flights SELECT * LIMIT 10" # Get the first 10 rows of flights flights10 = spark.sql(query) # Show the results flights10.show() # Don't change this query query = "SELECT origin, dest, COUNT(*) as N FROM flights GROUP BY origin, dest" # Run the query flight_counts = spark.sql(query) # Convert the results to a pandas DataFrame pd_counts = flight_counts.toPandas() # Print the head of pd_counts print(pd_counts.head()) """ In the last exercise, you saw how to move data from Spark to pandas. However, maybe you want to go the other direction, and put a pandas DataFrame into a Spark cluster! The SparkSession class has a method for this as well. The .createDataFrame() method takes a pandas DataFrame and returns a Spark DataFrame. The output of this method is stored locally, not in the SparkSession catalog. This means that you can use all the Spark DataFrame methods on it, but you can't access the data in other contexts. For example, a SQL query (using the .sql() method) that references your DataFrame will throw an error. To access the data in this way, you have to save it as a temporary table. You can do this using the .createTempView() Spark DataFrame method, which takes as its only argument the name of the temporary table you'd like to register. This method registers the DataFrame as a table in the catalog, but as this table is temporary, it can only be accessed from the specific SparkSession used to create the Spark DataFrame. There is also the method .createOrReplaceTempView(). This safely creates a new temporary table if nothing was there before, or updates an existing table if one was already defined. You'll use this method to avoid running into problems with duplicate tables. Check out the diagram to see all the different ways your Spark data structures interact with each other. """ # Create pd_temp pd_temp = pd.DataFrame(np.random.random(10)) # Create spark_temp from pd_temp spark_temp = spark.createDataFrame(pd_temp) # Examine the tables in the catalog print(spark.catalog.listTables()) # Add spark_temp to the catalog spark_temp.createOrReplaceTempView("temp") # Examine the tables in the catalog again print(spark.catalog.listTables()) """Dropping the middle man Now you know how to put data into Spark via pandas, but you're probably wondering why deal with pandas at all? Wouldn't it be easier to just read a text file straight into Spark? Of course it would! Luckily, your SparkSession has a .read attribute which has several methods for reading different data sources into Spark DataFrames. Using these you can create a DataFrame from a .csv file just like with regular pandas DataFrames! The variable file_path is a string with the path to the file airports.csv. This file contains information about different airports all over the world. A SparkSession named spark is available in your workspace.""" # Don't change this file path file_path = "/usr/local/share/datasets/airports.csv" # Read in the airports data airports = spark.read.csv(file_path, header=True) # Show the data airports.show() """Let's look at performing column-wise operations. In Spark you can do this using the .withColumn() method, which takes two arguments. First, a string with the name of your new column, and second the new column itself. The new column must be an object of class Column. Creating one of these is as easy as extracting a column from your DataFrame using df.colName. Updating a Spark DataFrame is somewhat different than working in pandas because the Spark DataFrame is immutable. This means that it can't be changed, and so columns can't be updated in place. Thus, all these methods return a new DataFrame. To overwrite the original DataFrame you must reassign the returned DataFrame using the method like so: df = df.withColumn("newCol", df.oldCol + 1) The above code creates a DataFrame with the same columns as df plus a new column, newCol, where every entry is equal to the corresponding entry from oldCol, plus one. To overwrite an existing column, just pass the name of the column as the first argument! Remember, a SparkSession called spark is already in your workspace."""
e23d5e81dbea99a3c548a0f344faeed4670680d4
kuritan/codility-practice
/Lesson6-Triangle.py
1,158
3.75
4
# An array A consisting of N integers is given. # A triplet (P, Q, R) is triangular if 0 ≤ P < Q < R < N and: # # A[P] + A[Q] > A[R], # A[Q] + A[R] > A[P], # A[R] + A[P] > A[Q]. # For example, consider array A such that: # # A[0] = 10 A[1] = 2 A[2] = 5 # A[3] = 1 A[4] = 8 A[5] = 20 # Triplet (0, 2, 4) is triangular. # # Write a function: # # def solution(A) # # that, given an array A consisting of N integers, # returns 1 if there exists a triangular triplet for this array and returns 0 otherwise. # # For example, given array A such that: # # A[0] = 10 A[1] = 2 A[2] = 5 # A[3] = 1 A[4] = 8 A[5] = 20 # the function should return 1, as explained above. Given array A such that: # # A[0] = 10 A[1] = 50 A[2] = 5 # A[3] = 1 # the function should return 0. # # Write an efficient algorithm for the following assumptions: # # N is an integer within the range [0..100,000]; # each element of array A is an integer within the range [−2,147,483,648..2,147,483,647]. def solution(A): A.sort() for i in range(1, len(A)-1): if A[i] + A[i-1] > A[i+1]: return 1 return 0
64c5b1e80e20e2824b5592f3d78f3a91e3227dd1
Harnet69/HomeWork1
/fibonacciNumbersRecc.py
579
4.15625
4
# calculate a number of Fibonacci def fib_num(n): if n == 1: return 0 if n == 2: return 1 return fib_num(n-1) + fib_num(n-2) # create and fill sequance with number of Fibonacci def fib_seq(n): seq = [] for i in range(1, n+1): seq.append(fib_num(i)) return seq # display in apropriate format f.sequance def display(fib_seq): print("Fibonacci sequance:\n") for index, f_num in enumerate(fib_seq): print(f"{index+1}. {f_num}") def main(): display(fib_seq(10)) if __name__ == "__main__": main()
8ee4983f9ed9c28d47dcefa261662985ffb5a6b1
liujunsheng0/notes
/lintcode/permutation-index.py
1,018
3.625
4
#!/usr/bin/python3.6 # -*- coding: utf-8 -*- """ https://www.lintcode.com/problem/permutation-index/description 给出一个不含重复数字的排列, 求这些数字的所有排列按字典序排序后该排列的编号. 编号从1开始. 输入:[1,2,4] 输出:1 样例 2: 输入:[3,2,1] 输出:6 """ class Solution: """ @param A: An array of integers @return: A long integer """ def permutationIndex(self, A): ans = 0 idx = len(A) - 2 # factor 和 n 用于阶乘 factorial = 1 n = 2 # 排列组合, 从后面开始找比当前值小的 while idx > -1: success = len([None for i in A[idx + 1:] if i < A[idx]]) ans += success * factorial factorial *= n n += 1 idx -= 1 # end for # + 1为A的位置 return ans + 1 if __name__ == '__main__': print(Solution().permutationIndex([22, 7, 15, 10, 11, 12, 14, 8, 9, 1, 2, 3, 6, 5, 4]), 1263957845766)
f5e688029674df61e56808b19089510184e3f681
paulocaram/PENTEST
/MODULO04/portscan.py
1,116
3.53125
4
#!/usr/bin/python # Informa que irei utilizar as rotinas de socket import socket import sys def sai(): sys.exit() def resolva(): try: dominio = raw_input("Digite o dominio: ") print dominio,"=====>",socket.gethostbyname(dominio) print "\n" except Exception as e: print "Erro: %s"%e def soc1(): print "xxxx" def portascan(): ip = raw_input("Qual o alvo [IP]: ") for porta in range(1,65535): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if s.connect_ex((ip, porta)) == 0: print "Porta: ", porta, "- [ABERTA]" s.close() def menu(): try: print "Curso Profissional de Pentest" print "1 - Socket " print "2 - Portscan" print "3 - Resolva " print "4 - Sai\n " op = input("Qual a opcao: ") return op except Exception as e: print "Erro: %s"%e return 4 def switch(x): list_dict = {1:soc1, 2:portascan, 3:resolva, 4:sai} list_dict[x]() if __name__ == '__main__': while True: switch(menu())
8228947acfb5a2bf16f229b72d76d2fe2fe226d3
ed-cetera/project-euler-python
/053_solution.py
583
3.578125
4
#!/usr/bin/env python3 import math import time def binomial_coefficient(n, r): return math.factorial(n)//(math.factorial(r) * math.factorial(n - r)) def main(): n_limit = 100 lower_noninclusive_limit = 1000000 counter = 0 for n in range(1, n_limit + 1): for r in range(1, n + 1): if binomial_coefficient(n, r) > lower_noninclusive_limit: counter += 1 print("Solution:", counter) if __name__ == "__main__": start = time.time() main() end = time.time() print("Duration: {0:0.6f}s".format(end - start))
544b1ef122cd72095c4336b5a377e16c11522a46
StevenSoares14/ASTR_119
/annual_savings.py
1,471
4.0625
4
# -*- coding: utf-8 -*- # anaconda2/python 2.7 """ Compute annual dollar amount on savings invested at float_Interest over int_Years years Variables: int_Years = durations of investment flt_Interest = interest rates flt_iniInvest = initial investment """ #import numpy #============================================================================ # Define Variables #============================================================================ int_Years = 30 flt_Interest = 0.1 flt_iniInvest = 1e4 #============================================================================ # Do computation - Savings #============================================================================ def annual_return( flt_iniInvest, flt_Interest, int_Years): """ Computing annual savings :input Variables: int_Years = durations of investment flt_Interest = interest rates flt_iniInvest = initial investment :output Savings in last year ( int_Years) """ currInvest = flt_iniInvest for i in range( int_Years-1): flt_Growth = currInvest*flt_Interest print( 'Year', i+1, 'savings', currInvest, 'interest per year', flt_Growth) currInvest += flt_Growth return currInvest # Add a function call print(annual_return( flt_iniInvest, flt_Interest, int_Years))
49521eeead27ec5c05aa3b9ecd06aa9d2e9f3660
elim168/study
/python/basic/pillow/10.ImageDraw_画图_test.py
1,295
3.515625
4
from PIL import Image, ImageDraw, ImageFont # 创建一个图片 image = Image.new('RGBA', (500, 300), 'green') # 获取该图片的画笔,之后都通过该画笔进行绘画 draw = ImageDraw.Draw(image) # 画一个矩形,起点是(20, 20),终点是(480, 280)。 draw.rectangle((20, 20, 480, 280), fill='red', outline='blue') draw.text((50, 50), 'Hello World!', fill='blue') # 写的字如果是中文需要指定字体 draw.text((50, 100), '你好,世界!', font=ImageFont.truetype('NotoSansCJK-Regular.ttc', size=16)) # 画一个起点是(150, 50),终点是(350, 250),以这条直线为直径画圆弧,圆弧的起点是0度,终点是360度,即画的是一个圆 draw.arc((150, 50, 350, 250), 0, 360, fill='yellow') image.show() # 也可以在一张已有的图片之上进行绘图 image = Image.open('flower_01.jpg') w, h = image.size draw = ImageDraw.Draw(image) draw.line((0, h / 2, w, h / 2), fill=(123, 200, 102), width=5) image.show() # 绘制九宫格 image = Image.new('RGB', (300, 300)) draw = ImageDraw.Draw(image) def get_color(x, y): n = x // 100 + y // 100 colors = ['red', 'yellow', 'green', 'blue', 'orange'] return colors[n] for x in range(300): for y in range(300): draw.point((x, y), fill=get_color(x, y)) image.show()
997f758e9a49a373c0a88fecccb81f06e00653c6
PanMaster13/Python-Programming
/Week 8/Week 8, Functions/Tutorial Files/Week 8, Exercise 2.py
325
3.875
4
def function_2(): print("User input") ipt = input("What's your message?") list1 = [] counter = 1 for i in range(0, len(ipt)): list1.append(ipt[len(ipt)-counter]) counter +=1 list1 = "".join(list1) print("\n~Output") print("Message in reverse order:", list1) function_2()
9ca77f753e4299febecff8e9e956de70373410ff
JagritiG/interview-questions-answers-python
/code/set_1_array/34_find_range_sorted_array.py
1,456
4.03125
4
# Find first and last position of element in sorted array # Given an array of integers nums sorted in ascending order, # find the starting and ending position of a given target value. # Your algorithm's runtime complexity must be in the order of O(log n). # If the target is not found in the array, return [-1, -1]. # Example 1: # Input: nums = [5,7,7,8,8,10], target = 8 # Output: [3,4] # Example 2: # Input: nums = [5,7,7,8,8,10], target = 6 # Output: [-1,-1] # ============================================================== # method-1 def search_range_1(nums, target): if target not in nums: return [-1, -1] elif len(nums) == 1 and nums[0] == target: return [0, 0] else: res = [] for i in range(len(nums)): if nums[i] == target: res.append(i) return [res[0], res[-1]] # method-2 (faster) *** def search_range(nums, target): if target not in nums: return [-1, -1] elif len(nums) > 1: res = [] for i in range(len(nums)): if nums[i] == target: res.append(i) return [res[0], res[-1]] else: return [0, 0] if __name__ == "__main__": arr = [5, 7, 7, 8, 8, 10] t = 8 # arr = [5, 7, 7, 8, 8, 10] # t = 6 # arr = [1, 1] # t = 1 # arr = [1] # t = 1 # print(search_range_1(arr, t)) print(search_range(arr, t))
3195155e7854a870d1212bff880762aeeb7b9cf6
ubco-mds-2018-labs/Data533_Lab4_Sang_Wiese
/health/conversion/find_age.py
498
4.09375
4
from datetime import date from datetime import datetime def year_to_age(name,bdate): #enter a string in form yyyy-mm-dd today = datetime.now() # Calculate age try: dt = datetime.date(datetime.strptime(bdate, "%Y-%m-%d")) age = today.year - dt.year if today.month < dt.month or (today.month == dt.month and today.day < dt.day): age = age - 1 return age except ValueError: print("Please enter the date of birth as yyyy-mm-dd.")
6096a537d591e25362b1f093421899f37262f566
Yousef497/Professional-Data-Analyst-Track
/Exercises/Factorial with While.py
455
4.46875
4
# number to find the factorial of number = 6 # start with our product equal to one product = 1 # track the current number being multiplied current = 1 # write your while loop here while current <= number: product *= current current += 1 # multiply the product so far by the current number # increment current with each iteration until it reaches number # print the factorial of number print(product)
9579a0f65b4a5268924979366b837525ae34d0f7
hoogland/AdventOfCode2018
/day2.py
982
3.875
4
filename = "resources/day2.txt" boxes = [str(x).rstrip() for x in open(filename).readlines()] def check_freq(str): freq = {} for c in str: freq[c] = str.count(c) return freq #star 1 solution twoOccurance = 0 threeOccurance = 0 for box in boxes: frequencies = check_freq(box) if 2 in frequencies.values(): twoOccurance += 1 threeOccurance += list(frequencies.values()).count(3) print('The checksum = ' + str(twoOccurance) + " * " + str(threeOccurance) + " = " + str(twoOccurance * threeOccurance)) #star 2 solution commonLetters = '' for index, box1 in enumerate(boxes): for box2 in boxes[index:]: if sum(a != b for a, b in zip(box1, box2)) == 1: for a, b in zip(box1, box2): if a == b: commonLetters += a print("The common letters are: " + commonLetters) #Lessons learned # Zip events can be used to combine two variables and then to iterate through them together
83b205af7cea7e738f0e0e010fc73d1ff344ab2a
yungjoong/leetcode
/58.length-of-last-word.py
1,113
3.640625
4
# # @lc app=leetcode id=58 lang=python3 # # [58] Length of Last Word # # https://leetcode.com/problems/length-of-last-word/description/ # # algorithms # Easy (32.47%) # Likes: 582 # Dislikes: 2252 # Total Accepted: 356.3K # Total Submissions: 1.1M # Testcase Example: '"Hello World"' # # Given a string s consists of upper/lower-case alphabets and empty space # characters ' ', return the length of last word (last word means the last # appearing word if we loop from left to right) in the string. # # If the last word does not exist, return 0. # # Note: A word is defined as a maximal substring consisting of non-space # characters only. # # Example: # # # Input: "Hello World" # Output: 5 # # # # # # @lc code=start class Solution: def lengthOfLastWord(self, s: str) -> int: cnt = 0 prv = 0 for ch in s : if ch == ' ' : if cnt != 0 : prv = cnt cnt = 0 else : cnt += 1 if cnt == 0 : return prv else : return cnt # @lc code=end
f0fb4b6bcd0cbcc6f6b99eab87a70040b4d6ed07
JvRahul/DataStructures
/strings_lists_dicts_exercises.py
9,202
3.90625
4
#python :average length of words. l = 'Geeks', 'for', '', 'Rahul' v = l.split(',') def avg(L): if L == "": return None c= 0 for i in L: i = i.strip() print(i) c = c + len(i) print(c) n = len(L) print(n) avg = c/n return avg def AverageLenWords(sentence): words = sentence.split() l = 0 for word in words: l += len(word) return round((l / len(words)), 3) if len(words) > 0 else 0 print(AverageLenWords("a b cddefgh")) #Given k numbers which are less than n, return the set of prime numbers among them L = [0,1,2,3,2,3,31,5,34,12,43,13,23,2, -10] #res = [1,2,3,31,5,43,13,23] n = 50 res = [] def checkPrime(m): c = 0 if m <= 0: return False if (m == 2) or (m ==3): return True for i in range(1,m//2): if m % i == 0: c += 1 # print(i, c) if c == 1: return True else: return False def primeNum(L): for i in set(L): if checkPrime(i): res.append(i) # print(res) return res print(primeNum(L)) # print(checkPrime(3)) # print(3//2) #Count distinct words in a sentence dict = {} def uniqWord(word): if word in dict: dict[word] += 1 else: dict[word] = 1 def countUniqWrdSent(str): listOfWords = str.split(" ") for wrd in listOfWords: uniqWord(wrd) c = 0 for ele in dict: if dict[ele] == 1: c += 1 return c #count the number of times a word appear in a sentence using a Hash Map def uniqWord(word): if word in dict: dict[word] += 1 else: dict[word] = 1 #Return tuples of a list, matching each item to another item #Count the number of times a substring appear in a string test_str = "GeeksforGeeks is for Geeks" # initializing substring test_sub = "Geeks" # printing original string print("The original string is : " + test_str) # printing substring print("The original substring : " + test_sub) print(test_str.split(test_sub)) # using split() + len() # Frequency of substring in string res = len(test_str.split(test_sub))-1 # printing result print("The frequency of substring in string is " + str(res)) # flatten a given list that contain members that are numbers or nested lists. # find avg word len, # input is a string, identify if a string is a valid IP # Check if given array is Monotonic Calculate the average word length. Python:- [1,None,1,2,None] --> [1,1,1,2,2] if L[0] == None: L[0] = 0 or L[-1] for i in range(len(L)): if L[i] == None: L[i] = L[i-1] return L # Ensure you take care of case input[None] which means None object. # 1. Is the question to replace None with preceding value? # 2. Is the second question to find the number of occurrences or the position of s in the given word # Find common words in 2 sentences # Question 1: # Complete a function that returns the number of times a given character occurs in the given string # Enter a string and a character sample(mississippi,s): missiSSippi,S def findCharNum(s,c): /* * returns the number of times a given character occurs in the given string * * param : * s: string to search the given character in * c: the searching character in the given string */ test_str = "GeeksforGeeks" # using naive method to get count # of each element in string all_freq = {} for i in test_str: if i in all_freq: all_freq[i] += 1 else: all_freq[i] = 1 # printing result print ("Count of all characters in GeeksforGeeks is :\n " + str(all_freq)) OR test_str = "GeeksforGeeks" # using set() + count() to get count # of each element in string res = {i : test_str.count(i) for i in set(test_str)} # printing result print ("The count of all characters in GeeksforGeeks is :\n " + str(res)) Question 2: # Fill in the blanks # # Given an array containing None values fill in the None values # with most recent non None value in the array # # For example: # - input array: [1,None,2,3,None,None,5,None] a = [None,None,1,2,3,None,None,3,2,5,None,4,None,9,None,None,None] #for i in range(len(a)): #if a[0] == None: # if a[i] is not None: # a[0]=a[i] def repNone(a): for i in range(len(a)): if a[i] == None: a[i] = a[i-1] repNone(a) a[0] = a[-1] repNone(a) print(a) [OR_OR_OR_OR_OR] a = [None,2,4,None] b = [None,None,1,2,3,None,None,3,2,5,None,4,None,9,None,None,None] def nonRplc(a): if a == None or len(a) < 1: return 0 for i in range(len(a)): if a[0] == None: if a[i] is not None: a[0]=a[i] if a[0] == None: a[0] = 0 for i in range(len(a)): if a[i] == None: a[i] = a[i-1] return a #repNone(a) #a[0] = a[-1] #repNone(a) print(nonRplc(a)) print(nonRplc(b)) # - output array: [1,1,2,3,3,3,5,5] for # Question 3: # Complete a function that returns a list containing all the mismatched words (case sensitive) between two given input strings # 3. [[A],[A,B],[A,C],[B,D],[C,A]] -- Find the alphabet with highest neighbors? -- (Wasnt able to solve because of time limit but the interviewer was like I get what… # Python Questions: # Avg length of words, some of the edge cases are having spaces in the beginning and end of the words, returning a float instead of int, returning None for blank input. # Valid ip address, edge case to remember is if there are alphanumeric characters. # • Python Valid IP address 2 Answers # • Python graph node count 3 Answers # • Python average word length 2 Answers # Python # 1. Count the number of unique words in a sequence? # 2. Print the part of the array of numbers # 3. Check the substring in the string # 4. Question on exceptions # Python Questions - # 1) Print Max element of a given list # 2) Print median of a given list # 3) Print the first nonrecurring element in a list L = ['a','b','a'] def frst_recur(L): if L == None or len(L) <1: return 0 dct = {} for i in L: if i in dct: dct[i]+=1 else: dct[i] =1 for ele in dct: if dct[ele] ==1: return ele print(frst_recur(L)) # 4) Print the most recurring element in a list # L = [2, 1, 2, 2, 1, 3] L = ['Dog', 'cat', 'dog', 'dog', 'Dog'] def mostRecur(L): #c = 0 dct = {} for i in L: if i in dct: dct[i] += 1 else: dct[i] = 1 max_value = max(dct.values()) # maximum value max_keys = [k for k, v in dct.items() if v == max_value] # getting all keys containing the `maximum` # for k, v in dct.items(): # if v == max_value: # return k return max_keys print(mostRecur(L)) # 5) Greatest common Factor def computeGCD(x, y): if x > y: small = y else: small = x for i in range(1, small+1): if((x % i == 0) and (y % i == 0)): gcd = i return gcd #Reverse Digits def reverse(x: int) -> int: result, x_remaining = 0, abs(x) while x_remaining: result = result * 10 + x_remaining % 10 x_remaining //= 10 return -result if x < 0 else result print(abs(-123)) # Find common words in 2 sentences # sent_1 = 'A blue whale is whale which is blue' # sent_2 = 'The blue ocean has whales which are blue' # whether [] is monotonic: def m_increasing(A): if len(A) == 0: return 0 else: for i in range(len(A)-1): if A[i] > A[i+1]: return False return True def m_decreasing(A): if len(A) == 0: return 0 else: for i in range(len(A)-1): if A[i] < A[i+1]: return False return True def monotonic(A): if m_increasing(A) or m_decreasing(A): return True else: return False A = [1,2,2,3,4,5,6,2,3,4] #print(monotonic(A)) #common_words def common_words(ip1, ip2): L1 = ip1.split(' ') L2 = ip2.split(' ') L3 = [] for i in set(L1): if i in set(L2): L3.append(i) return L3 print(common_words('A blue whale is whale which is blue', 'The blue ocean has whales which are blue')) #Complete a function that returns a list containing all the mismatched words (case sensitive) between two given input strings # For example: str1 = "Firstly this is the first string" str2 = "Next is the second string" # def uncom(str1, str2): L1 = str1.split(' ') L2 = str2.split(' ') res = '' #l = [] for i in set(L1): if i not in set(L2): #l.append(i) res += ' ' + i for j in set(L2): if j not in set(L1): #l.append(i) res += ' ' + j #ls = str(l).strip('[]') #return ','.join(l) return res print(uncom(str1, str2)) # ipv4 and ipv6 validation check: def ipv4(s): try: return str(int(s)) == s and 0 < = int(s) <= 255 except: return False def ipv6(s): try: return len(s) <= 4 and int(s, 16) >= 0 and s[0] != '-' except: return False if IP.count('.') == 3 and all(ipv4(i) for i in IP.split('.')): return 'Ipv4' if IP.count(':') == 7 and all(ipv6(i) for i in IP.split(':')): return 'Ipv6' return 'Neither' def ipv4(s): try: return str(int(s)) == s and 0 <= int(s) <= 255 except: return False def ipv6(s): try return len(s) <= 4 and int(s, 16) >= 0 and s[0] != '-' except: return False if Ip.count('.') == 4 and all(ipv4(i) for i in IP.split('.')): return 'ipv4' if IP.count(':') == 7 and all(ipv6(i) for i in IP.split(':'): return "Ipv6" return Neither
102882f2ce1b0a2f155c417e7a015bb1ef49b599
Super0415/Python
/mycollect/lesson/lesson02/lesson02/homework.py
1,571
3.9375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # author:fei time:2018/11/27 # 数字类型:整数、浮点数、复数 # 初始数字类型 a = 5 b = 5.66 c = "6" # d = 1 + 2j print("a:", a) print("a的类型为:", type(a)) # a的类型为: <class 'int'> print("b:", b) print("b的类型为:", type(b)) # b的类型为: <class 'float'> print("c:", c) print("c的类型为:", type(c)) # c的类型为: <class 'str'> # print(d.real) # 实数 # print(d.imag) # 虚数 # 转换为整数 d = int(b) e = int(c) print("d:", d) print("d的类型为:", type(d)) # d的类型为: <class 'int'> print("e:", e) print("e的类型为:", type(e)) # e的类型为: <class 'int'> # 转换为浮点数 f = float(a) g = float(c) print("f:", f) print("f的类型为:", type(f)) # f的类型为: <class 'float'> print("g:", g) print("g的类型为:", type(g)) # g的类型为: <class 'float'> # 转换为复数 h = complex(a, b) i = complex(b, a) j = complex(c) print("h:", h) # h: (5+5.66j) print("h的类型为:", type(h)) # h的类型为: <class 'complex'> print("i:", i) # i: (5.66+5j) print("i的类型为:", type(i)) # i的类型为: <class 'complex'> print("j:", j) # j: (6+0j) print("j的类型为:", type(j)) # j的类型为: <class 'complex'> # 逆序 s = "hello,world!" print(s[::-1]) # 切片得到年月日 s1 = "20181127" year = s1[:4] month = s1[4:6] day = s1[6:] print("年:", year) print("月:", month) print("日:", day) S = "abcaodawf" print(S.count("a")) print(S.count("a", 3, 8))
292ec6ccbbf456f227d32ef18c01e460d761c035
chaoswork/leetcode
/056.MergeIntervals.py
1,133
3.96875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Author: Chao Huang ([email protected]) Date: Mon Feb 26 19:57:12 2018 Brief: https://leetcode.com/problems/merge-intervals/description/ Given a collection of intervals, merge all overlapping intervals. For example, Given [1,3],[2,6],[8,10],[15,18], return [1,6],[8,10],[15,18]. """ # Definition for an interval. class Interval(object): def __init__(self, s=0, e=0): self.start = s self.end = e def __str__(self): return '(%d, %d)' % (self.start, self.end) class Solution(object): def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ if len(intervals) == 0: return [] int_sort = sorted(intervals, key=lambda x: x.start) result = [] begin = int_sort[0] for item in int_sort: if item.start <= begin.end: if item.end > begin.end: begin.end = item.end else: result.append(begin) begin = item result.append(begin) return result
b49e8ed37014f1032faef58a2cc1bfad2b778b5d
shawnco/pyverse
/classes/objects/station.py
324
3.65625
4
''' General implementation for a Station object. These are constructed and float stationary in space. ''' import pygame class Station(pygame.sprite.Sprite): ''' Constructor doesn't do much. ''' def __init__(self): pass ''' Updates the display ''' def update(self): pass
a732b38d1d44c8de9eb7161abeef512a2001097c
misrashashank/Competitive-Problems
/construct_binary_tree_from_in-pre.py
1,366
4.09375
4
''' Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. Example: preorder = [3,9,20,15,7] inorder = [9,3,15,20,7] Return the following binary tree: 3 / \ 9 20 / \ 15 7 ''' # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def buildTree(self, preorder, inorder): if not preorder or not inorder: return None def check_inorder(left_i, right_i): # Base case if left_i > right_i: return None # Get the first element in preorder root_val = preorder.pop(0) # Create a TreeNode for the first element root = TreeNode(root_val) # Get the index of first element from preorder in inorder traversal root_i = inorder.index(root_val) # Break inorder as per the root node # As per the preorder traversal, first create left subtree, # then right subtree root.left = check_inorder(left_i, root_i - 1) root.right = check_inorder(root_i + 1, right_i) return root root = check_inorder(0, len(inorder)-1) return root
a85f4ffc36f89ba36a72f629501a8f933377332b
sodewumi/dictionary_word_count
/wordcount.py
976
3.5625
4
from sys import argv from collections import Counter script, filename = argv def count_words(filename): open_file = open(filename) rm_punctuation = [] word_count = {} for line in open_file: words = line.rstrip().split(" ") for word in words: alpha_wrd = "" for ltr in word: if ltr.isalpha() or ltr is "'": alpha_wrd = alpha_wrd + ltr rm_punctuation.append(alpha_wrd.lower()) word_count = Counter(rm_punctuation) return print_words(word_count) def print_words(full_dic): srt_keys = sorted(full_dic.items(), key = lambda x: x[1]) print srt_keys # for key,value in full_dic.iteritems(): # if srt_keys # for key in srt_keys: # print "%s: %d" %(srt_keys[key][0], srt_keys[key][1]) # for key, value in full_dic.iteritems(): # print "%s: %d" %(key, value) print(count_words(filename))
5108298808215f1151f28e700184bb05ae9b9ecd
AkshayGyara/Linked-List-2
/reorderList.py
1,192
3.828125
4
#143. Reorder List #Time Complexity : O(n) #Space Complexity : O(n) #Did this code successfully run on Leetcode : Yes class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead.slow """ if not head: return head slow = head fast = head while fast.next and fast.next.next : slow = slow.next fast = fast.next.next #node = ListNode() fast = self.reverse(slow.next) slow.next = None slow = head # merge two list while fast : curr = slow.next slow.next = fast fast = fast.next slow.next.next = curr slow = curr return head def reverse(self,node): if not node or not node.next: return node prev = None fast = node.next while fast: node.next = prev prev = node node = fast fast = fast.next node.next = prev return node
71c98f1dd557c921a809ea37eec3594902639503
zly7674/ThirdProject
/py实验一/bll.py
2,015
3.96875
4
# 1)添加学生信息 def add_student_info(): L = [] while True: n = input("(按回车直接退出)\n请输入名字:") if not n: # 名字为空 跳出循环 break try: a = int(input("请输入年龄:")) s = int(input("请输入成绩:")) except: print("输入无效,重新录入信息") continue info = {"name":n,"age":a,"score":s} L.append(info) print("学生信息录入完毕") return L # 2)显示所有学生的信息 def show_student_info(student_info): if not student_info: print("无学生信息") return print("名字".center(8),"年龄".center(4),"成绩".center(4)) for info in student_info: print(info.get("name").center(10),str(info.get("age")).center(4),str(info.get("score")).center(4)) # 3)删除学生信息 def del_student_info(student_info,del_name = ''): if not del_name: del_name = input("请输入删除的学生姓名:") for info in student_info: if del_name == info.get("name"): return info raise IndexError("没有找到%s" %del_name) # 4)修改学生信息 def mod_student_info(student_info): mod_name = input("请输入修改的学生姓名:") for info in student_info: if mod_name == info.get("name"): a = int(input("请输入年龄:")) s = int(input("请输入成绩:")) info = {"name":mod_name,"age":a,"score":s} return info raise IndexError("没有找到%s" %mod_name) # 5)按学生成绩高-低显示学生信息 def score_reduce(student_info): print("按学生成绩降序显示") mit = sorted(student_info ,key = get_score,reverse = True) show_student_info(mit) # 以下二个函数用于sorted排序, key的表达式函数 def get_age(*l): for x in l: return x.get("age") def get_score(*l): for x in l: return x.get("score")
e9fb91a55503f0e9482f8fdb4a54bb1550813e45
rorymer1989/testproject-python-sdk-example
/tests/traditional/test_duckduckgo.py
1,058
3.625
4
""" This module contains traditional pytest test cases. They test searches on the DuckDuckGo website. """ # ------------------------------------------------------------ # Imports # ------------------------------------------------------------ import pytest # ------------------------------------------------------------ # Tests # ------------------------------------------------------------ @pytest.mark.parametrize('phrase', ['panda', 'python', 'polar bear']) def test_basic_duckduckgo_search(search_page, result_page, phrase): # Given the DuckDuckGo home page is displayed search_page.load() # When the user searches for the phrase search_page.search(phrase) # Then the search result query is the phrase assert phrase == result_page.search_input_value() # And the search result links pertain to the phrase titles = result_page.result_link_titles() matches = [t for t in titles if phrase.lower() in t.lower()] assert len(matches) > 0 # And the search result title contains the phrase assert phrase in result_page.title()
4a03a7990cc748c73585c9db9f97787fdd1728e0
srishtishukla-20/List
/Q10(Tables).py
801
3.671875
4
l=[1,2,3,4,5,6,7,8,9,10] i=int(input("enter number")) j=0 while j<len(l): print(i,"*",j,"=",i*l[j]) j=j+1 #table List=[1,2,3,4,5,6,7,8,9,10] i=int(input("enter number")) j=0 while j<len(List): print(i*List[j]) j=j+1 #any table l=[0,1,2,3,4,5,6,7,8,9,10] i=int(input("enter number")) j=1 while j<len(l): print(i,"×",j,"=",i*l[j]) j=j+1 #table List=[1,2,3,4,5,6,7,8,9,10,11] p=int(input("enter number")) i=1 j=[] while i<len(List): a=(i*p) j.append(a) i=i+1 print(j) #Table of one digit in list list=[[1,3,4,5],[5,7,8,9],[3,7,8,8],[1,3,4,7]] i=0 while i<len(list): j=0 new=1 while j<len(list): new=list[j][i]*new j+=1 i=i+1 print(new) #multiples of list a1=[2,3,4,5,7] a2=[1,2,3,1,2] n=[] i=0 while i<len(a1): b=a1[i]*a2[i] n.append(b) i=i+1 print(n) #multiply both list
c60bacc93f9dcb4bc528892c3ee9578d1a60ddb1
lonnie-nguyen/TripIt
/main.py
3,566
3.84375
4
''' main.py: Project MapQuest_API Created on Aug 24, 2021 @author: lon ''' import out import maps import gui ''' CLI Gets user input of location number. User inputs the locations. Locations are appended to a list. ''' def inputlocations(): #CLI code while True: try: locnum = int(input('Enter the amount of destinations (including starting point: ')) if locnum < 2: print('Enter a number 2 or greater.') pass elif locnum >= 2: break except: print('Something weird happened, try again.') pass print('Enter one address per line:') loclist = [] for i in range(0, locnum): loc = input() loclist.append(loc) return loclist ''' GUI add to list ''' def gui_inputlist(values, inputlist): list1 = inputlist list1.append(values) return list1 ''' CLI Gets user input of output number. User inputs the outputs that they want. Outputs are appended to a list. ''' def outputrequest(): while True: try: outputnum = int(input('Input the amount of output requests: ')) if outputnum < 1: print('Enter a number from 1 through 5.') pass elif outputnum >= 1 and outputnum <= 5: break except: print('Something weird happened. Try again.') pass print('Options for output: STEPS, TOTALDISTANCE, TOTALTIME, LATLONG, ELEVATION') outputlist = [] for i in range(0, outputnum): while True: try: output = input() checkoutput = ['steps','totaldistance', 'totaltime', 'latlong', 'elevation'] if output.casefold() in checkoutput: outputlist.append(output.upper()) #print(outputlist) break else: print('Incorrect output request, try again.') pass except: print('Something weird happened, try again.') pass return outputlist ''' Passes in list of outputs and loops through each output in order to retrieve information for the user. ''' def outputinfo(output_list, json_file): for output in output_list: if output == 'STEPS': for i in out.STEPS().info(json_file): print(i) #out.STEPS().info(json) elif output == 'TOTALDISTANCE': print(next(out.TOTALDISTANCE().info(json_file))) elif output == 'TOTALTIME': print(next(out.TOTALTIME().info(json_file))) elif output == 'LATLONG': for i in out.LATLONG().info(json_file): print(i) elif output == 'ELEVATION': ejsonlist = out.LATLONG().latlnglist(json_file) ejson = maps.elevurl(ejsonlist) for i in out.ELEVATION().info(ejson): print(i) print() print('Directions Courtesy of MapQuest; Map Data Copyright OpenStreetMap Contributors.') def main(): # locations_list = inputlocations() # json = maps.directurl(locations_list) # output_list = outputrequest() # # outputinfo(output_list, json) gui.mainwindow() if __name__ == "__main__": main()
efe2fc06868853c1589325b59ef7dfcf6fc89977
komap2017/soc
/edtext.py
1,840
3.59375
4
# -*- coding: utf8 -*- import re import string def clean(string): # From Vinko's solution, with fix. return re.sub('\W+',' ', string.lower()) #return regex.sub('', string.lower()) def lighter_clean(string_to_clear): symbols = set(string.punctuation) symbols.remove('.') symbols.remove(',') for char in symbols: string_to_clear = string_to_clear.replace(char, ' ') string_to_clear = ''.join([i for i in string_to_clear if not i.isdigit() or i == '2' or i == '3']) return string_to_clear def main(): text = "1. Тян из ДС. Возраст и пол собеседника не важен, но желательно, чтобы вы были не дальше 24х часов езды от ДС. 2. Лес, выживач в лесу, путешествия, производство оптических систем, ебучая никому не известная музыка вперемешку с Бутыркой и краснодеревщиком, наркотики, говно, блевота и моральное разложение. На самом деле это все полная хуйня и пункт 2 по очевидной причине здесь (да и вообще) никого не интересует. 3. Ищу людей, чтобы сьебаться с ними через некоторое время в лес и замутить что-то вроде Tinkers Bubble. Ебанутых на дваче много, вдруг найдутся единомышленники и дело зайдет дальше пустой болтовни. Писать сюда: @assenizator" print(repr(text)) print(repr(lighter_clean(text))) if __name__ == "__main__": main()
94ab0df69caec7bee1e7b5dd1f7e20b815d20bc7
jiajia15401/pywidget
/pywidget/AI/__init__.py
830
3.5
4
__all__ = ['ai'] v = '1.0.0' class ai(): def make(self,path): n = path + '.py' self.name = n s = open(n ,'w') run = '''class ai(): name = "%s" def __init__(self): self.list = [] self.add = [] def why(self): pass def think(self): self.why() def work(self): now = [] while True: for i in self.add i() now.append('%s 1' % i) for o in self.goal: if not o(): list_of_goal("%s %s0" % now o) list_of_goal("%s 1" % now) self.think() def add(self,add): self.add.append(add) def list_of_goal(self,goal): self.list.append(goal) '''% name s.writelines (run) return ai()
9b7964bbedf26fe7e633067754f4ad1aa4b7bc11
cainellicamila/FRRo-Soporte-2018-Grupo4
/Tp3-11.py
590
3.9375
4
''' Ejercicio 11 Programar un función Divide que ingresa dos valores x, y y devuelve el cociente x/y. La función tiene que tener control de error, que imprima el nombre y el tipo de error. Ejemplos: Divide(6,0) Divide(60,”hola”) Divide(True,5) ''' def Divide (x, y): try: res = x/y except ZeroDivisionError: print('Error en la division, se intenta dividir por cero') except TypeError: print('Se ingreso un tipo de dato no valido') else: print('El resultado es', res) Divide(6,0) Divide(60, 'hola') Divide(True,5)
2eabb4ed1a8c30bba46e341725b1b3cfb0609f0f
PatrickHuembeli/Adversarial-Domain-Adaptation-for-Identifying-Phase-Transitions
/Code/Gradient_Reverse_Layer.py
1,546
3.578125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Gradient Reversal Layer implementation for Keras Credits: https://github.com/michetonu/gradient_reversal_keras_tf/blob/master/flipGradientTF.py """ import tensorflow as tf from keras.engine import Layer import keras.backend as K def reverse_gradient(X, hp_lambda): '''Flips the sign of the incoming gradient during training.''' try: reverse_gradient.num_calls += 1 except AttributeError: reverse_gradient.num_calls = 1 grad_name = "GradientReversal%d" % reverse_gradient.num_calls @tf.RegisterGradient(grad_name) def _flip_gradients(op, grad): return [tf.negative(grad) * hp_lambda] g = K.get_session().graph with g.gradient_override_map({'Identity': grad_name}): y = tf.identity(X) return y class GradientReversal(Layer): '''Flip the sign of gradient during training.''' def __init__(self, hp_lambda, **kwargs): super(GradientReversal, self).__init__(**kwargs) self.supports_masking = False self.hp_lambda = hp_lambda def build(self, input_shape): self.trainable_weights = [] def call(self, x, mask=None): return reverse_gradient(x, self.hp_lambda) def get_output_shape_for(self, input_shape): return input_shape def get_config(self): config = {} base_config = super(GradientReversal, self).get_config() return dict(list(base_config.items()) + list(config.items()))
d75e266a89aceb34445a35e2fcf5a387e1fb5597
pooja-subramaniam/2018_day2
/pass.py
566
3.65625
4
def get_credentials(): username = input('Please type your user name: ') password = input('Please type your password') return username, password def authenticate(username, password, pwdb): if username in pwdb: if pwdb[username] == password: return True return False def add_user(username, password, pwdb): pwdb.update({username:password}) pwdb = {} username, password = get_credentials() add_user(username, password, pwdb) if authenticate(username, password, pwdb): print('Match!') else: print('Not a match!')
f14aafa44ed0f040b2638de7ca7ca0a47ebd1e50
valthalion/ohhi
/cp_solver.py
4,287
4.25
4
""" Solve a constraint programming problem """ def propagate_constraints(problem, constraints): """ Apply the constraint propagation functions in constraints to problem. Each constraint in constraints should update the values in the problem and return True if changes were made, False otherwise. Apply each constraint, and repeat until no changes are made in a full cycle. """ changes = True while changes: changes = any(constraint(problem) for constraint in constraints) def get_undecided_variable(problem): """ Return one variable that is still unset in the problem """ for variable, domain in problem['variables'].items(): if len(domain) > 1: # Undecided if more than 1 value possible return variable def fix_variable(problem, pivot, value): """ Return a new problem that is a copy of the one provided with the pivot variable set to value This function is used for branching, and prints the selection made. """ new_problem = problem.copy() new_problem['variables'] = problem['variables'].copy() new_problem['variables'][pivot] = value print(f'choosing: {pivot} {value}') return new_problem def solve(problem, constraints, evaluate_state): """ Solve a constraint programming problem Inputs: - problem: a dictionary containing the information for the problem to be solved. It may contain additional fields for use in the constraint propagation functions, or the state evaluation function (or for any other reason), but it must contain at least the following fields: * 'variables': a dictionary with the variables to be solved as keys; the corresponding value is the domain of the variable, an iterable with all currently feasible values for the variable. This function will assume that a variable is set (decided) if its domain is of length 1 * 'state': the state of the problem; typically at call time it will be 'unsolved'. It will be updated as appropriate to 'solved' or 'infeasible'. - constraints: an iterable containing the constraint propagation functions available to the CP solver. Each one must accept a problem dictionary and apply update the domains of all variables where the constraint allows inference; this may mean determining one value, or reducing the current domain by emoving some of its elements - evaluate_state: a function that takes a problem as input and determines whether the problem is still unsolved, in an incoherent state (infeasible) or solved, and updates its 'state' field accordingly. Returns: - the problem at the last stage in the solution process. The problem 'state' field will be set to 'solved' or 'infeasible' as adequate. """ # Recursively explore the solution space: # - Fill in inferrable variables (constraint propagation) # - If this fully solves the problem, or identifies # infeasibility, return the problem # - Otherwise select an undecided variable, try to solve the problem with # that variable set to one of its remaining feasible values, if it # doesn't succeed, iteratively try the other potential values for that # variable # This results in a depth-first search of the solution tree, with # aggressive pruning (both from the leaps obtained by constraint # propagation and by abandoning a branch as soon as infeasibility is # identified, even if not all values are set) propagate_constraints(problem, constraints) evaluate_state(problem) if problem['state'] in ('solved', 'infeasible'): return problem # select variable to branch on pivot = get_undecided_variable(problem) # recursion on each domain value feasible for the pivot domain = problem['variables'][pivot] for value in domain: new_problem = fix_variable(problem, pivot, value) candidate_sol = solve(new_problem, constraints, evaluate_state) if candidate_sol['state'] == 'solved': return candidate_sol # if this point is reached, the problem must be infeasible return candidate_sol
a6d806085cb9e990a86bb15ce0d40294ada9e8fd
yamatakudesu/enshu
/gittest/RI/main.py
559
3.578125
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from network import Net def main(): net = Net([784,100,50,10]) print("neurons: {}".format(net.neurons)) B, W, acc, count = net.update(noise=0) x = np.array([i for i in range(count)]) y = np.array([acc[i] for i in range(count)]) plt.plot(x,y) plt.xlabel("epoch") plt.ylim(50.0, 100.0) plt.ylabel("accuracy[%]") plt.title("neurons: {}".format(net.neurons)) plt.show() if __name__ == "__main__": main()
313002c94f71331f28457a740cdb35974802fac8
CSmel/pythonProjects
/item_program/item_program.py
1,762
4.34375
4
import retailitem def main(): # Get a list for the retail objects. info = make_list() # Display the data in the list. display_list(info) # The _list function will ask the user how many retail items need # to be entered. The function will then return a list of item objects # containing the data. def make_list(): # Create an empty list. retail_list = [] amount = int(input('How many items do you need to add to the list? ')) for count in range(amount): # Get information from user. print('----------') print('Item #' + str(count + 1) + ':') print('----------') descr = input('Enter item description: ') units = int(input('Enter the amount of unit(s): ')) _price = float(input('Enter the price of the unit: ')) print() # Creat a new RetailItem object and assign it to the # retail variable. retail = retailitem.RetailItem(descr, units, _price) # Add the object to the list. retail_list.append(retail) # Return the list. return retail_list # The display_list function accepts a list containing # RetailItem objects as an object and displays the data stored # in each object. def display_list(retail_list): print('These are the items that you added:') print('---------------------------------') for item in retail_list: print('Item description: ',item.get_item_descr(), sep='') print('Unit(s): ',item.get_units_inven(), sep='') print('Price: $', format(item.get_price(),',.2f'), sep='') print() # Call the main functio. main()
9503c8b88e4d91654b223be96d31c94901a0d6fe
cowerman/python
/fir_11_19/input.py
195
3.96875
4
print("------------------Please input---------------") tmp=input("waiting for input: ") tmp=int(tmp) if tmp == 8: print("entered 8\n") else: print("enter not 8\n"); liu="100" print(int(liu))
196b2e73adf91b2e5b4df165ac4531ce3c6302fa
kpatel010/CS116
/Assignment 3/unicode_encoding.py
1,061
3.875
4
def unicode_encoding(s): ''' Return the correct UTF-8 binary encoded string dependant on s unicode_encoding: Str -> Str Requires: 0 < len(s) < 21 S inputted into unicode_encoding will either be '0' or have a leftmost digit of '1' S can have either digits '1' or '0' Examples: unicode_encoding('101001') => '00101001' unicode_encoding('11101001') => '1100001110101001' ''' if len(s) == 7 or len(s) == 11 or len(s) == 16 or len(s) == 21: return s if len(s) < 7: return '0' * (8 - len(s)) + s elif 7 < len(s) < 11: return '110' + ('0' * (11 - len(s)) + s)[:5] + '10' \ + ('0' * (11 - len(s)) + s)[5:] elif 11 < len(s) < 16: return '1110' + ('0' * (16 - len(s)) + s)[:4] + '10' + \ ('0' * (16 - len(s)) + s)[4:10] + '10' + \ ('0' * (16 - len(s)) + s)[10:] else: return '11110' + ('0' * (21 - len(s)) + s)[:3] + '10' + \ ('0' * (21 - len(s)) + s)[3:9] + '10' + \ ('0' * (21 - len(s)) + s)[9:15] + '10'\ + ('0' * (21 - len(s)) + s)[15:]
c8df6e18279a635e033538a8374f302fc7e7a09c
thomas-kw/birthday_wisher
/main.py
3,162
4.28125
4
##################### Normal Starting Project ###################### MY_EMAIL = "[email protected]" MY_PASSWORD = "abcd1234" # 1. Update the birthdays.csv with your friends & family's details. # HINT: Make sure one of the entries matches today's date for testing purposes. e.g. #name,email,year,month,day #YourName,[email protected],today_year,today_month,today_day # 2. Check if today matches a birthday in the birthdays.csv # HINT 1: Create a tuple from today's month and day using datetime. e.g. # today = (today_month, today_day) import datetime as dt import pandas as pd import random import smtplib now = dt.datetime.now() today = (now.month, now.day) # HINT 2: Use pandas to read the birthdays.csv birthdays = pd.read_csv("birthdays.csv") # HINT 3: Use dictionary comprehension to create a dictionary from birthday.csv that is formatted like this: # birthdays_dict = { # (birthday_month, birthday_day): data_row # } birthday_dict = {(birthdays["month"], birthdays["day"]): (birthdays["name"], birthdays["email"]) for (index, birthdays) in birthdays.iterrows()} print(birthday_dict) #Dictionary comprehension template for pandas DataFrame looks like this: # new_dict = {new_key: new_value for (index, data_row) in data.iterrows()} #e.g. if the birthdays.csv looked like this: # name,email,year,month,day # Angela,[email protected],1995,12,24 #Then the birthdays_dict should look like this: # birthdays_dict = { # (12, 24): Angela,[email protected],1995,12,24 # } #HINT 4: Then you could compare and see if today's month/day tuple matches one of the keys in birthday_dict like this: # if (today_month, today_day) in birthdays_dict: if today in birthday_dict: print(today) # 3. If there is a match, pick a random letter (letter_1.txt/letter_2.txt/letter_3.txt) from letter_templates and replace the [NAME] with the person's actual name from birthdays.csv # HINT 1: Think about the relative file path to open each letter. # HINT 2: Use the random module to get a number between 1-3 to pick a random letter. # HINT 3: Use the replace() method to replace [NAME] with the actual name. https://www.w3schools.com/python/ref_string_replace.asp letter_list = ("letter_1.txt", "letter_2.txt", "letter_3.txt") letter_choice = random.choice(letter_list) with open(f"letter_templates/{letter_choice}") as letter: letter_str = letter.read() new_letter = letter_str.replace("[NAME]", f"{birthday_dict[today][0]}") print(new_letter) # 4. Send the letter generated in step 3 to that person's email address. # HINT 1: Gmail(smtp.gmail.com), Yahoo(smtp.mail.yahoo.com), Hotmail(smtp.live.com), Outlook(smtp-mail.outlook.com) # HINT 2: Remember to call .starttls() # HINT 3: Remember to login to your email service with email/password. Make sure your security setting is set to allow less secure apps. # HINT 4: The message should have the Subject: Happy Birthday then after \n\n The Message Body. with smtplib.SMTP("smtp.gmail.com") as connection: connection.starttls() connection.login(MY_EMAIL, MY_PASSWORD) connection.sendmail( from_addr=MY_EMAIL, to_addrs=birthday_dict[today][1], msg=f"Subject=Happy Birthday\n\n{new_letter}", )
802948f0da443583188ce1a30044cd8a51bb0532
DaliahAljutayli/PythonCode
/Convert Decimal to Binary, Octal and Hexadecimal/Python Program to Convert Decimal to Binary, Octal and Hexadecimal.py
810
4.28125
4
#By Daliah Aljutayli #Python Program to Convert Decimal to Binary, Octal and Hexadecimal #Help: geeksforgeeks.org #---------------------- def desTbin(Decimal): if Decimal>1: desTbin(Decimal//2) print(Decimal%2,end='') def desToct(Decimal): if Decimal>1: desToct(Decimal//8) print(Decimal%8,end='') def desThex(Decimal): if Decimal>1: desThex(Decimal//16) print(Decimal%16,end='') #------------------------------- Decimal = int (input('Enter a Decimal Number: ')) print('Using a Function:') desTbin(Decimal) print('\n') desToct(Decimal) print('\n') desThex(Decimal) print('\n-------------------\nUsing a built-in functions') print('Binary= ',bin(Decimal)) print('Octal= ',oct(Decimal)) print('Hexadecimal= ',hex(Decimal))
f4950a82185c0aea01d72623a8a1aa4afe6bc2ce
stromatolith/py_schule
/ex04_amoeba_economy/ae_00a_random_walk.py
3,880
4.21875
4
#! /usr/bin/env python """ Once we can create moving circles with pygame, we can use that to start working on simulations of populations of moving and interacting little things. Preliminaries, step A: Let's create one moving dot doing a random walk and make sure it doesn't leave the box. """ import numpy as np from numpy import pi, exp, sin, cos, sqrt from numpy import array, asfarray, zeros, zeros_like from numpy.random import rand import pygame as pg class Amoeb(object): def __init__(self,position,radius): self.x=asfarray(position) self.r=0.04 # scaling factor for random walk self.radius=radius self.color=(255,200,100) self.world=None def set_position(self,newpos): self.x[:]=newpos def get_position(self): return self.x def one_step(self): step = self.r * (2*rand(2)-1) # additional random change of position self.x += step distances = self.world.wall_distances(self.x) # now checking whether any of the distances is negative, which is a # sure sign of having breached the boundary # if that's the case then we let the wall act as a sort of mirror and # the latest step is being bent inwards if distances['left'] < 0: self.x[0] -= 2*step[0]; print 'pushed back' if distances['right'] < 0: self.x[0] -= 2*step[0]; print 'pushed back' if distances['top'] < 0: self.x[1] -= 2*step[1]; print 'pushed back' if distances['bottom'] < 0: self.x[1] -= 2*step[1]; print 'pushed back' def show_up(self): pg.draw.circle(self.world.canvas, self.color, self.world.to_canvas_coords(self.x), int(self.radius*100)) class World(object): def __init__(self): pg.init() self.BG_colour = (0,0,0) self.ww = 480 # window width self.wh = 360 # window height self.ox = self.ww/2 # x-coordinate of origin (of ohysics coordinate system inside canvas coordinate system) self.oy = self.wh/2 # y-coordinate of origin (of ohysics coordinate system inside canvas coordinate system) self.canvas = pg.display.set_mode((self.ww,self.wh)) self.canvas.fill(self.BG_colour) self.inhabitants=[] def to_canvas_coords(self,vec): x,y = vec canvx = self.ox + int(100*x) # one unit in the physics coordinate system is 100 pixels canvy = self.oy - int(100*y) # why the minus sign? --> in the pygame canvas the origin is in the upper left corner return canvx,canvy def wall_distances(self,pos): x,y = self.to_canvas_coords(pos) answer={} answer['left'] = 0.01*x answer['right'] = 0.01*(self.ww-x) answer['top'] = 0.01*y answer['bottom'] = 0.01*(self.wh-y) return answer def add_inhabitants(self,new): if type(new) == list: for candidate in new: candidate.world=self self.inhabitants += new # making the method robust, now you can dump several planets at a time else: self.inhabitants.append(new) # accepting a single planet new.world=self def draw_inhabitants(self): for thing in self.inhabitants: thing.show_up() def one_step(self): stop = False for event in pg.event.get(): if event.type == pg.QUIT or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE): stop = True for thing in self.inhabitants: thing.one_step() self.canvas.fill(self.BG_colour) self.draw_inhabitants() pg.display.flip() return stop w = World() dot = Amoeb([0,0],0.14) w.add_inhabitants(dot) stop_flag = False while not stop_flag: stop_flag = w.one_step()
fd881fb8b83ebc085d34b128a1b4857123e2c83e
Yashmistry11/InnovationPython_Yash
/NUMBERS AND VARIABLES.py
123
3.734375
4
X = 20 ; Y = 40.5; Z = "Yash Mistry" # print( X, Y, Z ) print("Hello, this is my first python file") x=10 y=20 print("x")
a1ed9725064fd91660022b1534097ea59450e67d
Mostofa-Najmus-Sakib/Applied-Algorithm
/Leetcode/Python Solutions/Strings/ReverseVowelsofAString.py
2,056
3.765625
4
""" LeetCode Problem: 345. Reverse Vowels of a String Link: https://leetcode.com/problems/reverse-vowels-of-a-string/ Language: Python Written by: Mostofa Adib Shakib Time complexity: O(n) Space Complexity: O(n) """ class Solution: def reverseVowels(self, s: str) -> str: length = len(s) # Calculates the length of the string vowels = "aeiouAEIOU" # A string that contains all the lower-cased and upper-cased vowels indexArray = [] # An array that stores the index of all the vowels in the input string # index is your current position in the string # The for loop traverses from the 0th position to the end of the string for index in range(length): character = s[index] if character in vowels: # This line only executes if the character is a vowel indexArray.append(index) # This appends the index of the vowel into the array # In order to swap characters we need to convert the string to an array s = list(s) # converts a string to an array # Remember that the index array contains the position of all the vowels # If there are atmost one vowel then we do not need to do anything # This while loop only executes if the length of the array is greater than one while len(indexArray) > 1: # This removes the first element from the indexArray array and assigns it to the variable startingPosition startingPosition = indexArray.pop(0) # This removes the last element from the indexArray array and assigns it to the variable endingPosition endingPosition = indexArray.pop() # This swaps the position of the two characters in the array s s[startingPosition], s[endingPosition] = s[endingPosition], s[startingPosition] return ''.join(s) # This converts a string to an array
61eb06fa13186485450fbf851cc67827be7d634c
ictcubeMENA/Training_one
/codewars/8kyu/doha22/kata8/posotive_negative/positive_negative.py
410
3.75
4
def count_positives_sum_negatives(arr): res_num = [0,0] if (arr == [] ): return [] for n in arr: if(n> 0 ): res_num[0] += 1 elif(n < 0): res_num[1] += n return res_num def count_positives_sum_negatives2(arr): pos = sum(1 for x in arr if x > 0) neg = sum(x for x in arr if x < 0) return [pos, neg] if len(arr) else []
5cd1af8789fd03566ea1896673eab1c9f8374518
WonyJeong/algorithm-study
/koalakid1/Math/bj-3009.py
415
3.5625
4
import sys input = sys.stdin.readline x = {} y = {} other_x = [] other_y = [] for i in range(3): _x, _y = map(int, input().strip().split()) if _x not in x: x[_x] = [i] other_x.append(_x) else: other_x.remove(_x) if _y not in y: y[_y] = [i] other_y.append(_y) else: y[_y].append(i) other_y.remove(_y) print(f"{other_x[0]} {other_y[0]}")
8566b6be101a8839b2bd0a127ddf61e1e791f3bc
ottomattas/py
/user-input.py
962
4.25
4
#!/usr/bin/env python """This is a simple user input function.""" __author__ = "Otto Mättas" __copyright__ = "Copyright 2021, The Python Problems" __license__ = "MIT" __version__ = "0.1" __maintainer__ = "Otto Mättas" __email__ = "[email protected]" __status__ = "Development" # DEFINE THE USER CHOICE INPUT FUNCTION def user_choice(): # DEFINE VARIABLES choice = ' ' within_range = False # KEEP ASKING FOR USER CHOICE INPUT while choice.isdigit() == False or within_range == False: choice = input('Please enter a number (0-10): ') # VALIDATE INPUT AS DIGIT if choice.isdigit() == False: print('Sorry, that is not a digit!') # VALIDATE INPUT RANGE if choice.isdigit() == True: if int(choice) in range(0,10): within_range = True else: within_range = False # RETURN THE USER CHOICE AS AN INT return int(choice)
c70942bb49117831530bc3ae8ddf3e6a45a69c56
anu-coder/Basics-of-Python
/scripts/L3Q48.py
195
3.875
4
''' Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included). ''' even = filter(lambda x: x%2==0, range(1,21)) print([i for i in even])
ca41df81c90979ec1bda8e1bd31daecc2ac7a19b
gcvalderrama/python_foundations
/atest/IntegertoEnglishWords.py
1,048
3.546875
4
def getHundred(y): sb = "" units = ["", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine ", "Ten ", "Eleven " , "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen "] tens = ["", "", "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety "] if y % 100 < 20: sb += units[y % 100] y = y // 100 else: sb += units[y % 10] y = y // 10 sb = tens[y % 10] + sb y = y // 10 if y > 0: sb = "Hundred " + sb sb = units[y] + sb return sb def numberToWords(num): if not num : return "Zero" nearest = ["", "", "", "Thousand ", "", "", "Million ", "", "", "Billion "] i = 0 n = num sb = "" while n > 0: y = n % 1000 n = n // 1000 if y > 0: sb = nearest[i] + sb sb = getHundred(y) + sb i += 3 return sb if __name__ == '__main__': print(numberToWords(12345))
c2626775f87d1ad7cde152a8748528fcb1f6605c
katger4/uwmediaspace
/add_bionote.py
3,006
3.515625
4
#!/usr/bin/env python import pickle # this python script takes in a list of resources from an ASpace repo, filters that list by a specified creator, then adds a biographical note or a historical note (from a text file) to each resource ############################################################ def load_pickled(filename): with open(filename, "rb") as fp: # Unpickling return pickle.load(fp) def open_txt(filename): with open(filename, "r") as f: text_list = ['<p>'+line.strip()+'</p>' for line in f if line != ''] text = ''.join(text_list) return text def write_pickle(item, filename): with open(filename, "wb") as fp: #Pickling pickle.dump(item, fp) ############################################################ # load text filename_t = input('enter the path to the text file containing the biographical/historical note (e.g. ./data/note.txt): ') content = open_txt(filename_t) print('Formatted note text to add:\n'+content) # # load resources filename_r = input('enter the path to the saved list of resources (e.g. ./data/resources.txt): ') resources = load_pickled(filename_r) creator_type = input('enter the type of creator to limit the resource list by (person or corporate): ') creator_id = input('enter the ASpace ID of the creator to limit the resource list by (just the numeric value - located at the end of the url for each agent on ASpace): ') if creator_type == 'person': agent_ref = '/agents/people/'+creator_id note_label = 'Biographical Note' elif creator_type == 'corporate': agent_ref = '/agents/corporate_entities/'+creator_id note_label = 'Historical Note' else: print('invalid creator type provided.') bioghist = {'jsonmodel_type': 'note_multipart', 'publish': False, 'label': note_label, 'subnotes': [{'content': content, 'jsonmodel_type': 'note_text', 'publish': False}], 'type': 'bioghist'} # limit resources by creator resources_to_edit = [i for i in resources if any(a.get('ref') == agent_ref and a.get('role') == 'creator' for a in i['linked_agents'])] updates = [] for i in resources_to_edit: # resources on AW will have an ARK ID if '[Insert ARK ID]' in i['ead_location']: # check for existing bioghist content if any(n.get('type') == 'bioghist' for n in i['notes']): proceed = input('the resource '+i['id_0']+': '+i['title']+' already has a biographical/historical note. do you want to overrwrite that note with new content? (y/n) ') if proceed == 'y': i['notes'] = [n for n in i['notes'] if n['type'] != 'bioghist'] i['notes'].append(bioghist) updates.append(i) if not any(n.get('type') == 'bioghist' for n in i['notes']): i['notes'].append(bioghist) updates.append(i) if updates != []: print('added biographical notes to '+str(len(updates))+' resources') output = input("enter the path and name of the data file to store your data file in (e.g. ./data/updates.txt): ") write_pickle(updates, output) print('data saved!') else: print('no data to save')