blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
96bc6a316a1b91b120a79da08ff05a42c87238e4
saiphaniedara/HackerRank_Python_Practice
/DateTime_DateTime.py
719
3.9375
4
''' Problem Statement: https://www.hackerrank.com/challenges/python-time-delta ''' #!/bin/python3 import math import os import random import re import sys import datetime import time # Complete the time_delta function below. def time_delta(t1, t2): timedelta = t2 - t1 return timedelta.days * 24 * 3600 + timedelta.seconds if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): t1 = input() t2 = input() date1 = datetime.strptime(t1) date2 = datetime.strptime(t2) delta = time_delta(date1, date2) fptr.write(delta + '\n') fptr.close()
24bcd74781be84169e4955ec115ad78a9fbe7125
jashymko/reversi
/minimax.py
2,501
3.5625
4
import random import copy INFINITY = float("inf") N_INFINITY = float("-inf") class Minimax: def best_move(self, game, depth): best_score = N_INFINITY best_moves = [] best_move = None turn = game.turn if game.find_moves(game.grid, turn): for move in game.find_moves(game.grid, turn): grid = game.move(move[0][0], move[0][1], copy.deepcopy(game.grid), turn) score = self.minimax(game, grid, turn, depth-1, False, N_INFINITY, INFINITY) if score > best_score: best_score = score best_moves = [move] elif score == best_score: best_moves.append(move) best_move = random.choice(best_moves) else: best_move = [[None, None], None] return best_move def random_move(self, game): moves = game.find_moves(game.grid, game.turn) if moves: move = random.choice(moves) else: move = [[None, None], [None, None]] return move def minimax(self, game, grid, turn, depth, maximizing, alpha, beta): current_turn = turn if not maximizing: current_turn = game.opp(turn) if depth == 0 or not game.find_moves(grid, current_turn): best_score = self.eval_grid(game, grid, turn) return best_score elif maximizing: best_score = N_INFINITY for move in game.find_moves(grid, current_turn): grid = game.move(move[0][0], move[0][1], grid, current_turn) score = self.minimax(game, copy.deepcopy(grid), turn, depth - 1, False, alpha, beta) best_score = max(best_score, score) alpha = max(alpha, score) if beta <= alpha: break return best_score else: best_score = INFINITY for move in game.find_moves(grid, current_turn): grid = game.move(move[0][0], move[0][1], grid, current_turn) score = self.minimax(game, copy.deepcopy(grid), turn, depth - 1, True, alpha, beta) best_score = min(best_score, score) beta = min(beta, score) if beta <= alpha: break return best_score def eval_grid(self, game, grid, turn): count = game.count_score(grid) score = count[turn] return score
2c66bd5186b288dc812c4bf0221ff63c9fd99921
mylessbennett/reinforcement_exercises_feb12
/exercise1.py
969
4.15625
4
drama = "Titanic" documentary = "March of the Penguins" comedy = "Step Brothers" dramedy = "Crazy, Stupid, Love" user_drama = input("Do you like dramas? (answer y/n) ") user_doc = input("Do you like documentaries? (answer y/n) ") user_comedy = input("Do you like comedies? (answer y/n) ") if user_drama == "y" and user_doc == "y" and user_comedy == "y": print("You might enjoy {}, {}, or {}".format(drama, documentary, comedy)) elif user_doc == "n" and user_drama == "y" and user_comedy == "y": print("You might enjoy {}".format(dramedy)) elif user_doc == "y" and user_drama != "y" and user_comedy != "y": print("You might enjoy {}".format(documentary)) elif user_comedy == "y" and user_doc != "y" and user_drama != "y": print("You might enjoy {}".format(comedy)) elif user_drama == "y" and user_doc != "y" and user_comedy != "y": print("You might enjoy {}".format(drama)) else: print("You might want to try a good book instead!")
42fc4b50c35076c5be55b9d6ffe3fbb0e3da7715
daniel-reich/ubiquitous-fiesta
/TDrfRh63jMCmqzGjv_5.py
118
3.71875
4
def is_anti_list(lst1, lst2): return len(set(lst1+lst2))==2 and all([lst1[i]!=lst2[i] for i in range(len(lst1))])
81a85a9820b366becff4342d3bda4c8b7fd1e4f4
nwthomas/code-challenges
/src/leetcode/medium/longest-increasing-subsequence/longest_increasing_subsequence.py
1,128
4.09375
4
""" https://leetcode.com/problems/longest-increasing-subsequence/ Given an integer array nums, return the length of the longest strictly increasing subsequence. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7]. Example 1: Input: nums = [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. Example 2: Input: nums = [0,1,0,3,2,3] Output: 4 Example 3: Input: nums = [7,7,7,7,7,7,7] Output: 1 Constraints: 1 <= nums.length <= 2500 -104 <= nums[i] <= 104 """ from typing import List def get_longest_increasing_subsequence(nums: List[int]) -> int: if type(nums) != list: raise TypeError('Argument must be of type list') tracker = [1] * len(nums) for i in range(len(nums) - 2, -1, -1): for j in range(i + 1, len(nums)): if nums[i] < nums[j]: tracker[i] = max(tracker[i], tracker[j] + 1) return max(tracker)
268ca157a1823db01cef037177b4281f4d740757
rnsilveira22/Cursos-Python
/capitulo 03/exercicio/cap3/exercicio/exercicio3.10.py
442
3.734375
4
""" Faça um programa que calcule o aumento de salário. Ele deve solicitar o valor do salário e a porcetagem do aumento. Exiba o valor do aumento e o novo salário. """ salario = float(input('Qual o valor do salário? ')) aumento = int(input("Qual a porcetagem de aumento? ")) novoSalario = salario +(salario*(aumento/100)) print("-"*30+"\n" "O aumento foi de %d %% \n" "Novo salário é: R$ %7.2f" %(aumento, novoSalario))
21240ced9cb85ba65f0164d16d96a2eb751959d8
wtmatthias/learn-python-the-hard-way
/ex08.py
385
3.640625
4
#ex8.py formatter = "{} {} {} {}" print(formatter .format(1, 2, 3, 4)) print(formatter .format("one", "two", "three", "four")) print(formatter .format(True, False, False, True)) print(formatter .format(formatter, formatter, formatter, formatter)) print(formatter .format( "I'm trying my own", "text right here", "in an attempt to learn", "the '.format' function." ))
384823629ea04c8ecbfffa7af0ea0b97172abb3d
Yuchen112211/Leetcode
/problem402.py
2,014
3.71875
4
''' 402. Remove K Digits Medium Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible. Note: The length of num is less than 10002 and will be ≥ k. The given num does not contain any leading zero. Example 1: Input: num = "1432219", k = 3 Output: "1219" Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. Example 2: Input: num = "10200", k = 1 Output: "200" Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. Example 3: Input: num = "10", k = 2 Output: "0" Explanation: Remove all the digits from the number and it is left with nothing which is 0. Solution: My original solution is to go over the whole list k times, for each time we find out the biggest number from the beginning, we select the biggest number each time, after k time, the remaining should be the smallest number possibile. It is very slow, may be optimized. ''' ''' class Solution(object): def removeKdigits(self, num, k): if not num: return '0' if k >= len(num): return '0' while k > 0: maxIndex = 0 for i in range(1,len(num)): if num[i] < num[i - 1]: maxIndex = i - 1 break if i == len(num) - 1: maxIndex = i num = num[:maxIndex] + num[maxIndex + 1:] k -= 1 zeroIndex = 0 for i in range(len(num)): if num[i] == '0': zeroIndex += 1 else: break num = num[zeroIndex:] if not num: return "0" return num ''' class Solution(object): def removeKdigits(self, num, k): if k >= len(num): return '0' num = [l for l in num] while k > 0: flag = True for i in range(len(num)-1): if str(num[i]) > str(num[i+1]): num.pop(i) k, flag = k - 1, False break if flag == True and num[i+1] == num[-1]: num.pop(i+1) k -= 1 return str(int(''.join(num))) s = Solution() num = "1432219" k = 3 print s.removeKdigits(num, k)
c53d5e61f69ce928e4fc606f7f631b6122c244c1
udayreddy026/pdemo_Python
/Vijay_Sir/15-04-2021/LocalVariables_GlobalVariabale.py
243
3.59375
4
a = 10 # Global Variable class A: def m1(self): b = 20 # Local Variable 'b' c = 30 # Local Variable 'c' print(b) print(c) print(a) def m2(self): print(a) a1 = A() a1.m2() a1.m1()
902430998e383f64950a770965ab3dafa325d8ec
lizzzcai/leetcode
/python/math/0382_Linked_List_Random_Node.py
2,481
3.828125
4
''' 08/02/2020 382. Linked List Random Node - Medium Tag: Reservoir Sampling Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen. Follow up: What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space? Example: // Init a singly linked list [1,2,3]. ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(3); Solution solution = new Solution(head); // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. solution.getRandom(); ''' from typing import List # Solution from random import randrange # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def __init__(self, head: ListNode): """ @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. """ self.head = head def getRandom(self) -> int: """ Returns a random node's value. """ ''' Revervoir Sampling Prove: https://www.youtube.com/watch?v=Ybra0uGEkpM https://www.cnblogs.com/python27/p/Reservoir_Sampling_Algorithm.html https://leetcode.com/problems/linked-list-random-node/discuss/85659/Brief-explanation-for-Reservoir-Sampling 1/i * (1 - 1/(i+1)) * (1 - 1/(i+2)) * ... * (1 - 1/n) = 1/i * i/(i+1) * (i+1)/(i+2) * ... * (n-1)/n = 1/n ''' p = self.head i, res = 0, None while p: i += 1 if randrange(1, i+1) == i: res = p.val p = p.next return res # Your Solution object will be instantiated and called as such: # obj = Solution(head) # param_1 = obj.getRandom() # Unit Test import unittest class TestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_testCase(self): head = ListNode(1) head.next = ListNode(2) head.next.next = ListNode(3) # Your Solution object will be instantiated and called as such: obj = Solution(head) param_1 = obj.getRandom() self.assertIn(param_1, [0,1,2]) if __name__ == '__main__': unittest.main()
61bb7c7f3de7a0fea82bf38d4bbb58c68fed2955
jamesclyeh/pysimiam
/scripts/simobject.py
4,228
3.625
4
from math import sin, cos import pylygon from pose import Pose class SimObject: """The base class for creating drawn objects in the simulator. Posses both a Pose object and a color""" def __init__(self, pose, color = 0): self.set_color(color) self.set_pose(pose) def get_color(self): """gets the color""" return self.__color def set_color(self, color): """sets the color""" self.__color = color def get_pose(self): """Returns the pose of the object in world coordinates """ return self.__pose def set_pose(self,pose): """Returns the pose of the object in world coordinates """ self.__world_envelope = None self.__pose = pose def draw(self,dc): """Draws the object on the passed DC """ pass def get_envelope(self): """The envelope of the object in object's local coordinates """ ## At the moment the proposed format is a list of points pass def get_world_envelope(self, recalculate=False): """gets the envelop for checking collision""" if self.__world_envelope is None or recalculate: x,y,t = self.get_pose() self.__world_envelope = [(x+p[0]*cos(t)-p[1]*sin(t), y+p[0]*sin(t)+p[1]*cos(t)) for p in self.get_envelope()] return self.__world_envelope def get_bounding_rect(self): """Get the smallest rectangle that contains the object Returns a tuple (x,y,width,height) """ xmin, ymin, xmax, ymax = self.get_bounds() return (xmin,ymin,xmax-xmin,ymax-ymin) def has_collision(self, other): """Check if the object has collided with other. Return True or False""" self_poly = pylygon.Polygon(self.get_world_envelope()) other_poly = pylygon.Polygon(other.get_world_envelope()) # TODO: use distance() for performance #print "Dist:", self_poly.distance(other_poly) collision = self_poly.collidepoly(other_poly) if isinstance(collision, bool): if not collision: return False # Test code - print out collisions #print "Collision between {} and {}".format(self, other) # end of test code return True def get_contact_points(self, other): """Get a list of contact points with other object Retrun a list of (x, y)""" self_poly = pylygon.Polygon(self.get_world_envelope()) other_poly = pylygon.Polygon(other.get_world_envelope()) return self_poly.intersection_points(other_poly) def get_bounds(self): """Get the smallest rectangle that contains the object. Returns a tuple (xmin,ymin,xmax,ymax)""" xs, ys = zip(*self.get_world_envelope()) return (min(xs), min(ys), max(xs), max(ys)) class Polygon(SimObject): """The polygon simobject is used to draw objects in the world""" def __init__(self, pose, shape, color): SimObject.__init__(self,pose, color) self.__shape = shape def get_envelope(self): return self.__shape def draw(self,r): r.set_pose(self.get_pose()) r.set_brush(self.get_color()) r.draw_polygon(self.get_envelope()) class Path(SimObject): """The path is used to track the history of robot motion""" def __init__(self,start,color): SimObject.__init__(self, Pose(), color) self.points = [(start.x,start.y)] def reset(self,start): """sets teh start point to start.x and start.y""" self.points = [(start.x,start.y)] def add_point(self,pose): """adds a point to the chain of lines""" self.points.append((pose.x,pose.y)) def draw(self,r): """draw the polyline from the line list""" r.set_pose(self.get_pose()) # Reset everything r.set_pen(self.get_color()) for i in range(1,len(self.points)): x1,y1 = self.points[i-1] x2,y2 = self.points[i] r.draw_line(x1,y1,x2,y2)
0497f25737de25b80bfaf2554050bb9e92b965fa
KevinAS28/Python-Training
/latihana.py
105
3.6875
4
#!/usr/bin/python x = 4 y = 2 if not 1+1 == y or x == 4 and 7 == 8: print 'yes' elif x > y: print 'no'
9751179e4d04152566e140ac4c24f65ab97e3ec4
lvandijk/Portfolio_Prog_AntoonvandenBosch.py
/Practice exercises/Practice Exercises 5/Practice Exercise 5_4.py
791
3.59375
4
# Bij een marathonwedstrijd worden bij een controlepost alle voorbijkomende hardlopers genoteerd. # De gegevens van elke hardloper worden in het bestand hardlopers.txt opgeslagen. Schrijf een # programma waarmee een tekstbestand wordt aangemaakt (als het bestand nog niet bestaat) of # aangevuld (gebruik de append-mode) met de gegevens van één hardloper (inlezen van toetsenbord). import datetime def toevoegen(hardloper): hardlopers = open('hardlopers.txt', 'a') vandaag = datetime.datetime.today() addition = vandaag.strftime("%a %d %b %Y, %H:%M:%S") hardlopers.write('\n') hardlopers.write(addition) hardlopers.write(', ') hardlopers.write(hardloper) hardlopers.close() toevoeginput = input('Geef de naam van de hardloper: ') toevoegen(toevoeginput)
588d5c0f3820a02d1c09645ea9de7550bab2eb4d
mathankrish/Infy-Programs
/InfyTq Basic Programming/Day3/Day3Ass28.py
593
4.09375
4
# Maximum of two numbers with the conditions def find_max(num1, num2): max_num=-1 num_list = [] if(num1 < num2): if((num1 + num2) % 3 == 0 and len(str(num1)) == 2 and len(str(num2)) == 2 and num1 % 5 == 0 and num2 % 5 == 0): num_list.append(num1) num_list.append(num2) max_num = max(num1, num2) elif(num_list is []): return max_num else: return max_num return max_num #Provide different values for num1 and num2 and test your program. max_num=find_max(15,45) print(max_num)
ef66a9f3de5219a10f8ef9b2116e4f023e9f03fb
eamt/holbertonschool-higher_level_programming
/0x0B-python-input_output/3-to_json_string.py
331
3.96875
4
#!/usr/bin/python3 """Module for a to_json_string function""" import json def to_json_string(my_obj): """Returns the JSON repr of an object Args: my_obj (class object): the object to converto to JSON string Returns: The JSON string representation of the object """ return json.dumps(my_obj)
c90f3993d287e31fd38bc90078d66b9e8dc2198d
ashwinids/python
/learning_scripts/rotated_version.py
304
4.125
4
#!/usr/bin/env python def rotate(): if len(array1) != len(array2): return False for i in range(len(array1)): c= array1[-i:] + array1[:-i] print c if array2 == c: return True return False array1=[1,2,3,5,6,7,8] array2=[5,6,7,8,1,2,3] rotate() print rotate()
bc5d3b76dd8462dc2c9d363f99956797ade53e55
fsgtrshhs/store
/5.py
244
3.625
4
tard = input('请输入成绩') tard = int(tard) if tard >= 90: print('A') if tard < 90 and tard >=80: print('B') if tard <80 and tard >=70: print('C') if tard <70 and tard >=60: print('D') if tard <60: print('E')
30186e69172f89b7ada9be5dbf12a1668f554c39
filizlin/IntroToProg-Python
/Assignment05/ToDoList.py
4,339
3.84375
4
# ------------------------------------------------------------------------ # # Title: Assignment 05_ToDoList # Description: Working with Dictionaries and Files # When the program starts, load each "row" of data # in "ToDoToDoList.txt" into a python Dictionary. # Add the each dictionary "row" to a python list "table" # ChangeLog (Who,When,What): # RRoot,1.1.2030,Created started script # <YLin>,<11.17.2020>,Added code to complete assignment 5 # ------------------------------------------------------------------------ # # -- Data -- # # declare variables and constants objFile = "ToDoList.txt" # An object that represents a file strData = "" # A row of text data from the file dicRow = {} # A row of data separated into elements of a dictionary {Task,Priority} lstTable = [] # A list that acts as a 'table' of rows strMenu = "" # A menu of user options strChoice = "" # A Capture the user option selection # -- Processing -- # # Step 1 - When the program starts, load the any data you have # in a text file called ToDoList.txt into a python list of dictionaries rows (like Lab 5-2) try: objFile=open("ToDoList.txt", "r") objFile.read(lstTable) for row in lstTable: strData = row.split(",") dicRow = {"Task": strData[0].strip, "Priority": strData[1].strip()} lstTable.append(dicRow) except: print("There is no data in this file yet. Please proceed with the menu to input data.") # -- Input/Output -- # # Step 2 - Display a menu of choices to the user while (True): print(""" Menu of Options 1) Show current data 2) Add a new item. 3) Remove an existing item. 4) Save Data to File 5) Exit Program """) strChoice = str(input("Which option would you like to perform? [1 to 5] - ")) print() # adding a new line for looks # Step 3 - Show the current items in the table if (strChoice.strip() == '1'): if len(lstTable) == 0: print("Currently, there is no Data in the ToDoList.txt File") else: for row in lstTable: print (row["Task"] + '\t' + row["Priority"]) continue # Step 4 - Add a new item to the list/Table elif (strChoice.strip() == '2'): strTask = input("Type in a Task: ") strPriority = input("Indicate its Priority (High/Medium/Low): ") print("Adding", strTask, strPriority, "to Table", sep=" ") dicRow = {"Task": strTask.strip(), "Priority" : strPriority.strip()} lstTable.append(dicRow) continue # Step 5 - Remove a new item from the list/Table elif (strChoice.strip() == '3'): strDelete = input("Which task would you like to delete from the To-Do list? ") for row in lstTable: if strDelete.strip().lower() in row["Task"].strip().lower(): #try see if can do remove task and priority strConfirmDelete = input("Are you sure you would like to delete the task " + strDelete + " from the file? [Y/N] ") if strConfirmDelete.lower() == 'y': lstTable.remove(row) print("The task" + strDelete + "has been removed from the file.") else: print("The task" + strDelete + "was not removed from the file.") else: print("The task entered does not exist in this row.") continue # Step 6 - Save tasks to the ToDoToDoList.txt file elif (strChoice.strip() == '4'): strResponse = input("Would you like to save your Data? [Y/N] ") if strResponse.lower().strip() == 'y': objFile = open("ToDoList.txt", "w") for row in lstTable: objFile.write(row["Task"] + "," + row["Priority"] + "\n") objFile.close() else: print("The data entered was not saved.") # Step 7 - Exit program elif (strChoice.strip() == '5'): strConfirmExit = input("Are you sure you want to exit the program? [Y/N] ") if strConfirmExit.lower().strip() == 'y': break else: continue # and Exit the program else: print("Invalid entry, please enter a number between 1-5.")
85d3b0cab53c9161a442bd55e96c4e6d6ddbdc3d
subbul/python
/listOps.py
585
4.53125
5
#example to show various list operations daysOfWeek = ["Tuesday","Wednesday"] print "Initial List ", daysOfWeek daysOfWeek.append('Thursday') print "Appended list", daysOfWeek daysOfWeek.insert(0,'Monday') print "Inserted list ", daysOfWeek daysOfWeek.extend(['Friday','saturday','sunday']) print "Extended list", daysOfWeek daysOfWeek.append('TempDay') print "New list", daysOfWeek print "Position of Wednesday in a week",daysOfWeek.index('Wednesday') daysOfWeek.remove('TempDay') print "Clean list", daysOfWeek print "Poping saturday",daysOfWeek.pop(5) print daysOfWeek
701d5d6ff97fc3e195f29cb044dbcccfc548b467
ttheikki2/Usadel-for-nanowires
/src/frange.py
589
3.96875
4
import sys def frange(start, end=None, inc=None): "A range function, that does accept floats" if end == None: end = start + 0.0 start = 0.0 else: start += 0.0 # force it to be a float if inc == None: inc = 1.0 count = int((end - start) / inc) if start + count * inc != end + inc: count += 1 L = [None,] * count for i in xrange(count): L[i] = start + i * inc return L start = float(sys.argv[1]) end = float(sys.argv[2]) inc = float(sys.argv[3]) for item in frange(start, end, inc): print("%.2f" % item)
5556da5e6f28c17234a436dc25591f0fff37955c
CelsoSimoes/CS50_Harvard_Course
/Aula_2_Flask/aplicacoes_rotas.py
855
4.125
4
from flask import Flask #Importacao padrao para executar um aplicacao web com Flask app = Flask(__name__) #Cria a variavel que sera a raiz da aplicacao que estamos criando @app.route("/") #Cria uma rota para minha aplicacao Web, no caso a rota principal so com o '/' def index(): return "Ola Mundo!!!" #Rotas comuns com enderecos pre-setados #Cria a segunda rota da minha aplicacao web, '/celso' @app.route("/celso") def celso(): return "Ola Celso!" #Terceira rota @app.route("/maria") def maria(): return "Ola Mariaaaa!" #Este e um exemplo de aplicacao web dinamica #Estas linhas de codigo criam sites nao pre-setados, para qualquer nome que o usuario venha a digitar na barra de enderecos @app.route("/<string:name>") def ola(name): name = name.capitalize() #Ira tornar a primeira letra do nome maiuscula return f"Ola, {name}!"
1c14f23d8e88a955cb14d67a5492506e80aafcd4
jnaneshjain/PythonProjects
/pythonoperators.py
209
3.984375
4
#This file demonstrates the python math operators import math print(10 / 3) print(10 // 3) print(10 ** 3) x = 10 x += 10 print(x) x = 2.9 print(math.ceil(x)) print(math.floor(x)) print(round(x)) #End of file
c116181996c1af5f150cbb1037654089e2099808
KarmanyaT28/Python-Code-Yourself
/27_dictionary.py
1,853
4.4375
4
# is an unordered collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, myDict = { "Fast": " In a quick manner", "TalkPy" : "A community", "Marks":[1,2,3,4], "AnotherDict": {'karmanya': 'Coder'}, 3:7 } # A collection of key-value pairs. # print(myDict['Fast']) # print(myDict['TalkPy']) # print(myDict['Marks']) print(myDict['AnotherDict']['karmanya']) # Properties '''1. It is unordered 2. It is mutable 3. It is indexed 4. Cannot contain duplicate keys''' #MUTABLE myDict['Marks'] = [26,38,48] print(myDict['Marks']) #methods print(myDict.keys()) #Prints the keys of the dictionary print(myDict.values()) #Prints the values of keys of the dictionary print(myDict.items()) # Prints the (key,value) for all contents in the dictionary print(myDict) updateDict = { "Lovish" : "Friend", "Divya":"Friend", "Shubah":"Best Friend", "Karan" : "Normal friend" } myDict.update(updateDict) # Updates the dictionary by adding key-value pairs from updateDict print(myDict) print(myDict.get("Karan")) #Prints value associated with key "Karan" print(myDict["Karan"]) #Also prints the value associated with key "Karan" print(myDict.get("kjkf")) # Returns none as kjkf is not present in the dictionary # print(myDict["kjkf"]) # throws an error as kjkf is not present in the dictionary print("Some checking done-----------------------------------------------------------") NewDict = {"All":"good","All":"dheuhd"} print(NewDict) print(NewDict["All"]) print(NewDict.get("All")) #Only prints the new value of the key. # This shows that a dictionary cannot contains same keys in it. It will update the value of that key if used in future. print(type(myDict))
369bccd1699853c2af817fab9884c6ef921a42e0
andreinaoliveira/Exercicios-Python
/Exercicios/002 - Respondendo ao Usuário.py
240
4.0625
4
# Exercício Python 002 - Respondendo ao Usuário # Faça um programa que leia o nome de uma pessoa e mostre uma mensagem de boas-vindas. nome = str(input("Informe seu nome: ")) print("É um prazer de conhecer, {}!".format(nome))
40a3833c0446576530da06f9b28b0c112ebc3534
donsheehy/geomcps
/trajectories/point.py
684
3.625
4
import math # A point in time. class Point: def __init__(self, coords, time = 0): self.coords = coords self.t = time def eq_degree(self, other): return len(self) == len(other) def dist_sq(self, other): return sum((a-b)**2 for a,b in zip(self, other)) def dist(self, other): return math.sqrt(self.dist_sq(other)) def time(self): return self.t def __len__(self): return len(self.coords) def __iter__(self): return iter(self.coords) def __getitem__(self, item): return self.coords[item] def __str__(self): return "(" + str(self.t) + " " + str(self.coords) + ")"
066eaf5928f55c67f714a3a132442fdf77fc63ff
keras-team/autokeras
/docs/py/structured_data_classification.py
7,316
3.625
4
"""shell pip install autokeras """ import pandas as pd import tensorflow as tf import autokeras as ak """ ## A Simple Example The first step is to prepare your data. Here we use the [Titanic dataset](https://www.kaggle.com/c/titanic) as an example. """ TRAIN_DATA_URL = "https://storage.googleapis.com/tf-datasets/titanic/train.csv" TEST_DATA_URL = "https://storage.googleapis.com/tf-datasets/titanic/eval.csv" train_file_path = tf.keras.utils.get_file("train.csv", TRAIN_DATA_URL) test_file_path = tf.keras.utils.get_file("eval.csv", TEST_DATA_URL) """ The second step is to run the [StructuredDataClassifier](/structured_data_classifier). As a quick demo, we set epochs to 10. You can also leave the epochs unspecified for an adaptive number of epochs. """ # Initialize the structured data classifier. clf = ak.StructuredDataClassifier( overwrite=True, max_trials=3 ) # It tries 3 different models. # Feed the structured data classifier with training data. clf.fit( # The path to the train.csv file. train_file_path, # The name of the label column. "survived", epochs=10, ) # Predict with the best model. predicted_y = clf.predict(test_file_path) # Evaluate the best model with testing data. print(clf.evaluate(test_file_path, "survived")) """ ## Data Format The AutoKeras StructuredDataClassifier is quite flexible for the data format. The example above shows how to use the CSV files directly. Besides CSV files, it also supports numpy.ndarray, pandas.DataFrame or [tf.data.Dataset]( https://www.tensorflow.org/api_docs/python/tf/data/Dataset?version=stable). The data should be two-dimensional with numerical or categorical values. For the classification labels, AutoKeras accepts both plain labels, i.e. strings or integers, and one-hot encoded encoded labels, i.e. vectors of 0s and 1s. The labels can be numpy.ndarray, pandas.DataFrame, or pandas.Series. The following examples show how the data can be prepared with numpy.ndarray, pandas.DataFrame, and tensorflow.data.Dataset. """ # x_train as pandas.DataFrame, y_train as pandas.Series x_train = pd.read_csv(train_file_path) print(type(x_train)) # pandas.DataFrame y_train = x_train.pop("survived") print(type(y_train)) # pandas.Series # You can also use pandas.DataFrame for y_train. y_train = pd.DataFrame(y_train) print(type(y_train)) # pandas.DataFrame # You can also use numpy.ndarray for x_train and y_train. x_train = x_train.to_numpy() y_train = y_train.to_numpy() print(type(x_train)) # numpy.ndarray print(type(y_train)) # numpy.ndarray # Preparing testing data. x_test = pd.read_csv(test_file_path) y_test = x_test.pop("survived") # It tries 10 different models. clf = ak.StructuredDataClassifier(overwrite=True, max_trials=3) # Feed the structured data classifier with training data. clf.fit(x_train, y_train, epochs=10) # Predict with the best model. predicted_y = clf.predict(x_test) # Evaluate the best model with testing data. print(clf.evaluate(x_test, y_test)) """ The following code shows how to convert numpy.ndarray to tf.data.Dataset. """ train_set = tf.data.Dataset.from_tensor_slices((x_train.astype(str), y_train)) test_set = tf.data.Dataset.from_tensor_slices( (x_test.to_numpy().astype(str), y_test) ) clf = ak.StructuredDataClassifier(overwrite=True, max_trials=3) # Feed the tensorflow Dataset to the classifier. clf.fit(train_set, epochs=10) # Predict with the best model. predicted_y = clf.predict(test_set) # Evaluate the best model with testing data. print(clf.evaluate(test_set)) """ You can also specify the column names and types for the data as follows. The `column_names` is optional if the training data already have the column names, e.g. pandas.DataFrame, CSV file. Any column, whose type is not specified will be inferred from the training data. """ # Initialize the structured data classifier. clf = ak.StructuredDataClassifier( column_names=[ "sex", "age", "n_siblings_spouses", "parch", "fare", "class", "deck", "embark_town", "alone", ], column_types={"sex": "categorical", "fare": "numerical"}, max_trials=10, # It tries 10 different models. overwrite=True, ) """ ## Validation Data By default, AutoKeras use the last 20% of training data as validation data. As shown in the example below, you can use `validation_split` to specify the percentage. """ clf.fit( x_train, y_train, # Split the training data and use the last 15% as validation data. validation_split=0.15, epochs=10, ) """ You can also use your own validation set instead of splitting it from the training data with `validation_data`. """ split = 500 x_val = x_train[split:] y_val = y_train[split:] x_train = x_train[:split] y_train = y_train[:split] clf.fit( x_train, y_train, # Use your own validation set. validation_data=(x_val, y_val), epochs=10, ) """ ## Customized Search Space For advanced users, you may customize your search space by using [AutoModel](/auto_model/#automodel-class) instead of [StructuredDataClassifier](/structured_data_classifier). You can configure the [StructuredDataBlock](/block/#structureddatablock-class) for some high-level configurations, e.g., `categorical_encoding` for whether to use the [CategoricalToNumerical](/block/#categoricaltonumerical-class). You can also do not specify these arguments, which would leave the different choices to be tuned automatically. See the following example for detail. """ input_node = ak.StructuredDataInput() output_node = ak.StructuredDataBlock(categorical_encoding=True)(input_node) output_node = ak.ClassificationHead()(output_node) clf = ak.AutoModel( inputs=input_node, outputs=output_node, overwrite=True, max_trials=3 ) clf.fit(x_train, y_train, epochs=10) """ The usage of [AutoModel](/auto_model/#automodel-class) is similar to the [functional API](https://www.tensorflow.org/guide/keras/functional) of Keras. Basically, you are building a graph, whose edges are blocks and the nodes are intermediate outputs of blocks. To add an edge from `input_node` to `output_node` with `output_node = ak.[some_block]([block_args])(input_node)`. You can even also use more fine grained blocks to customize the search space even further. See the following example. """ input_node = ak.StructuredDataInput() output_node = ak.CategoricalToNumerical()(input_node) output_node = ak.DenseBlock()(output_node) output_node = ak.ClassificationHead()(output_node) clf = ak.AutoModel( inputs=input_node, outputs=output_node, overwrite=True, max_trials=1 ) clf.fit(x_train, y_train, epochs=1) clf.predict(x_train) """ You can also export the best model found by AutoKeras as a Keras Model. """ model = clf.export_model() model.summary() print(x_train.dtype) # numpy array in object (mixed type) is not supported. # convert it to unicode. model.predict(x_train.astype(str)) """ ## Reference [StructuredDataClassifier](/structured_data_classifier), [AutoModel](/auto_model/#automodel-class), [StructuredDataBlock](/block/#structureddatablock-class), [DenseBlock](/block/#denseblock-class), [StructuredDataInput](/node/#structureddatainput-class), [ClassificationHead](/block/#classificationhead-class), [CategoricalToNumerical](/block/#categoricaltonumerical-class). """
64b74aba77630f13ce182a07b2c32401c452dde2
jsmundi/TechDevGoogle
/subSeq.py
1,060
4.09375
4
''' Given a string S and a set of words D, find the longest word in D that is a subsequence of S. Word W is a subsequence of S if some number of characters, possibly zero, can be deleted from S to form W, without reordering the remaining characters. Note: D can appear in any format (list, hash table, prefix tree, etc. For example, given the input of S = "abppplee" and D = {"able", "ale", "apple", "bale", "kangaroo"} the correct output would be "apple" The words "able" and "ale" are both subsequences of S, but they are shorter than "apple". The word "bale" is not a subsequence of S because even though S has all the right letters, they are not in the right order. The word "kangaroo" is the longest word in D, but it isn't a subsequence of S. ''' S = "abpplee" D = {"able", "ale", "apple", "bale", "kangaroo"} charS = list(S) listD = list(D) dAns = {} count = 0 for x in listD: charD = list(x) count = 0 for a in charS: if a in charD: count = count + 1 else: break dAns[x] = count result = max(dAns, key=dAns.get) print(result)
e62474eea068cca82e63a7b194414cbd6920242c
Nigirimeshi/leetcode
/0114_flatten-binary-tree-to-linked-list.py
1,787
4.09375
4
""" 二叉树展开为链表 链接:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list 给你二叉树的根结点 root ,请你将它展开为一个单链表: 展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 null 。 展开后的单链表应该与二叉树 先序遍历 顺序相同。 示例 1: 输入:root = [1,2,5,3,4,null,6] 输出:[1,null,2,null,3,null,4,null,5,null,6] 示例 2: 输入:root = [] 输出:[] 示例 3: 输入:root = [0] 输出:[0] 提示: 树中结点数在范围 [0, 2000] 内 -100 <= Node.val <= 100 解法: 1. 前序遍历。 二叉树展开为单链表后,单链表中节点的顺序与前序遍历相同。 因此先前序遍历,再更新每个节点的左右子节点即可。 时间复杂度:O(N) 空间复杂度:O(N) """ import unittest from typing import List, Union from structure.tree import TreeNode class Solution: def flatten(self, root: TreeNode) -> None: # 存放前序遍历后的各节点。 preorder_list: List[TreeNode] = [] # 前序遍历。 self.preorder(root, preorder_list) n = len(preorder_list) for i in range(1, n): prev, curr = preorder_list[i - 1], preorder_list[i] prev.left = None prev.right = curr def preorder(self, root: TreeNode, preorder_list: List[TreeNode]) -> None: if not root: return preorder_list.append(root) self.preorder(root.left, preorder_list) self.preorder(root.right, preorder_list) class TestSolution(unittest.TestCase): def setUp(self) -> None: self.s = Solution() if __name__ == "__main__": unittest.main()
f42c58ec96b0527235c7126617fa5ae05c249e77
william-lin7/softdev
/fall/08_app0/flaskapp.py
671
3.59375
4
#William Lin #SoftDev1 pd2 #demo -- My First Flask App #2019-09-18 from flask import Flask app = Flask(__name__) #create instance of class Flask @app.route("/") #assign following fxn to run when root route requested def hello_world(): print(__name__) #where will this go? return "No hablo queso!" @app.route("/cooldude") def cooldude(): print(__name__) return "You're a cool dude!!" @app.route("/pizzadog") def pizzadog(): print(__name__) return "Come here pizza dog!" @app.route("/milkbeforecereal") def milkbeforecereal(): print(__name__) return "Milk comes before cereal!" if __name__ == "__main__": app.debug = True app.run()
bf684b834d512129b7e912d1422d05607a20d8ad
erdyneevzt/stepik_algorithms
/Introduction/evklid_1.py
746
3.765625
4
# По данным двум числам 1≤a,b≤ 2⋅10**9 найдите их наибольший общий делитель. # def gcd(a, b): # if a != 0 and b !=0: # if a > b: # a = a % b # return gcd(a,b) # else: # b = b % a # return gcd(a,b) # else: # if a == 0: # return b # else: # return a # Решение из форума def gcd(a, b): return gcd(b, a % b) if b else a # Более читаемый вариант # def gcd(a, b): # if b == 0: # return a # # return gcd(b, a % b) def main(): a, b = map(int, input().split()) print(gcd(a, b)) if __name__ == "__main__": main()
08dd93536a93a09f0b1d7bfd517cf41ebb941f9a
singulared/fields
/tests.py
2,120
3.78125
4
import unittest from fields import Field, euclid_extended class IntegerTest(unittest.TestCase): def setUp(self): Field.prime = 9 def test_add(self): a = Field(7) b = Field(2) self.assertEqual((a + b).value, 0) self.assertEqual((a + 1).value, 8) self.assertEqual((a + 2).value, 0) self.assertEqual((a + 3).value, 1) self.assertEqual((a + Field.prime).value, a.value) self.assertEqual((0 + b).value, b.value) self.assertEqual((3 + b).value, 5) self.assertEqual((8 + b).value, 1) def test_mul(self): a = Field(7) b = Field(2) self.assertEqual((a * b).value, 5) self.assertEqual((a * 1).value, a.value) self.assertEqual((a * 2).value, 5) self.assertEqual((a * 0).value, 0) self.assertEqual((0 * b).value, 0) self.assertEqual((3 * b).value, 6) self.assertEqual((8 * b).value, 7) def test_sub(self): a = Field(7) b = Field(2) self.assertEqual((a - b).value, 5) self.assertEqual((a - 0).value, a.value) self.assertEqual((a - 1).value, 6) self.assertEqual((a - 8).value, 8) self.assertEqual((0 - b).value, 7) self.assertEqual((3 - b).value, 1) self.assertEqual((8 - b).value, 6) def test_neg(self): a = Field(7) self.assertEqual((-a).value, 2) def test_abs(self): a = Field(-7) self.assertEqual(abs(a), 2) def test_eq(self): a = Field(7) b = Field(2) c = Field(5) self.assertEqual(a, b + c) self.assertEqual(a, a) self.assertNotEqual(a, b) self.assertNotEqual(a, 7) def test_euclid_extended(self): a = Field(20, 23) b = Field(8, 23) self.assertEqual(euclid_extended(a, b)[2].value, 4) self.assertEqual(euclid_extended(a, 0)[2], a) def test_inverse(self): a = Field(7, 23) self.assertEqual(a.inverse().value, 10) self.assertEqual((a.inverse() * 7).value, 1) if __name__ == '__main__': unittest.main()
20e95410baef0be81e81aaaf88de18a137871a11
coxas/CAPP30254
/hw1/hw1_part2.py
5,104
3.953125
4
# Alyssa Cox # Machine Learning # Homework 1, part 2 from hw1 import get_df import requests import pandas as pd import json from urllib.request import urlopen Buildings_df = get_df("Buildings.csv", "DATE SERVICE REQUEST WAS RECEIVED") Buildings_daterow = 3 Sanitation_df = get_df("Sanitation.csv", "Creation Date") Sanitation_daterow = 1 latest_date = 20170401 def to_integer(dt_time): ''' Turns a datetime object into an integer. Inputs: dt_time, a datetime object Outputs: int ''' return 10000 * dt_time.year + 100 * dt_time.month + dt_time.day def truncate_df(df, date_column_name, date_column_no, months, latest_date): ''' Truncates a given dataframe to only include data from dates in a given timeframe. Inputs: df: the dataframe date_column_name: the name of the column in the dataframe that holds the dates date_column_no: the number of the column in the dataframe that holds the dates months: how many months back from the starting date the new df should include latest_date: starting date to calculate months back Outputs: dataframe ''' df.sort(date_column_name, ascending=False) new_df = [] for row in df.itertuples(): date_int = to_integer(row[date_column_no]) time_frame = latest_date - (months * 100) if date_int > time_frame: new_df.append(row[0]) length = len(new_df) return df[-length:-1] def get_request(url): ''' Open a connection to the specified URL and if successful read the data. Inputs: url: must be an absolute URL Outputs: request object or None ''' try: r = requests.get(url) if r.status_code == 404 or r.status_code == 403: r = None except: # fail on error r = None return r def get_loc(lat, long): ''' Retrieves a FIPS location object for a given latitude and longitude. Inputs: lat: latitude long: longitude Outputs: string of numbers ''' FIPS_url = 'http://data.fcc.gov/api/block/find?format=json&latitude={}&longitude={}&showall=true'.format(lat,long) response = urlopen(FIPS_url) FIPS = response.read().decode("utf-8") FIPS = json.loads(FIPS) return FIPS['Block']['FIPS'] def get_locs_for_df(df): ''' Breaks down the FIPS location into state, county, tract, and block, and uses these to make specific API calls. Gather data from API calls. Appends new data in new columns on the original dataframe. Inputs: df: original dataframe Outputs: augmented dataframe ''' # initialize lists pop_white_list = [] stemdegrees_list = [] disabilities_list = [] count = 0 # iterate through dataframe to get FIPS info and break it down for row in df.itertuples(): lat = row[21] long = row[22] loc = get_loc(lat, long) state = loc[0:2] county = loc[2:5] tract = loc[5:11] block = loc[11] #make API calls population_request = get_request('http://api.census.gov/data/2013/acs5?get=NAME,B02001_001E&for=block+group:' + block + '&in=state:' + state + '+county:' + county + '+tract:' + tract + '&key=f584b1ef67466bf282be1268df5a899b2c114192') population_white_request = get_request('http://api.census.gov/data/2013/acs5?get=NAME,B02001_002E&for=block+group:' + block + '&in=state:'+state+'+county:'+county+'+tract:'+tract+'&key=f584b1ef67466bf282be1268df5a899b2c114192') stemdegrees_request = get_request('http://api.census.gov/data/2013/acs5?get=NAME,C15010_002E&for=block+group:' + block + '&in=state:' + state + '+county:'+ county + '+tract:' + tract + '&key=f584b1ef67466bf282be1268df5a899b2c114192') disabilities_request = get_request('http://api.census.gov/data/2013/acs5?get=NAME,C18108_001E&for=block+group:' + block + '&in=state:' + state + '+county:'+ county + '+tract:' + tract + '&key=f584b1ef67466bf282be1268df5a899b2c114192') population_white = population_white_request.json()[1][1] stemdegrees = stemdegrees_request.json()[1][1] disabilities = disabilities_request.json()[1][1] total_pop = population_request.json()[1][1] pop_white = int(population_white) pop_stem = int(stemdegrees) pop_tot = int(total_pop) if pop_tot != 0: pop_white_list.append(pop_white/pop_tot) stemdegrees_list.append(pop_stem/pop_tot) else: pop_white_list.append(0) stemdegrees_list.append(0) disabilities_list.append(disabilities) count += 1 print(count) new_df = pd.concat([df, pd.DataFrame(columns=list('w'), data=pop_white_list, index=df.index)], axis=1) new_df2 = pd.concat([new_df, pd.DataFrame(columns=list('s'), data=stemdegrees_list, index=df.index)], axis=1) new_df3 = pd.concat([new_df2, pd.DataFrame(columns=list('d'), data=disabilities_list, index=df.index)], axis=1) return new_df3
636283345b70a27eab773a9ffd3dbd0a340694a7
prachi464/Python-assignment
/PYTHONTRAINNING/modul7/car.py
215
3.640625
4
class Car: def __init__(self,color,mileage): self.color=color self.mileage=mileage print(color,mileage) def __str__(self): return f'a{self.color}car' c=Car('red',123)
12c7b5cee58b8ff2c1d84eba79a09686d8d5dd11
kannankandasamy/GeneralPrograms
/ChessBoardCellColor.py
610
4.03125
4
""" Given two cells on the standard chess board, determine whether they have the same color or not. Example For cell1 = "A1" and cell2 = "C3", the output should be chessBoardCellColor(cell1, cell2) = true. For cell1 = "A1" and cell2 = "H3", the output should be chessBoardCellColor(cell1, cell2) = false. """ def chessBoardCellColor(cell1, cell2): def get_color(c1): boxes = "#ABCDEFGH" i,i1 = boxes.index(c1[0])%2, int(c1[1])%2 retval = "Black" if ((i==1 and i1==1) or (i==0 and i1==0) ) else "White" return retval return get_color(cell1)==get_color(cell2)
a6d17423349d39d8cb81294ddaec0d149072863f
adrian4b/py
/print_test.py
114
3.65625
4
name = "my name is Adrian and my name is Adrian and gata" print(name.split()) print('This is a {} from '.format('test'))
a6ffe770a3eb518f3b2a890a96827baf95b7a112
gravypod/GradeO
/examples/labs/hw001_jk369.py
258
3.53125
4
""" HW001 Joshua Katz 12/14/2015 An example homework file. """ QUESTIONS_1 = "A" QUESTIONS_2 = "B" QUESTIONS_3 = "C" QUESTIONS_4 = "D" QUESTIONS_5 = "A" def multiply_by_four(number): return number * 4.1 def multiply_by_two(number): return number * 2
0279e62b0c2ecafe4b503e29dbaacb9fd28560a1
vegeta008/FundamentosP
/Ejercicio3.py
415
3.90625
4
#3.Realice un programa que obtenga el índice de masa corporal de una persona, ingresando la estatura en centímetros y el peso en kilos. # -*- coding: utf-8 -*- """ @author: aorozco@dragonjar.org """ var_ingresarestatura = int(input("tu estatura :")) var_ingresarpeso = int(input("Cual es tu peso :")) masa_corporal = var_ingresarpeso / var_ingresarestatura**2 print("Tu masa corporal es de :", masa_corporal )
14a7c64c730e86f2c8b8863918e830bb26d185ff
qinggeouye/ProjectEuler
/pro29.py
187
3.578125
4
def distinct_powers(k, s): ans = set(a**b for a in range(2, k+1) for b in range(2, s+1)) return str(len(ans)) if __name__ == "__main__": print(distinct_powers(100, 100))
e7f7e418ce79ab37f62bb040bcb1088df294536d
Ali-Mahmood/Leetcode
/Easy/1.twosum.py
945
3.90625
4
# Given an array of integers, return indices of the two numbers such that they add up to a specific target. # # You may assume that each input would have exactly one solution, and you may not use the same element twice. # # Example: # # Given nums = [2, 7, 11, 15], target = 9, # # Because nums[0] + nums[1] = 2 + 7 = 9, # return [0, 1] from typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: numIndex = {} for index, number in enumerate(nums): # assigning an index to each number in nums using enumerate if target - number in numIndex: # minus the number from the target and check if the remainder in numIndex return [numIndex[target - number], index] numIndex[number] = index # add number to numIndex if it isnt in there already solution = Solution() print(solution.twoSum([2, 11, 7, 10], 9)) print(solution.twoSum([3, 3], 6))
017cc0c2fad5dcccdc3bc70a66c0bbdc03f44e18
KatieButler/Final-Project
/cleaning_data.py
5,812
4.3125
4
# a program to sort the data needed for the map # and then put the usable data into a new csv file import pandas as pd import numpy as np import csv def panda_to_list(file_name, title1): """ The opens a saved csv file and convert it to a panda file. The panda file is separated into columns and the columns are made into lists. The lists are the output of the funciton. """ datafile = pd.read_csv(file_name) #opens a data file # puts the data in a column for col in datafile.columns: datafile[col] = datafile[col].astype(str) column1 = datafile[title1] # creates a list from column data in the csv list1 = [] for col_value in column1: list1.append(col_value) return list1 def college_coords(name): """ returns the latitude and longitude depending of the list of colleges determined by the input variable "name". The variable name is a list of the name of colleges in a file matching to assault data (a dataset that does not contain college coordinates). The purpose of this function is to match a college to it's coordinates by comparing two datasets. The ouput of this function can then be put into a csv file for later use. """ # lists from college we have case data for size = panda_to_list('Private_oncampus.csv', 'Institution Size') case1 = panda_to_list('Private_oncampus.csv', 'Sex offenses - Forcible') case2 = panda_to_list('Private_oncampus.csv', 'Sex offenses - Non-forcible') # lists from college we have coordinates for names_with_coords = panda_to_list('hd2014.csv', 'INSTNM') lat = panda_to_list('hd2014.csv', 'LATITUDE') lon = panda_to_list('hd2014.csv', 'LONGITUD') state = panda_to_list('hd2014.csv', 'STABBR') # initializes empty lists lons = [] lats = [] coords_list = [] no_coords = [] sizes = [] cases1 = [] cases2 = [] cases3 = [] states = [] # Sorts between the two data lists by checking if the names of # the colleges match (if college1 == college2). If the names of the # colleges match, that college can be matched with a latitude # and longitude. for college1 in name: for college2 in names_with_coords: if college1 == college2: index2 = names_with_coords.index(college2) index1 = name.index(college1) lons.append(float(lon[index2])) lats.append(float(lat[index2])) states.append((state[index2])) sizes.append(float(size[index1])) cases1.append(float(case1[index1])) cases2.append(float(case2[index1])) cases3.append(float(case2[index1])+float(case1[index1])) coords_list.append(college1) # makes a list of colleges still wihtout coordinates if college1 not in coords_list: no_coords.append(college1) return [coords_list, lons, lats, sizes, cases1, cases2, cases3, states, no_coords] def non_zero_sorting(return_what): """ returns a list of information about the college used in basemap. This program is meant to separate the colleges by the number they reported (either zero, 'nan', or nonzero). """ college_info = college_coords(panda_to_list('Public_public.csv', 'Institution name')) name = college_info[0] lons = college_info[1] lats = college_info[2] size = college_info[3] unsorted_list = college_info[4] # initialize empty lists for nonzero numbers nonzero_college = [] nonzero_size = [] nonzero_num = [] nonzero_lats = [] nonzero_lons = [] nonzero_state = [] # initialize empty lists for zero numbers zero_college = [] zero_size = [] zero_num = [] zero_lats = [] zero_lons = [] zero_states = [] # separates the unsorted list according to zero versus nonzero for i in range(len(unsorted_list)): if unsorted_list[i] == 0.0 or unsorted_list[i] == 'nan': zero_college.append(name[i]) zero_size.append(float(size[i])) zero_num.append(float(0)) zero_lats.append(float(lats[i])) zero_lons.append(float(lons[i])) elif unsorted_list[i] > 0: nonzero_college.append(name[i]) nonzero_size.append(float(size[i])) nonzero_num.append(float(unsorted_list[i])) nonzero_lats.append(float(lats[i])) nonzero_lons.append(float(lons[i])) if return_what == 'nonzero': return [nonzero_college, nonzero_lons, nonzero_lats, nonzero_size, nonzero_num] elif return_what == 'zero': return [zero_college, zero_lons, zero_lats, zero_size, zero_num] # calls lists that will later be added to the csv info = college_coords(panda_to_list('Private_oncampus.csv', 'Institution name')) c_name = info[0] c_lons = info[1] c_lats = info[2] c_size = info[3] c_case1 = info[4] c_case2 = info[5] c_case3 = info[6] c_state = info[7] no_c = info[8] # creates the percent list percent_list = [] for i in range(len(c_size)): try: percentage = (float(c_case3[i])/float(c_size3[i]))*10000 percent_list.append(float(percentage)) except: percent_list.append(0.0) # creating columns in the csv file my_df = pd.DataFrame({'name' : c_name, 'size' : c_size, 'lats' : c_lats, 'lons' : c_lons, 'Forible' : c_case1, 'Non-forcible' : c_case2, 'Combined' : c_case3, 'state' : c_state, 'perc' : percent_list}) # creates the csv, with its name my_df.to_csv('private_oncampus_nonforcible_forcible.csv', index=False)
be885f8fa8e5c6c36b0914077dd2d1f86ac2d1d6
OhMesch/Algorithm-Problems
/299-Bulls-and-Cows.py
1,076
3.6875
4
# Problem: Given a secret number, and a guess at the secret number # Return: The number of correct digits in the right spot, A's # And: The number of correct digits in an incorreect spot, B's class Solution(object): def getHint(self, secret, guess): """ :type secret: str :type guess: str :rtype: str """ counter = {} A = B = 0 for elm in secret: if elm in counter: counter[elm] +=1 else: counter[elm]=1 for i in range(len(secret)): if secret[i] == guess[i]: A+= 1 if counter[secret[i]] > 0: counter[secret[i]]-=1 else: B-=1 elif guess[i] in secret and counter[guess[i]] > 0: counter[guess[i]] -=1 B+=1 return("%dA%dB" % (A,B)) driver = Solution() t1,g1 = "1807","7810" t2,g2 = "1123","0111" t3,g3 = "1122","1222" print('Number and Guess:',t1,g1,'Program vs Expected sol:\n',driver.getHint(t1,g1),'\n 1A3B\n') print('Number and Guess:',t2,g2,'Program vs Expected sol:\n',driver.getHint(t2,g2),'\n 1A1B\n') print('Number and Guess:',t3,g3,'Program vs Expected sol:\n',driver.getHint(t3,g3),'\n 3A0B\n')
cc0fb054a346fdacdaba8230bd9b786aadf178f2
AdulIT/Week_2
/trenirovochnoe_1_hod_king.py
195
3.625
4
column1 = int(input()) ceil1 = int(input()) column2 = int(input()) ceil2 = int(input()) if abs(column1 - column2) <= 1 and abs(ceil1 - ceil2) <= 1: print('YES') else: print('NO')
d1e157f948380bb0b0d3ceb5b69258a369e1ddc1
craigpauga/Data-Structure-and-Algorithms
/1. Algorithm Toolbox/week2_algorithmic_warmup/4_least_common_multiple/least.py
440
3.71875
4
# Uses python3 import math import sys def gcd(a, b): current_gcd = 1 if b == 0: return a else: a_prime = a%b a = gcd(b,a_prime) return a def lcm(a, b): greatcd = gcd(a,b) top = a * b ans = int(top//greatcd) #ans = int(int((a*b)) // int(gcd(a,b))) return ans if __name__ == '__main__': input = sys.stdin.read() a, b = map(int, input.split()) print(lcm(a, b))
85dd5c189b49327b3ae9df4deb8a6fc3795db0bb
sid2364/HowRandomCanIBe
/numberToColumn.py
833
4.09375
4
''' Converts a number to it's column name, like in Excel. For e.g.:- 1 -> A 2 -> B 27 -> AA ''' from string import ascii_lowercase as al alpha_dict = {x:i for i, x in enumerate(al, 1)} num_dict = {} for key, value in alpha_dict.items(): num_dict[value] = key def calculateColumnName(n): string = [] while n > 0: rem = n % 26 if rem == 0: string.append('z') n = (n/26)-1 else: string.append(chr((rem-1) + ord('A'))) n = n/26 string = string[::-1] print(''.join(string).upper()) calculateColumnName(5899) # HRW calculateColumnName(5899999) # LWQUA calculateColumnName(2) # B calculateColumnName(2500) calculateColumnName(13) # M calculateColumnName(96) # CR calculateColumnName(2800) # DCR calculateColumnName(27) # AA
0e732195a1b5a3aa2ef15be15418771999e5ce0b
kor0p/IoTLab1Algorithms
/main.py
1,888
3.609375
4
from time import time class Ship: def __init__(self, tonnage=0, name="NoName", numOfPassengers=0): self.tonnage = int(tonnage) self.name = name self.numOfPassengers = int(numOfPassengers) def __repr__(self): return f'\n{self.tonnage}, {self.name}, {self.numOfPassengers}' with open("input.txt") as file: ships = [Ship(*line.split(',')) for line in file.readlines()] A = ships[:] i = 1 permutations = 0 comparings = 0 start_time = time() for i in range(1, len(A)): j = i comparings += 1 while j > 0 and A[j-1].tonnage > A[j].tonnage: A[j], A[j-1] = A[j-1], A[j] j -= 1 permutations += 1 comparings += 1 print(f"Insertion sort\ntime: {time()-start_time},\npermutations: {permutations},\ncomparings: {comparings},\nres:{A}.\n\n") def mergeSort(alist, p=0, c=0): if len(alist)>1: mid = len(alist)//2 lefthalf = alist[:mid] righthalf = alist[mid:] p, c = mergeSort(lefthalf, p, c) p, c = mergeSort(righthalf, p, c) # merging i=0 j=0 k=0 while i < len(lefthalf) and j < len(righthalf): c += 1 p += 1 if lefthalf[i].numOfPassengers >= righthalf[j].numOfPassengers: alist[k]=lefthalf[i] i += 1 else: alist[k]=righthalf[j] j += 1 k += 1 while i < len(lefthalf): p += 1 alist[k]=lefthalf[i] i += 1 k += 1 while j < len(righthalf): p += 1 alist[k]=righthalf[j] j += 1 k += 1 return p, c A = ships[:] start_time = time() permutations, comparings = mergeSort(A) print(f"Merge sort\ntime: {time()-start_time},\npermutations: {permutations},\ncomparings: {comparings},\nres:{A}.\n")
52458ec1be4f5b7166334100be46a8c1b27dab74
ehdgua01/Algorithms
/data_structures/queue/linear_queue/linear_queue.py
845
4.03125
4
class LinearQueue(object): def __init__(self, capacity: int): self.capacity = capacity self.front = 0 self.rear = 0 self.queue = [None] * capacity def put(self, value) -> None: if self.is_full: """앞에 공간이 남아있지만, 후단이 맨 뒤에 위치해 있으므로 오류 발생""" raise OverflowError("Overflow") self.queue[self.rear] = value self.rear += 1 def get(self): if self.is_empty: raise Exception("Underflow") value = self.queue[self.front] self.front += 1 return value @property def is_empty(self) -> bool: return self.front == self.rear @property def is_full(self) -> bool: return False if self.is_empty else self.rear == self.capacity
d21c8f06261a2bb9a003a6db1d63eeb7ea12fbb9
anyasd123/isc-work
/Tuples.py
699
3.953125
4
#An immutable and heterogenous sequence #Dont need parantheses if context is enough #Item is temporary variable that takes on value in loop until loop is complete colours = ['yellow', 'magenta', 'lavender'] left, middle, right = colours print left, middle, right pairs = [(1, 10), (2, 20), (3, 30), (4, 40)] for (low, high) in pairs: print low + high #Exercise 1 t = (1,) print t[-1] tulip = range(100, 201) tup = tuple(tulip) print tup [0], tup [-1] #Exercise 2 mylist = [23, "hi", 2.4e-10] for (count, item) in enumerate(mylist): print count, item #Exercise 3 first, middle, last = mylist print first, middle, last (first, middle, last) = (middle, last, first) print middle, last, first
9c49a850c350ce11934e2a51c91bbde880630f29
TorchAI/reclib
/reclib/data/instance.py
1,772
3.859375
4
from typing import Dict, MutableMapping, Mapping from reclib.data.fields.field import Field class Instance(Mapping[str, Field]): """ An ``Instance`` is a collection of :class:`~reclib.data.fields.field.Field` objects, specifying the inputs and outputs to some model. We don't make a distinction between inputs and outputs here, though - all operations are done on all fields, and when we return arrays, we return them as dictionaries keyed by field name. A model can then decide which fields it wants to use as inputs as which as outputs. Parameters ---------- fields : ``Dict[str, Field]`` The ``Field`` objects that will be used to produce data arrays for this instance. """ def __init__(self, fields: MutableMapping[str, Field]) -> None: self.fields = fields self.indexed = False # Add methods for ``Mapping``. Note, even though the fields are # mutable, we don't implement ``MutableMapping`` because we want # you to use ``add_field`` and supply a vocabulary. def __getitem__(self, key: str) -> Field: return self.fields[key] def __iter__(self): return iter(self.fields) def __len__(self) -> int: return len(self.fields) def add_field(self, field_name: str, field: Field) -> None: """ Add the field to the existing fields mapping. If we have already indexed the Instance, then we also index `field`, so it is necessary to supply the vocab. """ self.fields[field_name] = field def __str__(self) -> str: base_string = f"Instance with fields:\n" return " ".join( [base_string] + [f"\t {name}: {field} \n" for name, field in self.fields.items()] )
433b0cac602815affb402c02bf507ae3e5b5f3aa
ugaliguy/Data-Structures-and-Algorithms
/Algorithmic-Toolbox/majority_element/majority_element.py
756
3.53125
4
# Uses python3 import sys def get_majority_element(a, left, right): # if left == right: # return -1 # if left + 1 == right: # return a[left] #write your code here maj = a[0] count = 1 for num in a: if num == maj: count += 1 elif count == 0: maj = num count = 1 else: count -= 1 maj_count = 0 for i in range(len(a)): if a[i] == maj: maj_count += 1 if maj_count > n//2: return maj else: return -1 if __name__ == '__main__': input = sys.stdin.read() n, *a = list(map(int, input.split())) if get_majority_element(a, 0, n) != -1: print(1) else: print(0)
32ee2cfad58f92923eee423403000ad53475b459
kolesnikandrei/observatory
/python/Lessons/lec4/t_method.py
1,558
3.859375
4
# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod class Unit(metaclass=ABCMeta): def __init__(self, speed): self._speed = speed def hit_and_run(self): """ Шаблонный метод """ self._move('вперед') self._stop() self._attack() self._move('назад') @abstractmethod def _attack(self): pass @abstractmethod def _stop(self): pass def _move(self, direction): """ Передвижение - у всех отрядов одинаковое, в шаблон не входит :param direction: направление движения """ self._output('движется {} со скоростью {}'.format(direction, self._speed)) def _output(self, message): print('Отряд типа {} {}'.format(self.__class__.__name__, message)) class Archers(Unit): def _attack(self): self._output('обстреливает врага') def _stop(self): self._output('останавливается в 100 шагах от врага') class CavaleryMen(Unit): def _attack(self): self._output('на полном скаку врезается во вражеский строй') def _stop(self): self._output('летит вперед, не останавливаясь') if __name__ == '__main__': archers = Archers(4) archers.hit_and_run() cavalery_men = CavaleryMen(8) cavalery_men.hit_and_run()
c033d07c861d48ce4e1b913a0063f8ff9f5749d7
mariannamarch/B-pack
/17122018/17122018.py
132
3.671875
4
import random a = ['abc', 1, 2, 3, 'def'] x = random.choice(a) print(x) for _ in range(10): print(random.randint(5, 8))
7fa596220a70f5ea648d7c98a8d8088a3c615901
cminahan/CPE101
/LAB6/filter_tests.py
1,455
3.703125
4
# Lab 6: Polynomial Functions Test # Section: CPE101-03 # Name: Claire Minahan # Instructor: S. Einakian import unittest from filter import* class TestCases(unittest.TestCase): # do not delete this part use this to comapre two list def assertListAlmostEqual(self, l1, l2): self.assertEqual(len(l1), len(l2)) for el1, el2 in zip(l1, l2): self.assertAlmostEqual(el1, el2) #returns a list of all even values in the input list def test_are_even(self): self.assertAlmostEqual(are_even([3, 5, 2, 6, 8]), [2, 6, 8]) self.assertAlmostEqual(are_even([18, 3, 7, 26]), [18, 26]) self.assertAlmostEqual(are_even([4, 6, 7, 90]), [4, 6, 90]) #returns a a list with no duplicates def test_remove_duplicates(self): self.assertAlmostEqual(remove_duplicates([3, 4, 2, 5, 2, 1]), [3, 4, 2, 5, 1]) self.assertAlmostEqual(remove_duplicates([1, 1, 1, 1, 4, 2, 1]), [1, 4, 2]) self.assertAlmostEqual(remove_duplicates([2.3, 4.2, 3.5, 4.2, 7]), [2.3, 4.2, 3.5, 7]) #returns list of all input values divisable by n def test_divisable_by_n(self): self.assertAlmostEqual(are_divisable_by_n([3, 7, 9, 12], 3), [3, 9, 12]) self.assertAlmostEqual(are_divisable_by_n([7, 30, 49, 20, 1], 7), [7, 49]) self.assertAlmostEqual(are_divisable_by_n([12, 16, 7, 23], 4), [12, 16]) if __name__ == '__main__': unittest.main()
2b3df1d92a0f75e7c481d9ea6d2c48840ecbc3c1
toasterbob/python
/Fundamentals1/Functions/function_exercises.py
7,237
3.984375
4
def difference(a: int, b: int) -> int: return a - b difference(2,2) # 0 difference(0,2) # -2 def product(a, b): return a * b product(2,2) # 4 product(0,2) # 0 def print_day(a: int): if a < 1 or a > 7: return None days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] return days[a - 1] print_day(4) # "Wednesday" print_day(41) # None #theirs def print_day(n): try: return ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][n - 1] except IndexError as e: return None print_day(4) # "Wednesday" print_day(41) # None def last_element(arr): try: return arr[-1] except IndexError as e: return None last_element([1,2,3,4]) # 4 last_element([]) # None def number_compare(a, b): if a > b: return "First is greater" elif a < b: return "Second is greater" else: return "Numbers are equal" number_compare(1,1) # "Numbers are equal" number_compare(1,2) # "Second is greater" number_compare(2,1) # "First is greater" # theirs has no else def number_compare(a,b): if a > b: return "First is greater" elif b > a: return "Second is greater" return "Numbers are equal" def single_letter_count(word, letter): return word.lower().count(letter.lower()) single_letter_count('amazing','A') # 2 def multiple_letter_count(word): return { char: word.count(char) for char in word } multiple_letter_count("hello") # {h:1, e: 1, l: 2, o:1} multiple_letter_count("person") # {p:1, e: 1, r: 1, s:1, o:1, n:1} def list_manipulation(list, command, location, value = None): if command == "remove": if location == "end": return list.pop() elif location == "beginning": return list.pop(0) elif command == "add": print('hi') if location == "end": list.append(value) return list elif location == "beginning": list.insert(0, value) return list list_manipulation([1,2,3], "remove", "end") # 3 list_manipulation([1,2,3], "remove", "beginning") # 1 list_manipulation([1,2,3], "add", "beginning", 20) # [20,1,2,3] list_manipulation([1,2,3], "add", "end", 30) # [1,2,3,30] # theirs def list_manipulation(collection, command, location, value=None): if(command == "remove" and location == "end"): return collection.pop() elif(command == "remove" and location == "beginning"): return collection.pop(0) elif(command == "add" and location == "beginning"): collection.insert(0,value) return collection elif(command == "add" and location == "end"): collection.append(value) return collection def is_palindrome(word): word = word.replace(" ", "") # remove whitespace return word.lower() == word.lower()[::-1] is_palindrome('testing') # False is_palindrome('tacocat') # True is_palindrome('hannah') # True is_palindrome('robert') # False is_palindrome('a man a plan a canal Panama') # True def frequency(list, item): return list.count(item) frequency([1,2,3,4,4,4], 4) # 3 frequency([True, False, True, True], False) # 1 def flip_case(string, case): result = [letter.swapcase() if letter.lower() == case.lower() else letter for letter in string] return "".join(result) flip_case("Hardy har har", "h") # "hardy Har Har" #theirs def flip_case(string, letter): return "".join([char.swapcase() if char.lower() == letter.lower() else char for char in string]) def multiply_even_numbers(list): result = 1 for num in list: if num % 2 == 0: result *= num return result multiply_even_numbers([2,3,4,5,6]) # 48 #theirs def multiply_even_numbers(list): # you can import reduce from the functools module if you would like total = 1 for val in list: if val % 2 == 0: total = total * val return total def mode(list): high = 0 val = None dictionary = {num: list.count(num) for num in list} print(dictionary) for k,v in dictionary.items(): if v > high: high = v val = k return val mode([2,4,1,2,3,3,4,4,5,4,4,6,4,6,7,4]) # 4 def mode(nums): dictionary = {num: nums.count(num) for num in nums} max_value = max(dictionary.values()) idx = list(dictionary.values()).index(max_value) return list(dictionary.keys())[idx] mode([2,4,1,2,3,3,4,4,5,4,4,6,4,6,7,4]) # 4 #theirs def mode(collection): # you can import mode from statistics to cheat # you can import Counter from collections to make this easier # or we can just solve it :) count = {val: collection.count(val) for val in collection} # find the highest value (the most frequent number) max_value = max(count.values()) # now we need to see at which index the highest value is at correct_index = list(count.values()).index(max_value) # finally, return the correct key for the correct index (we have to convert cou) return list(count.keys())[correct_index] def capitalize(string): result = "" for idx, char in enumerate(string): if idx == 0: result += char.upper() else: result += char return result capitalize("tim") # "Tim" capitalize("matt") # "Matt" def capitalize(string): return string[:1].upper() + string[1:] capitalize("tim") # "Tim" capitalize("matt") # "Matt" def compact(list): return [el for el in list if bool(el) == True] compact([0,1,2,"",[], False, {}, None, "All done"]) # [1,2, "All done"] #theirs def compact(l): return [val for val in l if val] compact([0,1,2,"",[], False, {}, None, "All done"]) # [1,2, "All done"] def is_even(num): return num % 2 == 0 def partition(arr, func): yes = [] no = [] for el in arr: if func(el): yes.append(el) else: no.append(el) return [yes, no] partition([1,2,3,4], is_even) # [[2,4],[1,3]] # One liner def partition(arr,func): return [[el for el in arr if func(el)], [el for el in arr if not func(el)]] # but this would be double the time complexity O(2n) partition([1,2,3,4], is_even) # [[2,4],[1,3]] def intersection(arr1, arr2): return [el for el in arr1 if el in arr2] intersection([1,2,3], [2,3,4]) # [2,3] def once(func): inner.ran = False def inner(*args): if inner.ran == False: inner.ran = True return func(*args) else: return None return inner def add(a,b): return a+b one_addition = once(add) one_addition(2,2) # 4 one_addition(2,2) # undefined one_addition(12,200) # undefined def once(fn): fn.is_called = False def inner(*args): if not(fn.is_called): fn.is_called = True return fn(*args) return inner one_addition = once(add) one_addition(2,2) # 4 one_addition(2,2) # undefined one_addition(12,200) # undefined # Decorator def once(fn): fn.is_called = False def inner(*args): if not(fn.is_called): fn.is_called = True return fn(*args) return inner @once def add(a,b): return a+b add(2,2) # 4 add(2,20) # None add(12,20) # None #
4a47ebf0b8bb693e0e2aaaf2a51a5745d441273f
dhananjayagurav/algorithms
/binary_search.py
540
4.0625
4
#Code reference : http://quiz.geeksforgeeks.org/binary-search/ def bin_search(arr, ele): low = 0 high = len(arr)-1 while low <= high: mid = low + (high-1)/2 if arr[mid] == ele: return mid elif arr[mid] < ele: low = mid + 1 else: high = mid -1 #If element is not present in array, return -1 return -1 myarr = (2,3,6,18,22,28,35,41,48,57,63,69,72,81) key=35 index = bin_search(myarr, key) print "Desired index of element in array is : " + str(index)
3cc7007de4a641dee14ff2b795541a4730c3201e
fixiabis/python-socket-test
/13-echo-client-UDP.py
1,699
3.515625
4
# 引入 socket import socket # 引入 sys import sys # 引入 argparse import argparse # 主機 為 localhost host = 'localhost' # 定義 迴響client端 需要 埠號 def echo_client(port): # sock 為 讓socket 建立 socket 代入 設定domain為IPV4協定, type為UDP sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 伺服器地址 為 (主機, 埠號) server_address = (host, port) # 印出 連接到的 port print ("Connecting to %s port %s" % server_address) message = 'This is the message. It will be repeated.' # 嘗試 try: # 訊息 為 Test message. This will be echoed message = "Test message. This will be echoed" # 印出 送出 訊息 print ("Sending %s" % message) # 送出 為 讓sock 執行 送去 代入 訊息 執行 編碼 utf-8, 伺服器地址 sent = sock.sendto(message.encode('utf-8'), server_address) # 資料, 伺服器 為 data, server = sock.recvfrom(data_payload) print ("received %s" % data) finally: print ("Closing connection to the server") sock.close() # 若 該檔案 為 主程式 時 if __name__ == '__main__': # 解析器 為 從argparse中 建立參數解析器 parser = argparse.ArgumentParser(description='Socket Server Example') # 從解析器中 增加參數 parser.add_argument('--port', action="store", dest="port", type=int, required=True) # 被給予的參數 為 讓解析器 執行 解析參數 given_args = parser.parse_args() # 埠號 為 被給予的參數 的 埠號 port = given_args.port # 執行 迴響client端 代入 埠號 echo_client(port)
cf76593144a156aebcf20a68fbcb77ffd40281bb
ArturoCBTyur/Prueba_Nueva
/assert_statement.py
352
4.09375
4
def divisors(num): divisors = [i for i in range(1, num + 1) if num % i == 0] return divisors def main(): num = input("Digita un número: ") assert num.isnumeric(), "You cannot put a character" print(divisors(int(num))) print("Fin owo") print("Ese no es un numero. Digita un numero") if __name__ == "__main__": main()
fa60027dafca5bf61f907ab12346f89bfb2e48d6
amrkhailr/python_traning-
/LOOP/exo13.py
807
4.65625
5
#4. Distance Traveled #The distance a vehicle travels can be calculated as follows: #distance speed  time #For example, if a train travels 40 miles per hour for three hours, the distance traveled is 120 #miles. Write a program that asks the user for the speed of a vehicle (in miles per hour) and #the number of hours it has traveled. It should then use a loop to display the distance the #vehicle has traveled for each hour of that time period. Here is an example of the desired #output: #What is the speed of the vehicle in mph? 40e #How many hours has it traveled? 3e #our Distance Traveled #1 40 #2 80 #3 120 speed = float(input('What is the speed of the vehicle in mph?')) time = int(input('How many hours has it traveled?')) for n in range(time + 1): distance = speed * n print(distance)
fe31a51c4880591ea9a82ac4d9625bff2b5945a2
ellynnhitran/Fundamentals_C4T4
/Session06/Assignment06/turtle2.py
234
3.796875
4
from turtle import * shape("turtle") speed(-1) for i in range(4,10): for j in range (i): forward(100) left(360//i) if j%2 == 0: color('blue') else: color('red') mainloop()
6c3f14a60484f952add501aac7e7f43dd3857147
4ndrewJ/CP1404_Practicals
/prac_01/shop_calculator.py
583
4.0625
4
""" Shop calculator first takes the number of items and the cost of each item then displays the total price of the items 10% discount applied for total costs > $100 """ total_price = 0 number_items = int(input('Number of items: ')) while number_items < 0: print('Invalid number of items!') number_items = int(input('Number of items: ')) for i in range(number_items): item_price = float(input('Price of item: ')) total_price += item_price if total_price > 100: total_price *= 0.9 print('Total price for {:.0f} items is ${:.2f}'.format(number_items, total_price))
04e2ff9bcee5df65f66d57d53ed4d4eadfeb6a94
junaidabdool/python
/bettercalculator.py
332
4.375
4
num1 = float(input("Enter num1 please :\n")) op = input("Enter the Operation :\n") num2 = float(input("Enter num2 please :\n")) if op == "+": print(num1+num2) elif op == "-": print(num1-num2) elif op == "*": print(num1*num2) elif op == "/": print(num1/num2) else: print("ERROR PLEASE ENTER A PROPER OPERATION")
d666a4ab411ee982ac03bd74bc9c5cc81fb02fe9
xtreia/pythonBrasilExercicios
/03_EstruturasRepeticao/12_gerador_tabuada.py
174
3.890625
4
numero = int(raw_input('Informe o numero que voce quer ver a tabuada: ')) print 'Tabuada de', numero, ':' for i in range(1, 11): print numero, 'X', i, '=', (numero * i)
5868756c836a243b097e5b70f0be254bd8a0943b
Berzok/TP_Python
/Voyage_à_Tri_Poli/triHybride.py
3,931
3.53125
4
#coding: utf-8 import os import random os.system('clear') def alea_tableau(*n): tableau = [] try: n = int(n[0]) taille = n for i in range(taille): tableau.append(random.randint(-999, 1000)) tableau.append(max(tableau)+(random.randint(0, 413))) return tableau except: taille = random.randint(1, 1000) for i in range(taille): tableau.append(random.randint(-999, 1000)) tableau.append(max(tableau)+(random.randint(0, 413))) return tableau def afficher_tableau(leTableau): tableau = leTableau print "" for i in tableau: if i is tableau[0]: print "["+str(i)+",", continue if i is tableau[len(tableau)-1]: print str(i)+"]" break print str(i)+",", ########################################################################################### ############### TRI RAPIDE #################################################### def tri_rapide(tableau, gauche, droite, leCompteur=0, r=5): leCompteur = 0 + leCompteur k = 0 if gauche < droite: tableau, k, leCompteur = placer_dans_tableau(tableau, gauche, droite, leCompteur) tableau, leCompteur = tri_rapide(tableau, gauche, k-1, leCompteur) tableau, leCompteur = tri_rapide(tableau, k+1, droite, leCompteur) return tableau, leCompteur def placer_dans_tableau(tableau, gauche, droite, leCompteur): bas = gauche+1 haut = droite while bas <= haut: while tableau[bas] <= tableau[gauche]: bas += 1 leCompteur += 1 while tableau[haut] > tableau[gauche]: haut -= 1 leCompteur += 1 if bas < haut: echanger_elements(tableau, bas, haut) bas += 1 haut -= 1 leCompteur += 1 echanger_elements(tableau, gauche, haut) k = haut return tableau, k, leCompteur def echanger_elements(tableau, a, b): leTemporaire = tableau[a] tableau[a] = tableau[b] tableau[b] = leTemporaire def triParInsertion(tableau): i = 0 j = 0 leCompteur = 0 for i in range(1, len(tableau)): j = i-1 laValeur = tableau[i] while tableau[j] > laValeur: leCompteur += 1 tableau[j+1] = tableau[j] j -= 1 tableau[j+1] = laValeur leCompteur += 1 tableau.reverse() tableau.reverse() return tableau, leCompteur def avgComparaisons(n, p): leCompteur = 0 for i in range(p): tableau = alea_tableau(n) unCompteur = 0 tableau, unCompteur = tri_hybride(tableau, 0, len(tableau)-1) leCompteur += unCompteur return leCompteur ############################################################################################## ############## TRI HYBDRIDE ########################################## def tri_hybride(tableau, gauche, droite, r=2): """tri rapide de sous tableaux de taille r au plus, dont les elements doivent etre inferieurs aux elements du sous tableau suivant le tableau intermediaire est ensuite trie par insertion""" leCompteur = unCompteur = 0 if r <= 0: return tableau tableau, leCompteur = tri_rapide(tableau, gauche, droite, r) tableau, unCompteur = triParInsertion(tableau) return tableau, (leCompteur + unCompteur) print "Taille limite du tableau ? Ou rien pour une taille aléatoire" valeur = raw_input() unCompteur = 0 tableau = alea_tableau(valeur) print "Tableau de base:" afficher_tableau(tableau) print "\nValeur limite du triage?" r = int(input()) tableau, unCompteur = tri_hybride(tableau, 0, len(tableau)-1, r) print "" print "Tableau trié, et ceci en " + str(unCompteur) + " comparaisons.", afficher_tableau(tableau) print "##########################################################################" print "Sélectionnez une taille de tableau:" n = int(input()) print "Sélectionnez maintenant un nombre de tableaux:" p = int(input()) lesComparaisons = avgComparaisons(n, p) print "" print "Pour " + str(p) + " tableaux de taille " +str(n) + ", on aura effectué " + str(lesComparaisons) + " comparaisons." print "Soit une moyenne de " + str(lesComparaisons/p) + " comparaisons par tableau."
44cafc842e5dba2c30d658dec1da47b54fc94b46
RevansChen/online-judge
/Codewars/6kyu/title-case/Python/solution1.py
205
3.546875
4
# Python - 3.6.0 title_case = lambda title, minor_words = '': ' '.join([e.lower() if i != 0 and (e in minor_words.lower().split(' ')) else e.capitalize() for i, e in enumerate(title.lower().split(' '))])
91a6026b816975df44a0c916f4fc9d559975709a
TobiWo/merkle-tree
/example_usage.py
559
3.671875
4
from merkle.merkletreeplot import MerkleTreePlot # create a merkle tree with 32 leafes tree = MerkleTreePlot(32) # highlight nodes which are necessary to confirm that particular leaf (24) is in merkle tree #tree.mark_verification_nodes(24, "yellow") # highlight nodes which will change when one leaf (here leaf 24) is changed tree.change_leaf(24) # rotate the merkle tree tree.rotation = 90 # plot the tree tree.plot_merkletree() # Note: You can either highlight the verification nodes or change a leaf and highlight all nodes in the branch of the leaf
6a9616ef78cb36a003b90bc85efe8753df1d2404
Bradysm/daily_coding_problems
/longestWordInDic.py
3,596
3.953125
4
# Given a string and a string dictionary, # find the longest string in the dictionary that can be formed by deleting some characters of the given string. # If there are more than one possible results, return the longest word with the smallest lexicographical order. # If there is no possible result, return the empty string. # # Example 1: # Input: # s = "abpcplea", d = ["ale","apple","monkey","plea"] # # Output: # "apple" # Example 2: # Input: # s = "abpcplea", d = ["a","b","c"] # # Output: # "a" # Note: # All the strings in the input will only contain lower-case letters. # The size of the dictionary won't exceed 1,000. # The length of all the strings in the input won't exceed 1,000 # Immediately when I saw this question, I was a little nervous. The reason being is that # I tend to be not as good with string problems as I am with other problems. BUT, this # means I just need to work on them more, so here we go. I'm going to describe two different # solutions for this problem. # the first solution is a brute force solution. You've probably seen this in all kinds of # interview problems on this repo, but it's thinking of teh solution like a powerset. # we get to each character and thn choose to either add it to the list or not. We then # check to see if that list matches on of the words in the dictionary and make the # current word equal to that word. Then choose to not add it and update the current # word if the word that didn't add it is longer or is the same length and lexiographically # less than the currennt word. Sheesh. This will be O(2^n) time and O(n) space due # to the stack space needed for recursion. The 2 comes from the node at each branch in the # recursion tree branching by a factor of 2 due to adding and not adding the value # That was a lot. Okay, now let's get to the arguably # more simple solution that. # My problem with initially solving this was that I was going to user a counter and then # just make sure that the string s had >= the number of that specific character needed # in the word. The problem that I ran into is that it's not just about the correct number, # but also the order. That got me thinking. What if we had two "pointers" for each string # we then move down the string s and as we move down, we check if the character at s[i] is the # same character at word[j]; if it is, increment j because we found that character in the correct order # We always increment i because we're passing down s, so no matter what we increment i. Then I had to think # about the conditions for the loop. We want to stop when we've seen all the characters in word, or if # we ran out of characters in s, so that is a simple condition to meet. You then update the max # word if the current word is longer. I then added a little code tuning by just continuing if the current # word that we're on is < len(m_word). This is because no matter if we found that word, it wouldn't replace # m_word. BOOM, we now have a Olen(dic)*max(words)) complexity and are using O(max(word)) def findLongestWord(s, d): m_word = "" for word in d: w_len = len(word) if w_len < len(m_word): continue s_index = w_index = 0 # indexes for the two strings while w_index < w_len and s_index < len(s): w_index = w_index + 1 if s[s_index] == word[w_index] else w_index s_index += 1 # found all characters if w_index == w_len: if w_len == len(m_word): m_word = min(m_word, word) elif w_len > len(m_word): m_word = word return m_word
55a317a0d768706565e710b076c89c8d3d923137
aprilcarter/python-course-practice
/OOP_Examples/inheritance.py
757
3.96875
4
class Animal: def __init__(self, name, species): self.name = name self.species = species def __repr__(self): return f"{self.name} is a {self.species}" def make_sound(self, sound): return f"This animal says {sound}" # Just pass the parent class in as an argument to indicate inheritance class Cat(Animal): def __init__(self, name, breed, toy): # Can call Animal.__init__(self, etc.), but there's a function for that super().__init__(name, species="Cat") self.breed = breed self.toy = toy def play(self): return f"{self.name} plays with {self.toy}." # some_animal = Animal(name="Po", species="Bear") # my_cat = Cat(name="Kitty", breed="Mix", toy="Fishing Rod")
dac62c8ba921265fa19f4af2aaf5565ea5b0ce0f
AlanAS3/Curso-de-Python-Exercicios
/Exercícios/Mundo 1/Exercícios Coloridos/ex034.py
336
3.734375
4
print('\033[32;1m=== Aumento de Salário ===\033[m') Sal = float(input('\033[31mQual o seu salário? ')) if Sal >= 1250.00: Sal = Sal + Sal * (10 / 100) print(f'\033[36mO seu novo salário é de \033[34;1m{Sal}\033[m') else: Sal = Sal + Sal * (15 / 100) print(f'\033[36mO seu novo salário é de \033[34;1m{Sal}\033[m')
f2f44bd561e31cf2b0dcdd024a3adee41b6227d6
lakshsharma07/training2019
/day13/solution/ign.py
1,890
3.859375
4
""" Code Challenge Name: IGN Analysis Filename: ign.py Problem Statement: Read the ign.csv file and perform the following task : Let's say we want to find games released for the Xbox One that have a score of more than 7. review distribution for the Xbox One vs the review distribution for the PlayStation 4.We can do this via a histogram, which will plot the frequencies for different score ranges. Hint: The columns contain information about that game: score_phrase — how IGN described the game in one word. This is linked to the score it received. title — the name of the game. url — the URL where you can see the full review. platform — the platform the game was reviewed on (PC, PS4, etc). score — the score for the game, from 1.0 to 10.0. genre — the genre of the game. editors_choice — N if the game wasn't an editor's choice, Y if it was. This is tied to score. release_year — the year the game was released. release_month — the month the game was released. release_day — the day the game was released. """ import pandas as pd df = pd.read_csv('ign.csv') ##### games released for the Xbox One that have a score of more than 7 xbox_one_filter = (df["score"] > 7) & (df["platform"] == "Xbox One") filtered_reviews = df[xbox_one_filter] games_list_xbox_one = filtered_reviews['title'] print (games_list_xbox_one) # review distribution for the Xbox One xbox_one = df['platform']=="Xbox One" xbox_one_only_df = df[xbox_one] xbox_one_reviews = xbox_one_only_df['score_phrase'] xbox_one_reviews.hist(bins=20,grid=False,xrot=90) # review distribution for the PlayStation 4 ps4 = df['platform']=="PlayStation 4" ps4_only_df = df[ps4] ps4_reviews = ps4_only_df['score_phrase'] ps4_reviews.hist(bins=20,grid=False,xrot=90)
2965fdbbccb10430e9320c7278c8c754f8e2dd3b
j-a-c-k-goes/guess_my_number
/guessNumber.py
3,772
4.1875
4
""" Game is "Guess my number" """ # .................................................................. imports from random import * # .................................................................. main_function def main(): global secret secret = secret_number(n_1,n_2) think = thinking(n_1,n_2) your_guesses = [] for guesses in range(1, max_guesses): print() try: guess = int(input("input your guess as a number: ")) print() if guess < secret: your_guesses.append(guess) print("your guess\t{}".format(guess)) guess_too_low() guesses += 1 print("your guesses: " + "".join(str(your_guesses))) print("guesses left\t{}".format(max_guesses - guesses)) elif guess > secret: your_guesses.append(guess) print("your guess\t{}".format(guess)) guess_too_high() guesses += 1 print("your guesses: " + "".join(str(your_guesses))) print("guesses left\t{}".format(max_guesses - guesses)) else: break except ValueError: error_message() guess = int(input("input your guess as a number: ")) if guess == secret: correct_guess(secret, guesses) print() else: fail_guess(secret) print() # .................................................................. sub_functions def secret_number(n_1, n_2): return randint(n_1, n_2) def thinking(n_1,n_2): string = "i am thinking of a number between {} and {}".format(n_1,n_2) print(string.title()) def guess_too_high(): string = "your guess is too high" print(string.title()) def guess_too_low(): string = "your guess is too low" print(string.title()) def take_guess(): string = "take a guess" print(string.title()) def error_message(): string = "please enter a valid number!" print(string) def fail_guess(value): string = "actually the number i was thinking of was {}".format(secret) print(string.title()) def correct_guess(value_1, value_2): string = "nice! you guessed my secret number '{}' in {} attempts".format(value_1, value_2) print(string.title()) def menu(): print("(1) for easy\n(2) for medium\n(3) for hard") # .................................................................. on_load_export if __name__ == "__main__": modes = ["easy", "medium", "hard"] while True: print("new game!".upper()) menu() mode = int(input("choose a difficulty, (1),(2),(3): ")) #if mode != 1 or mode != 2 or mode != 3: #print("difficulty does not exist...please use 1, 2, 3 to select a difficulty.") #mode = int(input("select (1),(2),or (3): ")) if mode == 1: print("you selected {} for {}".format(mode,modes[0])) guesses = 0 max_guesses = 3 n_1 = 1 n_2 = randint(15,20) if mode == 2: print("you selected {} for {}".format(mode,modes[1])) guesses = 0 max_guesses = 5 n_1 = 1 n_2 = randint(25,100) if mode == 3: print("you selected {} for {}".format(mode,modes[2])) guesses = 0 max_guesses = 7 n_1 = 1 n_2 = randint(100,1000) print() main() # .................................................................. bugs """ line 85, fix conditional statement if mode inputted not a valid mode """ # .................................................................. updates
8ba2b85d8ffd10f1e4eb11389b51172c76b0b1fe
zikfood/budg-intensive
/day_3/data_structure/task_2/question.py
265
4.25
4
""" Что выведет данный код? Почему? """ some_list = [[]] * 3 some_list[1].append(420) print(some_list) """ [[420], [420], [420]] потому что все вложенные листы ссылаются на одно значение """
50c2543c936d2a979ea2ece3cb053739e794648f
aayushbaral/Postgresql_examples
/problem3.py
2,892
3.59375
4
#!/usr/bin/env python3 """ problem3.py - Python3 program Author: Aayush Baral (aayushbaral@bennington.edu) Created: 10/24/2017 """ import psycopg2 import psycopg2.extras class Business(object): def __init__(self, business_dict=None): if business_dict is None: raise ValueError("No business details provided") self.id = business_dict['id'] self.name = business_dict['name'] self.neighborhood = business_dict['neighborhood'] self.address = business_dict['address'] self.city = business_dict['city'] self.state = business_dict['state'] self.postal_code = business_dict['postal_code'] self.latitude = business_dict['latitude'] self.longitude = business_dict['longitude'] self.stars = business_dict['stars'] self.review_count = business_dict['review_count'] self.is_open = business_dict['is_open'] def __str__(self): return "Name: {0}, ID: {1}, Neighborhood: {2}, Address: {3}, City: {4}, State: {5}, Postal Code: {6}, Latitude: {7}, Longitude: {8}, Stars: {9}, Review Count: {10}, Is Open: {11}".format( self.name, self.id, self.neighborhood, self.address, self.city, self.state, self.postal_code, self.latitude, self.longitude, self.stars, self.review_count, self.is_open) def add_business(given_business): try: given_business = Business(given_business) conn = psycopg2.connect("dbname='yelp_db' user='aayushbaral'") cur = conn.cursor() cur.execute("""INSERT INTO business(id, name, neighborhood, address, city, state, postal_code, latitude, longitude, stars, review_count, is_open) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);""",(given_business.id, given_business.name, given_business.neighborhood, given_business.address, given_business.city, given_business.state, given_business.postal_code, given_business.latitude, given_business.longitude, given_business.stars, given_business.review_count, given_business.is_open, )) conn.commit() except Exception as e: print("Unable to connect to database: {0}".format(e)) def get_business_details(name=""): try: conn = psycopg2.connect("dbname='yelp_db' user='aayushbaral'") cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("""SELECT * FROM business WHERE name = '{0}'""".format(name)) business = cur.fetchone() my_business = Business (business) return my_business except Exception as e: print("Unable to connect to database: {0}".format(e)) if __name__ == '__main__': adding_business = {'id': '6Mefjghkdkndfk', 'name': 'Aayush_Baral', 'neighborhood': 'Booth', 'address': 'One COllege Drive', 'city': 'Bennington', 'state': 'VT', 'postal_code': '05201', 'latitude': 42, 'longitude': 3243, 'stars': 3, 'review_count': 10, 'is_open': 0} add_business(adding_business) my_business = get_business_details('Aayush_Baral') print(my_business)
e835e59be1b9b9dbe4315af73b3bed9c8598d86c
here0009/LeetCode
/Python/256_PaintHouse.py
1,677
3.921875
4
""" There is a row of n houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. The cost of painting each house with a certain color is represented by a n x 3 cost matrix. For example, costs[0][0] is the cost of painting house 0 with the color red; costs[1][2] is the cost of painting house 1 with color green, and so on... Find the minimum cost to paint all houses.   Example 1: Input: costs = [[17,2,17],[16,16,5],[14,3,19]] Output: 10 Explanation: Paint house 0 into blue, paint house 1 into green, paint house 2 into blue. Minimum cost: 2 + 5 + 3 = 10. Example 2: Input: costs = [] Output: 0 Example 3: Input: costs = [[7,6,2]] Output: 2   Constraints: costs.length == n costs[i].length == 3 0 <= n <= 100 1 <= costs[i][j] <= 20 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/paint-house 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ class Solution: def minCost(self, costs) -> int: if not costs: return 0 n = len(costs) dp = costs[0] for i in range(1, n): dp2 = [] dp2.append(costs[i][0] + min(dp[1], dp[2])) dp2.append(costs[i][1] + min(dp[0], dp[2])) dp2.append(costs[i][2] + min(dp[0], dp[1])) dp = dp2 return min(dp) S = Solution() costs = [[17,2,17],[16,16,5],[14,3,19]] print(S.minCost(costs)) costs = [] print(S.minCost(costs)) costs = [[7,6,2]] print(S.minCost(costs))
3d4454f10f92764e945a9251012e3fb827188d06
jaleonro/Classic-algorithms
/BFS.py
1,053
3.578125
4
import math def bfs(adjDict,s): visited=set() distance = dict.fromkeys(adjDict.keys(), math.inf) parent = dict.fromkeys(adjDict.keys(), None) distance [s]=0 queue=[] queue.append(s) while queue: u=queue.pop(0) for i in range(0, len(adj[u])): v = adj[u][i] if v not in visited: visited.add(v) distance[v] = distance[u] + 1 parent[v] = u queue.append(v) visited.add(u) return parent def printPath(adj,parent,s,v): if s==v: print(str(s)) else: if parent[v]==None: print("there is no path beetween s and v") else: printPath(adj,parent,s,parent[v]) print (str(v)) adj=dict([('r', ['s','v']), ('v', ['r']), ('s', ['r','w']), ('w', ['s','t','x']), ('t', ['w','x','u']), ('x', ['w','t','u','y']),('u', ['t','x','y']),('y', ['u','x'])]) parents=bfs(adj,'s') printPath(adj,parents,'s','u')
17c046233d152baccbb3038aaad16758f81944b0
CarlosRodriguezzz/software_design
/module1/poo_encapsulation_library.py
1,221
3.640625
4
from abc import ABC class TransporteAereo(ABC): def __init__(self, origen, destino, pasajeros): self.origen = origen self.destino = destino self.pasajeros = pasajeros def volar(self): return 'volando de {} a {} con {} pasajeros...'.format( self.origen, self.destino, self.pasajeros ) class Helicoptero(TransporteAereo): # Opcionalmente podemos modificar el constructor # def __init__(self, origen, destino, pasajeros): # super().__init__(origen, destino, pasajeros) def volar(self): return 'en helicóptero {}'.format( super().volar() ) class Avion(TransporteAereo): def volar(self): return 'en avión {}'.format( super().volar() ) class DronParaHumanos(TransporteAereo): def volar(self): return 'en un dron para humanos {}'.format( super().volar() ) class AvionPapel(): def volar(self): return 'no podemos volar en un avion de papel' # En caso de que ejecutemos la librería en vez de importarla if __name__ == '__main__': transporte = DronParaHumanos('GDL', 'OAK', 180) print(transporte.volar())
1682da2f77c55b432574cb4e621b68e8feb29f0c
kalyankilaru/CSEE5590_python_DeepLearning
/Python-Lab1/Source Code/problem2.py
1,474
4.40625
4
# Function to which we pass the sentence and perform the operations def sentence(input): # We split the sentence based on the spaces words_list = input.split(" ") # The length of the words is stored words_count = len(words_list) # To find the middle words in a sentence # we will find the mid point of the total number of words middle_word = int((words_count / 2)) # If total number of words are even if words_count%2 == 0: print("The Middle words are: ", words_list[middle_word-1],",", words_list[middle_word]) # If total number of words are odd else: print("The Middle words are: ", words_list[middle_word]) # To get the longest word from the given input sentence words_sorted = sorted(words_list, key=len) # We sort the words list length_word = len(words_sorted[-1]) print("The Longest words in the sentence are: ", end=" ") # If there are more words with the same length for word in words_sorted: if len(word) == length_word: print(word,",", end=" ") # To reverse each word of a sentence and print it print("\nThe sentence with each word in the reverse is: ", end=" ") for i in range(0,words_count): reverse_words = words_list[i] print(reverse_words[::-1],end=" ") # User will give the input from the console sentenceOfWords = input("Enter the sentence: ") sentence(sentenceOfWords) # Calling the function by passing the sentence
f8d7850c0bfd8261af9db8f49c9edf9290fe64e4
C-Robbins/Girls-Who-Code
/Python/pokemon.py
3,164
3.734375
4
import random from random import randint pokemon_list = ["ghastly","zubat","pidgey","magikarp","jynx","pikachu","dialga"] play = True class Pokemon(): def __init__ (self, pokemon_type, name, cp, hp, attack_strength): self.pokemon_type = pokemon_type self.name = name self.cp = cp self.hp = hp self.attack_strength = attack_strength def get_status(self): self.get_status print(str(self.pokemon_type)+ ", " +str(self.name)+ ", Your CP: " +str(self.cp)+ ", Your HP: " +str(self.hp)) return(self.pokemon_type, self.name, self.cp, self.hp) def rename(self): self.name = input("Give your Pokemon a nickname: ") def increase_cp(self, amount): self.cp = self.cp + amount def decrease_cp(self, amount): self.cp = self.cp - amount def is_attacked(self, damage): self.hp = self.hp - damage def attack(self, another, attack_strength): print ("A wild " +another+ " appeared!") if self.cp <= 20: attack_strength = attack_strength*1 elif self.cp > 20 and self.cp <= 40: attack_strength = attack_strength*2 elif self.cp > 40 and self.cp <= 60: attack_strength = attack_strength*3 elif self.cp > 60 and self.cp <= 80: attack_strength = attack_strength*4 elif self.cp > 80 and self.cp <= 100: attack_strength = attack_strength*5 hit = randint(0,1) if hit == 0: print("Your attack was successful") self.increase_cp(5) elif hit == 1: print("Your attack missed! Your enemy counter attacked") self.decrease_cp(5) self.is_attacked(15) print("Your hp = " + str(self.hp)) # self.get_status() # if self.cp <= 0 or self.hp <= 0: # print ("You can't battle anymore. Game over") # play = False # else: # play = True class ghastly(Pokemon): def __init__(self, my_attack): self.my_attack = "nightshade" def special_attack(self, my_attack_strength): self.my_attack_strength = attack_strength+5 def string_to_attack (self, other_pokemon): class zubat(Pokemon): def __init__(self, my_attack, my_attack_strength): self.my_attack = "confusion" def special_attack(self, my_attack_strength): self.my_attack_strength = attack_strength+5 class pidgey(Pokemon): def special_attack(self, fly): self.fly = attack_strength+10 class magikarp(Pokemon): def special_attack(self, splash): self.splash = attack_strength+1 class jynx(Pokemon): def special_attack(self, psychic): psychic = attack_strength+10 class pikachu(Pokemon): def special_attack(self, thunderbolt): thunderbolt = attack_strength+10 class dialga(Pokemon): def special_attack(self, dragon_breath): dragon_breath = attack_strength+15 other_pokemon = Pokemon(pokemon_list[randint(0,6)], "0", 10, 100, 10) my_pokemon = Pokemon(pokemon_list[randint(0,6)], "0", 10, 100, 10) my_pokemon.get_status() my_pokemon.rename() # while play == True: my_pokemon.get_status() my_pokemon.attack(other_pokemon, 10) user_input = input("Play on? ") # if user_input == ("yes"): # play = True # elif user_input == ("no"): # play = False # print ("Thanks for playing!")
653fbe7c8153a5b095bd990dceae3e65de4478e8
rain-zhao/leetcode
/py/Task86.py
1,242
3.8125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None from ListNode import ListNode class Solution: def partition(self, head: ListNode, x: int) -> ListNode: if not head: return None lo, hi = ListNode(-1), ListNode(-1) curLo, curHi, cur = lo, hi, head while cur: if cur.val < x: curLo.next = cur curLo = curLo.next else: curHi.next = cur curHi = curHi.next cur = cur.next curLo.next, curHi.next = hi.next, None return lo.next # 2020-01-04 def partition2(self, head: ListNode, x: int) -> ListNode: lo = dummyLo = ListNode(-1) hi = dummyHi = ListNode(-1) p = head while p: if p.val < x: lo.next = p lo = lo.next else: hi.next = p hi = hi.next p = p.next lo.next = dummyHi.next hi.next = None return dummyLo.next head = ListNode(1) head.nextItm(4).nextItm(3).nextItm(2).nextItm(5).nextItm(2) so = Solution() so.partition(head, 3)
b2ddc8e2f4f3622db55649e061d861a0422e7770
avrybintsev/PyTasks
/task6/infix.py
254
3.578125
4
#!/usr/bin/python def func1(a, b): return a + b def func2(a, b): return a * b def func3(a, b): return a ** b def getOpDict(): dictOp = {} dictOp["op1"] = func1 dictOp["op2"] = func2 dictOp["op3"] = func3 return dictOp
aaf5a36c22382fc73520a02bdf40a8aac91c9bef
hupsuni/BloomFilters
/ALOHA_IBLT/aloha_iblt.py
12,166
4.09375
4
# Created By Nick Huppert on 4/5/20. import mmh3 import random import math from random import randint, seed class IBLT: """ Simple implementation of an invertible bloom lookup table. The IBLT returned will have the format for a list of lists. Each list in an element, each element is of the form [idSum, hashSum, count]. A list of seed keys is used to seed hash functions for item placement. A list of random numbers is used to decide how many times a given item is added to the IBLT. """ _M = 10 SEED_RANGE = 1000000 MAX_HASHES = 15 MAX_RANDOM_HASHES = 1000 DEFAULT_A_VALUE = 0 @staticmethod def generate_seed_list(seed_key, max_hashes=MAX_HASHES, seed_range=SEED_RANGE): """ List of seeds to be used to derive the item locations. Args: seed_key: Shared key to instantiate hash functions. max_hashes: Upper bound for total hashes to be used. seed_range: Range of random numbers to be used to generate a new seed key if not specified. Returns: list[int]: A list of seed keys which are used to seed hash functions for item placement. """ random.seed(seed_key) seed_list = [] i = 0 while i < max_hashes: chosen_seed = random.randint(0, seed_range) if chosen_seed not in seed_list: seed_list.append(chosen_seed) i += 1 return seed_list @staticmethod def generate_hash_decider(seed_key, n_value, a_value, length=MAX_RANDOM_HASHES): """ List of random numbers between min and max to decide how many times an item is hashed to locations. Args: a_value: The value for a in the ALOHA style distribution function. seed_key: Shared key to instantiate hash functions. n_value: Upper bound for total hashes to be used. length: Size of list of random numbers to be generated. Returns: list[int]: A list of random numbers which decide how many times an item is hashed to be placed into IBLT. """ return Distribution.create_randomly_generated_sequence(length, n_value, a_value, seed_key) @staticmethod def generate_table(item_ids, seed_key, table_size=_M, max_hashes=MAX_HASHES, a_value=DEFAULT_A_VALUE, hash_decider=None, hash_decider_length=MAX_RANDOM_HASHES, seed_range=MAX_RANDOM_HASHES): """ Generate the randomized hash function quantity based IBLT Args: a_value: The value for a in the ALOHA style distribution function. item_ids: The IDs of the items to be inserted. seed_key: Shared key to instantiate hash functions. table_size: Size of the IBLT. max_hashes: Upper bound for total hashes to be used. hash_decider(list[int]): List of random numbers for hashing iterations. hash_decider_length: Size of the list of random numbers determining the amount of times an item is added. seed_range: The upper bound of the values of any given seed key. Returns: tuple[list[tuple], list[int], list[int]]: An IBLT as a list of tuples, each element is of the form (idSum, hashSum, count). """ bloom = [(0, 0, 0)] * table_size if hash_decider is None: hash_decider = IBLT.generate_hash_decider(seed_key, max_hashes, a_value, hash_decider_length) seed_list = IBLT.generate_seed_list(seed_key, max_hashes, seed_range) for item in item_ids: item_hash = mmh3.hash128(str(item).encode(), seed_key) hash_quantity = hash_decider[item_hash % len(hash_decider)] hash_values = [] # Calculate hash values for the item and derive the index for encoding for i in range(hash_quantity): hash_values.append(mmh3.hash128(str(item).encode(), seed_list[i])) for hash_value in hash_values: index = hash_value % table_size id_sum = bloom[index][0] ^ item if bloom[index][1] == 0: hash_sum = item_hash else: hash_sum = bloom[index][1] ^ item_hash count = bloom[index][2] + 1 bloom[index] = (id_sum, hash_sum, count) return bloom, seed_list, hash_decider @staticmethod def compare_tables(table1, table2, seed_key, seed_list=None, hash_decider=None, max_hashes=MAX_HASHES, a_value=DEFAULT_A_VALUE, hash_decider_length=MAX_RANDOM_HASHES, seed_range=MAX_RANDOM_HASHES): """ Compares 2 IBLTs and attempts to return the symmetric difference. Args: a_value: The value for a in the ALOHA style distribution function. table1: Invertible bloom filter 1 table2: Invertible bloom filter 2 seed_key: Shared key to instantiate hash functions. seed_list: List of seed keys for hashing item ids. hash_decider(list[int]): List of random numbers for hashing iterations. max_hashes: Upper bound for total hashes to be used. hash_decider_length: Size of the list of random numbers determining the amount of times an item is added. seed_range: The upper bound of the values of any given seed key. Returns: tuple[list[tuple], list[tuple], str]: The symmetric difference of the IBLTs, list 1 is the extra elements from filter 1, list 2 is the extra elements from filter 2, and a string to confirm if the decoding was successful. """ # Check tables are equal size. if len(table1) != len(table2): return False # Generate hash decider or seed list from default values if none are passed in. if hash_decider is None: hash_decider = IBLT.generate_hash_decider(seed_key, max_hashes, a_value, hash_decider_length) if seed_list is None: seed_list = IBLT.generate_seed_list(seed_key, max_hashes, seed_range) # Create lists for differences and a list to decode. table_size = len(table1) table1_differences = [] table2_differences = [] table3 = [[0, 0, 0]] * table_size # Generate symmetric difference table for index in range(table_size): id_sum = table1[index][0] ^ table2[index][0] hash_sum = table1[index][1] ^ table2[index][1] count = table1[index][2] - table2[index][2] table3[index] = [id_sum, hash_sum, count] # Begin decoding table decodable = True while decodable is True: decodable = False for index in range(table_size): element = table3[index] # Check that the count for an element is 1 or -1. if element[2] == 1 or element[2] == -1: # Ensure that the hash of the item ID is equal to the value stored in the table. element_hash = mmh3.hash128(str(element[0]).encode(), seed_key) # If they match, we have a decodable item, now derive which table this element exists # in and remove accordingly. if element_hash == element[1]: table3 = IBLT.peel_element(element[0], seed_key, table3, element[2], seed_list, hash_decider) decodable = True # Add decoded element to appropriate table based on which IBLT it existed in. if element[2] == 1: table1_differences.append(element[0]) else: table2_differences.append(element[0]) success = "Success" # Scan list to ensure all elements have been decoded. for index in range(table_size): if table3[index][1] != 0: success = "Failed" break # print("ALOHA: %s" % success) return table1_differences, table2_differences, success @staticmethod def peel_element(element_id, seed_key, table, alteration, seed_list, hash_decider): """ Peels a single element from a given IBLT. Args: element_id(int): The element to be peeled. seed_key: Shared key to instantiate hash functions. table(list): The invertible bloom lookup table. alteration(int): The indicator as to which list this element was stored in (1 OR -1) seed_list: List of seed keys for hashing item ids. hash_decider: List of random numbers for hashing iterations. Returns: list[tuple]: An updated invertible bloom lookup table with the given element removed. """ # Get initial hash values of element id. item_hash = mmh3.hash128(str(element_id).encode(), seed_key) hash_values = [] # Derive how many times the element has been inserted into the IBLT. hash_quantity = hash_decider[item_hash % len(hash_decider)] # Generate the list of hashes for the elements positions. for i in range(hash_quantity): hash_values.append(mmh3.hash128(str(element_id).encode(), seed_list[i])) # Remove the element from each index in the table, altering the count field based # on the table it came from. for hash_value in hash_values: index = hash_value % len(table) id_sum = table[index][0] ^ element_id if table[index][1] == 0: hash_sum = item_hash else: hash_sum = table[index][1] ^ item_hash count = table[index][2] - alteration table[index] = (id_sum, hash_sum, count) return table class Distribution: MAXIMUM_ACCURACY = 10000000 @staticmethod def create_aloha_style_distribution(a, n): """ Creates a probability distribution based off the ALOHA style research methods. Args: a: The weighting factor of the algorithm. n: The size of maximum hashes as a subset of M Returns: list[int]: A list of weights whose sum is 1. """ distributions = [] denominator = 0 for i in range(2, n+1): denominator += 1/(i*(i-1)) - (a/2) numerator = 0 for i in range(2, n+1): numerator += 1/(i*(i-1)) - a/2 distributions.append((i, numerator / denominator)) return distributions @staticmethod def create_randomly_generated_sequence(size, n_value, a_value, seed_value): """ Creates a sequence of numbers between 2 and N with weightings based on the ALOHA distribution. Args: size: The length of the list of values. n_value: The subset of M where n is the most hash functions. a_value: The weighting for the ALOHA distribution. seed_value: The seed key used across IBLTs to ensure randomized results are predictable. Returns: """ distribution_list = Distribution.create_aloha_style_distribution(a_value, n_value) seed(seed_value) hash_list = [] for i in range(0, size): random_number = randint(0, Distribution.MAXIMUM_ACCURACY) random_number = random_number/Distribution.MAXIMUM_ACCURACY for j in range(0, len(distribution_list)): if random_number <= distribution_list[j][1]: hash_list.append(distribution_list[j][0]) break return hash_list if __name__ == "__main__": elements = [1, 2, 3] elements2 = [2, 4, 3] bloom_full, seed_list1, hash_quantity_list1 = IBLT.generate_table(elements, 5) bloom_2, seed_list2, hash_quantity_list2 = IBLT.generate_table(elements2, 5) print("Decode::") diff = IBLT.compare_tables(bloom_full, bloom_2, 5) print(diff)
0ff8e753bb1fd68924650e9924c0faf1d7b0a6e3
1139411732/AID2011
/day09/write_db1.py
788
3.640625
4
""" 数据库写操作示例1 """ import pymysql # 生成数据库链接对象,链接数据库 database = {'host': 'localhost', 'port': 3306, 'user': 'root', 'password': '123456', 'database': 'stu', 'charset': 'utf8'} db = pymysql.connect(**database) cur = db.cursor() # 数据操作 # 写操作示例 insert delete update try: name = input('请输入学生姓名') # sql = 'update cls set score = %s where name = "%s";' sql = f'update cls set score={100} where name = "{name}";' print(sql) cur.execute(sql) # cur.execute(sql, [90, name]) db.commit() # 事物提交 except Exception as e: print(e) db.rollback() # 事物回滚 # 关闭游标和数据库链接 cur.close() db.close()
85181a451ba3f6460127fe893eedf289ac0494a6
pragatirahul123/Function_question
/more_exercise6.py
121
3.671875
4
user=int(raw_input("enter a number")) fact=1 index=1 while index<=user: fact=fact*index index=index+1 print fact
4b0dac906a1d2703b27b59cad97efc4733bd5cd8
satishhiremath/LearningPython
/practicePython.py
209
4.0625
4
names = ['satish', 'manjunath', 'sharath', 'sali'] for i in names: if i is 'sali': print(i) elif i is 'sharath': print('sharath is here') else: print('hi everyone')
5253a4d027fd8117a008777492ee2b71998bf391
Maxtasy/adventofcode2020
/day06-2.py
841
3.671875
4
#https://adventofcode.com/2020/day/6 def part2(input_file): with open(input_file, "r") as f: groups = f.read().strip().split("\n\n") groups_array = [] for group in groups: groups_array.append(group.split("\n")) yes_counts = [] for group in groups_array: question_chars = {} yes_count = 0 for person in group: for char in person: if not question_chars.get(char): question_chars[char] = 1 else: question_chars[char] += 1 for key in question_chars.keys(): if question_chars[key] == len(group): yes_count += 1 yes_counts.append(yes_count) return sum(yes_counts) def main(): input_file = "day06-input.txt" print(part2(input_file)) if __name__ == "__main__": main()
768e2f09829822f51e38d0b37d1b2265aa61bfad
DiksonSantos/Curso_Intensivo_Python
/Pagina_166_Metodo_keys.py
307
3.984375
4
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } for pessoa in favorite_languages.keys(): #Com este metodo keys ele exibiu apenas as chaves ou nomes do dicionario print(pessoa.upper()) # Resumo :É o mesmo que -> 'for name in favorite_languages:'
2d44d93bfab8003c8ace9d35521fd77ea6e88de7
gustaver/kattis-problems
/yoda/yoda.py
1,631
3.546875
4
import sys first = int(sys.stdin.readline()) second = int(sys.stdin.readline()) first_as_list = map(int, str(first)) second_as_list = map(int, str(second)) if (len(first_as_list) >= len(second_as_list)): for i in range(0, len(second_as_list)): first_list_length = len(first_as_list) second_list_length = len(second_as_list) first_list_digit = first_as_list[first_list_length - i - 1] second_list_digit = second_as_list[second_list_length - i - 1] if (first_list_digit > second_list_digit): second_as_list[second_list_length - i - 1] = None if (first_list_digit < second_list_digit): first_as_list[first_list_length - i - 1] = None else: for i in range(0, len(first_as_list)): first_list_length = len(first_as_list) second_list_length = len(second_as_list) first_list_digit = first_as_list[first_list_length - i - 1] second_list_digit = second_as_list[second_list_length - i - 1] if (first_list_digit > second_list_digit): second_as_list[second_list_length - i - 1] = None if (first_list_digit < second_list_digit): first_as_list[first_list_length - i - 1] = None first_as_string = "" second_as_string = "" for integer in first_as_list: if (integer != None): first_as_string += str(integer) for integer in second_as_list: if (integer != None): second_as_string += str(integer) if (first_as_string == ""): print("YODA") else: print(int(first_as_string)) if (second_as_string == ""): print("YODA") else: print(int(second_as_string))
916c07c9041fb1e5093120f6172340906925cb1f
mirkomantovani/page-rank-word-graph
/graph.py
628
3.5
4
# Mirko Mantovani class UndirectedGraph: def __init__(self): self.graph = {} def __repr__(self): return 'Graph:'+ str(self.graph) def add_node(self, node): if node not in self.graph: self.graph[node] = {} def add_edge(self, i, j, weight): if i not in self.graph: self.add_node(i) if j not in self.graph: self.add_node(j) self.graph[i][j] = weight self.graph[j][i] = weight def get_edge(self, i, j): if i in self.graph: if j in self.graph[i]: return self.graph[i][j] return -1
d7c3239941d3c1a3d15ece4772930a1c21943a03
Someperson99/Assign-3
/json_handler.py
1,576
4.15625
4
import json import os def create_json_file(letter: str, index: dict, version: int): '''given a starting letter and an index this function will create a json file nammed after the letter parameter and insert the index parameter into the json file''' with open("/Users/allysonyamasaki/PycharmProjects/Assign-3/results/"+letter + str(version) + '.json', 'w') as file: json.dump(index, file) file.close() def get_json_content(path: str) -> dict: '''given a path to a json file this function will return the json data in dictionary form''' f = open(path, 'r') index = json.load(f) f.close() return index def write_to_file(index: dict, times_written_to_disk: int): curr_dir = os.getcwd() letter_dict = {} curr_letter = "" # temporary dictionary that will store all the words that start with a certain letter for i in sorted(index.keys()): first_letter = i[0] if curr_letter == "": curr_letter = first_letter elif curr_letter == first_letter: pass else: """ MAC USERS: if os.path.exists(curr_dir + "/" + first_letter + ".json"): prev_index = get_json_content(curr_dir + "/" + first_letter + ".json") """ create_json_file(curr_letter, letter_dict, times_written_to_disk) curr_letter = i[0] letter_dict = {} letter_dict[i] = index[i] if curr_letter == "z": create_json_file(curr_letter, letter_dict, times_written_to_disk)
cd93fa67078a7baf3147db1e3b6141123876c2ff
Giby666566/programacioncursos
/gui/programa1.py
801
3.84375
4
#hacer un programa donde tienes un boton que dice "explorar archivo" donde seleccionas una imagen y # esa imagen la pone en un label import tkinter from tkinter import PhotoImage from tkinter import filedialog from PIL import image def abrirarchivo(): global miimagen global imagen tipos=[("Archivos jpg","*.jpeg"),("Archivos png","*.png"),("todos los archivos","*.*")] archivo=tkinter.filedialog.askopenfilename(title="dame un arhivo para abrir...",defaultextension=".jpg",filetypes=tipos) imagen=tkinter.PhotoImage(file=archivo) miimagen.configure(image=imagen) miimagen.image=imagen root=tkinter.Tk() boton=tkinter.Button(root,text="explorar archivo...",command=abrirarchivo) miimagen=tkinter.Label(root,text="hola") boton.pack() miimagen.pack() root.mainloop()
ab9feca924746c8b3e551d80f6a183bbd2387a04
Monty42/DS_and_Python_courses
/GeekBrains/les_7/les_7_task_1.py
1,258
4.125
4
# Отсортируйте по убыванию методом пузырька одномерный целочисленный массив, # заданный случайными числами на промежутке [-100; 100). Выведите на экран исходный и отсортированный массивы. # # Примечания: # 1. алгоритм сортировки должен быть в виде функции, которая принимает на вход массив данных, # 2. постарайтесь сделать алгоритм умнее, но помните, что у вас должна остаться сортировка пузырьком. import random def bubble_sort(lst): n = 1 while n < len(lst): count = 0 for i in range(len(lst) - 1 - (n - 1)): if lst[i] < lst[i + 1]: lst[i], lst[i + 1] = lst[i + 1], lst[i] count += 1 if count == 0: break n += 1 SIZE = 10 MIN_ITEM = -100 MAX_ITEM = 99 array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)] print('Массив:', array, sep='\n') bubble_sort(array) print('После сортировки:', array, sep='\n')
73479e032bd547c580f0d3c1cbd5138abf689bb1
soumyasen1809/NPTEL_IITG_Numerical_Methods_and_Simulation
/Monte_Carlo_Pi.py
699
3.96875
4
# Use Monte Carlo Integration to calculate the value of pi import random itns = 1000 # Number of iterations count = 0 # Counter for number of points in the circle of radius 1 for i in range(0, itns): x_rand = random.random() # Random X co-ordinates; random.random() gives random values from 0 to 1 y_rand = random.random() # Random Y co-ordinates; the max value is 1 if x_rand**2 + y_rand**2 < 1: # Condition for points inside the circle region x^2 + y^2 = 1 count = count + 1 pi_val = 4*(count/float(itns)) print ('Value of pi via Monte Carlo Method is: {}'.format(pi_val)) print ('Error is {}'.format(pi_val - (22/float(7))))
3bb4716bfa8484e4dfe83335bf85d6502cca851b
shihyuuuuuuu/LeetCode_practice
/prob690.py
662
3.625
4
""" # Definition for Employee. class Employee: def __init__(self, id: int, importance: int, subordinates: List[int]): self.id = id self.importance = importance self.subordinates = subordinates """ class Solution: def getImportance(self, employees: List['Employee'], id: int) -> int: d = {} for i in employees: d[i.id] = [i.importance, i.subordinates] subs = [id] def DFS(subs, imp): if not subs: return imp for i in subs: imp += d[i][0] imp = DFS(d[i][1], imp) return imp return DFS(subs, 0)
9e8c6e69d0f6a4ae80ef27ef26052c6c71488a85
LeviCoelho/SistemasInteligentes
/perceptron.py
3,736
3.578125
4
# Só consegue separar em duas coisas import numpy as np # Biblioteca para algebra linear from activation_functions import signum_function import matplotlib.pyplot as plt # Responsavel pelos graficos= class Perceptron(): def __init__(self, input_size, act_func=signum_function, epochs=100, learning_rate=0.01, labelGraphic = 'Perceptron'): self.act_func = act_func self.epochs = epochs self.learning_rate = learning_rate self.weights = np.random.rand(input_size + 1) self.labelGraphic = labelGraphic self.truePositive = 0 self.falseNegative = 0 self.falsePositive = 0 self.trueNegative = 0 def Graphic(self, x ,y,Label): plt.scatter(x, y, label = Label, color = 'r', marker = '.', s = 10) plt.legend() plt.show() def predict(self, inputs): inputs = np.append(-1, inputs) u = np.dot(inputs, self.weights)# np.dot ->Muktiplicação de matrizes, multiplicaçã vetorial return self.act_func(u) def testNetwork(self, training_inputs, labels): for inputs, label in zip(training_inputs, labels): # Tupla predicton = self.predict(inputs) if predicton == label and predicton == 1: self.truePositive = self.truePositive + 1 if predicton != label and predicton == -1 : self.falseNegative = self.falseNegative + 1 if predicton != label and predicton == 1 : self.falsePositive = self.falsePositive + 1 if predicton == label and predicton == -1: self.trueNegative = self.trueNegative + 1 def showConfusionMatrix(self): text = ['True Positive', 'False Negative', 'False Positive', 'True Negative'] qty = [self.truePositive, self.falseNegative, self.falsePositive, self.trueNegative] plt.bar(text, qty, color = 'b') plt.xticks(text) plt.ylabel('Quantidade de resultados') plt.xlabel('Valores da Matriz de confusao') plt.title('Confusion Matrix') plt.show() def train(self, training_inputs, labels): error = True vetorE = [] vetorY = [] for e in range(self.epochs): #Quantidade de vezes que o algoritimo vai rodar error = False #print(f'>>> Start epoch {e + 1}') #print(f'Actual weights {self.weights}') for inputs, label in zip(training_inputs, labels): # Tupla #print(f'Input {inputs}') predicton = self.predict(inputs) vetorE.append(e) vetorY.append(predicton) if predicton != label: #print(f'Expected {label}, got {predicton}. Start trainning!') inputs = np.append(-1, inputs) self.weights = self.weights + self.learning_rate * (label - predicton) * inputs #Equação de ajuste de pesos #print(f'New weights {self.weights}') error = True break #else: #print(f'Everything is OK!') #print('') if not error: print('Perceptron Concluido na epoca %i' % e) break else : if e >= (self.epochs-1): print('Dados nao podem ser separados atraves do perceptron') #self.Graphic(vetorE,vetorY,self.labelGraphic)
56950b760493954929577f894180448b83c57b72
Gaya1858/-100daysofCode-Python
/day2/primitive.py
952
4.3125
4
# Data types # String # "Hello" is 5 character word. It has length of 5 character. Also counting from 0. # Position of H starts 0 ''' print("Hello",[len("Hello")]) #integer number = 123_456_789 # _ treated as comma in python number1 = 123_456_789 num2 = number+number1 print(num2) # float x = 3.14567 print(round(x, 2)) # boolean boo = True print(type(boo)) # extra stuff num_char = len(input("enter your name: ")) print(type(num_char)) # now num_char is in interger, as it takes the input and stores its length in the variable. # adding integer characters together. print("Welcome to the project adding input characters!") u_input = input("enter a two digit number") x = int(u_input[0]) y =int(u_input[1]) print("You have entered: "+u_input+ " .The sum of the digits is: ",x+y)''' # mathematical symbols # 6/3 - float # 2 ** 3 - 2 to the power of 3 which is 8 # python follows PEMDAS rule for processing the mathematical signs print(3/3+3*3-3)
25a75bdf2b3f3908fe204569332cdbfe38bd62d7
allen5103/pythonStart
/datatype.py
403
4.0625
4
# 數字 321 # 字串 '測試中文' # 布林值 True False # 有順序、可動的列表 List [3, 4, 5] # 有順序、不可動的列表 Tuple (3, 4, 5) # 集合 Set {3, 4, 5} # 字典 Dicrionary {'apple': '蘋果'} # 變數:用來儲存資料的自訂名稱 data = {3, 4, 5} # for x in data: # print(x) thisset = set(("apple", "banana", "cherry")) # note the double round-brackets print(thisset)
8526492e124c2190666335460d39d827e3f00051
TieZhuNo1/lemon_code
/homework/2021.8.8/code_03.py
420
3.53125
4
""" ========================================== Author:天天 Time:2021/8/8 ========================================== """ # 3、通过字典推导式,颠倒字典的键名和值:将{'py': "python09", 'java': "java09"} 转换为: {'python09': "py", 'java09': "java"} dic_1 = {'py': "python09", 'java': "java09"} dic_2 = {value: key for key, value in dic_1.items()} print(dic_2) # {'python09': 'py', 'java09': 'java'}
8e9c7079452edd97996e49f2737d652b91d63be8
viveklele/ExternalProjectPython
/ubuntu_path.py
138
3.5
4
path = input("Enter path: ") new_path = path.replace('\\', '/').replace('D:', 'cd /mnt/d').replace('C:', 'cd /mnt/c') print(new_path)
af704da0705d0b532784cfc7227009048c2399d3
Ran500/Python
/Github-python/print.py
501
3.921875
4
# لطباعة تستخدم ==> print # مثال: print('Hello python') print(' I love python ') # ________________________________________________________________________________ # ;اما اذا اردت كتابة الكود على سطر واحد ضع علامة print('Hello python') print('I love python') # نفس النتيجة # ________________________________________________________________________________ e = """First Line Second Line Third Line""" print(e) print("=" * 50)
f07995fb84617efc87721472562287d8dd73ab40
wdhif/daily-coding-problem
/14.py
1,000
4.1875
4
#!/usr/bin/env python3 """ The area of a circle is defined as πr². Estimate π to 3 decimal places using a Monte Carlo method. Hint: The basic equation of a circle is x2 + y2 = r2. """ import unittest import math import random def generate_points(radius): x = random.randint(-radius, radius) y = random.randint(-radius, radius) return x, y def in_circle(x, y, radius): distance = math.sqrt(x ** 2 + y ** 2) if distance < radius: return True return False def compute_pi(): points_in_circle = 0 points_in_square = 0 radius = 200 for i in range(250000): x, y = generate_points(radius) if in_circle(x, y, radius): points_in_circle += 1 points_in_square += 1 return 4 * (points_in_circle / points_in_square) class Test(unittest.TestCase): def test(self): accuracy = (compute_pi() / math.pi) * 100 self.assertGreater(accuracy, 99) if __name__ == '__main__': unittest.main()
9dca882eb21bf60229db1936e0b344a46ecae2ff
maayan20-meet/y2s19-mainstream-python-review
/part2.py
901
3.890625
4
# Part 2 of the Python Review lab. def encode(x, y): if not (500 < x or x > 1000) or not (1 < y or y < 250): print("Invalid input: Outside range.") return while not is_prime_number(x): x += 1 while not is_prime_number(y): y += 1 return x*y def decode(coded_message): prime_numbers = list() for i in range(2, 1000): if is_prime_number(i): prime_numbers.append(i) for i in prime_numbers: if coded_message%i == 0: break return coded_message/i, i def is_prime_number(x): # function will check if a number is a prime # :param: x - int, number to check # return: True if number is prime, flase other wise # credit: https://linuxconfig.org/function-to-check-for-a-prime-number-with-python if x >= 2: for y in range(2,x): if not ( x % y ): return False else: return False return True print(decode(encode(550, 200)))
43977fbe11ff36b5046bb63c28d4d885357471f4
abiodun0/amity-room-allocation
/models/room.py
1,585
4.28125
4
"""This is the model class for Amity""" class Room(object): def __init__(self, name): """ initialize the function with room name only """ self.name = name self.people = [] def get_people(self): """ gets the number of occupants for this office/living space and returns them in a string """ return ', '.join([people.name for people in self.people]) def add_person(self, person): """ This utility method add person to the room @params instace of People """ if not self.is_filled(): self.people.append(person) if isinstance(self, Office): person.set_office(str(self)) else: person.set_living(str(self)) else: print "No more spaces in this room" def is_filled(self): """ Checks if this room is avaialble """ if len(self.people) < self.max_people: return False else: return True class Office(Room): def __init__(self, name, max_people=6): """ This calls the super class to set the maximum number of people needed for this office """ super(Office,self).__init__(name) self.max_people = max_people def __str__(self): """ Changes the way this room displays to the format e.g ROOM 1 (Office) """ return self.name + " (Office)" class Living(Room): def __init__(self, name, max_people=4): """This calls the super class to set the maximum number of people needed for this room """ super(Living,self).__init__(name) self.max_people = max_people def __str__(self): """ Changes the way this room displays to the format e.g ROOM 1 (Living) """ return self.name + " (Living)"