blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
324e4ca6292ef63cd68fb5708144e7f33454af3d
VaibhavRangare/python_basics_part1
/List1.py
790
4.0625
4
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 8] print(len(list1)) print(list1[0]) print(list1) # start index:end index:step print(list1[::2]) print(list1[:]) list1.append(9) print(list1) print(list1.count(8)) # how many times an item is there in the list print(list1.index(4)) # index position of an item list1.insert(3, 3) # insert an item at index list1.pop(0) # remove element at index list1.remove(4) # removes object list1.reverse() list1.sort() print(list1) list2 = [10, 11, 12] list3 = list1 + list2 print(list3) list1.clear() # empty the list print(list1) coordinates = [1, 2, 3] x, y, z = coordinates # unpacking print(x) print(y) print(z)
f16366640ba48446b1afeaac2bc1f976e42e75ec
TechKrowd/sesion2python_10062020
/alternativas/01.py
174
3.8125
4
""" Pedir un nรบmero por teclado y comprobar si estรก comprendido entre 1 y 10. """ n = int(input("Introduce un nรบmero: ")) print("Si") if n>=1 and n<=10 else print("No")
3d78654f3592bc041d7322d41be9f1f0ebd30fb9
daniiarkhodzhaev-at/lab1
/2.py
300
3.53125
4
#!/usr/bin/python3 import matplotlib.pyplot as plt import numpy as np def y(x: np.ndarray) -> np.ndarray: return x ** 2 - x - 6 def main() -> int: _x = np.array(range(-300,400)) / 100 _y = y(_x) plt.plot(_x, _y) plt.show() return 0 if (__name__ == "__main__"): main()
85ecf178f301c7dec9407eb66554058bd9dafd64
Danilo-mr/Python-Exercicios
/Exercรญcios/ex005.py
106
3.96875
4
n = int(input('Digite um nรบmero: ')) print('Antecessor รฉ {} e o sucessor รฉ {}'.format(n-1, n+1))
cbb1f87b88123c1286fb127dd8e76bfed156663e
Sranciato/holbertonschool-interview
/0x13-count_it/0-count.py
1,141
3.5625
4
#!/usr/bin/python3 """Queries Reddit API and finds keywords from all hot posts""" import requests from sys import argv def count_words(subreddit, word_list, after="", counter={}, check=0): """Queries Reddit API and finds keywords from all hot posts" """ if check == 0: for word in word_list: counter[word] = 0 headers = {'User-Agent': 'steve'} json = requests.get('https://api.reddit.com/r/{}/hot?after={}'. format(subreddit, after), headers=headers).json() try: key = json['data']['after'] parent = json['data']['children'] for obj in parent: for word in counter: counter[word] += obj['data']['title'].lower().split(' ').count( word.lower()) if key: count_words(subreddit, word_list, key, counter, 1) else: res = sorted(counter.items(), key=lambda i: i[1], reverse=True) for key, value in res: if value != 0: print('{}: {}'.format(key, value)) except Exception: return None
ed8c3082a7b09917a031102ffa1b96752a637726
Elmlea/pythonLearn
/ex23.py
1,103
3.921875
4
import sys # this is command line argument handling script, encoding, error = sys.argv def main(language_file, encoding, errors): line = language_file.readline() #reads a line from language_file if line: #if statement; the indented lines below run if true print_line(line, encoding, errors) #lines 9/10 skipped if above false return main(language_file, encoding, errors) # calling main within main makes it loop until line 8 is false def print_line(line, encoding, errors): next_lang = line.strip() # removes the white space (and apparently \n) # we can put a string in to strip too raw_bytes = next_lang.encode(encoding, errors=errors) # this calls encode on the next_lang string, and the arguments are the encoding # and error handling cooked_string = raw_bytes.decode(encoding, errors=errors) #this is the inverse of line 16 print(raw_bytes, "<===>", cooked_string) languages = open("languages.txt", encoding="utf-8") # we define here that the file we're handling is encoded in UTF-8 main(languages, encoding, error)
4cd89955a81924314ebea33ad83f2b07c5d59a12
peltierchip/the_python_workbook_exercises
/chapter_5/exercise_122.py
990
4.03125
4
## #Translating the string entered by the user into Pig Latin language #Read the string from the user s_e=input("Enter a string:\n") w="" #Create a list to store the words of the string entered l_s_e=s_e.split() #Create a list to store the words stored in l_s_e in Pig Latin language l_s_p_l=[] #Translate each stored word into l_s_e and store it in l_s_p_l for i in l_s_e: w=i #Check if w starts by vowel or consonant if w[0]=="a" or w[0]=="e" or w[0]=="i" or w[0]=="o" or w[0]=="u": w=w+"way" l_s_p_l.append(w) else: j=0 p_w="" p_w=p_w+w[j] j=j+1 #Keep looping while the character of w is different by a vowel while w[j]!="a" and w[j]!="e" and w[j]!="i" and w[j]!="o" and w[j]!="u": p_w=p_w+w[j] j=j+1 p_w=w[j:]+p_w+"ay" l_s_p_l.append(p_w) delimeter=" " print("\n") #Display the result print("Your string in Pig Latin:") s_p_l=delimeter.join(l_s_p_l) print(s_p_l)
37deb9eabf9cbf639c7c4d9a7f387e546577fd5e
westyyyy/What-am-i
/What am I.py
924
4.125
4
def valid(question): answer = input(question + "\n> ") while not(answer == "y" or answer == "n"): answer = input(question + "\n> ") if answer == "y": return True return False print ("Welcome to what am I\nRespond with y/n\n") if valid("Does it have legs?"): if valid("Does it have wings?"): print ("It's a bird!") elif valid("Does it live in a cage?"): if valid("Is it a hamster?"): print ("It's a hamster!") else: if valid("Does it live indoors?"): if valid("Is it a cat?"): print ("It's a cat!") else: print ("It's a dog!") else: print ("It's a fox!") elif valid("Does it live underwater?"): if valid("Is it a fish?"): print ("It's a fish!") else: print ("It's a snake!") else: print("It's a snake!")
4cdb7e1693b8e5d73aeab0b115a38a36d4d2df58
himanshu2801/hackerrank_code
/filling jars.py
703
3.578125
4
""" Link of the question... https://www.hackerrank.com/challenges/filling-jars/problem Solution... """ #!/bin/python3 import os import sys # Complete the solve function below. def solve(n, operations): sum=0 for i in range(len(operations)): sum=sum + (operations[i][1] - operations[i][0] + 1)*operations[i][2] avr=sum//n return avr if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nm = input().split() n = int(nm[0]) m = int(nm[1]) operations = [] for _ in range(m): operations.append(list(map(int, input().rstrip().split()))) result = solve(n, operations) fptr.write(str(result) + '\n') fptr.close()
bed0e874f9a755ecd5d04e3c0c5ed6f8ef2a8eb0
DavidGavaghan/pints
/pints/_util.py
2,366
3.5
4
# # Utility classes for Pints # # This file is part of PINTS. # Copyright (c) 2017, University of Oxford. # For licensing information, see the LICENSE file distributed with the PINTS # software package. # from __future__ import absolute_import, division from __future__ import print_function, unicode_literals import pints import numpy as np import timeit def strfloat(x): """ Converts a float to a string, with maximum precision. """ return pints.FLOAT_FORMAT.format(float(x)) class Timer(object): """ Provides accurate timing. Example:: timer = pints.Timer() print(timer.format(timer.time())) """ def __init__(self, output=None): self._start = timeit.default_timer() self._methods = {} def format(self, time): """ Formats a (non-integer) number of seconds, returns a string like "5 weeks, 3 days, 1 hour, 4 minutes, 9 seconds", or "0.0019 seconds". """ if time < 60: return '1 second' if time == 1 else str(time) + ' seconds' output = [] time = int(round(time)) units = [ (604800, 'week'), (86400, 'day'), (3600, 'hour'), (60, 'minute'), ] for k, name in units: f = time // k if f > 0 or output: output.append(str(f) + ' ' + (name if f == 1 else name + 's')) time -= f * k output.append('1 second' if time == 1 else str(time) + ' seconds') return ', '.join(output) def reset(self): """ Resets this timer's start time. """ self._start = timeit.default_timer() def time(self): """ Returns the time (in seconds) since this timer was created, or since meth:`reset()` was last called. """ return timeit.default_timer() - self._start def vector(x): """ Copies ``x`` and returns a 1d read-only numpy array of floats with shape ``(n,)``. Raises a ``ValueError`` if ``x`` has an incompatible shape. """ x = np.array(x, copy=True, dtype=float) x.setflags(write=False) if x.ndim != 1: n = np.max(x.shape) if np.prod(x.shape) != n: raise ValueError('Unable to convert to 1d vector of scalar values') x = x.reshape((n,)) return x
c277727f39f20dc1baa477f5c6183affdc81a2cb
wolfgang-stefani/computer-vision_canny_edge_detection
/canny-edge-detection.py
1,264
3.65625
4
# Do all the relevant imports import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 # Read in the image and convert to grayscale # Note: in the previous example we were reading a .jpg # Here we read a .png and convert to 0,255 bytescale image = mpimg.imread('exit-ramp.jpg') gray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY) # Define a kernel size for Gaussian smoothing / blurring kernel_size = 3 # Must be an odd number (3, 5, 7...) blur_gray = cv2.GaussianBlur(gray,(kernel_size, kernel_size),0) # Define our parameters for Canny and run it low_threshold = 80 high_threshold = 200 # high_threshold ist der wichtigere Schwellwert der beiden. # Je hรถher dieser ist, um so weniger Edges werden angezeigt. # Logik: Erst ab einem Gradienten von 200 (von Pixel zum benachbarten Pixel) wird der Pixel als Edge angezeigt. # low_threshold: Er bestimmt im Wesentlichen nur noch die Spanne zwischen low und high_threshold. Je grรถรŸer # diese Spanne ist, umso mehr direkt benachbarte Pixel werden zusรคtzlich als Edges angezeigt. edges = cv2.Canny(blur_gray, low_threshold, high_threshold) # Display the image plt.imshow(edges, cmap='Greys_r')
e13854d98c9ff420c1a7d1c2cf59866fe23efa39
kristophbee/general
/guessurnum.py
1,238
3.890625
4
import random validVal=False guessed=False maxVal=100#max zakres minVal=0#min zakres tries=0 while validVal == False: print("Enter a number") resp = input() try: val=int(resp)#zrzut do inta if int(resp) < minVal or int(resp) > maxVal: print("Values between "+str(minVal)+" and "+str(maxVal)+" are allowed. Try again.") else: validVal=True except ValueError:#na wypadek kaplicy z konwersjฤ… ze stringa print("Very funny. Try again") while guessed == False: aiguess = random.randint(minVal,maxVal) if aiguess == int(resp): print("Its "+str(aiguess)+"! And it only took me "+str(tries)+" tries!") guessed = True elif aiguess < int(resp): print(str(aiguess)+" is too low.") minVal=aiguess+1#redukcja zakresu aby zmniejszyฤ‡ iloล›ฤ‡ moลผliwoล›ci tries+=1 elif aiguess > int(resp): print(str(aiguess)+" is too high.") maxVal=aiguess-1#adaptacja zakresu tries+=1 else:#na wszelki. print("Oops") break
04b841123a22899f60724a23e7154f46b6e3106c
slmnptl11/Simple-Expense-Tracker
/Expense_tracker_.py
4,062
4.375
4
import sqlite3 import datetime class Mymain: # Defining the main function to operate other function in the body def main(self): while (True): print("=====================================================") print(" -=-=-| Welcome to the Expense Tracker system |-=-=- ") print("=====================================================") print("Enter 1. To enter expenses into your database") print("Enter 2. To view current expenses with date") print("Enter 3. To see total spending") print("Enter 4. To exit") print("=====================================================") try: self.a = int(input("Select a choice (1-4): ")) print() if (self.a == 1): d = Data_input() # creating a Data_input class object d.data() # calling data() function with the Data_input class object elif (self.a == 2): v = Data_input() # creating a Data_input class object v.view_data() # calling view_data() function with the Data_input class object elif (self.a == 3): t = Data_input() # creating a Data_input class object t.total_amount() # calling total_amount() function with the Data_input class object elif (self.a == 4): print("Thank you for using Expense Tracker system.") break else: print("Please enter a valid choice from 1-4") except ValueError: # Exception-handling print("Oops ! Please input as suggested.") class Data_input: # Function for entering data into database def data(self): conn = sqlite3.connect('my_expns_database.db') cursor = conn.cursor() # creating the Expense table in the database cursor.execute(''' create table if not exists expense( item string, price number, date string ) ''') # Getting user input for the expense data i_item = str(input('Enter the item you purchased:')) i_price = float(input('Cost of item in Dollars:')) date_entry = input('Enter a purchase date in YYYY/MM/DD format:') year, month, day = map(int, date_entry.split('/')) i_date = datetime.date(year, month, day) # sql query to enter data into the database cursor.execute(""" INSERT INTO expense(item, price, date) VALUES (?,?,?) """, (i_item, i_price, i_date)) conn.commit() print('Data entered successfully.') # Function for viewing expense data from database def view_data(self): conn = sqlite3.connect('my_expns_database.db') cursor = conn.cursor() # Sql query to get all the stored data in database cursor.execute(""" SELECT * from expense """) rows = cursor.fetchall() # Fetching all the entries from the database based on query print ('*** Every Expense data you entered with date ***') print() for r in rows: print("Item-Name:", r[0], "|", "Price:", '$', r[1], "|", "Date:", r[2]) print("--------------------------------------------------------------------") # Function for viewing total expense so far def total_amount(self): conn = sqlite3.connect('my_expns_database.db') cursor = conn.cursor() cursor.execute(""" SELECT sum(price) from expense """) total = cursor.fetchone() # Fetching only one output which is the total amount for row in total: print("Total Spending in Dollars:", "$", row) # Calling the main Function m = Mymain() m.main()
2b3c55daa8a1ab27a0bcb5c7e794557fbf87f731
ehoversten/flask_fundamentals
/assignment_routing.py
876
4.34375
4
# ------------------------------------------------------------------------------/ # Assignment: Understanding Routing # Objectives: # Practice building a server with Flask from scratch # Get comfortable with routes and passing information to the routes # # ------------------------------------------------------------------------------/ from flask import Flask app = Flask(__name__) print(__name__) @app.route('/') def hello(): return "Hello World!" @app.route('/dojo') def dojo(): return "Dojo!" @app.route('/say/<name>') def say(name): print(name) return "Hi " + name @app.route('/repeat/<count>/<given_input>') def repeat_hello(count, given_input): print(count) print(given_input) print(f"{given_input} \n" * int(count)) return given_input * int(count) if __name__=="__main__": app.run(debug=True)
8e4e199418dd4e581bd5cacc6694be07f2e67598
wahab14131211/Bell_pey_challenge_Wahab
/Files for Testing/pred_war_testing.py
1,915
3.71875
4
from random import * #This script is a simple version of the predwar game described in the challenge statement. #This is used to test 2 strategies, to determine which one is better def player2(x,y,z,b,r,k): #where k is the desired betrayal rate for player2 if randint(0,100) < k: return "cooperate" else: return "betray" def wahab_predwar (x,y,z,b,r): if (r**1.1)>randint(1,10000): avg_tokens_lost= ((x*b) + (z-y)*(1-b))/2 if avg_tokens_lost <= 1: return "cooperate" return "betray" else: if b>0.85 or (b>0.0001 and b<0.15): return "betray" if (z-y)/(y-x)>= 1: return "betray" return "cooperate" player1_tokens=0 player2_tokens=0 player1_betrayals=0 player2_betrayals=0 for round in range (1,10001): token = [] for _ in range (3): num = randint(1,10) while num in token: num = randint(1,10) token.append(num) token.sort() player1_choice=wahab_predwar(token[0],token[1],token[2],player2_betrayals/round,round) player2_choice=player2(token[0],token[1],token[2],player1_betrayals/round,round,randint(0,100)) if (player1_choice == "betray" and player2_choice == "betray"): player1_tokens += token[0] player2_tokens += token[0] player1_betrayals += 1 player2_betrayals += 1 elif (player1_choice == "cooperate" and player2_choice == "cooperate"): player1_tokens += token[1] player2_tokens += token[1] else: if (player1_choice == "betray"): player1_tokens += token[2] player1_betrayals += 1 else: player2_tokens += token[2] player2_betrayals += 1 print ("Player1:\n\tTokens:%i\n\tBetrayal:%f\nPlayer2\n\tToken:%i\n\tBetrayal:%f"% (player1_tokens,player1_betrayals/10000,player2_tokens,player2_betrayals/10000.0))
ffa8014c4526962ceb18bf32e2452300ac8baa5e
AlekhyaMupparaju/pyothon
/79.py
120
3.53125
4
import math s,m=map(int,raw_input().split()) a=s * m if math.sqrt(a).is_integer(): print "yes" else: print "no"
9efb509eee250a0d29f3d76076da55f22f051002
mmfrenkel/brain-teasers
/python_problems/problem7/main.py
1,257
3.765625
4
#!/bin/python3 import math import os import random import re import sys # Complete the hourglassSum function below. def hourglassSum(arr): largest_sum = 0 if not arr or len(arr) < 3 or len(arr[0]) < 3: return largest_sum rows_of_hour_glasses = len(arr) - 2 for row in range(0, rows_of_hour_glasses): top_arr = arr[row] middle_arr = arr[row + 1] lower_arr = arr[row + 2] hour_glasses_in_row = len(top_arr) - 2 indicies_top_bottom = [0, 1, 2] index_middle = 1 count = 0 while count < hour_glasses_in_row: top = sum([top_arr[index + count] for index in indicies_top_bottom]) bottom = sum([lower_arr[index + count] for index in indicies_top_bottom]) middle = middle_arr[index_middle + count] curr_sum = top + bottom + middle print(curr_sum) largest_sum = curr_sum if curr_sum > largest_sum else largest_sum count += 1 return largest_sum if __name__ == '__main__': arr = [[-1, -1, 0, -9, -2, -2], [-2, -1, -6, -8], [], [], [], []] for _ in range(6): arr.append(list(map(int, input().rstrip().split()))) result = hourglassSum(arr) print(result)
1f3041f20e0e7e00802a75e2411ecc21c3338e63
RALF34/McGyver_Game
/classes.py
9,391
3.59375
4
"""classes for McGyver game""" import pygame import random from pygame.locals import * from constants import * class Labyrinth: def __init__(self, code_file): """File coding the structure of the labyrinth """ self.code_file = code_file """Dictionnary containing the three objects as keys and their positions as values""" self.position_tools = {'ether': (0,0), 'tube': (0,0), 'needle': (0,0)} def display_game(self, position_mcgyver, screen): """Method to display the labyrinth""" screen.fill((34,177,76)) mcgyver = pygame.image.load("mcgyver.png").convert() guard = pygame.image.load("guard.png").convert() needle = pygame.image.load("needle.png").convert() tube = pygame.image.load("plastic_tube.png").convert() ether = pygame.image.load("ether.png").convert() screen.blit(mcgyver, position_mcgyver) screen.blit(guard, ((nbr_cells_on_board-1)*lenght_cell, \ (nbr_cells_on_board-1)*lenght_cell)) """The following tests are telling which tool(s) has been found by McGyver, so they don't appears on the screen anymore""" if 'ether' in self.position_tools.keys(): screen.blit(ether, self.position_tools['ether']) if 'tube' in self.position_tools.keys(): screen.blit(tube, self.position_tools['tube']) if 'needle' in self.position_tools.keys(): screen.blit(needle, self.position_tools['needle']) #pygame.display.flip() wall = pygame.image.load("WALL.png").convert() """Reading of "code_file" and loop to display the walls of the labyrinth""" with open(self.code_file, "r") as f: text = f.read() i, j, k = 0, 0, 0 while text[k] != 't': if text[k] == '\n': i += 1 j = 0 k += 1 elif text[k] == 'M': screen.blit(wall, (j*lenght_cell, i*lenght_cell)) #pygame.display.flip() j += 1 k += 1 else: j += 1 k += 1 def placing_tools(self): """Mรฉthod for randomly placing tools that McGyver has to collect in order to make the syringue """ needle_correctly_placed = False tube_correctly_placed = False ether_correctly_placed = False with open(self.code_file, "r") as f: lines = f.readlines() while not ether_correctly_placed: x_cell_ether = random.randint(2, nbr_cells_on_board-2) y_cell_ether = random.randint(2, nbr_cells_on_board-2) if lines[y_cell_ether][x_cell_ether] == "C": self.position_tools['ether'] = \ (x_cell_ether*lenght_cell, y_cell_ether*lenght_cell) ether_correctly_placed = True while not tube_correctly_placed: x_cell_tube = random.randint(2, nbr_cells_on_board-2) y_cell_tube = random.randint(2, nbr_cells_on_board-2) if lines[y_cell_tube][x_cell_tube] == "C": """test to prevent the tube and the ether bottle from being at the same place in the labyrinth""" if (x_cell_tube, \ y_cell_tube) != (x_cell_ether, y_cell_ether): self.position_tools['tube'] = \ (x_cell_tube* lenght_cell, y_cell_tube* lenght_cell) tube_correctly_placed = True while not needle_correctly_placed: x_cell_needle = random.randint(2, nbr_cells_on_board-2) y_cell_needle = random.randint(2, nbr_cells_on_board-2) if lines[y_cell_needle][x_cell_needle] == "C": """New tests to avoid having several tools at the same place in the labyrinth""" if (x_cell_needle, \ y_cell_needle) != (x_cell_tube, y_cell_tube): if (x_cell_needle, \ y_cell_needle) != (x_cell_ether, \ y_cell_ether): self.position_tools['needle'] = \ (x_cell_needle*lenght_cell, \ y_cell_needle*lenght_cell) needle_correctly_placed = True class Character: def __init__(self): self.x_cell = 0 self.y_cell = 0 self.x_pixel_pos = 0 self.y_pixel_pos = 0 self.tools_found = 0 def turning(self, laby, towards): mcgyver = pygame.image.load("mcgyver.png").convert() with open(laby.code_file, "r") as f: lines = f.readlines() if towards == 'right': """Making sure that Mcgyver is not on the right border of the labyrinth""" if self.x_cell != nbr_cells_on_board-1: """Making sure that the cell on the right is not a wall ? """ if lines[self.y_cell][self.x_cell+1] != 'M': """Making sure whether or not McGyver is moving to a position of a tool""" if (self.x_pixel_pos+lenght_cell, \ self.y_pixel_pos) in \ laby.position_tools.values(): self.tools_found += 1 """Loop to remove the tool (that McGyver has just found) from the dictionnary""" for key in laby.position_tools.keys(): if laby.position_tools[key] == \ (self.x_pixel_pos+lenght_cell, \ self.y_pixel_pos): laby.position_tools.pop(key) break self.x_cell += 1 self.x_pixel_pos = self.x_cell*lenght_cell if towards == 'left': """Making sure that McGyver is not on the left border of the labyrinth""" if self.x_cell != 0: """Making sure that there is no wall""" if lines[self.y_cell][self.x_cell-1] != 'M': """Checking the presence of a tool on the way""" if (self.x_pixel_pos-lenght_cell, \ self.y_pixel_pos) in \ laby.position_tools.values(): self.tools_found += 1 """Loop to remove the tools from the dictionnary""" for key in laby.position_tools.keys(): if laby.position_tools[key] == \ (self.x_pixel_pos-lenght_cell, \ self.y_pixel_pos): laby.position_tools.pop(key) break self.x_cell = self.x_cell-1 self.x_pixel_pos = self.x_cell*lenght_cell if towards == 'up': """Making sure that McGyver is not on the top of the screen""" if self.y_cell != 0: """Making sure that there's no wall""" if lines[self.y_cell-1][self.x_cell] != 'M': """Checking the presence of a tool""" if (self.x_pixel_pos, \ self.y_pixel_pos-lenght_cell) in \ laby.position_tools.values(): self.tools_found += 1 """Removing the element from the dictionnary""" for key in laby.position_tools.keys(): if laby.position_tools[key] == \ (self.x_pixel_pos, \ self.y_pixel_pos-lenght_cell): laby.position_tools.pop(key) break self.y_cell = self.y_cell-1 self.y_pixel_pos = self.y_cell*lenght_cell if towards == 'down': if self.y_cell != nbr_cells_on_board-1: if lines[self.y_cell+1][self.x_cell] != 'M': if (self.x_pixel_pos, \ self.y_pixel_pos+lenght_cell) in \ laby.position_tools.values(): self.tools_found += 1 for key in laby.position_tools.keys(): if laby.position_tools[key] == \ (self.x_pixel_pos, \ self.y_pixel_pos+lenght_cell): laby.position_tools.pop(key) break self.y_cell += 1 self.y_pixel_pos = self.y_cell*lenght_cell
061277ad4e1e23eedbb5572746c03bed5973720d
Chiranjit-Mukherjee/code-20210227-cmukherjee
/bmi_index.py
2,028
3.75
4
import argparse import pandas as pd from pandas import ExcelWriter import sys def process_bmi(input, output): try: df = pd.read_json(input) except Exception as e: print("Error: Specified file could not be found. Please check the file name and path") sys.exit() # calculating and storing BMI df['BMI'] = (df['WeightKg'] / (df['HeightCm']/100)) # calculating and storing BMI Category df['BMI Category'] = df['BMI'].apply(lambda x: 'Underweight' if x <= 18.4 else \ "Normal weight" if x >= 18.5 and x <= 24.9 else \ "Overweight" if x >= 25 and x <= 29.9 else \ "Moderately obese" if x >= 30 and x <= 34.9 else \ "Severely obese" if x >= 35 and x <= 39.9 else "Very severely obese") # calculating and storing Health risk df['Health Risk'] = df['BMI'].apply(lambda x: 'Malnutrition risk' if x <= 18.4 else \ "Low risk" if x >= 18.5 and x <= 24.9 else \ "Enhanced risk" if x >= 25 and x <= 29.9 else \ "Medium risk" if x >= 30 and x <= 34.9 else \ "High risk" if x >= 35 and x <= 39.9 else "Very high risk") # row in which value of 'BMI' column is more than 25 and less than or equal to 29.9 (Overweight) seriesObj = df.apply(lambda x: True if x['BMI'] >= 25 and x['BMI'] <= 29.9 else False , axis=1) # Count number of True in series numOfRows = len(seriesObj[seriesObj == True].index) if output: if output == 'CSV': filename = "output.csv" df.to_csv(filename, index=False) else: writer = ExcelWriter('output.xlsx') df.to_excel(writer,'Sheet1',index=False) writer.save() return numOfRows if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', help='input json file', required=True) parser.add_argument('-o', '--output', help='output file type', choices=['CSV', 'XLS'], type=str.upper) args = parser.parse_args() response = process_bmi(args.input, args.output) print("Total no of Overweight patient is : ", response)
2a041e301a6aa0d8dcbb6ec69393e5cda869155a
sandhiyasajiv/python
/positive or negative.py
167
4.28125
4
num=float (input(Input a number:")) if num>0: print("it is positive number") elif num==0: print("it is zero") else: print("it is a negative number")
2ec29932c1277baad3568b37839de1dfc81e6eab
peterpanGreg/Snake-in-blender-python
/Function.py
4,675
3.578125
4
from random import choice class Table(): def __init__(self,x,y): self.cord={} for i in range(y): for k in range(x): self.cord[(k,i)]=True self._keys=[] for i in self.cord.keys(): self._keys.append(i) self._values=[] for i in self.cord.values(): self._values.append(i) def __repr__(self): return str(self.cord) def __iter__(self): return iter(self.cord) def __getitem__(self,cord): return self.cord[cord] def __setitem__(self,cord,value): if (cord in self.cord)==True: self.cord[cord]=value def __contains__(self,i): return i in self.cord def keys(self): """Renvoie toutes les cordonnรฉes de l'objet sous forme de liste""" return self._keys def values(self): """Renvoie tous les รฉtats des cordonnรฉes de l'objet sous forme de liste""" return self._values def items(self): """Renvoie une liste [ (cordonnรฉes,รฉtat) , (...) , ... ]""" a=[] for i in self.cord.items(): a.append(i) return a def remplir(self,cord=None): """Change l'รฉtat d'une ou plusieures cordonnรฉe(s) True=>False""" if cord==None: for key in self: self.cord[key]=False elif len(cord)==2 and (cord in self.cord)==True: self.cord[cord]=False def nettoyer(self,cord=None): """Change l'รฉtat d'une ou plusieures cordonnรฉe(s) False=>True""" if cord==None: for key in self: self.cord[key]=True elif len(cord)==2 and (cord in self.cord)==True: self.cord[cord]=True class Pomme: def __init__(self,cords,cord=None): self.cords=cords if cord!=None: self.cord=(cord) else: cord=choice(cords.keys()) good=False while good!=True: if cords[cord]==True: self.cord=cord good=True def __repr__(self): return repr(self.cord) def __len__(self): return len(self.cord) def change(self): cord=choice(self.cords.keys()) good=False while good!=True: if self.cords[cord]==True: self.cord=cord good=True class Serpent: def __init__(self,cord=[(5,2),(4,2),(3,2),(2,2)],direct="E",cords=None): self.cord=cord self.tete=cord[0] self.queue=cord[1:] self.bout=cord[len(cord)-1] self.direct=direct x=0 y=0 for _x,_y in cords: if _x>x: x=_x if _y>y: y=_y self.limite=(x,y) def __repr__(self): return repr(self.cord) def __len__(self): return len(self.cord) def __iter__(self): return iter(self.cord) def __contains__(self,cord): return cord in self.cord def avancer(self,direct): if direct=='N': x,y=self.tete cord=[(x,y-1)] for key,i in enumerate(self.queue): cord.append(self.cord[key]) self.cord=cord self.tete=cord[0] self.queue=cord[1:] self.direct=direct elif direct=='S': x,y=self.tete cord=[(x,y+1)] for key,i in enumerate(self.queue): cord.append(self.cord[key]) self.cord=cord self.tete=cord[0] self.queue=cord[1:] self.direct=direct elif direct=='W': x,y=self.tete cord=[(x-1,y)] for key,i in enumerate(self.queue): cord.append(self.cord[key]) self.cord=cord self.tete=cord[0] self.queue=cord[1:] self.direct=direct elif direct=='E': x,y=self.tete cord=[(x+1,y)] for key,i in enumerate(self.queue): cord.append(self.cord[key]) self.cord=cord self.tete=cord[0] self.queue=cord[1:] self.direct=direct def avancer_bout(self): self.bout=self.cord[len(self.cord)-1] def ajout(self): self.cord.append(self.bout) self.queue=self.cord[1:] def perdre(self): if (self.tete in self.queue)==True or \ self.tete[0]>self.limite[0] or self.tete[1]>self.limite[1]\ or self.tete[0]<0 or self.tete[1]<0: return True
abd44b923998a7121f4a1ab426f44aa32ec6cefd
Jaswantsinghh/Python-Codes
/conversion to list and tuple.py
120
3.796875
4
a=input("Input comma seperated numbers :") list=a.split(",") tuple=tuple(list) print('list:',list) print('tuple:',tuple)
1d47f8f4d3e911cb2ae264088dac920ee3e45b0e
larafonse/cti-ips-2020
/math_m2/excel_column.py
239
3.96875
4
def excel_column_to_number(column): sum, count = 0,0 for i in range(len(column)-1,-1,-1): sum += (26**count) * (ord(column[i]) - 64) count+=1 return sum if __name__ == "__main__": print(excel_column_to_number(input()))
e87ebaf99af3550abea7494250b3da1d9aaced58
flashfinisher7/ML_Fellowship
/Week1/Program35.py
516
4.125
4
while True: try: ele1 = input("Enter the element1:") ele2 = input("Enter the element2:") ele3 = input("Enter the element3:") ele1 = int(ele1) ele2 = int(ele2) ele3 = int(ele3) List = [ele1, ele2, ele3] print('Your List is: ' + str(List)) new_list = list(filter(lambda x: (x % 15 == 0), List)) print("number is divided by 15:=", new_list) break except ValueError: print('Please enter a integer number')
c022575d283077e5d609f82142e566286f2ddf67
bssrdf/pyleet
/S/SubstringXORQueries.py
3,589
3.78125
4
''' -Medium- *Robin Karp* *Rolling Hash* *Hash Table* You are given a binary string s, and a 2D integer array queries where queries[i] = [firsti, secondi]. For the ith query, find the shortest substring of s whose decimal value, val, yields secondi when bitwise XORed with firsti. In other words, val ^ firsti == secondi. The answer to the ith query is the endpoints (0-indexed) of the substring [lefti, righti] or [-1, -1] if no such substring exists. If there are multiple answers, choose the one with the minimum lefti. Return an array ans where ans[i] = [lefti, righti] is the answer to the ith query. A substring is a contiguous non-empty sequence of characters within a string. Example 1: Input: s = "101101", queries = [[0,5],[1,2]] Output: [[0,2],[2,3]] Explanation: For the first query the substring in range [0,2] is "101" which has a decimal value of 5, and 5 ^ 0 = 5, hence the answer to the first query is [0,2]. In the second query, the substring in range [2,3] is "11", and has a decimal value of 3, and 3 ^ 1 = 2. So, [2,3] is returned for the second query. Example 2: Input: s = "0101", queries = [[12,8]] Output: [[-1,-1]] Explanation: In this example there is no substring that answers the query, hence [-1,-1] is returned. Example 3: Input: s = "1", queries = [[4,5]] Output: [[0,0]] Explanation: For this example, the substring in range [0,0] has a decimal value of 1, and 1 ^ 4 = 5. So, the answer is [0,0]. Constraints: 1 <= s.length <= 104 s[i] is either '0' or '1'. 1 <= queries.length <= 105 0 <= firsti, secondi <= 109 ''' from typing import List from collections import defaultdict class Solution: def substringXorQueries(self, s: str, queries: List[List[int]]) -> List[List[int]]: n, m = len(queries), len(s) mp = defaultdict(list) ans = [[-1, -1] for _ in range(n)] for i,(a, b) in enumerate(queries): mp[b^a].append(i) for l in range(1, 31): q, t = 2**(l-1), 0 for i in range(m): if i >= l: t = 2*(t - int(s[i-l])*q) + int(s[i]) else: t = t*2 + int(s[i]) if i >= l-1 and t in mp: for k in mp[t]: ans[k] = [i-l+1, i] mp.pop(t) if not mp: return ans return ans def substringXorQueries2(self, s: str, queries: List[List[int]]) -> List[List[int]]: n, m = len(queries), len(s) mp = defaultdict(list) ans = [[-1, -1] for _ in range(n)] for i,(a, b) in enumerate(queries): mp[b^a].append(i) for l in range(1, 31): q, t = 2**(l-1), 0 for i in range(min(l, m)): t = t*2 + int(s[i]) if t in mp: for k in mp[t]: ans[k] = [i-l+1, i] mp.pop(t) for i in range(l, m): t = 2*(t - int(s[i-l])*q) + int(s[i]) if t in mp: for k in mp[t]: ans[k] = [i-l+1, i] mp.pop(t) if not mp: return ans return ans if __name__ == '__main__': print(Solution().substringXorQueries(s = "101101", queries = [[0,5],[1,2]])) print(Solution().substringXorQueries(s = "0101", queries = [[12,8]])) print(Solution().substringXorQueries(s = "1", queries = [[4,5]])) print(Solution().substringXorQueries2(s = "101101", queries = [[0,5],[1,2]]))
a920c30a15a1c137cfbe6ccfc63cad331342fb3f
Anshikaverma24/meraki-function-questions
/meraki functions ques/debug last part/q2.py
168
3.75
4
# function multi(a,b): # multiply=a*b # return multiply # print(multi(3,4)) # ANSWER def multi(a,b): multiply=a*b return multiply print(multi(3,4))
a1e86e90766f33f078b4a59b89ae01ab26479377
radomirbrkovic/algorithms
/hackerrank/other/manasa-and-stones.py
317
3.765625
4
# Manasa and Stones https://www.hackerrank.com/challenges/manasa-and-stones/problem def stones(n, a, b): result = set() if a > b: a, b = b,a for i in range(n): result.add(i * a + (n-1 - i) * b) return sorted(list(result)) print stones(3, 1, 2) print stones(4, 10, 100)
7f1188a91a4d8502f042568b541d070b794687c7
xfree86/Python
/code/ex00007.py
1,320
3.953125
4
# -*- coding: utf-8 -*- # ๅญ—็ฌฆไธฒใ€ๅ˜้‡ใ€ๆ ผๅผๅŒ–็ฌฆๅทใ€่ฟ็ฎ—็ฌฆ็ปƒไน  # ๆ‰“ๅฐๅญ—็ฌฆไธฒ print "Mary had a little lamb." # ๆ‰“ๅฐๅญ—็ฌฆไธฒ๏ผŒ%sๆ ผๅผๅŒ–ๅญ—็ฌฆ่ฐƒ็”จๅŽ้ข็š„snowๅญ—็ฌฆไธฒ print "Its fleece was white as %s." % 'snow' # ๆ‰“ๅฐๅญ—็ฌฆไธฒ print "And everywhere that Mary went." # ๆ‰“ๅฐๅญ—็ฌฆไธฒ๏ผŒ10ไธช็‚น print "." * 10 # what'd that do? # ็ป™ๅ˜้‡end1่ต‹ๅ€ผๅญ—็ฌฆไธฒC end1 = "C" # ็ป™ๅ˜้‡end2่ต‹ๅ€ผๅญ—็ฌฆไธฒh end2 = "h" # ็ป™ๅ˜้‡end3่ต‹ๅ€ผๅญ—็ฌฆไธฒe end3 = "e" # ็ป™ๅ˜้‡end4่ต‹ๅ€ผๅญ—็ฌฆไธฒe end4 = "e" # ็ป™ๅ˜้‡end5่ต‹ๅ€ผๅญ—็ฌฆไธฒs end5 = "s" # ็ป™ๅ˜้‡end6่ต‹ๅ€ผๅญ—็ฌฆไธฒe end6 = "e" # ็ป™ๅ˜้‡end7่ต‹ๅ€ผๅญ—็ฌฆไธฒB end7 = "B" # ็ป™ๅ˜้‡end8่ต‹ๅ€ผๅญ—็ฌฆไธฒu end8 = "u" # ็ป™ๅ˜้‡end10่ต‹ๅ€ผๅญ—็ฌฆไธฒr end9 = "r" # ็ป™ๅ˜้‡end10่ต‹ๅ€ผๅญ—็ฌฆไธฒg end10 = "g" # ็ป™ๅ˜้‡end11่ต‹ๅ€ผๅญ—็ฌฆไธฒe end11 = "e" # ็ป™ๅ˜้‡end12่ต‹ๅ€ผๅญ—็ฌฆไธฒr end12 = "r" # watch that comma at the end. try removing it to see what happens # ้€—ๅท่กจ็คบๅœจๅŒไธ€่กŒ่พ“ๅ‡บ # ๆ‰“ๅฐๅ˜้‡end1ใ€end2ใ€end3ใ€end4ใ€end5ๅ’Œend6ๅˆๅนถๅŽ็š„ๅ€ผ๏ผŒๅนถๅœจๅŒไธ€่กŒ่พ“ๅ‡บ็š„print่ฏญๅฅ็š„ๅ€ผ๏ผŒไธคไธชๅ€ผ็”จไธ€ไธช็ฉบๆ ผ้š”ๅผ€ใ€‚ print end1 + end2 + end3 + end4 + end5 + end6, #ๆ‰“ๅฐๅ˜้‡end7ใ€end8ใ€end9ใ€end10ใ€end11ๅ’Œend12ๅˆๅนถๅŽ็š„ๅ€ผ print end7 + end8 + end9 + end10 + end11 + end12
5e36bdfc807bb3aac84c558f18433c53dd399b74
RitwickRoy/Annova
/Anova_analysis.py
3,113
3.703125
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 2 07:04:41 2020 @author: Ritwick """ # # ANOVA analysis # import pandas as pd # # read sample data and perform Anova analysis. # # Read input Excel file # Each sample/group is a column with first row containing # the sample name. The data is assumed to be in Sheet1 # each group is expected to have the same sample size # # def Anv_GroupMean(df): # # Compute mean of each group # grp_mean = [] for column in df: grp_mean.append(df[column].mean()) return grp_mean # def Anv_GrandMean(grp_mean, ngrp): # # Compute grand mean # sum_grp_mean = sum(grp_mean) grand_mean = sum_grp_mean/ngrp return grand_mean # def Anv_SSB(grp_mean, grand_mean, ngrp): # # Compute Sum of squares between groups # SSB = 0.0 for i in range(ngrp): SSB += ndata*(grp_mean[i] - grand_mean)**2 return SSB # def Anv_SSW(df, grp_mean, ndata): # # Compute Sum of squares within groups # SSW = 0.0 iC = 0 for column in df: for j in range(ndata): SSW += (df.loc[j,column] - grp_mean[iC])**2 iC += 1 return SSW # def Anv_SST(df,ndata,grand_mean): # # Compute Sum of squares Total # SST = 0.0 for column in df: for j in range(ndata): SST += (df.loc[j,column] - grand_mean)**2 return SST # ################################################################# # # Main body of execution steps # 1. REad Sample data from spreadsheet into a DataFrme # 2. Compute group mean for samples # 3. Compute grand mean for all samples # 4. Compute SSB # 5. Compute SSW # 6. Compute SST (This is for cross checking: SST = SSB+SSW ) # 7. Compute MSB and MSW # 8. Compute F_statistics ################################################################# # u_str = input('enter Excel filename: ') df = pd.read_excel(u_str, sheet_name = 'Sheet1') ndata, ngrp = df.shape # Sample size and number of samples/groups (returned as tuple) grp_mean = Anv_GroupMean(df) grand_mean = Anv_GrandMean(grp_mean, ngrp) SSB = Anv_SSB(grp_mean, grand_mean, ngrp) SSW = Anv_SSW(df, grp_mean, ndata) SST = Anv_SST(df, ndata, grand_mean) # # Compute F_stat # MSB = SSB / (ngrp -1) MSW = SSW / ((ndata*ngrp) - ngrp) F_Stat = MSB/MSW # # Output statistics # print() print('######### ANOVA analysis output ##########') print() print('Number of smaples/group (k) : ', ngrp) print('Sample size per group (n) : ', ndata) print('Population size (N) : ', ndata*ngrp) print('Grand mean : ',grand_mean) print('Sum of squares between groups (SSB) : ',SSB) print('Sum of squares within groups (SSW) : ',SSW) print('Sum of squares total (SST) : ',SST) print('Mean square between groups (MSB) : ',MSB) print('Mean square within groups (MSW) : ',MSW) print('F_Stat : ',F_Stat)
b63dee02f8fc3c33c3d89774ff44b7c27e983e62
ruoilegends/NGUYENTANLOC_43807_CA18A1A
/NguyenTanLoc_43807_CH03/exercise/Page92_Exercise_01.py
487
4.09375
4
""" Author: Nguyen Tan Loc Date: 10/09/2021 Problem: Translate the following for loops to equivalent while loops: a. for count in range(100): print(count) b. for count in range(1, 101): print(count) c. for count in range(100, 0, โ€“1): print(count) Solution: a. count = 0 while count < 100: print(count) count += 1 b. count = 100 while count > 0: print(count) count -= 1 c. count = 10 while count >= 1: print(count, end = " ") count -= 1 .... """
372f073cf48acd32f48a979cc3c141e4c4e0e7bd
IshratEpsi16/Book-Library
/bookbd.py
2,532
3.546875
4
from tkinter import * import backend #select the row def get_selected_row(event): global selected_tuple #global variable index=l1.curselection()[0] selected_tuple=l1.get(index) e1.delete(0,END) # 0 to end e1.insert(END,selected_tuple[1]) e2.delete(0,END) e2.insert(END,selected_tuple[2]) e3.delete(0,END) e3.insert(END,selected_tuple[3]) e4.delete(0,END) e4.insert(END,selected_tuple[4]) def view_command(): l1.delete(0,END) for row in backend.view(): l1.insert(END,row) def search_command(): l1.delete(0,END) for row in backend.search(title.get(),author.get(),year.get(),isbn.get()): l1.insert(END,row) def add_command(): backend.insert(title.get(),author.get(),year.get(),isbn.get()) l1.delete(0,END) l1.insert(END,(title.get(),author.get(),year.get(),isbn.get())) def delete_command(): backend.delete(selected_tuple[0]) def update_command(): backend.update(selected_tuple[0],title.get(),author.get(),year.get(),isbn.get()) window=Tk() window.wm_title("Book Library") #Title of the app #All labels l1=Label(window,text="Title") l1.grid(row=0,column=0) l2=Label(window,text="Author") l2.grid(row=0,column=2) l3=Label(window,text="Year") l3.grid(row=1,column=0) l4=Label(window,text="ISBN") l4.grid(row=1,column=2) #4 Input title=StringVar() e1=Entry(window, textvariable=title) e1.grid(row=0,column=1) author=StringVar() e2=Entry(window, textvariable=author) e2.grid(row=0,column=3) year=StringVar() e3=Entry(window, textvariable=year) e3.grid(row=1,column=1) isbn=StringVar() e4=Entry(window, textvariable=isbn) e4.grid(row=1,column=3) #output which will showed in a box l1=Listbox(window,height=6,width=35) l1.grid(row=2,column=0,rowspan=6,columnspan=2) #scrollbar sb1=Scrollbar(window) sb1.grid(row=2,column=2,rowspan=6) #configure l1.configure(yscrollcommand=sb1.set) sb1.configure(command=l1.yview) l1.bind('<<ListboxSelect>>',get_selected_row) #all buttons b1=Button(window,text="View All",width=12,command=view_command) b1.grid(row=2,column=3) b2=Button(window,text="Search",width=12,command=search_command) b2.grid(row=3,column=3) b3=Button(window,text="Add Entry",width=12,command=add_command) b3.grid(row=4,column=3) b4=Button(window,text="Update",width=12,command=update_command) b4.grid(row=5,column=3) b5=Button(window,text="Delete",width=12,command=delete_command) b5.grid(row=6,column=3) b6=Button(window,text="Close",width=12,command=window.destroy) b6.grid(row=7,column=3) window.mainloop()
3bc304f5fec8a3f16efd4077a3538a205459f545
RafalProkopowicz/Grafy
/graf2.py
1,977
3.625
4
size = int(raw_input("rozmiar tablicy: ")) tab = [[None] * size for i in range(size)] # pomocnicza macierz sasiedztwa, jak jej nie bedzie to poprosi o uzupelnienie danych tab = [[0, 1, 0, 0, 0], [1, 0, 0, 1, 0], [0, 0, 0, 0, 0], [0, 1, 0, 0, 1], [0, 0, 0, 1, 0]] #jak cos puste to uzupelnic for x in range(0, size): for y in range(x, size): if x == y: tab[x][y] = 0 elif tab[x][y] == None: print(tab[x]) print "wartosc [", x, "][", y, "]" tab[x][y] = int(input()) tab[y][x] = tab[x][y] # wyswietlenie tablicy for x in range(0, size): print(tab[x]) # wypisanie wszystkich stopni stopnie = [0 for i in range(size)] for x in range(0, size): for y in range(0, size): if tab[x][y] == 1: stopnie[x] = int(stopnie[x] + 1) # podliczenie parzystych parzyste = 0 for x in range(0, size): if not stopnie[x] % 2: parzyste += 1 """ kod na przeszukanie zachlanne - jak obejelo wszystkie wierzczolki to spojny """ # poszukiwanie zachlanne rekurencyjne def search(wierzcholek): if not odwiedzone.__contains__(wierzcholek): odwiedzone.append(wierzcholek) for x in range(0, size): if tab[x][wierzcholek] == 1: search(x) odwiedzone = [] search(0) if odwiedzone.__len__() != size: spojny = False else: spojny = True """ eulerowski - spojny, wszystkie wierzcholki parzystego stopnia """ if size == parzyste and spojny: print ">Eulerowski" """ pol-eulerowski - - spojny, wszystkie wierzcholki parzystego stopnia oprocz max 2 0 1 2 """ if (size == parzyste or size == parzyste + 1 or size == parzyste + 2) and spojny: print ">Pol-Eulerowski" """ nie spojny - dfs/bfs nei przejdzie po wszystkich wierzcholkach """ if spojny == False: print ">Nie Spojny" """ nie eulerowski i nie pol eulerowski """ if parzyste + 2 < size: print ">Nie Eulerowski ani Pol-Eulerowski"
d3c945f4ff3f03c5da6c64830b30c3284acc4dd1
chavp/MyPython
/ThinkPython/fruitfull_function.py
466
3.875
4
import math def area(radies): return 2 * math.pi * radies def factorial (n): if not isinstance(n, int): print('Factorial is only defined for integers.') return None elif n < 0: print('Factorial is not defined for negative integers.') return None elif n == 0: return 1 else: return n * factorial(n-1) def a(m, n): if m == 0: return n + 1 if m > 0 and n == 0: return a(m - 1, 1) if m > 0 and n > 0: return a(m-1, a(m, n-1)) print(a(3, 3))
85365ea40f822190ef1853e996fe0e508e622dd7
dudu9999/Exercicio_Aula_01
/ExercicioPiramide.py
559
3.921875
4
# Autor: Eduardo Caetano ''' Faรงa um algoritmo para imprimir a imagem abaixo. # ### ##### ####### ######### ########### ############# ############### ################# ################### Altere o algoritmo para que o usuรกrio digite a coluna inicial (ponta) e a quantidade de linhas. ''' c = "#" d = 20 e = 2 print(" #") for x in range(0, 9): print((d*" ")+"#"+(e*c)) d = d -1 e = e +2
c764b453c3153fe46cb2cff7b246af70efae3dbf
henriquekfmaia/curso-python
/601_c_arquivo_r.py
468
3.984375
4
filename = "zen.txt" file_in = open(filename, "r") # O parรขmetro "r" significa "read", indicando que o arquivo somente serรก lido ## O comando read() retorna todo o texto do arquivo text = file_in.read() # file_in = open(filename, "r") ## O comando readlines() retorna uma lista com cada linha do texto que estรก dentro do arquivo lines = file_in.readlines() print("Texto completo:") print(text) print("-------------------------------------------------") print(lines)
fd1fa0e12990bd0598b90d218c672b36ce694ee7
HduiOSClub/HduiOSClub
/projects/ๆฒˆๅญ™ๅณฐ/Python/่ฃดๆณข็บณๅฅ‘ๆ•ฐๅˆ—.py
172
3.90625
4
def F(n): if (n == 0 or n == 1) : return n else : return F(n-1)+F(n-2) n = int(input("่ฏท่พ“ๅ…ฅไธ€ไธชๆ•ฐ")) for i in range(0,n) : print(F(i))
bc01f4688dd6baf7a7f7d76981c9f34f08a620b3
tbro28/intermediatepython
/python-interm-class files/EXAMPLES/testrandom.py
1,223
3.640625
4
#!/usr/bin/env python # Test three functions from the random module: import random import unittest class TestSequenceFunctions(unittest.TestCase): # <1> @classmethod def setUpClass(cls): # <2> print("Starting all tests") def setUp(self): # <3> self.seq = list(range(10)) print("\n\nHello! : ", self.seq, "\n") def testshuffle(self): # <4> # make sure the shuffled sequence does not lose any elements random.shuffle(self.seq) print(self.seq) self.seq.sort() print(self.seq) self.assertEqual(self.seq, list(range(10))) # <5> def testchoice(self): element = random.choice(self.seq) print("Single element ----> ", element) self.assertIn(element, self.seq) # <6> def testsample(self): self.assertRaises(ValueError, random.sample, self.seq, 11) for element in random.sample(self.seq, 10): print("random sample: ", element) self.assertIn(element, self.seq) def tearDown(self): # <7> print("Goodbye!") @classmethod def tearDownClass(cls): # <8> print("Ending all tests") if __name__ == '__main__': unittest.main() # <9>
25eb31986557393c5c87020b0c238b09e3ccad2f
Gabrielatb/Interview-Prep
/hackbright/word_break.py
2,480
3.71875
4
# Build a function that is given a phrase and a vocab set. # It should return a set of the possible legal phrases that can be made # from that vocabulary. # >>> vocab = {'i', 'a', 'ten', 'oodles', 'ford', 'inner', 'to', # ... 'night', 'ate', 'noodles', 'for', 'dinner', 'tonight'} # >>> sentences = parse('iatenoodlesfordinnertonight', vocab) # >>> for s in sorted(sentences): # ... print s # i a ten oodles for dinner to night # i a ten oodles for dinner tonight # i a ten oodles ford inner to night # i a ten oodles ford inner tonight # i ate noodles for dinner to night # i ate noodles for dinner tonight # i ate noodles ford inner to night # i ate noodles ford inner tonight def wordBreak(s, wordDict, memo={}): """ :type s: str :type wordDict: List[str] :rtype: List[str] """ if s in memo: return memo[s] if not s: return [] rest_sentence = [] for word in wordDict: if word == s: rest_sentence.append(word) elif s.startswith(word): rest = s[len(word):] for item in wordBreak(rest, wordDict, memo): sentence = word + ' ' + item rest_sentence.append(sentence) memo[s] = rest_sentence return rest_sentence # vocab = ['i', 'a', 'ten', 'oodles', 'ford', 'inner', 'to', # 'night', 'ate', 'noodles', 'for', 'dinner', 'tonight'] # sentence = 'iatenoodlesfordinnertonight' sentence = 'a' vocab = ['a'] print wordBreak(sentence, vocab) # def word_break(phrase, vocab): # """Break a string into words. # Input: # - string of words without space breaks # - vocabulary (set of allowed words) # Output: # set of all possible ways to break this down, given a vocab # """ # # 'set of all possible legal phrases' ---> recursion # poss_breaks = set() # for word in vocab: # #base case no parsing required # if phrase == word: # poss_breaks.add(word) # elif phrase.startswith(word): # #word matches beginning of string # #rest of the string # rest = phrase[len(word):] # #recurse to find the various possibilities of end of sentence # for parsed in word_break(rest, vocab): # print parsed # # word_and_rest = [word + ' ' + parsed] # # return_lst.append(word_and_rest) # # return return_lst
fb98eae4bf16eb4c620f6e11b3bb0d60761acf7e
12315jack/j1st-python
/python-basic/game_code_files/game1.py
719
4.03125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- import random print('---------------------happy study python------------------') guess = random.randint(1, 10) while guess != 8: temp = input("็Œœ็Œœ็”จๆˆท่พ“ๅ…ฅ็š„ๆ•ฐๅญ—ๆ˜ฏๅคšๅฐ‘๏ผŸ๏ผš") guess = int(temp) if guess == 8: print("ๅ“ˆๅ“ˆ๏ผŒไฝ ็œŸ็‰›้€ผ๏ผŒ่ฟ™้ƒฝ่ƒฝ็Œœๅพ—ๅˆฐ") print("ไธ่ฟ‡็Œœไธญไบ†ไนŸๆฒก็”จ๏ผŒๅ“ˆๅ“ˆๅ“ˆ๏ผŒๆด—ๆด—็กๅง") else: if (8 - guess) > 0: print("็Œœ็š„ๆ•ฐๅญ—ๅฐไบ†") guess = int(input("่ฏท่พ“ๅ…ฅไธ€ไธชๅคงไธ€็‚น็š„ๆ•ฐ")) else: print("็Œœ็š„ๆ•ฐๅญ—ๅคชๅคงไบ†") print("ๆธธๆˆ็ป“ๆŸ๏ผŒๅฅฝๆ— ่Š๏ผŒๆ‹œๆ‹œ") # builtins dir(__builtins__) BIF=build in functions ๅ†…็ฝฎๅ‡ฝๆ•ฐ
d2d48c6100c4b514b0c879eb2409390b62f1df96
sy0837/Assistant
/venv/AudioCommand/AudioCmd.py
3,453
3.53125
4
import speech_recognition as sr import webbrowser as wb def Youtube(): print("Do you want to search a video") with sr.Microphone() as source: audio = r2.listen(source) try: output = r2.recognize_google(audio) print("You said {}".format(output)) except: print("Cannot recognize the voice") if "yes" in r2.recognize_google(audio): url = 'https://www.youtube.com/results?search_query=' with sr.Microphone() as source: print("Search For video") audio = r2.listen(source) try: get = r2.recognize_google(audio) print(get) wb.get().open_new_tab(url + get) except sr.UnknownValueError: print("Error") except sr.RequestError as e: print("Failed to get Result as {}".format(e)) else: url = 'https://www.youtube.com/' wb.get().open_new_tab(url) try: output = r.recognize_google(audio) print("your said {}".format(output)) except: print("Cannot recognize the voice") def FaceBook(): url = 'https://www.Facebook.com/' wb.get().open_new_tab(url) def Instagram(): url = 'https://www.Instagram.com/' wb.get().open_new_tab(url) def Twitter(): url = 'https://www.twitter.com/' wb.get().open_new_tab(url) def Google(): print(" Do you want to search something") with sr.Microphone() as source: audio = r2.listen(source) try: output = r2.recognize_google(audio) # print("You asked for {}".format(output)) except: print("Cannot recognize the voice") if "yes" in r2.recognize_google(audio): url = 'https://www.google.com/search?q=' with sr.Microphone() as source: print("What do you want to search") audio = r2.listen(source) try: get = r2.recognize_google(audio) print(get) wb.get().open_new_tab(url + get) except sr.UnknownValueError: print("Error") except sr.RequestError as e: print("Failed to get Result as {}".format(e)) else: url = 'https://www.google.com/' wb.get().open_new_tab(url) if __name__=='__main__': r = sr.Recognizer() r2 = sr.Recognizer() r3 = sr.Recognizer() with sr.Microphone() as source: print("How may I help you") audio = r3.listen(source) try: output = r3.recognize_google(audio) except: print("Cannot recognize the voice") if 'YouTube' in r2.recognize_google(audio): print("Opening YouTube") Youtube() elif 'Facebook' in r2.recognize_google(audio): print("Opening Facebook") FaceBook() elif 'Instagram' in r2.recognize_google(audio): print("Opening Instagram") Instagram() elif 'Google' in r2.recognize_google(audio): print("Opening Google") Google() elif 'Twitter' in r2.recognize_google(audio): print("Opening Twitter") Twitter() else: print("Sorry I am not prepared for your request")
58d0b347e000f5d327793229a775d29f673afd93
grigor-stoyanov/PythonAdvanced
/functions/min_max_sim.py
270
3.546875
4
line = list(map(int, input().split())) minimum_number = min(line) maximum_number = max(line) sum_of_all_numbers = sum(line) print(f"The minimum number is {minimum_number}") print(f"The maximum number is {maximum_number}") print(f"The sum number is {sum_of_all_numbers}")
616df6d2012fd745ef7adfd11c8af4fb77209aba
jagandecapri/XAI4ESN
/OldCode/GenerateVideoDataset.py
6,150
3.5625
4
''' This code generates a simplified video dataset for action recognition video Each video will be 60 frames of 28x28 grayscale with representation of 10 basic movements. - Bouncing - 0 - Vertical Upward - 1 - Vertical Downward - 2 - Horizontal Rightward - 3 - Horizontal Leftward - 4 - Diagonal Upward - 5 - Diagonal Downward - 6 - Circling - 7 - Crossing - 8 - Random movement - 9 Each class will contain 100 different videos ''' import cv2 import os import time import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm from numpy.random import randint as r_int from math import radians as rad def movement_function(_clase, _pos, _speed, _dire, _center=None, _radius=None, _t=None, _square_dir=0): x = pos[0] y = pos[1] x_dire = _dire[0] y_dire = _dire[1] x_speed = _speed[0] y_speed = _speed[1] if _clase == 0: # Bouncing if x + (s_dim[0] * x_dire) > f_dim[0]-1 or \ x + (s_dim[0] * x_dire) < -1: x_dire *= -1 if y + (s_dim[1] * y_dire) > f_dim[1]-2 or \ y + (s_dim[1] * y_dire) < 0: y_dire *= -1 x = x + x_speed * x_dire y = y + y_speed * y_dire if _clase == 1: # Vertical Upward if x + (s_dim[0] * -1) < -1: x = x + f_dim[0] x = x - x_speed if _clase == 2: # Vertical Downward if x + (s_dim[0] * 1) > f_dim[0]-1: x = x - f_dim[0] x = x + x_speed if _clase == 3: # Horizontal rightward if y + (s_dim[1] * 1) > f_dim[1]-1: y = y - f_dim[1] y = y + y_speed if _clase == 4: # Horizontal lefttward if y + (s_dim[1] * -1) < -1: y = y + f_dim[1] y = y - y_speed if _clase == 5: # Diagonal upward if x + (s_dim[0] * -x_dire) > f_dim[0]-1 or \ x + (s_dim[0] * -x_dire) < -1: x = x + f_dim[0] if y + (s_dim[1] * -y_dire) > f_dim[1]-2 or \ y + (s_dim[1] * -y_dire) < 0: y = y + f_dim[1] x = x + x_speed * -x_dire y = y + y_speed * -y_dire if _clase == 6: # Diagonal downward if x + (s_dim[0] * x_dire) > f_dim[0]-1 or \ x + (s_dim[0] * x_dire) < -1: x = x - f_dim[0] if y + (s_dim[1] * y_dire) > f_dim[1]-2 or \ y + (s_dim[1] * y_dire) < 0: y = y - f_dim[1] x = x + x_speed * x_dire y = y + y_speed * y_dire if _clase == 7: # Circling x = int(_center[0] + np.cos(_t) * 2*_radius) y = int(_center[1] + np.sin(_t) * 2*_radius) _t += 1 if _clase == 8: # Crossing if x + (s_dim[0] * -x_dire) > f_dim[0]-1 or \ x + (s_dim[0] * -x_dire) < -1: x = x + f_dim[0] y_dire *= -1 if y + (s_dim[1] * -y_dire) > f_dim[1]-2 or \ y + (s_dim[1] * -y_dire) < 0: y = y + f_dim[1] x_dire *= -1 x = x + x_speed * -x_dire y = y + y_speed * -y_dire if _clase == 9: # Centered Squaring if x_dire == 1 and y_dire == 0: x = x + x_speed y = _radius if x == f_dim[0]/2 + _radius: x_dire = 0 y_dire = -1 if x_dire == 0 and y_dire == 1: x = x + x_speed y = _radius if x == f_dim[0]/2 + _radius: x_dire = 0 y_dire = -1 if _clase == 10: # Centered Circling x = int(f_dim[0]/2 + np.cos(_t) * 2*10) y = int(f_dim[1]/2 + np.sin(_t) * 2*10) _t += 1 return [x, y], [x_dire, y_dire], _t n_videos = 600 n_frames = 60 fps = 2 show = True if show: cv2.namedWindow("show", cv2.WINDOW_NORMAL) VIDEO_PATH = '../datasets/SimplifiedVideos/Videos-row/' class_names = ['Bouncing', 'Vertical_Upward', 'Vertical_Downward', 'Horizontal_Rightward', 'Horizontal_Leftward', 'Diagonal_Upward', 'Diagonal_Downward', 'Circling', 'Crossing', 'Random_Movement'] f_dim = [28, 28] s_dim = [2, 2] # subject dimension empty_frame = np.zeros(f_dim) # np.random.seed(10) for clase in tqdm(list(range(10, 11))): for idx_video in range(n_videos): video_name = VIDEO_PATH + class_names[clase] + '/' + str(idx_video) \ + '_' + class_names[clase] + '_.npy' video = [] if not os.path.exists(VIDEO_PATH + class_names[clase]): os.mkdir(VIDEO_PATH + class_names[clase]) radius = list(r_int(2, 5, 1))[0] center = list(r_int(0 + radius, 28 - radius, 2)) pos_x = list(r_int(0, 3, 1))[0] pos_y = int(np.sqrt(np.power(radius, 2) - np.power(pos_x, 2))) pos = [center[0] + pos_x, center[1] + pos_y] delta = [center[0] - pos[0], center[1] - pos_y] speed = list(r_int(1, 6, 2)) t = 0 dire = [1, 1] new_frame = np.zeros(f_dim) new_frame[pos[0]:pos[0]+s_dim[0], pos[1]:pos[1]+s_dim[1]] = 1 if show: imS = cv2.resize(new_frame, (1920, 1920)) cv2.imshow('show', imS) cv2.waitKey(1) for idx_frame in range(n_frames): if clase == 9: if idx_frame % 5 == 0: r_clase = list(r_int(0, 8, 1))[0] pos, dire, t = movement_function(r_clase, pos, speed, dire, center, radius, t) else: pos, dire, t = movement_function(clase, pos, speed, dire, center, radius, t) new_frame = np.zeros(f_dim) new_frame[pos[0]:pos[0]+s_dim[0], pos[1]:pos[1]+s_dim[1]] = 1 if show: imS = cv2.resize(new_frame, (1920, 1920)) cv2.imshow('show', imS) cv2.waitKey(1) video.append(new_frame[..., np.newaxis]) video = np.concatenate(video, axis=2) np.save(video_name, video, allow_pickle=False)
7c9c7416756db65e091e1f2758f3f452f6863b30
FedeMatt/Algorithms-for-bioinformatics
/problems_week6/Problem_31.py
271
3.546875
4
def SuffixArray(Text): l = [(Text[j:],j) for j in range(len(Text))[::-1]] new_l = [index[1] for index in sorted(l)] for number in new_l: if number == new_l[-1]: print(number, end = "") else: print(number, end=", ")
abd47c8c1474d3ca264ebf50adff30cb61c70838
Vesihiisi/WLE_import
/importer/WikidataItem.py
9,081
3.671875
4
# -*- coding: utf-8 -*- """ An object that represent a Wikidata item. This is a basic object used to construct a Wikidata item. It contains the basic functions to create statements, qualifiers and sources, as well as labels and descriptions with specified languages. The purpose of it is to serve as a base for a data-specific object that will turn some data into Wikidata objects. It can then be uploaded to Wikidata using the uploader script. """ from wikidataStuff.WikidataStuff import WikidataStuff as WDS from wikidataStuff import helpers as helpers import pywikibot import importer_utils as utils DATA_DIR = "data" class WikidataItem(object): """Basic data object for upload to Wikidata.""" def __init__(self, db_row_dict, repository, data_files, existing): """ Initialize the data object. :param db_row_dict: raw data from the data source :type db_row_dict: string :param repository: data repository (Wikidata site) :type repository: site instance :param data_files: dict of various mapping files :type data_files: dictionary :param existing: WD items that already have an unique id :type existing: dictionary """ self.repo = repository self.existing = existing self.wdstuff = WDS(self.repo) self.raw_data = db_row_dict self.props = data_files["properties"] self.items = data_files["items"] self.construct_wd_item() self.problem_report = {} def make_q_item(self, qnumber): """ Create a regular Wikidata ItemPage. :param qnumber: Q-item that we want to get an ItemPage of :type qnumber: string :return: an ItemPage for pywikibot """ return self.wdstuff.QtoItemPage(qnumber) def make_pywikibot_item(self, value): """ Create a statement in pywikibot-ready format. The statement can be either: * a string (value is string) * an item (value is Q-string) * an amount with or without unit (value is dic) :param value: the content of the item :type value: it can be a string or a dictionary, see above. :return: a pywikibot item of the type determined by the input data, either ItemPage or Quantity or string. """ val_item = None if isinstance(value, list) and len(value) == 1: value = value[0] if utils.string_is_q_item(value): val_item = self.make_q_item(value) elif value == "novalue": val_item = value elif isinstance(value, dict) and 'quantity_value' in value: number = value['quantity_value'] if 'unit' in value: unit = self.wdstuff.QtoItemPage(value["unit"]) else: unit = None val_item = pywikibot.WbQuantity( amount=number, unit=unit, site=self.repo) elif isinstance(value, dict) and 'date_value' in value: date_dict = value["date_value"] val_item = pywikibot.WbTime(year=date_dict["year"], month=date_dict["month"], day=date_dict["day"]) elif value == "novalue": # raise NotImplementedError # implement Error print("Status: novalue will be added here") else: val_item = value return val_item def make_statement(self, value): """ Create a Wikidatastuff statement. Supports the special data types 'somevalue' and 'novalue'. :prop value: the content of the statement :type value: pywikibot item :return: a wikidatastuff statement """ if value in ['somevalue', 'novalue']: special = True else: special = False return self.wdstuff.Statement(value, special=special) def make_qualifier_applies_to(self, value): """ Create a qualifier to a statement with type 'applies to part'. :param value: Q-item that this applies to :type value: string :return: a wikidatastuff Qualifier """ prop_item = self.props["applies_to_part"] target_item = self.wdstuff.QtoItemPage(value) return self.wdstuff.Qualifier(prop_item, target_item) def add_statement(self, prop_name, value, quals=None, ref=None): """ Add a statement to the data object. :param prop_name: P-item representing property :type prop_name: string :param value: content of the statement :type value: it can be a string representing a Q-item or a dictionary of an amount :param quals: possibly qualifier items :type quals: a wikidatastuff Qualifier item, or a list of them :param ref: reference item :type ref: a wikidatastuff Reference item """ base = self.wd_item["statements"] prop = self.props[prop_name] if quals is None: quals = [] wd_claim = self.make_pywikibot_item(value) statement = self.make_statement(wd_claim) for qual in helpers.listify(quals): statement.addQualifier(qual) base.append({"prop": prop, "value": statement, "ref": ref}) def make_stated_in_ref(self, value, pub_date, ref_url=None, retrieved_date=None): """ Make a reference object of type 'stated in'. :param value: Q-item where sth is stated :type value: string :param pub_date: timestamp in format "1999-09-31" :type pub_date: string :param ref_url: optionally a reference url :type ref_url: string :param retrieved_date: timestamp in format "1999-09-31" :type retrieved_date: string :return: a wikidatastuff Reference item """ item_prop = self.props["stated_in"] published_prop = self.props["publication_date"] pub_date = utils.date_to_dict(pub_date, "%Y-%m-%d") timestamp = self.make_pywikibot_item({"date_value": pub_date}) published_claim = self.wdstuff.make_simple_claim( published_prop, timestamp) source_item = self.wdstuff.QtoItemPage(value) source_claim = self.wdstuff.make_simple_claim(item_prop, source_item) if ref_url and retrieved_date: ref_url_prop = self.props["reference_url"] retrieved_date_prop = self.props["retrieved"] retrieved_date = utils.date_to_dict(retrieved_date, "%Y-%m-%d") retrieved_date = self.make_pywikibot_item( {"date_value": retrieved_date}) ref_url_claim = self.wdstuff.make_simple_claim( ref_url_prop, ref_url) retrieved_on_claim = self.wdstuff.make_simple_claim( retrieved_date_prop, retrieved_date) ref = self.wdstuff.Reference( source_test=[source_claim, ref_url_claim], source_notest=[published_claim, retrieved_on_claim]) else: ref = self.wdstuff.Reference( source_test=[source_claim], source_notest=published_claim ) return ref def associate_wd_item(self, wd_item): """ Associate the data object with a Wikidata item. :param wd_item: Q-item that shall be assigned to the data object. :type wd_item: string """ if wd_item is not None: self.wd_item["wd-item"] = wd_item print("Associated WD item: ", wd_item) def add_label(self, language, text): """ Add a label in a specific language. :param language: code of language, e.g. "fi" :type language: string :param text: content of the label :type text: string """ base = self.wd_item["labels"] base.append({"language": language, "value": text}) def add_description(self, language, text): """ Add a description in a specific language. :param language: code of language, e.g. "fi" :type language: string :param text: content of the description :type text: string """ base = self.wd_item["descriptions"] base.append({"language": language, "value": text}) def construct_wd_item(self): """ Create the empty structure of the data object. This creates self.wd_item -- a dict container of all the data content of the item. """ self.wd_item = {} self.wd_item["upload"] = True self.wd_item["statements"] = [] self.wd_item["labels"] = [] self.wd_item["descriptions"] = [] self.wd_item["wd-item"] = None
55a725253cbe65c9bf386b43b052007cce786791
luvhalvorson/Leetcode-Python-Solutions
/problems/remove_palindromic_subsequences/solution.py
455
3.578125
4
class Solution: def ispalindrome(self, s): #if len(set(s)) == 1: # return True for i in range(len(s)//2): if s[i] == s[-(i+1)]: continue else: return False return True def removePalindromeSub(self, s: str) -> int: if not s: return 0 elif self.ispalindrome(s): return 1 else: return 2
1e500274af2ddc2d34173b4557747ce00d06f24a
jeong123456789/MyPython
/Ch01/Ex08.py
154
3.5
4
import turtle t = turtle.Turtle() t.shape("turtle"); t.goto(100) t.forward(100) t.up t.forward(100) t.down t.goto(200) t.forward(100) t.down
5a1909fb09026e9c42bd16dd1255223b973030ba
Fincap/dicomfuse
/dicomfuse/transform.py
3,157
3.515625
4
from typing import List, Tuple import numpy as np def __validate_points(fixed_points: List[Tuple[float, ...]], moving_points: List[Tuple[float, ...]]): """ Validates that the two list of points given are of equal length and dimensionality (i.e. they correspond). """ # Check neither list is empty: if len(moving_points) == 0 or len(fixed_points) == 0: raise Exception("Points cannot be empty.") # Check the lists are both the same length if len(moving_points) != len(fixed_points): raise Exception("From and to points are not the same length.") # Check if the dimensionality is consistent throughout both lists primary_dimensionality = len(moving_points[0]) for p in moving_points: if len(p) != primary_dimensionality: raise Exception("Inconsistent dimensionality in moving points.") secondary_dimensionality = len(fixed_points[0]) for s in fixed_points: if len(s) != secondary_dimensionality: raise Exception("Inconsistent dimensionality in fixed points.") def get_transform_matrix(fixed_points: List[Tuple[float, ...]], moving_points: List[Tuple[float, ...]]): """ Calculate the affine transformation matrix from moving to fixed, given that moving_points is a known transformation of fixed_points. Credit to Stack Overflow user 'mathematical.coffee': https://stackoverflow.com/a/8874969 for basis of function. """ try: __validate_points(fixed_points, moving_points) except Exception as e: raise e fixed_matrix = np.transpose(np.matrix(fixed_points)) moving_matrix = np.transpose(np.matrix(moving_points)) # Augment '1' at the end of all vectors augment_row = [1 for i in range(len(moving_points))] fixed_matrix = np.vstack((fixed_matrix, augment_row)) moving_matrix = np.vstack((moving_matrix, augment_row)) # Solve for augmented matrix transformation_matrix = fixed_matrix * moving_matrix.I return transformation_matrix # TODO split this up into two functions: get transformation matrix (A2) and apply matrix to vector. # Also should probably rename 'x' and 'y' to something more descriptive such as original_points and # known_transformed_points. # Return function that takes input x and transforms it, removing addittional row # return lambda x: (A2 * np.vstack((np.matrix(from_matrix).reshape(dimensionality, 1), 1)))[0:dimensionality,:] def apply_transform_to_points(transformation_matrix: np.matrix, moving_points: List[Tuple[float, ...]]): """Apply the transformation matrix to a set of moving points and return the the transformed moving points. Args: transformation_matrix (np.matrix): Affine transformation matrix. moving_points (List[Tuple[float, ...]]): The set of points to be transformed. """ dimensionality = len(moving_points[0]) moving_matrix = np.transpose(np.matrix(moving_points)) augment_row = [1 for i in range(len(moving_points))] moving_matrix = np.vstack((moving_matrix, augment_row)) transformed_matrix = (transformation_matrix * moving_matrix)[0:dimensionality,:].T transformed_points = [tuple(row.tolist()[0]) for row in transformed_matrix] return transformed_points
276b21c33dee10074484a0fcf85860deb7e9c857
THEKINGSTAR/udacity_data_analysis_pro-nano-dgree
/2. Introduction to Python/Lesson 5 Functions/readable_timedelta.py
1,768
4.21875
4
""" Quiz: readable_timedelta Write a function named readable_timedelta. The function should take one argument, an integer days, and return a string that says how many weeks and days that is. For example, calling the function and printing the result like this: print(readable_timedelta(10)) #should output the following: 1 week(s) and 3 day(s). """ # write your function here def readable_timedelta(input_days): weeks = 0 days = 0 for i in range(input_days): if input_days >= 7: weeks += 1 input_days = input_days - 7 elif input_days < 7 and input_days > 0: days += 1 input_days -= 1 return("{} week(s) and {} day(s).".format(weeks, days)) # test your function print(readable_timedelta(3769)) """ readable_timedelta(1466) The expected output is: 209 week(s) and 3 day(s). readable_timedelta(7637) The expected output is: 1091 week(s) and 0 day(s). readable_timedelta(468) The expected output is: 66 week(s) and 6 day(s). readable_timedelta(1) The expected output is: 0 week(s) and 1 day(s). readable_timedelta(6) The expected output is: 0 week(s) and 6 day(s). readable_timedelta(7) The expected output is: 1 week(s) and 0 day(s). readable_timedelta(9) The expected output is: 1 week(s) and 2 day(s). readable_timedelta(3769) The expected output is: 538 week(s) and 3 day(s) """ ############################################### """ Quiz Solution: readable_timedelta """ def readable_timedelta(days): # use integer division to get the number of weeks weeks = days // 7 # use % to get the number of days that remain remainder = days % 7 return "{} week(s) and {} day(s).".format(weeks, remainder) # test your function print(readable_timedelta(10))
3d9ad81d3a63522a848be02e0fceaf721894021d
TrentBrunson/Neural_Networks
/working/RandomForest_DeepLearning.py
3,501
3.515625
4
#%% """ Build a classifier that can predict if a loan will be provided. Random forest models will only handle tabular data Deep learning will handle images, NLP, etc. """ #%% # Import dependencies from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.preprocessing import OneHotEncoder import pandas as pd import tensorflow as tf # Import input dataset loans_df = pd.read_csv('loan_status.csv') loans_df.head() # %% # both models require pre-processing data # pre-processing first this time; get ready to encode: # Generate our categorical variable list loans_cat = loans_df.dtypes[loans_df.dtypes == "object"].index.tolist() # Check the number of unique values in each column loans_df[loans_cat].nunique() # %% # Check the unique value counts to see if binning is required loans_df.Years_in_current_job.value_counts() # %% # categorical variables look ready to encode # Create a OneHotEncoder instance enc = OneHotEncoder(sparse=False) # Fit and transform the OneHotEncoder using the categorical variable list encode_df = pd.DataFrame(enc.fit_transform(loans_df[loans_cat])) # Add the encoded variable names to the DataFrame encode_df.columns = enc.get_feature_names(loans_cat) encode_df.head() # %% # Merge one-hot encoded features and drop the originals loans_df = loans_df.merge(encode_df,left_index=True, right_index=True) loans_df = loans_df.drop(loans_cat,1) loans_df.head() # %% # split data for training and testing # Remove loan status target from features data y = loans_df.Loan_Status_Fully_Paid X = loans_df.drop(columns=["Loan_Status_Fully_Paid","Loan_Status_Not_Paid"]).values # Split training/test datasets X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42, stratify=y) # Create a StandardScaler instance scaler = StandardScaler() # Fit the StandardScaler X_scaler = scaler.fit(X_train) # Scale the data X_train_scaled = X_scaler.transform(X_train) X_test_scaled = X_scaler.transform(X_test) # %% # after splitting data, it is ready for evaluation in both models # 1st Random Forest Classifier model # Create a random forest classifier, # using max recommended # of estimators of 128 rf_model = RandomForestClassifier(n_estimators=128, random_state=78) # Fitting the model rf_model = rf_model.fit(X_train_scaled, y_train) # Evaluate the model y_pred = rf_model.predict(X_test_scaled) print(f" Random forest predictive accuracy: {accuracy_score(y_test,y_pred):.3f}") # %% # build and evaluate deep learning model # Define the model - deep neural net number_input_features = len(X_train_scaled[0]) hidden_nodes_layer1 = 24 hidden_nodes_layer2 = 12 nn = tf.keras.models.Sequential() # First hidden layer nn.add( tf.keras.layers.Dense(units=hidden_nodes_layer1, input_dim=number_input_features, activation="relu") ) # Second hidden layer nn.add(tf.keras.layers.Dense(units=hidden_nodes_layer2, activation="relu")) # Output layer nn.add(tf.keras.layers.Dense(units=1, activation="sigmoid")) # Compile the Sequential model together and customize metrics nn.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"]) # Train the model fit_model = nn.fit(X_train_scaled, y_train, epochs=50) # Evaluate the model using the test data model_loss, model_accuracy = nn.evaluate(X_test_scaled,y_test,verbose=2) print(f"Loss: {model_loss}, Accuracy: {model_accuracy}") # %%
b70d2733a400dac2179a4c4ff6ad179448048d59
thijsBoet/small-python-projects
/create-random-password.py
305
3.578125
4
import random import string def createRandomPassword(amountOfCharacters): chars = list(string.ascii_letters + string.digits) password = '' for letter in range(amountOfCharacters): password += chars[random.randrange(0, len(chars))] return password print(createRandomPassword(32))
813039c6417ed384b6c346a1d30a2683af9d1f28
bunnybryna/Coursera_MIT_Intro_To_CS
/Code/wk3ps3_hangman.py
5,580
4.25
4
# 6.00 Problem Set 3 # # Hangman game # # ----------------------------------- # Helper code # You don't need to understand this helper code, # but you will have to know how to use the functions # (so be sure to read the docstrings!) import random import string WORDLIST_FILENAME = "words.txt" def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # line: string line = inFile.readline() # wordlist: list of strings wordlist = string.split(line) print " ", len(wordlist), "words loaded." return wordlist def chooseWord(wordlist): """ wordlist (list): list of words (strings) Returns a word from wordlist at random """ return random.choice(wordlist) # end of helper code # ----------------------------------- # Load the list of words into the variable wordlist # so that it can be accessed from anywhere in the program wordlist = loadWords() def isWordGuessed(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: boolean, True if all the letters of secretWord are in lettersGuessed; False otherwise ''' for letter in secretWord: if letter in lettersGuessed: continue else: return False if not False: return True def getGuessedWord(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far. ''' ls = len(secretWord) word = '_' * ls for letter in lettersGuessed: num = secretWord.count(letter) # if num=1,.find()will return the index # if num>=2,.find() will return the first one # and go to the while block,.find(,beg) method will give the next index # and when num-1=0 will get out of the loop if num > 0 : ind = secretWord.find(letter) rightWord = secretWord[ind] word = word[:ind]+rightWord+word[ind+1:] num = num-1 while num >= 1: ind2 = secretWord.find(letter,ind+1) rightWord2 = secretWord[ind2] word = word[:ind2]+rightWord2+word[ind2+1:] num = num - 1 ind = ind2 if num == 0: continue # add a space after each underscore # it's clear to the user how many unguessed letters are left in the string holder = '' for i in range(len(word)): holder = holder + word[i] + ' ' return holder def getAvailableLetters(lettersGuessed): ''' lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters that represents what letters have not yet been guessed. ''' alpha = '' for letter in 'abcdefghijklmnopqrstuvwxyz': if letter not in lettersGuessed: alpha += letter return alpha def hangman(secretWord): ''' secretWord: string, the secret word to guess. Starts up an interactive game of Hangman. * At the start of the game, let the user know how many letters the secretWord contains. * Ask the user to supply one guess (i.e. letter) per round. * The user should receive feedback immediately after each guess about whether their guess appears in the computers word. * After each round, you should also display to the user the partially guessed word so far, as well as letters that the user has not yet guessed. Follows the other limitations detailed in the problem write-up. ''' print 'Welcome to the game, Hangman!' ls = len(secretWord) print 'I am thinking of a word that is ',ls,' letters long.' count = 8 lettersGuessed = [] while count > 0: print '-' * 10 print 'You have ',count,' guesses left.' print 'Available letters: ' print getAvailableLetters(lettersGuessed) letterGuess = raw_input('Please guess a letter: ') letterGuess = letterGuess.lower() if letterGuess in lettersGuessed: print "Oops! You've already guessed that letter: " print getGuessedWord(secretWord, lettersGuessed) continue lettersGuessed.append(letterGuess) if letterGuess in secretWord: print 'Good guess: ' print getGuessedWord(secretWord, lettersGuessed) if isWordGuessed(secretWord, lettersGuessed) is True: print '-' * 10 print 'Congratulations, you won!' break else: print 'Oops! That letter is not in my word: ', getGuessedWord(secretWord, lettersGuessed) count -= 1 if count == 0: print '-' * 10 print 'Sorry, you ran out of guesses. The word was ',secretWord,'.' break # When you've completed your hangman function, uncomment these two lines # and run this file to test! (hint: you might want to pick your own # secretWord while you're testing) secretWord = chooseWord(wordlist).lower() hangman(secretWord)
a89809fc93c49bd1776f02482003981fb229b24d
homawccc/class-example
/tk/newfolder_git/lists.py
238
3.890625
4
fruit = ["apple", "blueberries", "cranberries", "cranberries"] print(set(fruit)) veges = ["onion", "tomato", "kale"] print(set(veges)) newlist = fruit.extend(veges) length = len(fruit) print(fruit[0:length]) for f in fruit: print(f)
d2f1cea3fe908ec8a9d42138d7497f0987d5138f
xaca/fundamentos_python
/reto1.py
290
3.890625
4
usuario = input("Ingrese usuario ") # print(type(usuario)) # usuario = int(usuario) # print(type(usuario)) if usuario == "51619": clave = input("Ingresar clave ") if clave == "91615": print("Bienvenido usuario") else: print("Error") else: print("Error")
3e40352eba2ce73d106a7dee3517f41d4f60052b
automoto/python-code-golf
/graph/detect-a-cycle-medium-bad-attempt.py
1,072
4.0625
4
""" You are given an array of integers. Each integer represents a jump of its value in the array. For instance, the integer 2 represents a jump of 2 indices forward in the array; the integer -3 represents a jump of 3 indices backward in the array. If a jump spills past the array's bounds, it wraps over to the other side. For instance, a jump of -1 at index 0 brings us to the last index in the array. Similarly, a jump of 1 at the last index in the array brings us to index 0. Write a function that returns a boolean representing whether the jumps in the array form a single cycle. A single cycle occurs if, starting at any index in the array and following the jumps, every element is visited exactly once before landing back on the starting index. input = [2, 3, 1, -4, -4, 2] output = True """ def hasSingleCycle(array): search = True cycleFound = False count = 0 jump = 0 array_len = len(array) while search: if(count > array_len): cycleFound = array.index(next) == 0 search = False next = array[jump] jump = next count += 1 return cycleFound
faf82ccb7295ad495eb36037e21233f4781c5b72
jzhangfob/jzhangfob.csfiles
/Intervals.py
1,967
4.21875
4
# File: Intervals.py # Description: Create a program that will output merged intervals so that there are no longer any overlapping intervals # Student Name: Jonathan Zhang # Student UT EID: jz5246 # Course Name: CS 303E # Unique Number: 50860 # Date Created: 4/19/2016 # Date Last Modified: 4/19/2016 def main(): #Open the file for reading infile = open("intervals.txt", "r") #Initialize the list that will hold each pair of numbers in a tuple list = [] #First, add each line to the file unformatted for line in infile: list.append(line) #Next, take out the white space characters and split each pair of numbers into a list for i in range(len(list)): list[i] = list[i].rstrip() list[i] = list[i].split(' ') #Convert strings into integers for j in range(len(list[i])): list[i][j] = int(list[i][j]) #Turn each separate list into a tuple list[i] = tuple(list[i]) #new_list sorts the tuples in ascending order based on the first number in each pair new_list = [] for i in range(len(list)): new_list.append(min(list)) list.remove(min(list)) #Print the header print() print('Non-intersecting Intervals:') i = 0 #Go through the length of the list while (i < len(new_list) - 1): #Establish coordinate values for first tuple and second tuple x1 = new_list[i][0] y1 = new_list[i][1] x2 = new_list[i+1][0] y2 = new_list[i+1][1] #If the intervals overlap, remove the first two tuples if (y1 >= x2): new_list.pop(i) new_list.pop(i) #Insert a new tuple into the list with the biggest interval possible if (y2 >= y1): new_list.insert(i, (x1, y2)) else: new_list.insert(i, (x1, y1)) #If the intervals do not overlap, move the index over one if (x2 > y1): i += 1 #Print the contents of the list for i in range (0, len(new_list)): print(new_list[i]) main()
efc8214779d0511a6565cc3b9306415132e2f2cc
Alexsan3005/Learn-Python
/Calk.py
809
4.1875
4
x,oper,y=float(input("ะ’ะฒะตะดะธั‚ะต ะฟะตั€ะฒะพะต ั‡ะธัะปะพ ")),input("ะ’ะฒะตะดะธั‚ะต ะพะฟะตั€ะฐั†ะธัŽ "),float(input("ะ’ะฒะตะดะธั‚ะต ะฒั‚ะพั€ะพะต ั‡ะธัะปะพ ")) if oper == "+": print(x+y) elif oper == "-": print(x-y) elif oper == "*": print(x*y) elif oper == "pow": print(x**y) elif oper == "/" and y == 0: print("ะ”ะตะปะตะฝะธะต ะฝะฐ 0!") y=float(input("ะ’ะฒะตะดะธั‚ะต ะฝะต 0:")) print(x/y) elif oper == "/" and y != 0: print(x/y) if oper == "mod" and y == 0: print("ะ”ะตะปะตะฝะธะต ะฝะฐ 0!") y=float(input("ะ’ะฒะตะดะธั‚ะต ะฝะต 0:")) print(x%y) elif oper == "mod" and y != 0: print(x%y) if oper == "div" and y == 0: print("ะ”ะตะปะตะฝะธะต ะฝะฐ 0!") y=float(input("ะ’ะฒะตะดะธั‚ะต ะฝะต 0:")) print(x//y) elif oper == "div" and y != 0: print(x//y)
1985004962625ad160ab0ed10b949f4108e26fb4
zhaolixiang/python_cookbook
/7-1.py
421
3.9375
4
prices={ 'ACME':45.23, 'AAPL':612.78, 'IBM':205.55, 'HPQ':37.20, 'FB':10.75 } #ๆ‰พๅ‡บไปทๆ ผๆœ€ไฝŽๆ”พๅ…ฅ่‚ก็ฅจ min_price=min(zip(prices.values(),prices.keys())) print(min_price) #ๆ‰พๅ‡บไปทๆ ผๆœ€้ซ˜ๆ”พๅ…ฅ่‚ก็ฅจ max_price=max(zip(prices.values(),prices.keys())) print(max_price) #ๅŒๆ ท๏ผŒ่ฆๅฏนๆ•ฐๆฎๆŽ’ๅบๅช่ฆไฝฟ็”จzip()ๅ†้…ๅˆsorted() prices_sorted=sorted(zip(prices.values(),prices.keys())) print(prices_sorted)
9c081aff52a3657796626aa1c918d7e51f0b0003
functorial/DataScienceFromScratch--Notes
/DecisionTrees.py
10,991
4.0625
4
# # Decision Trees # # A decision tree is a model that forms a tree-like structure # like the game 'Twenty Questions' # Pros: # (*) Can handle data of various types, e.g. numeric and categorical # (*) Easy to understand # (*) Easy to interpret # # Cons: # (*) Computationally very hard to find an optimal descision tree # Get around this by building one that is 'good enough' # (*) Very easy to overfit to data # e.g. a 'guess the animal' game with a 3 layer deep tree # Classification Trees: # Produce categorical outputs # # Regression Trees: # Produce numerical outputs # Two things to decide: # (1) Which questions to ask? # (2) In what order? # Would like to choose questions whose answers 'give a lot of information' # Regard a 'question' as a partition of the data into classes (based on their answers tot he question) # We will quantify the notion of 'amount of info given by a partition' with /entropy/ # # Entropy: # Let S be a set of data points, # each labeled by a category from C_0, ..., C_{n-1}, # and let p_i be the proportion of points in S labeled by C_i # # Then, define the /entropy/ of S to be the quantity # # H(S) = - (p_0 * log_2(p_0) + ... + p_n * log_2(p_{n-1})) # = - log_2(product( p_i ^ p_i for i in range(0, n) if p_i != 0 )) # Note: # Use the convention 0 * log_2(0) = 0 # The quantities -p_i * log_2(p_i) are between 0 and ~0.53, # since p_i is between 0 and 1 # Graph of p log_2(p) import matplotlib.pyplot as plt import numpy as np xs = [0] + [i/100 for i in range(1, 101)] ys = [0] + [-x * np.log2(x) for x in xs if x != 0] plt.plot(xs, ys) plt.title('f(p) = -p * log_2(p)') #plt.show() # Define Entropy function: def f(p): return -p * np.log2(p) vf = np.vectorize(f) def entropy(class_probabilities: np.ndarray) -> float: return np.sum(vf(class_probabilities)) # The entropy will be small when every p_i is close to 0 or 1 # and will be larger when many of the p_i's are more evenly distributed assert entropy(np.array( [1.0] )) == 0.0 assert entropy(np.array( [0.5, 0.5] )) == 1.0 # After our data answers our question, # the data will consist of pairs (input, label) # we will need to compute the class probabilities ourself to compute the entropy from collections import Counter def data_entropy(labels: np.ndarray) -> float: total_count = np.size(labels) class_probabilities = np.array([count / total_count for count in Counter(labels).values()]) # we don't care about order return entropy(class_probabilities) assert data_entropy(['a']) == 0 assert data_entropy([True, False]) == 1.0 # Entropy of a Partition: # Given a partition of a set S into subsets S_1, ..., S_n, # want to define the notion of /entropy of a partition/ so that: # (1) if all S_i have low entropy, # then the partition should have low entropy # (2) if some S_i have high entropy (and are large), # then the partition should have high entropy # Define as a weighted sum: # H = q_1 * H(S_1) + ... + q_n * H(S_n) from typing import List def partition_entropy(subsets: List[np.ndarray]) -> float: sizes = [len(subset) for subset in subsets] total_size = sum(sizes) proportions = np.array([size / total_size for size in sizes]) entropies = np.array([data_entropy(subset) for subset in subsets]) return np.dot(proportions, entropies) # # Creating a Decision Tree Example # Implementing the ID3 algorithm # from typing import NamedTuple, Optional class Candidate(NamedTuple): level: str lang: str tweets: bool phd: bool did_well: Optional[bool] = None # allow unlabeled data inputs = [Candidate('Senior', 'Java', False, False, False), Candidate('Senior', 'Java', False, True, False), Candidate('Mid', 'Python', False, False, True), Candidate('Junior', 'Python', False, False, True), Candidate('Junior', 'R', True, False, True), Candidate('Junior', 'R', True, True, False), Candidate('Mid', 'R', True, True, True), Candidate('Senior', 'Python', False, False, False), Candidate('Senior', 'R', True, False, True), Candidate('Junior', 'Python', True, False, True), Candidate('Senior', 'Python', True, True, True), Candidate('Mid', 'Python', False, True, True), Candidate('Mid', 'Java', True, False, True), Candidate('Junior', 'Python', False, True, False) ] # ID3 Algorithm: # # Let S be a set of labeled data (e.g. candidate list = List[Candidate, did_well]) # Let A be a list of attributes (e.g. [level, lang, tweets, phd]) # # (*) If the data all have the same label, # create a leaf node which predicts that label, and STOP # (*) If the list of attributes is empty (i.e. there are no more possible questions to ask) # create a lead node which predicts the most common label, and STOP # (*) Otherwise, try partitioning the data by each of the attributes. # (*) Choose the partition with the lowest partition entropy. # (*) Add a decision node based on the chosen attribute # (*) Recur on each partitioned subset using the remaining attributes # First, we will implement the 'stuff to do' at each node. # Later, we will set up the recursion logic for the tree-based model from typing import Dict, TypeVar, Any from collections import defaultdict T = TypeVar('T') # generic type for inputs, e.g. Candidate # break set into partitions by attribute, represented by a Dict[attribute, partition] def partitions_by_attribute(inputs: List[T], attribute: str) -> Dict[Any, List[T]]: """Partition the inputs into lists based on the specified attribute.""" partitions: Dict[Any, List[T]] = defaultdict(list) for input in inputs: key = getattr(input, attribute) # value of the specified attribute of `input` partitions[key].append(input) return partitions # compute partition entropy for a list of partitions def entropy_by_partition(inputs: List[T], attribute: str, label_attribute: str) -> float: """Compute the entropy corresponding to the given artition""" # partitions consist of our inputs partitions = partitions_by_attribute(inputs, attribute) # but partition_entropy needs just the class labels labels = [np.array([getattr(input, label_attribute) for input in partition]) for partition in partitions.values()] return partition_entropy(labels) # now, find the minimum entropy partition for the whole dataset: def min_entropy_partition(inputs: List[T], attributes: List[str], label_attribute: str) -> str: entropies = [entropy_by_partition(inputs, attribute, label_attribute) for attribute in attributes] return attributes[np.argmin(entropies)] # test attributes = ['level', 'lang', 'tweets', 'phd'] label_attribute = 'did_well' for attribute in attributes: print(f"{attribute} Entropy: {entropy_by_partition(inputs, attribute, label_attribute)}") print(f"Min Entropy Partition Attribute: {min_entropy_partition(inputs, attributes, label_attribute)}") # Now, lets implement the algorithm # First let's build the tree data type # A node is either a leaf class Leaf(NamedTuple): value: Any # or a subtree class Split(NamedTuple): attribute: str subtrees: dict default_value: Any = None from typing import Union # use Union when something could be one of a few types DecisionTree = Union[Leaf, Split] def build_tree_id3(inputs: List[Any], split_attributes: List[str], target_attribute: str) -> DecisionTree: """Builds subtree at a given node""" # count target labels label_counts = Counter(getattr(input, target_attribute) for input in inputs) most_common_label = label_counts.most_common(1)[0][0] # if there is a unique label, predict it if len(label_counts) == 1: return Leaf(most_common_label) # if no split attributes left, predict most common label print(split_attributes) if not split_attributes: print('bruh') return Leaf(most_common_label) # otherwise, split by attribute with lowest entropy # helper function def split_entropy(attribute:str) -> float: return entropy_by_partition(inputs, attribute, label_attribute) best_attribute = min(split_attributes, key=split_entropy) partitions = partitions_by_attribute(inputs, best_attribute) new_attributes = [attribute for attribute in attributes if attribute != best_attribute] # recursively build the child trees subtrees = {attribute_value : build_tree_id3(subset, new_attributes, label_attribute) for attribute_value, subset in partitions.items()} return Split(best_attribute, subtrees, default_value=most_common_label) # Use this to create a model represented by a predict function def classify(tree: DecisionTree, input: Any) -> Any: """classify the input using the given decision tree""" # if tree=leaf, return its value if isinstance(tree, Leaf): return tree.value # otherwise, this tree consists of an attribute to split on # and a dictionary whose keys are values of that attribute # and whose values are subtrees to consider next subtree_key = getattr(input, tree.attribute) if subtree_key not in tree.subtrees: # if no subtree for key return tree.default_value # return the default value subtree = tree.subtrees[subtree_key] # Choose the appropriate subtree return classify(subtree, input) # and use it to classify the input # test my_tree = build_tree_id3(inputs, attributes, label_attribute) print('Tree: ', my_tree) me = Candidate('Junior', 'Python', False, True) print('Hire?: ', classify(my_tree, me)) # do not hire :( # NOTE: Big problem # With how well the model can fit to the data, # it's not a surprise that it is easy to overfit the data # The Fix: # /Random Forests/ # Build multiple trees (semi-randomly) and combine the results: # (*) If output is numerical, we can take an average # (*) If output is categorical, we can let them vote # How to get randomness? # (*) Bootstrap aggregate samples from the inputs # Train each tree on a bootstrap sample # Resulting trees will be pretty different # (*) Change the way we choose best_attribute to split on # Rather than looking at all remaining attributes, # Take a random subset and split on the best one of those # # May also consider applying Principal Component Analysis to the set of attributes(?) # NOTE: A random forest is an example of a breader technique called /ensemble learning/ # where we combine several 'weak learners' (high-bias, low-variance) # to produce a 'strong learner' # try to implement later
1ea45e4f7a3db371b1ee4da03618b86aa30d2330
Lumpsum/heuristieken
/assets/solver.py
8,519
3.53125
4
import Queue class Solver(object): def __init__(self, grid, car_list): self.grid = grid self.car_list = car_list def a_star(self, grid, car_list): # Initialize variables queue, pre_grid = init_var_queue(grid, car_list, True) # Main loop while queue: # Take first grid from queue get_grid, gridObj = retrieve_grid(queue, True) # Check for all cars in the grid if there are moves possible for car in get_grid[2]: # Skip the placeholder car if car != 'placeholder': # Find the car number car_n = gridObj.retrieve_value(car[2], car[3]) # Try to move selected car both ways returned = try_move(gridObj, car_n, get_grid, pre_grid, queue, "A", None) if returned: return returned return "No solution" def beam(self, grid, car_list): # Initialize variables beam = [(0, grid, car_list)] pre_grid = {} pre_grid[str(grid)] = "finished" width = 100 solution = True while solution: queue = Queue.PriorityQueue() for x in beam: # Take first grid from queue get_grid = x gridObj = Grid(get_grid[1], get_grid[2]) # Check for all cars in the grid if there are moves possible for car in get_grid[2]: # Skip the placeholder car if car != 'placeholder': # Find the car number car_n = gridObj.retrieve_value(car[2], car[3]) # Function for moving the car, checking for solution and creating new states def move_car(move): # Check if move is possible if gridObj.check_move_car(car_n, move): # Create copy of grid and move the car in the new grid newGridObj = Grid([x[:] for x in get_grid[1]], get_grid[2][:]) newGridObj.move_car(car_n, move) newGridObjGridStr = str(newGridObj.grid) # Check if grid has already existed if newGridObjGridStr not in pre_grid: # Heuristic: Distance red car to exit distancetoboard = len(newGridObj.grid) - newGridObj.car_list[1][2] - newGridObj.car_list[1][1] cost = distancetoboard + get_grid[0] # Heuristic: Cost of blocking car is higher than blocking truck for i in range(newGridObj.car_list[1][2] + newGridObj.car_list[1][1], len(newGridObj.grid)): if newGridObj.retrieve_value(i, newGridObj.car_list[1][3]) != 0: if newGridObj.car_list[1][1] == 3: cost += 10 if newGridObj.car_list[1][1] == 2: cost += 100 # Check for solution (clear path to endpoint) if newGridObj.check_solution(): # Check if red car is at the endpoint if newGridObj.car_list[1][2] != (len(newGridObj.grid[0])-2): # Add grid to queue to be further processed queue.put((cost, newGridObj.grid, newGridObj.car_list, get_grid[1][:])) # Return and finish algorithm else: pre_grid[newGridObjGridStr] = get_grid[1][:] return (newGridObj, pre_grid) # Add state to queue to be further processed queue.put((cost, newGridObj.grid, newGridObj.car_list, get_grid[1][:])) # Try to move selected car both ways returned = move_car(1) if returned: return returned returned = move_car(-1) if returned: return returned if queue.empty(): print "Empty" return "No Solution" beam = [] for i in range(width): if queue.empty(): break else: obj = queue.get() beam.append(obj[:3]) pre_grid[str(obj[1])] = obj[3] print len(pre_grid) def bfs(self, grid, car_list): queue, pre_grid = init_var_queue(grid, car_list, False) while queue: # Take first grid from queue get_grid, gridObj = retrieve_grid(queue, False) # Check for all cars in the grid if there are moves possible for car in get_grid[1]: # Skip the placeholder car if car != 'placeholder': # Find the car number car_n = gridObj.retrieve_value(car[2], car[3]) # Try to move selected car both ways returned = try_move(gridObj, car_n, get_grid, pre_grid, queue, False, None) if returned: return returned return "No solution" def best_first(self, grid, car_list): queue, pre_grid = init_var_queue(grid, car_list, True) # Main loop while queue: # Take first grid from queue get_grid, gridObj = retrieve_grid(queue, True) # Check for all cars in the grid if there are moves possible for car in get_grid[2]: # Skip the placeholder car if car != 'placeholder': # Find the car number car_n = gridObj.retrieve_value(car[2], car[3]) # Try to move selected car both ways returned = try_move(gridObj, car_n, get_grid, pre_grid, queue, "Best", None) if returned: return returned return "No solution" # Init vars. etc def init_var_queue(grid, car_list, heuristic): if heuristic == True: queue = Queue.PriorityQueue() queue.put((0, grid, car_list)) else: queue = Queue.Queue() queue.put((grid, car_list)) pre_grid = {} pre_grid[str(grid)] = "finished" return queue, pre_grid def retrieve_grid(queue, heuristic): get_grid = queue.get() if heuristic == True: gridObj = Grid(get_grid[1], get_grid[2]) else: gridObj = Grid(get_grid[0], get_grid[1]) return get_grid, gridObj # Function for moving the car, checking for solution and creating new states def move_car(move, gridObj, car_n, get_grid, pre_grid, queue, heuristic, placeholder_pre_grid): if heuristic != False: num = 1 else: num = 0 cost = None # Check if move is possible if gridObj.check_move_car(car_n, move): # Create copy of grid and move the car in the new grid newGridObj = Grid([x[:] for x in get_grid[num]], get_grid[num+1][:]) newGridObj.move_car(car_n, move) newGridObjGridStr = str(newGridObj.grid) # Check if grid has already existed if newGridObjGridStr not in pre_grid: if heuristic == "A": # Heuristic: Distance red car to exit distancetoboard = len(newGridObj.grid) - newGridObj.car_list[1][2] - newGridObj.car_list[1][1] cost = distancetoboard + get_grid[0] # Heuristic: Cost of blocking car is higher than blocking truck for i in range(newGridObj.car_list[1][2] + newGridObj.car_list[1][1], len(newGridObj.grid)): if newGridObj.retrieve_value(i, newGridObj.car_list[1][3]) != 0: if newGridObj.car_list[1][1] == 3: cost += 10 if newGridObj.car_list[1][1] == 2: cost += 1000 if heuristic == "Best": cost = len(newGridObj.grid) - newGridObj.car_list[1][2] - newGridObj.car_list[1][1] cost*= 5 cost -= newGridObj.grid[newGridObj.car_list[1][3]].count(0)*10 # Check for solution (clear path to endpoint) if newGridObj.check_solution(): # Check if red car is at the endpoint if newGridObj.car_list[1][2] != (len(newGridObj.grid[0])-2): # Add grid to queue to be further processed if placeholder_pre_grid == None: queue, pre_grid = add_state(queue, cost, newGridObj, get_grid, pre_grid, newGridObjGridStr, num, heuristic) else: queue, placeholder_pre_grid = add_state(queue, cost, newGridObj, get_grid, placeholder_pre_grid, newGridObjGridStr, num, heuristic) # Return and finish algorithm else: pre_grid[newGridObjGridStr] = get_grid[num][:] return (newGridObj, pre_grid) # Add state to queue to be further processed if placeholder_pre_grid == None: queue, pre_grid = add_state(queue, cost, newGridObj, get_grid, pre_grid, newGridObjGridStr, num, heuristic) else: queue, placeholder_pre_grid = add_state(queue, cost, newGridObj, get_grid, placeholder_pre_grid, newGridObjGridStr, num, heuristic) def add_state(queue, cost, newGridObj, get_grid, pre_grid, newGridObjGridStr, num, heuristic): if heuristic != False: queue.put((cost, newGridObj.grid, newGridObj.car_list)) else: queue.put((newGridObj.grid, newGridObj.car_list)) pre_grid[newGridObjGridStr] = get_grid[num][:] return queue, pre_grid def try_move(gridObj, car_n, get_grid, pre_grid, queue, heuristic, placeholder_pre_grid): returned = move_car(1, gridObj, car_n, get_grid, pre_grid, queue, heuristic, placeholder_pre_grid) if returned: return returned returned = move_car(-1, gridObj, car_n, get_grid, pre_grid, queue, heuristic, placeholder_pre_grid) if returned: return returned
b52b170c64b22041c7f938a8705a757e12f0d318
JMW0503/CSCI_4
/conditionals.py
637
4.125
4
import sys def main(): myInput = int(input("Enter a number, please. ")) myVariable = 4 #myVariable == 4 if (myVariable < 10 and myVariable > -10): print("number between -10 and 10") #same thing^ if (myVariable < 10): if (myVariable > -10): print("match found") if (myInput > 20 or myVariable > 2) and myVariable > 3: print("Greater than twenty") else: print("less than or equal to twenty") print("the end") return 0 if __name__ == '__main__': sys.exit(main()) #Practical Application Examples:
294b259296e7c76916e75bba77bd89a7b4531b4a
luanlelis12/Avaliacao1-Luan-Alves
/Avalicao1-Luan Alves/Questรฃo07.py
724
4.125
4
salario = float(input("Insira o salรกrio do colaborador:")) if salario <= 280: perAumento = 0.20 aumento = salario*perAumento nSalario = salario+aumento elif salario > 280 and salario < 700: perAumento = 0.15 aumento = salario*perAumento nSalario = salario+aumento elif salario > 700 and salario < 1500: perAumento = 0.10 aumento = salario*perAumento nSalario = salario+aumento elif salario > 1500: perAumento = 0.05 aumento = salario*perAumento nSalario = salario+aumento print("Salรกrio antigo: R$ %.2f" %salario) print("Percentual de aumento: %.2f" %perAumento) print("Aumento: R$ %.2f" %aumento) print("Salรกrio novo: R$ %.2f" %nSalario) input()
39b34f94ccbbb99c30b13b4bc0dd3bcbfce9eeaf
Alex19-91/Python
/Lesson_2/2.2.py
271
3.765625
4
my_list = input ("ะ’ะฒะตะดะธั‚ะต ะทะฝะฐั‡ะตะฝะธั ัะปะตะผะตะฝั‚ะพะฒ ัะฟะธัะบะฐ ั‡ะตั€ะตะท ะฟั€ะพะฑะตะป:") my_list = my_list.split() i = 1 a = my_list[i] while i< len(my_list): a= my_list[i-1] my_list[i-1] = my_list[i] my_list[i] = a i+=2 print (my_list)
f3d3fc9ee9c633aa7d012f1fa91ba259b43cacd6
huhudaya/leetcode-
/็จ‹ๅบๅ‘˜้ข่ฏ•้‡‘ๅ…ธ/้ข่ฏ•้ข˜ 16.19. ๆฐดๅŸŸๅคงๅฐ.py
1,555
3.578125
4
''' ไฝ ๆœ‰ไธ€ไธช็”จไบŽ่กจ็คบไธ€็‰‡ๅœŸๅœฐ็š„ๆ•ดๆ•ฐ็Ÿฉ้˜ตland๏ผŒ่ฏฅ็Ÿฉ้˜ตไธญๆฏไธช็‚น็š„ๅ€ผไปฃ่กจๅฏนๅบ”ๅœฐ็‚น็š„ๆตทๆ‹”้ซ˜ๅบฆใ€‚่‹ฅๅ€ผไธบ0ๅˆ™่กจ็คบๆฐดๅŸŸใ€‚็”ฑๅž‚็›ดใ€ๆฐดๅนณๆˆ–ๅฏน่ง’่ฟžๆŽฅ็š„ๆฐดๅŸŸไธบๆฑ ๅก˜ใ€‚ๆฑ ๅก˜็š„ๅคงๅฐๆ˜ฏๆŒ‡็›ธ่ฟžๆŽฅ็š„ๆฐดๅŸŸ็š„ไธชๆ•ฐใ€‚็ผ–ๅ†™ไธ€ไธชๆ–นๆณ•ๆฅ่ฎก็ฎ—็Ÿฉ้˜ตไธญๆ‰€ๆœ‰ๆฑ ๅก˜็š„ๅคงๅฐ๏ผŒ่ฟ”ๅ›žๅ€ผ้œ€่ฆไปŽๅฐๅˆฐๅคงๆŽ’ๅบใ€‚ ็คบไพ‹๏ผš ่พ“ๅ…ฅ๏ผš [ [0,2,1,0], [0,1,0,1], [1,1,0,1], [0,1,0,1] ] ่พ“ๅ‡บ๏ผš [1,2,4] ๆ็คบ๏ผš 0 < len(land) <= 1000 0 < len(land[i]) <= 1000 ''' from typing import List # DFS class Solution: def pondSizes(self, land: List[List[int]]) -> List[int]: m = len(land) n = len(land[0]) # ๅ‘จๅ›ด็š„8ไธชๆ–นๅ‘๏ผˆๅŒ…ๆ‹ฌๆ–œๅฏน่ง’๏ผ‰ directions = [(0, 1), (1, 0), (1, 1), (-1, -1), (0, -1), (-1, 0), (-1, 1), (1, -1)] res = [] seen = [[False] * n for i in range(m)] def dfs(i, j): seen[i][j] = True res = 1 for di in directions: row = i + di[0] col = j + di[1] if not (row >= 0 and row < m and col >= 0 and col < n): continue if seen[row][col]: continue if land[row][col] == 0: res += dfs(row, col) return res cnt = 0 for i in range(m): for j in range(n): if not seen[i][j] and land[i][j] == 0: cnt += 1 res.append(dfs(i, j)) res.sort() return res
49cfefbfe97f7a593023e3a215ab2b251836af3c
makozi/Sal-s-Shipping
/script.py
1,218
3.796875
4
# Premium Ground Shipping Flat charge: $125.00 cost_premium_ground= 125.00 def cost_ground_shipping(weight): if weight <=2: price_per_pound=1.50 elif weight <=6: price_per_pound=3.00 elif weight <=10: price_per_pound=4.00 else: price_per_pound= 4.75 return 20 + (price_per_pound * weight) # Testing the function # print(cost_ground_shipping(8.4)) def cost_drone_shipping(weight): if weight <=2: price_per_pound=4.50 elif weight <=6: price_per_pound=9.00 elif weight <=10: price_per_pound=12.00 else: price_per_pound= 14.25 return 0.00 + (price_per_pound * weight) # Testing the function # print(cost_drone_shipping(1.5)) def cheapest_shipping_method(weight): ground= cost_ground_shipping(weight) drone= cost_drone_shipping(weight) premium=cost_premium_ground if ground< premium and ground < drone: method= 'Standard Ground' cost = ground elif drone < premium and drone <ground: method= 'Drone' cost = drone else: method= 'Premium Ground' cost = premium print("The cheapest option available is $%.2f with %s shipping" % (cost, method)) # cheapest_shipping_method(4.8) # cheapest_shipping_method(41.5)
07109e0211e7c00b1f20ecb9404bd4390f92a051
yutoo89/python_programing
/basic_grammar/list_copy.py
519
3.765625
4
# ๅ‚็…งๆธกใ— i = [1, 2, 3, 4, 5] j = i j[0] = 100 print('i =', i) print('j =', j) # i = [100, 2, 3, 4, 5] # j = [100, 2, 3, 4, 5] print('i.id =', id(i)) print('j.id =', id(j)) # ๅŒใ˜IDใŒๅ‡บๅŠ›ใ•ใ‚Œใ‚‹ # i.id = 140443418909888 # j.id = 140443418909888 # ๅ€คๆธกใ— x = [1, 2, 3, 4, 5] y = x.copy() y[0] = 100 print('x =', x) print('y =', y) # x = [1, 2, 3, 4, 5] # y = [100, 2, 3, 4, 5] print('x.id =', id(x)) print('y.id =', id(y)) # ็•ฐใชใ‚‹IDใŒๅ‡บๅŠ›ใ•ใ‚Œใ‚‹ # x.id = 140443420522368 # y.id = 140443420522560
79d246215be7494004a6a36b29a1ad933124e5ad
betty29/code-1
/recipes/Python/438810_First_last_item_access_predicates_increase/recipe-438810.py
1,055
4.03125
4
def first(seq, pred=None): """Return the first item in seq for which the predicate is true. If the predicate is None, return the first item regardless of value. If no items satisfy the predicate, return None. """ if pred is None: pred = lambda x: True for item in seq: if pred(item): return item return None def last(seq, pred=None): """Return the last item in seq for which the predicate is true. If the predicate is None, return the last item regardless of value. If no items satisfy the predicate, return None. """ if pred is None: pred = lambda x: True for item in reversed(seq): if pred(item): return item return None # Just get the first item :) # >>> seq = 'abc' # >>> first(seq) # 'a' # Get the first item greater than 10 # >>> seq = [1, 2, 4, 12, 13, 15, 17] # >>> first(seq, lambda x: x > 10) # 12 # Get the last non-None/False/empty item # >>> seq = ["one", "two", "three", "", None] # >>> last(seq, bool) # 'three'
556ce9fc798886174ea4bb8fded3abe0b175e958
vladkudiurov89/Test_book
/function.py
496
3.984375
4
# x = math.sqrt(x + 3) - x + 1 # f(0); f(1); f(sqrt(2)); f(sqrt(2)-1 import math def f(x): return math.sqrt(x + 3) - x + 1 # # List of values to plug in for x in [0,1,math.sqrt(2), math.sqrt(2)-1]: print("f({:.3f}) = {:.3}f".format(x, f(x))) # y = math.sqrt(y + 1) - y + 5 # fn(5); fn(sqrt(7)); fn(0); fn(sqrt(13)-10) def fn(y): return math.sqrt(y + 1) - y + 5 for y in [ 0, 5, math.sqrt(7), math.sqrt(13) - 1 ]: print("fn({:.3f}) = {:.3}fn".format(y, fn(y)))
a80dc4288cbb6c6686fd86b7540179fd5ec93be0
crobird/aoc2020
/day5/part1.py
1,959
3.5625
4
#!/usr/bin/env python """ Advent of Code 2020 """ import os import re import math import collections from enum import Enum from dataclasses import dataclass me = os.path.basename(__file__) DEFAULT_INPUT_FILE = "input/" + me.replace(".py", ".txt") LOW_HIGH_MAP = dict( F = 0, L = 0, B = 1, R = 1 ) class Seat(object): def __init__(self, s): self.s = s self.row = None self.col = None self.set_position() @property def id(self): return self.row * 8 + self.col def set_position(self): row_orders = self.s[:7] col_orders = self.s[-3:] self.row = Seat.find_position(row_orders, 0, 127) self.col = Seat.find_position(col_orders, 0, 7) @staticmethod def find_position(items, low, high): for i in items: new_low, new_high = Seat.refine_nums(low, high, LOW_HIGH_MAP[i]) print(f"refine_nums({low}, {high}, {i}) = {new_low}, {new_high}") low = new_low high = new_high assert low == high return low @staticmethod def refine_nums(low, high, is_high): items = high - low + 1 half = int(items/2) if is_high: return (low + half, high) else: return (low, low + half - 1) def parse_seats(filepath): with open(filepath, "r") as fh: seats = [Seat(l.strip()) for l in fh] return seats def main(args): seats = parse_seats(args.file) highest = max([s.id for s in seats]) print(f"The highest ID is {highest}") if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('-f', '--file', help='Input file, default: {}'.format(DEFAULT_INPUT_FILE), default=DEFAULT_INPUT_FILE, required=True) parser.add_argument('-v', '--verbose', help="Verbose output", default=False, action="store_true") args = parser.parse_args() main(args)
ab8c05899374825ca7b207f741b3a2c7da3153fb
destinyadams/calculator
/functions.py
657
4
4
def addition(num1,num2,num3,num4): result = num1 + num2 + num3 + num4 print ("{0} + {1} = {2}".format(num1,num2,num3,num4,result)) def subtraction(num1,num2,num3,num4): result = num1 - num2 - num3 - num4 print ("{0} - {1} = {2}".format(num1,num2,num3,num4,result)) def multiplication(num1,num2,num3,num4): result = num1 * num2 * num3 * num4 print ("{0} * {1} * {2}".format(num1,num2,num3,num4,result)) def division(num1,num2,num3,num4): if num2 == 0.0: print(" Cannot divide by Zero") else: result = num1 / num2 print ("{0} / {1} = {2}".format(num1,num2,num3,num4,result))
f2446bb1bf79ca45becd4cec523b69f51a246a65
NirmalVatsyayan/python-revision
/language_programs/43_super.py
662
3.9375
4
''' question asked by linga ''' class Student(object): c = "1111" def __init__(self): self.name = "linga" self.roll_number = "1" class Programmer(Student): '''this is a programmer class''' def __init__(self): self.language = "python" super(Programmer, self).__init__() def print_data(self): '''this is a print data function''' print(self.name) print(self.roll_number) print(self.language) print(self.c) obj = Programmer() obj.print_data() print(__doc__) # call module doc print(obj.__doc__) # call class doc print(obj.print_data.__doc__) # call function doc
201780a280471160c78a71299e3a236d748b433d
wandererzzx/GloVe
/CPU_co_occur.py
3,169
3.515625
4
import numpy as np import os import csv import time # read csv file and return a list with each row in the csv file as an element def read_csv(csv_path,delimiter=' '): ''' csv_path: preprocessed csv file path ''' with open(csv_path) as csvfile: reader = csv.reader(csvfile,delimiter=delimiter) data = list(reader) return data # count the co_occurrance of words in single article def co_occurrance_count(article,freq_dict,co_occurMat,window_size=10): ''' article: a list of word integers in single article freq_dict: a list indicates the most frequent words co_occurMat: word-word co-occurrence matrix window_size: the size of context window ''' length = len(article) for i in range(length): # iterate through every word in article target = article[i] context = [] if target in freq_dict: # if the word is frequent word, get its index in freq_dict ind_tar = freq_dict.index(target) # find the context of our target word if i < window_size: context_left = article[0:i] if i+1+window_size < length: context_right = article[i+1:i+1+window_size] else: context_right = article[i+1:] else: context_left = article[i-window_size:i] if i+1+window_size < length: context_right = article[i+1:i+1+window_size] else: context_right = article[i+1:] # populate co_occurMat with 1/distance to target word for count,context_word in enumerate(context_left): if context_word in freq_dict: ind_con = freq_dict.index(context_word) co_occurMat[ind_tar,ind_con] += 1.0/np.float32(len(context_left)-count) #co_occurMat[ind_tar,ind_con] += 1 for count,context_word in enumerate(context_right): if context_word in freq_dict: ind_con = freq_dict.index(context_word) co_occurMat[ind_tar,ind_con] += 1.0/np.float32(count+1) #co_occurMat[ind_tar,ind_con] += 1 def convert(data_dir,dict_source): freq_dict = read_csv(dict_source)[0] size = len(freq_dict) print('dict_size:{}'.format(size)) print('dict_samples:{}'.format(freq_dict[0:10])) # initialize co_occurrance matrix co_occurMat = np.zeros((size,size)) file_num = len(os.listdir(data_dir)) # read preprocessed article csv for number,name in enumerate(os.listdir(data_dir)): wiki = data_dir + name articles = read_csv(wiki) num_article_per_file = len(articles) print('counting file {}/{}:'.format(number+1,file_num)) print('number of articles:{}'.format(num_article_per_file)) # count each article for article in articles: co_occurrance_count(article,freq_dict,co_occurMat,window_size=10) del articles # prevent OOM error return co_occurMat if __name__ == '__main__': # directory of preprocessed csv file wiki_00,wiki_01... data_dir = os.path.abspath('.') # frequent word file dict_source = os.path.abspath('.') + '\\freq_word.csv' # the file storing output co-occurrence matrix save_file = os.path.abspath('.') + '\\CPU_co_occurMat.csv' start = time.time() co_occurMat = convert(data_dir,dict_source) time_spent = time.time() - start print(co_occurMat) print(time_spent) # save the co_occurMat to csv file np.savetxt(save_file,co_occurMat,delimiter=',')
bf7c6b06e7d510bcbdb674a051efb608b49439ac
chenzhixun/Learning-Python3
/002-Control Structures/01_if_statements.py
471
4.25
4
if 10 > 5: print("10 greater than 5") print("Program ended") spam = 7 if spam > 5: print("five") if spam > 8: print("eight") num = 12 if num > 5: print("Bigger than 5") if num <= 47: print("Between 5 and 47") x = 4 if x == 5: print("Yes") else: print("No") num = 7 if num == 5: print("Number is 5") elif num == 11: print("Number is 11") elif num == 7: print("Number is 7") else: print("Number isn't 5, 11 or 7")
db1863f4e73a74bcd132111792109c1e6ce95cc6
Seonaid/MyExercismCode
/python/isbn-verifier/isbn_verifier.py
660
3.6875
4
def filterNumbers(character): return character.isdigit() def makeNumbers(character): if character == 'X': return 10 else: return int(character) def is_valid(isbn): # check length and format raw_isbn = list(filter(filterNumbers, isbn[0:-1])) if (len(raw_isbn) != 9): return False if (isbn[-1].isdigit()) or (isbn[-1]=='X'): raw_isbn.append(isbn[-1]) digits = list(map(makeNumbers, raw_isbn)) else: return False n = 10 digit_sum = 0 for number in digits: digit_sum += n*number n -= 1 return (digit_sum%11 == 0) # print(is_valid('359821507X'))
32b559f9d19db243b78afa1267436ad893b4a205
yvlee/Univeristy-Project
/FIT1008-Algorithms and Data structure/Prac2/Task6_AssPrac.py
5,911
3.9375
4
from Task4_AssPrac import ArrayBasedList class TextEditor: def __init__(self): self.newArray = ArrayBasedList(10) def insertNum(self,num, item): ''' This function inserts a new item at the position before the index selected complexity: bests and worst case O(1) :param num: the index that is chosen to insert the item :param item: item to be inserted to the position before index selected :return: an updated list that is grown in size after inserting more items ''' num = int(num) if num >= 1 and num <= len(command.newArray): self.newArray.insert(num,item) print(self.newArray) def readFile(self,filename): ''' This function is to read in a file complexity: best case and worst case: O(n) :param filename:The file name of the file that is used to read in :return: the content in the file ''' infile = open(filename, 'r') content = infile.readlines() infile.close() for i in range(len(content)): row = str(content[i].rstrip('\n')) self.newArray.append(row) print(self.newArray) return self.newArray def writeFile(self,filename): ''' This function is to write in a file complexity: :param filename:The file name of the file that is used to write in :return: contents will be overwrited ''' outfile = open(filename, 'w') for i in range(1, (len(self.newArray) + 1)): outfile.write(self.newArray[i] + '\n') outfile.close() return self.newArray def print(self,num): ''' This function is to print the contents given the index. Function is supposed to print out whole list if no index given :param num: the index of item that is chosen to be printed :return: printed item or printed list ''' num = int(num) if num > len(self.newArray): raise IndexError print(self.newArray[num]) def deleteNum(self,num): ''' This function is to delete the contents given the index. Function is supposed to delete whole list if no index given complexity: best case worst case: O(N) :param num: the index of item that is chosen :return: either empty list or list without the deleted items ''' num = int(num) if num > len(self.newArray): raise IndexError self.newArray.delete(num) #print(self.newArray) def quit(self): print("bye bye") raise SystemExit def frequency(self): ''' This function is to check for the amount of time the same item appeared in the list :return: the item and the amount of time it appeared ''' tempList = [] for i in range(1, len(command.newArray) + 1): target = command.newArray[i] target = target.split(" ") print(target) for j in range(len(target)): tempList.append(target[j]) print(tempList) for i in range(len(tempList)): newtarget = tempList[i] count = 0 for j in range(i+1, len(tempList)): if newtarget == tempList[j]: count += 1 #print(newtarget + str(count)) #for j in range(i+1, len(command.newArray)): #if target == command.newArray[j]: #count += 1 #print(target + "count") if __name__ == '__main__': print("1. insert // type insert* (space) *index*") print("2. read // type *read* (space) *filename.txt*") print("3. write // type *write* (space) *filename.txt*") print("4. print // type *print* (space) *index or nothing*") print("5. delete // type *delete* (space) *index or nothing*") print("6. quit") print("7. frequency") command = TextEditor() while True: try: option = input() option = option.split(" ") # print(len(option)) if len(option) < 3: if option[0] == "read": filename = option[1] command.readFile(filename) # print(len(command.newArray)) if option[0] == "insert": num = int(option[1]) if num >= 1 and num <= len(command.newArray): item = input("Enter:") num = int(num) # print('hi') command.insertNum(num, item) # print('hi') else: print("?") if option[0] == "write": file_name = option[1] command.writeFile(file_name) # print(hi) # print(command.newArray) if option[0] == "print": if len(option) == 1: print(str(command.newArray)) else: command.print(option[1]) if option[0] == "delete": if len(option) == 1: print(range(1, len(command.newArray))) for item in range(len(command.newArray), 0, -1): print(command.newArray[item]) command.deleteNum(item) else: index = int(option[1]) command.deleteNum(index) if option[0] == "quit": command.quit() if option[0] == "frequency": command.frequency() else: print("?") except Exception: print("?")
29245d44544f01199e03edabd5e54aae6e513643
namhee33/selection_sort
/timed_selection_sort2.py
1,042
3.640625
4
import random import datetime x=[] def create_list(): for i in range(0,100): random_num = random.randint(0,10000) x.append(random_num) def print_pretty(): for i in range(0,10): for j in range(0,10): print '{0:5d}'.format(x[j+i*10]), print def selection_sort(): print 'half size: ' + str(len(x)//2) for i in range(0,len(x)//2): min_index = i min_value = x[i] max_index = len(x) - 1 - i max_value = x[max_index] for j in range(i+1,len(x)-i): if min_value > x[j]: min_index = j min_value = x[j] elif max_value < x[j]: max_index = j max_value = x[j] temp = x[i] x[i] = min_value x[min_index] = temp temp = x[j] x[j] = max_value x[max_index] = temp create_list() print '.......Unsorted List.....' print_pretty() start_time = datetime.datetime.now() selection_sort() print '.......Sorted List.....' print_pretty() end_time = datetime.datetime.now() duration = end_time - start_time print 'Time for selection_sort with both min and max value (hrs, mins, seconds): ' print duration
bdd6e5c93acd57ee7928702f750e4e4ad9ad6ded
Lincoln12w/OJs
/PAT/Basic Level/1013.py
382
3.71875
4
def isPrime(num): for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True edge = raw_input().split() beg = int(edge[0]) end = int(edge[1]) if beg <= 2: print 2, n = 3 primecnt = 1 while primecnt < end: if isPrime(n): primecnt += 1 if primecnt >= beg: if (primecnt - beg + 1) % 10 == 0: print n else: print n, n += 2
e84c1ab8d381c53061f6934d4a1d6b57606b5310
ZakBibi/PracticePython
/CodingPractice/OOPPractice/tests/test_MaxSizeList.py
753
3.703125
4
import unittest from CodingPractice.OOPPractice.assignments.MaxSizeList import MaxSizeList class TestMaxListClass(unittest.TestCase): def test_list_three_elements(self): a = MaxSizeList(3) a.push('Hey') a.push('hi') a.push('you') a.push('guys') self.assertEqual(['hi', 'you', 'guys'], a.get_list()) def test_list_one_element(self): b = MaxSizeList(1) b.push('Hey') b.push('hi') b.push('you') self.assertEqual(['you'], b.get_list()) def test_copy_is_made(self): a = MaxSizeList(1) a.push('hello') b = a.get_list() b.append('world') self.assertNotEqual(a, b) if __name__ == '__main__': unittest.main()
2eec7b387b09eef6060ed005a89124ed26785427
924070845/TanzhouPythonVipSecondClass
/ๆ•ฐๆฎๅบ“01/datetimeๆ ‡ๅ‡†ๅบ“.py
691
3.765625
4
import datetime # ๅฟ…้กป่‡ช็„ถ่ง„่Œƒ๏ผŒไธ็„ถๆŠฅ้”™ # ๆŒ‡ๅฎšๆ—ถ้—ด time = datetime.time(20, 30, 59) print(time) # ๆ—ฅๆœŸ date = datetime.date(2018, 9, 7) print(date) # ๅนดๆœˆๆ—ฅไธ่ƒฝๅฐ‘๏ผŒๆ—ถๅˆ†็ง’ๅฏไปฅๅฐ‘ date_time = datetime.datetime(2018, 9, 6, 20, 30 ,59) print(date_time) # ่Žทๅ–ๅฝ“ๅ‰ๆ—ถ้—ด now = date_time.now() print(now) # ๅฐ†ๆŒ‡ๅฎšๆ—ถ้—ดๅฏน่ฑก่ฝฌๆขไธบๆ—ถ้—ดๆˆณ time_stamp = date_time.timestamp() print(time_stamp) # ๅฐ†ๆ—ถ้—ดๆˆณ่ฝฌๅŒ–ไธบๆ—ถ้—ด nowtime = date_time.fromtimestamp(time_stamp) print(nowtime) # ๅฐ†nowๆ—ถ้—ด่ฝฌๆขไธบๅญ—็ฌฆไธฒ๏ผŒๅนถๆŒ‰ๆŒ‡ๅฎšๆ ผๅผ๏ผŒไนŸๅฏไน‹้—ดๆ’ๅ…ฅๅ€ผ result = now.strftime('%Y-%m-%d %H: %M') print(result)
6992e8064e8031e1b0023071471f937152b69263
Dakarai/war-card-game
/main.py
3,338
3.53125
4
import random suits = ('Clubs', 'Diamonds', 'Hearts', 'Spades') ranks = ('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A') values = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14} war_cards_count = 3 class Card: def __init__(self, suit, rank): self.suit = suit[0].lower() self.rank = rank self.value = values[rank] def __repr__(self): return self.rank + "" + self.suit class Deck: def __init__(self): self.all_cards = [] for suit in suits: for rank in ranks: self.all_cards.append(Card(suit, rank)) def shuffle(self): random.shuffle(self.all_cards) def deal_one(self): return self.all_cards.pop(0) class Player: def __init__(self, name): self.name = name.capitalize() self.all_cards = [] def remove_one(self): return self.all_cards.pop(0) def add_cards(self, new_cards): if type(new_cards) == type([]): self.all_cards.extend(new_cards) else: self.all_cards.append(new_cards) def __str__(self): return f"Player {self.name} has {len(self.all_cards)} cards." if __name__ == '__main__': # create players player_one = Player("One") player_two = Player("Two") # create deck object and shuffle it new_deck = Deck() new_deck.shuffle() # split shuffled deck between players for x in range(26): player_one.add_cards(new_deck.deal_one()) player_two.add_cards(new_deck.deal_one()) play_game = True round_number = 0 while play_game: round_number += 1 print(f"Round {round_number}") if len(player_one.all_cards) == 0: print('Player One has lost!') play_game = False break elif len(player_two.all_cards) == 0: print('Player Two has lost!') play_game = False break # start a new round player_one_cards = [player_one.remove_one()] player_two_cards = [player_two.remove_one()] end_of_round = False while not end_of_round: # evaluate round if player_one_cards[-1].value > player_two_cards[-1].value: player_one.add_cards(player_one_cards) player_one.add_cards(player_two_cards) end_of_round = True print(player_one_cards) print(player_two_cards) print(player_one) print(player_two) break elif player_one_cards[-1].value < player_two_cards[-1].value: player_two.add_cards(player_two_cards) player_two.add_cards(player_one_cards) end_of_round = True print(player_one_cards) print(player_two_cards) print(player_one) print(player_two) break else: for _ in range(war_cards_count): if len(player_one.all_cards) > 0: player_one_cards.append(player_one.remove_one()) if len(player_two.all_cards) > 0: player_two_cards.append(player_two.remove_one())
258a0abde9684ef44adb9c2ad4423f01b9037bb4
RomanPutsilouski/M-PT1-37-21
/Tasks/Lappo_Tasks/Class_Task8/phone_book.py
336
3.765625
4
book = {} def get_book(): def AddPhone(d): fn=input("ะ’ะฒะตะดะธั‚ะต ะธะผั:") ln=input("ะ’ะฒะตะดะธั‚ะต ั„ะฐะผะธะปะธั:") ph=input("ะ’ะฒะตะดะธั‚ะต ั‚ะตะปะตั„ะพะฝ:") if d.get((fn,ln)): d[(fn,ln)].append(ph) else: d[(fn,ln)]=[ph] def DeletePhone(dict): del dict["A1"] #def FindPhone:
9c7e0f3f122882fdb3da7818b01d6a18b2db2fae
Toubat/Stanford-Algorithm
/Assignment2.py
1,268
3.65625
4
# assignment 2 def countSplitInv(arr_left, arr_right, n): # arrA is a sorted array arrA, inv = [], 0 i, j = 0, 0 while i < len(arr_left) and j < len(arr_right): if arr_left[i] <= arr_right[j]: arrA.append(arr_left[i]) i += 1 else: arrA.append(arr_right[j]) j += 1 inv += len(arr_left) - i if i == len(arr_left) and j < len(arr_right): arrA += arr_right[j:] elif j == len(arr_right) and i < len(arr_left): arrA += arr_left[i:] return arrA, inv def sortCountInv(arrA): # base case n = len(arrA) if n == 1: return arrA, 0 else: arrB, x = sortCountInv(arrA[: n // 2]) arrC, y = sortCountInv(arrA[n // 2:]) arrD, z = countSplitInv(arrB, arrC, n) return arrD, x + y + z def isSorted(arr): i = 0 while i < len(arr) - 1: if arr[i] > arr[i+1]: return False i += 1 return True def main(): file = open("assign2_input.txt", 'r') lst = [] while True: line = file.readline() if not line: break lst.append(int(line)) arr, inv = sortCountInv(lst) print(isSorted(arr)) print(inv) return 0 main()
6bb8dd2d88ccc6e2d5bb1bf9d0d19c023a24efb6
kenjimouriml/kyopro
/kenchon/ch03/test_get_min_value.py
648
3.71875
4
import unittest from main import get_min_value class SearchTest(unittest.TestCase): def test_get_min_value_ok(self): num_list = [1, 2.8, 3, 4, 5, 6, 0.2] returns = get_min_value(num_list) self.assertEqual(returns, (0.2, 6)) def test_get_min_value_typeerror(self): num_list = 4 with self.assertRaises(TypeError): get_min_value(num_list) def test_get_min_value_typeerror2(self): num_list = [1.0, 3.0, "string"] with self.assertRaises(TypeError): get_min_value(num_list) if __name__ == "__main__": unittest.main()
356b5f89360d1de462315688ff1a953e91b84adc
pmrowla/aoc2018
/day1.py
928
3.53125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """Advent of Code 2018 day 1 module.""" from __future__ import division, print_function from itertools import cycle def part_two(digits): seen = set([0]) current = 0 for x in cycle(digits): current += x if current in seen: return current seen.add(current) def main(): """Main entry point.""" import argparse import fileinput parser = argparse.ArgumentParser() parser.add_argument('infile', help='input file to read ("-" for stdin)') args = parser.parse_args() try: puzzle_input = [] for line in fileinput.input(args.infile): puzzle_input += [int(x) for x in line.split()] print('Part one: {}'.format(sum(puzzle_input))) print('Part two: {}'.format(part_two(puzzle_input))) except KeyboardInterrupt: pass if __name__ == '__main__': main()
d80538cff3b01893a142cd0112aa336ecb69a216
LucasWong02/Py_Uni_Prjcts
/Hackerrank_1.py
207
3.875
4
n = int(input("Pon un numero: ")) if n == (2,4): print("Not weird") elif (n % 2) == 0 and (5 < n < 21): print("Weird") elif (n % 2) == 0 and (n > 19): print("Not Weird") else: print("Weird")
e1b9c7c64322be53043374686fbc395a301b0a18
kuzovkov/python_labs
/4/task4.2.py
406
4
4
# def is_simple(n): # for x in range(2,n): if n%x ==0: return False return True def simple(n): n=int(n) ls=range(1,n+1) return filter(lambda x:is_simple(x),ls) n=input(' :') print " ",n,": ",simple(n)
2a58b5f4360e963cf11e59a980b3dc93599cb247
arthur11678/Desafio-1-STI-UFF
/Main.py
1,080
3.6875
4
from Consulta import Consulta #Importa a classe Consulta da biblioteca Consulta from Cadastro import Cadastro #Importa a classe Cadastro da biblioteca Cadastro matricula_aluno = input("\nDigite sua matricula\n") #Pergunta ao usuรกrio sua matrรญcula consulta = Consulta(matricula_aluno, None) #Instancia a classe Consulta aluno = Consulta.alunopodecriaruffmail(consulta) #Chama o mรฉtodo da classe Consulta que verifica se o aluno pode criar o uffmail, caso haja algum erro ele retorna o nรบmero do erro if aluno == -1: #As prรณximas etapas sรฃo executadas para tratamento de erros print("O aluno ja possui UFFmail") elif aluno == -2: print("A matricula do alunos consta como inativa") elif aluno == -3: print("A matricula nao foi encontrada no banco de dados") else: Cadastro(aluno, None).geraropecoes() #Gera as opรงรตes de email, printa a confirmaรงรฃo e edita o arquivo CVS
7d43bcdcc6890c363d9267554509d8b43e6b53be
crainte/ap-assignment
/addtime.py
2,085
4.0625
4
#!/usr/bin/env python -B import re def add_time(current_time, additional_time): # current_time can be "[H]H:MM {AM|PM}" # additional_time is number of minutes to add to the time of day # return should be same format if not isinstance(additional_time, int): raise ValueError("Expected Integer as second argument") # AM/PM are case sensitive here, not sure if wanted if not re.match(r"[0-1]?[0-9]:[0-5][0-9] [A|P]M$", current_time): raise SyntaxError("Invalid format. Please use [H]H:MM {AM|PM}") # break the string into parts time, period = current_time.split() # break into hours and minutes hour, minute = time.split(":") # validate hours if int(hour) > 12 or int(hour) < 1: raise ValueError("Hours must be between 1-12") # find minute sum minute_sum = int(minute) + int(additional_time) # leftover after mod is the remaining minutes of new time m_remainder = minute_sum % 60 # the quotient should be the additional hours to add on add_hours = int(minute_sum//60) # zfill the remainder to look pretty final_minutes = str(m_remainder).zfill(2) # find hour sum hour_sum = int(hour) + int(add_hours) # this should be the hour of the new time h_remainder = hour_sum % 12 # this should be the amount of toggles required of the time period toggles = int(hour_sum//12) if h_remainder > 0: final_hour = h_remainder else: # put a ceiling on the possible value of hour final_hour = max(1, min(hour_sum, 12)) # find final period if toggles % 2 == 0: # If the amount of times a period will toggle is even, it won't change # from it's current value pass else: if period == "AM": period = "PM" elif period == "PM": period = "AM" else: raise ValueError("Something went wrong with period validation") final_period = period return "{hour}:{minute} {period}".format(hour=final_hour, minute=final_minutes, period=final_period)
15535557d5d3af33dffbf6f75ad2bde9377530d9
r50206v/Leetcode-Practice
/2022/*Medium-75-SortColors.py
1,251
3.734375
4
''' dual-pivot partitioning time: O(N) space: O(1) ''' class Solution: def sortColors(self, nums: List[int]) -> None: """ Dutch National Flag problem solution. """ # for all idx < p0 : nums[idx < p0] = 0 # curr is an index of element under consideration p0 = curr = 0 # for all idx > p2 : nums[idx > p2] = 2 p2 = len(nums) - 1 while curr <= p2: if nums[curr] == 0: nums[p0], nums[curr] = nums[curr], nums[p0] p0 += 1 curr += 1 elif nums[curr] == 2: nums[curr], nums[p2] = nums[p2], nums[curr] p2 -= 1 else: curr += 1 class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ from collections import Counter counter = Counter(nums) idx_1 = counter[0] idx_2 = counter[0] + counter[1] for idx in range(len(nums)): if idx < idx_1: nums[idx] = 0 elif idx_1 <= idx < idx_2: nums[idx] = 1 else: nums[idx] = 2
2fe267c86c7ce2bf90f554ed58e17cd5550871a0
hermanschaaf/advent-of-code-2017
/day1.py
408
3.6875
4
#!/bin/python from __future__ import print_function, unicode_literals from collections import defaultdict def special_sum(i): n = i while n > 0: f = n % 10 n //= 10 s = 0 n = f while i > 0: c = i % 10 i //= 10 if c == n: s += c n = c return s if __name__ == "__main__": q = int(input()) print(special_sum(q))
a451fba49167c5eeab3a6d9b7432b9a47b3d53fa
Abdulkadir78/Python-basics
/q13.py
439
4.09375
4
''' Write a program that accepts a sentence and calculate the number of letters and digits. Suppose the following input is supplied to the program: hello world! 123 Then, the output should be: LETTERS 10 DIGITS 3 ''' sentence = input('Enter a string: ') letters = 0 digits = 0 for i in sentence: if i.isalpha(): letters += 1 elif i.isdigit(): digits += 1 print('Letters: ', letters) print('Digits: ', digits)
d380d12c851a225d2b4825a0ae47b33eac21ac66
pkmm91/competitive-programming-solutions
/Hackerearth/comapnies_based_questions/p17.py
417
3.671875
4
from math import factorial def fib(n): return factorial(n) for i in range(input()): num = int(raw_input()) if num in [1,2,3]: print "0000" + str(fib(num)) elif num in [4]: print "000" + str(fib(num)) elif num in [5,6]: print "00" + str(fib(num)) elif num in [7]: print "0" + str(fib(num)) else: str1 = str(fib(num)) print str1[len(str1)-5:]
cf67608998af9f7b7d9994a2267ba48975b8cc82
saad-abu-sami/Learn-Python-Programming
/basic learning py/function_social media.py
469
3.796875
4
class User: name = '' email = '' password = '' login = False def login(self): email = input('enter email') password = input('enter password') if email == self.email and password == self.password: login = True print('login successful!') else: print('login failed!') def logout(self): login = False print('logged out!') def function(self):
1a4a7a1520a55d15321d55425d575f7aefe962e5
seo1511kr/TIL
/pycharm/python/hw/hw26.py
4,730
3.53125
4
# 1. ์œ ํด๋ฆฌ๋“œ ํ˜ธ์ œ๋ฒ•์œผ๋กœ ๊ตฌํ˜„(๋บ„์…ˆ, ๋‚˜๋ˆ—์…ˆ) # ๋‚˜๋ˆ—์…ˆ # num1,num2=list(map(int,input().split())) # import copy # def getc_mm(small,big): # if small>big:small,big=big,small # while big%small!=0: # res = big % small # big=copy.copy(small) # small=res # return small # print(getc_mm(num1,num2)) # # # # num1,num2=list(map(int,input().split())) # import copy # def getc_mm(small,big): # while big-small!=0: # if small > big: small, big = big, small # res = big - small # big=copy.copy(small) # small=res # return small # print(getc_mm(num1,num2)) # 2. # ์ •๋ณดํ†ต์‹ ์ฒ˜์—์„œ๋Š” 2016๋…„ 6์›” 4์ผ ์ธํ•˜ ๊ด‘์žฅ์—์„œ ์ด๋ฒคํŠธ๋ฅผ ์ง„ํ–‰ํ•˜๋ ค๊ณ  ํ•œ๋‹ค. # ์ •๋ณดํ†ต์‹ ์ฒ˜์—์„œ ์ธํ•˜ ๊ด‘์žฅ์— ์˜ฌ๋ฆฐ ๊ฒŒ์‹œ๊ธ€์— N๋ฒˆ์งธ๋กœ ๋Œ“๊ธ€์„ ๋‹จ ๋ชจ๋“  ํ•™์ƒ์—๊ฒŒ ์ƒํ’ˆ์„ ์ง€๊ธ‰ํ•˜๊ธฐ๋กœ ํ•˜์˜€๋‹ค. # ๋‹จ, N์€ ์•ฝ์ˆ˜์˜ ๊ฐœ์ˆ˜๊ฐ€ ํ™€์ˆ˜์—ฌ์•ผ ํ•œ๋‹ค. ์ธํ•˜ ๊ด‘์žฅ์„ ์ฆ๊ฒจ๋ณด๋Š” ์ฐฌ๋ฏธ๋Š” ์ด ์ด๋ฒคํŠธ์— ์ฐธ๊ฐ€ํ•˜๊ธฐ๋กœ ํ•˜์˜€๋‹ค. # ์ฐฌ๋ฏธ๋Š” ๋Œ“๊ธ€์„ ์ž‘์„ฑํ•œ ํ›„ ์ž์‹ ์ด ์ƒํ’ˆ์„ ๋ฐ›์„ ํ™•๋ฅ ์ด ์–ผ๋งˆ๋‚˜ ๋˜๋Š”์ง€ ๊ถ๊ธˆํ•ด์กŒ๋‹ค. ์ฐฌ๋ฏธ๊ฐ€ ๋Œ“๊ธ€์„ ์ž‘์„ฑํ•˜๊ธฐ ์ „์˜ # ์ด ๋Œ“๊ธ€ ์ˆ˜๊ฐ€ a๊ฐœ์ด๊ณ , ๋Œ“๊ธ€์„ ์ž‘์„ฑ ํ›„์˜ ์ด ๋Œ“๊ธ€ ์ˆ˜๊ฐ€ b๊ฐœ์ผ ๋•Œ ์ฐฌ๋ฏธ์˜ ๋Œ“๊ธ€์€ a๋ณด๋‹ค ํฌ๊ณ  b๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ # ๋ฒ”์œ„ ์•ˆ์— ์กด์žฌํ•œ๋‹ค๊ณ  ํ•œ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด a๊ฐ€ 1์ด๊ณ , b๊ฐ€ 4์ธ ๊ฒฝ์šฐ [2, 3, 4] ์ค‘ ํ•œ ๊ณณ์— ๋Œ“๊ธ€์ด ์กด์žฌํ•œ๋‹ค. # ์ด ์ค‘ ์•ฝ์ˆ˜์˜ ๊ฐœ์ˆ˜๊ฐ€ ํ™€์ˆ˜์ธ ์ˆซ์ž๋Š” 4, ํ•œ ๊ฐœ์ด๋ฏ€๋กœ ์ƒํ’ˆ์„ ๋ฐ›์„ ํ™•๋ฅ ์€ 1/3์ด๋‹ค. ์ฐฌ๋ฏธ๋ฅผ ๋„์™€ ์ฐฌ๋ฏธ๊ฐ€ # ์ƒํ’ˆ์„ ๋ฐ›์„ ํ™•๋ฅ ์„ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜๋ผ. # ์ž…๋ ฅ # ์ž…๋ ฅ์˜ ์ฒซ ์ค„์—๋Š” ์ •์ˆ˜ a์™€ b๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. (1 โ‰ค a, b โ‰ค 2^60) b๋Š” a๋ณด๋‹ค ํ•ญ์ƒ ํฌ๋‹ค # ์ถœ๋ ฅ # ์ฐฌ๋ฏธ๊ฐ€ ์ƒํ’ˆ์„ ์ง€๊ธ‰๋ฐ›์„ ํ™•๋ฅ ์„ ๊ธฐ์•ฝ๋ถ„์ˆ˜ ํ˜•ํƒœ๋กœ ์ถœ๋ ฅํ•œ๋‹ค. ๋งŒ์•ฝ ํ™•๋ฅ ์ด 0์ธ ๊ฒฝ์šฐ 0์„ ์ถœ๋ ฅํ•œ๋‹ค. # ์˜ˆ์ œ ์ž…๋ ฅ # 1 4 # ์˜ˆ์ œ ์ถœ๋ ฅ # 1/3 # a,b=list(map(int,input().split())) # total=b-a # i=int(a**(1/2))+1 # cnt=0 # while i**2 <= b: # ๋‹น์ฒจ ๊ฐœ์ˆ˜๊ตฌํ•˜๊ธฐ, a+1๋ถ€ํ„ฐ b๊นŒ์ง€ ํŠน์ •์ˆ˜์˜ ์ œ๊ณฑ์ด ๋˜๋Š” ์ˆ˜๋ฅผ ๊ตฌํ•˜๊ธฐ # cnt+=1 #์•ฝ์ˆ˜์˜ ๊ฐœ์ˆ˜๊ฐ€ ํ™€์ˆ˜์ผ๋ ค๋ฉด ํŠน์ • ์ˆ˜์˜ ์ œ๊ณฑ์ธ ๊ฒฝ์šฐ ๋ฟ # i+=1 # #๊ธฐ์•ฝ๋ถ„์ˆ˜ ๋งŒ๋“ค๊ธฐ # import copy # def getG(small,big):#์œ ํด๋ฆฌ๋“œ ํ˜ธ์ œ๋ฒ• ๋‚˜๋ˆ—์…ˆ์„ ํ™œ์šฉํ•ด์„œ ์ตœ๋Œ€๊ณต์•ฝ์ˆ˜ ์ฐพ์Œ # if small>big:small,big=big,small # while big%small!=0: # res = big % small # big=copy.copy(small) # small=res # return small # G=getG(cnt,total) # print(str(int(cnt/G))+"/"+str(int(total/G))) # 3. # John๊ณผ Mary๋Š” "J&M ์ถœํŒ์‚ฌ"๋ฅผ ์„ค๋ฆฝํ•˜๊ณ  ๋‚ก์€ ํ”„๋ฆฐํ„ฐ 2๋Œ€๋ฅผ ๊ตฌ์ž…ํ•˜์˜€๋‹ค. # # ๊ทธ๋“ค์ด ์ฒซ๋ฒˆ์งธ๋กœ ์„ฑ์‚ฌ์‹œํ‚จ ๊ฑฐ๋ž˜๋Š” N๊ฐœ์˜ ํŽ˜์ด์ง€๋กœ ๊ตฌ์„ฑ๋œ ๋ฌธ์„œ๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ์ผ์ด์—ˆ๋‹ค. # # ๊ทธ๋“ค์ด ๊ตฌ์ž…ํ•œ ๋‘ ๋Œ€์˜ ํ”„๋ฆฐํ„ฐ๋Š” ๊ฐ๊ธฐ ๋‹ค๋ฅธ ์†๋„๋ก ๋ฌธ์„œ๋ฅผ ์ถœ๋ ฅํ•˜๊ณ  ์žˆ๋‹ค๊ณ  ํ•œ๋‹ค. # ํ•˜๋‚˜๋Š” ํ•œ ํŽ˜์ด์ง€๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๋ฐ X์ดˆ๊ฐ€ ๊ฑธ๋ฆฌ๊ณ  ๋‹ค๋ฅธ ํ•˜๋‚˜๋Š” Y์ดˆ๊ฐ€ ์†Œ์š”๋œ๋‹ค๊ณ  ํ•œ๋‹ค. # # John๊ณผ Mary๋Š” ๋‘ ๋Œ€์˜ ํ”„๋ฆฐํ„ฐ๋ฅผ ์ด์šฉํ•˜์—ฌ ์ „์ฒด ๋ฌธ์„œ๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๋ฐ ๋“œ๋Š” ์ตœ์†Œํ•œ์˜ ์‹œ๊ฐ„์ด ์•Œ๊ณ  ์‹ถ์–ด์กŒ๋‹ค. # # ์ž…๋ ฅ๊ณผ ์ถœ๋ ฅ # # ์ž…๋ ฅ๋ฐ์ดํ„ฐ์˜ ์ฒซ๋ฒˆ ์งธ ๋ผ์ธ์€ ํ…Œ์ŠคํŠธ์ผ€์ด์Šค์˜ ๊ฐฏ์ˆ˜๋ฅผ ๋œปํ•˜๊ณ  ๊ทธ ๊ฐฏ์ˆ˜๋งŒํผ์˜ ๋ผ์ธ์ด ์ถ”๊ฐ€๋กœ ์ž…๋ ฅ๋œ๋‹ค. # ์ถ”๊ฐ€๋˜๋Š” ๊ฐ ๋ผ์ธ์€ ์„ธ ๊ฐœ์˜ ์ •์ˆ˜๊ฐ’ X Y N ์œผ๋กœ ๊ตฌ์„ฑ๋œ๋‹ค. X๋Š” ์ฒซ๋ฒˆ์งธ ํ”„๋ฆฐํ„ฐ๊ฐ€ ํ•œ ํŽ˜์ด์ง€๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๋ฐ # ๋“œ๋Š” ์†Œ์š”์‹œ๊ฐ„, Y๋Š” ๋‘๋ฒˆ์งธ ํ”„๋ฆฐํ„ฐ๊ฐ€ ํ•œ ํŽ˜์ด์ง€๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๋ฐ ๋“œ๋Š” ์†Œ์š”์‹œ๊ฐ„์„ ๋œปํ•˜๊ณ  N์€ ์ถœ๋ ฅํ•  ๋ฌธ์„œ์˜ # ์ด ํŽ˜์ด์ง€ ์ˆ˜๋ฅผ ์˜๋ฏธํ•œ๋‹ค. (๋‹จ, ์ถœ๋ ฅํ•  ๋ฌธ์„œ์˜ ์ด ํŽ˜์ด์ง€ ์ˆ˜๋Š” 1,000,000,000๊ฐœ๋ฅผ ์ดˆ๊ณผํ•˜์ง€ ์•Š๋Š”๋‹ค.) # # ์ถœ๋ ฅ์€ ํ”„๋ฆฐํŒ…์— ๋“œ๋Š” ์ตœ์†Œํ•œ์˜ ์‹œ๊ฐ„์„ ํ…Œ์ŠคํŠธ์ผ€์ด์Šค์˜ ๊ฐฏ์ˆ˜๋งŒํผ ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„ํ•˜์—ฌ ์ถœ๋ ฅํ•˜๋„๋ก ํ•œ๋‹ค. # # ์ž…์ถœ๋ ฅ์˜ ์˜ˆ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค: # # input data: # 2 # 1 1 5 # 3 5 4 # # answer: # 3 9 # ๋‹จ์œ„์‹œ๊ฐ„๋‹น ์ž‘์—…๋Ÿ‰ # 1/3 ,1/5=> ๋”ํ•˜๋ฉด ์ตœ์†Œ๊ณต๋ฐฐ์ˆ˜ํ™œ์šฉ 8/15 # print(4*15/8) # print(7.5/3) =>3๊ฐœ # print((7.5/5))=>1๊ฐœ # # test_n=int(input()) # tests=[list(map(int,input().split())) for num in range(test_n)] # for test in tests: # i,j,N=test[0],test[1],test[2] # print(i,j,N) # cnt,time=0,0 # while cnt <N: # time+=1 # if time%i==0: # cnt+=1 # if time%j==0: # cnt+=1 # print(time,end=' ') test_n=int(input()) tests=[list(map(int,input().split())) for num in range(test_n)] for test in tests: i,j,N=test[0],test[1],test[2] k=N*i*j//(i+j) print(i,j,N,k) while (k//i+k//j)<N: k+=1 print(k,end=' ')
a12af68cf63e8e5ede06cf0ec9c71c157ea931ea
tutorialcreation/mlbib
/len_strings.py
723
4.03125
4
# Author: Martin Luther Bironga # Date: 27/1/2021 # problem statement """ Make a program that filters a list of strings and returns a list with only your friends name in it. If a name has exactly 4 letters in it, you can be sure that it has to be a friend of yours! Otherwise, you can be sure he's not... Ex: Input = ["Ryan", "Kieran", "Jason", "Yous"], Output = ["Ryan", "Yous"] i.e. friend ["Ryan", "Kieran", "Mark"] `shouldBe` ["Ryan", "Mark"] """ def friend(x): #Code friends=[] for i in range(len(x)): if len(x[i])==4: friends.append(x[i]) return friends # variations def friend(x): return [i for i in x if len(i) == 4] def friend(x): return filter(lambda name: len(name) == 4, x)
a854da4cc9f404a550c08303dab0e679bd93621f
evanqianyue/Python
/day12/property/property.py
868
4.125
4
# !/usr/bin/env python # -*- coding:utf-8 -*- """ @ Author ๏ผšEvan @ Date ๏ผš2018/10/31 18:37 @ Version : 1.0 @ Description๏ผš @ Modified By๏ผš """ class Person(object): def __init__(self, age): # ๅฑžๆ€ง็›ดๆŽฅๅฏนๅค–ๆšด้œฒ # self.age = age # ้™ๅˆถ่ฎฟ้—ฎ self.__age = age ''' def getAge(self): return self.__age def setAge(self, age): if age < 0: age = 0 self.__age = age ''' # ๆ–นๆณ•ๅไธบๅ—้™ๅˆถ็š„ๅ˜้‡ๅŽปๆމๅŒไธ‹ๅˆ’็บฟ @property def age(self): return self.__age @age.setter # ๅŽปๆމไธ‹ๅˆ’็บฟ.setter def age(self, age): if age < 0: age = 0 self.__age = age # ไธๅฎ‰ๅ…จ๏ผŒๆฒกๆœ‰ๆ•ฐๆฎ่ฟ‡ๆปค per = Person(18) per.age = 30 print(per.age) # ไฝฟ็”จ้™ๅˆถ่ฎฟ้—ฎ๏ผŒ้œ€่ฆ่‡ชๅทฑsetๅ’Œgetๆ–นๆณ•
a439375fb90a5dc295855cc9ee05de0689cb8be1
ramyasutraye/python--programming
/beginner level 1/set6-52.py
292
3.890625
4
s=raw_input() if (s=="1"): print "One" elif (s=="2"): print "Two" elif (s=="3"): print "Three" elif (s=="4"): print "Four" elif (s=="5"): print "Five" elif (s=="6"): print "Six" elif (s=="7"): print "Seven" elif (s=="8"): print "Eight" elif (s=="9"): print "Nine" else: print "Ten"
7161564f3595d4b9f885dbf3c47e2bbb16e7b368
snehashish090/Book_archive_CLI
/app.py
4,734
4.1875
4
# Made by Snehashish Laskar # Made on 15-03-2021 # Developer Contact: snehashish.laskar@gmail.com # This is a simple book archive manager that stores info about books import json # Opening the data.json file to extract data with open("data.json", "r") as file: data = json.load(file) read = [] reading = [] # Defining all the Valid Commands def listofcommands(): print("Type a to add a book") print("Type l to search and get info about a book ") print("Type r to see all the books that you have read") print("Type re to see the books that you are reading") print("Type c to change the status of a book") print("Type rm to remove a book") print("Type q to quit") # Creating a function to add a book to the archive def AddBook(): # Getting info about the book from the user book_name = input("Enter the name of the book: ") book_author = input("Enter the Author of the book: ") book_status = input("Enter the status of the book (type read if already completed, type reading if you are in the middle of the book or type new if you have not started yet): ") # Opening the JSON file and storing the info about the book with open("data.json", "w") as file: data.append({"name": book_name, "author": book_author, "status": book_status}) json.dump(data, file) print(f"added the book {book_name} whose author is {book_author} in the archive") # Creating a function to look up a certain book and tell the user the info def LookUpBook(): # Getting the name of the book book_name = input("Enter the name of the book you are looking for: ") for i in data: # Checking if the entered book is in the archive if i["name"] == book_name: name = i["name"] author = i["author"] status = i["status"] print(f"name of the book is {name}") print(f"author of the book is {author}") # Checking the status of the book if status == "read": print("you have read this book") elif status == "reading": print("you are reading this book") elif status == "new": print("you have to start this book") else: print("This book is not there in the archive") # Defining a function that will list all the books that have been read def list_Read_Books(): for i in data: if i["status"] == "read": read.append(i) print(read) # Defining a function that will list all the books that the user is reading def list_reading_books(): for i in data: if i["status"] == "reading": reading.append(i) print(reading) # Defining a function that will change the status of the book def change_status(): # Getting the book's name and the changed status book_name = input("Please enter the book's name that you wanna change the status of:") new_status = input("Please enter the new status of the book: ()") for i in data: name = i["name"] author = i["author"] if book_name == i["name"]: with open("data.json", "w") as file: i["status"] = new_status json.dump(data, file) # Defining a function that will remove a certain book from the archive def remove_book(): book_name = input("please enter the name of the book you wanna remove:") for i,j in enumerate(data): if j["name"] == book_name: del data[i] with open("data.json", "w") as file: json.dump(data, file) print("Done!") else: print("That book is not in the archive") # Defining a dictionary of commands commands = {"q": exit, "a": AddBook, "l" : LookUpBook, "r" : list_Read_Books, "re" : list_reading_books, "s":listofcommands, "rm" : remove_book, "c": change_status} # Defining a function that will notify the user about the books def notify(): for i in data: if i["status"] == "new": name = i["name"] print(f"Hey! You are yet to start reading {name}! If you already have then change the status to reading!\n") elif i["status"] == "reading": name = i["name"] print(f"Hey! You should finish reading the book {name}! If you already have then change the status to read!\n") # Main Proccess def main(): print("type s to see all the valid commands") while True: command = input("> ") for i, j in commands.items(): if i == command: j() notify() main()
b1df2c7e972242de2af45266600d9c7a4d928689
frances-zhao/ICS207
/homework/lesson 18/lesson18_6.py
1,792
4.28125
4
# ***************************************************** # # Program Author: Frances Zhao # Completion Date: May 20 2021 # Program Name: lesson18_6.py # Description: Write a function that models linear equations. The function should take three numbers as input m, x and b # Then it should use the relationship y = mx + b to find the value y and return this result. # The main program will ask the user for the slope (m), and y-intercept (b) of their line once. # Then, repetitively, it will ask for a x-value and output the corresponding y-value # until an appropriate sentinel value is reached. # # ***************************************************** # variable declaration m = 0 x = 0 b = 0 # function for finding the y-value def linear_equation(m, x, b): m = int(m) x = int(x) b = int(b) y = m * x + b return y # input: prompting the user for the slope and y-intercept m = input("Please input a slope: ") while not(m.isdigit()): # making program robust: making sure slope is a digit m = input("Please input a slope: ") b = input("Please input your y-intercept: ") while not(b.isdigit()): # making program robust: making sure y-intercept is a digit b = input("Please input your y-intercept: ") # process: while x != "exit": # exit = sentinel value x = input("Please input your x-value (enter 'exit' to stop): ") # prompting user for x-value if x != "exit": while not (x.isdigit()): # making program robust: making sure x-value is a digit x = input("Please input a numerical value: ") print(linear_equation(m, x, b)) # output: printing the result using the linear_equation function else: print("Thank you for using this program!") # once sentinel value is entered, break loop and wrap program break
7fe4c3c481a89fb9fdef226823ce1d293eb84f5c
fieldsfarmer/coding_problems
/decorator1.py
1,599
4.0625
4
import functools ### a decorator to count how many times a function is called def counter(func): @functools.wraps(func) def wrapper(*args,**kwargs): wrapper.count += 1 print('%s is called %d times' %(func.__name__, wrapper.count)) return func(*args, **kwargs) wrapper.count = 0 return wrapper # @counter def foo(): print('123') # or use the following to decorate foo = counter(foo) foo() foo() foo() print ('The function %s is called %d times totally' %(foo.__name__, foo.count)) ############################################################################################################ def log(func): @functools.wraps(func) def wrapper(*args, **kw): print('start calling %s' %func.__name__) func(*args, **kw) print('end calling %s' %func.__name__) return wrapper foo = log(foo) foo() # print(foo.__name__) def log1(text1, text2): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): print('%s' %text1) func(*args, **kwargs) print('%s' %text2) wrapper.call += 1 wrapper.call = 0 return wrapper # decorator.call = wrapper.call return decorator @log1('start...', 'end...') def say(name): print('Hello '+name+'!') say('Kevin') say = log1('HAHA', 'XIXI')(say) say('Eva') say('Lily') print('It is called %d times.' %say.call) # import time # def timeit(func): # @functools.wraps(func) # def wrapper(): # start = time.clock() # func() # end =time.clock() # print 'used:', end - start # return wrapper # @timeit # def bar(): # print 'in bar()' # bar() # print bar.__name__
7299979b219396e5e1318a8210a71728c2a6233c
sallyklpoon/data-structures-and-algorithms
/linked_lists/sll_node.py
1,629
4.09375
4
""" Implementation of a single linked list node. """ class SllNode: def __init__(self, data): """ Instantiate a Node class. Done in constant time. :param data: any data type :postcondition: instantiate a Node object """ self.data = data self.next = None def __repr__(self): """ Return printable representation of the node. :return: String """ return f"SLLNode object: data={self.data}" def get_data(self): """ Return the data of the node. Done in constant time :return: the data of the node """ return self.data def set_data(self, new_data): """ Update the node's data. Done in constant time :param new_data: a new data type to override current data :return: None, the node's data is updated """ self.data = new_data def get_next(self): """ Return the next node attribute. :return: the next node object """ return self.next def set_next(self, new_next): """ Replace the existing value of the self.next attribute with new_next :param new_next: a Node object :return: None, the current node with self.next updated """ self.next = new_next def is_last(self): """ Return True if node is at the end of the SLL, False if it is not the last element in the SLL. :return: Boolean. True if node is at end of SLL, else, False """ return self.next is None