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
26c57e4c586f37e462950c0bab4d57ba62412fc4
amirdharaja/sarah
/fact.py
196
3.6875
4
# by Amirdharajan try: def fact(n): fact=1 for i in range(1,n+1): fact=fact*i print(fact) n=int(input()) fact(n) except: print("invalid input")
0c5daa1d895769ac46181645ac90cf11374bc586
IamWilliamWang/Leetcode-practice
/2020.9/搜狗-2.py
1,248
3.5
4
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # 返回能创建的房屋数 # @param width int整型 要建的房屋面宽 # @param data int整型一维数组 已有房屋的值,其中 x0 a0 x1 a1 x2 a2 ... xi ai 就是所有房屋的坐标和房屋面宽。 其中坐标是有序的(由小到大) # @return int整型 # class Solution: def getHouses(self, width, data): centerPotential = [] for i in range(0, len(data), 2): # 左边 if i == 0: centerPotential.append(data[i] - data[i + 1] / 2 - width / 2) else: if (data[i] - data[i + 1] / 2) - (data[i - 2] + data[i - 1] / 2) >= width: centerPotential.append((data[i] - data[i + 1] / 2) - width / 2) # 右边 if i == len(data) - 2: centerPotential.append(data[i] + data[i + 1] / 2 + width / 2) else: if (data[i + 2] - data[i + 3] / 2) - (data[i] + data[i + 1] / 2) >= width: centerPotential.append((data[i] + data[i + 1] / 2) + width / 2) return len(set(centerPotential)) print(Solution().getHouses(2, [-1, 4, 5, 2]))
b7d0035e98565f306b2d70b9af400a33b0a606db
daanyaanand/ConnectFour-Game---Winter-2017
/overlapping_functions.py
3,363
3.625
4
import connectfour import collections GameStateAndMove = collections.namedtuple('GameStateAndMove', ['GameState','move']) def print_welcome_message() -> None: ''' Prints welcome message ''' welcome_message = 'Welcome to Connect Four!\nPlay by choosing column number to drop or pop (remove) your piece in or from.\nFirst player to 4-in-a-row wins.\n"DROP col#" to drop a piece.\n"POP col#" to pop a piece.' print(welcome_message) print() def display_board(gstate: connectfour.GameState) -> None: ''' Prints out given GameState board ''' matrix = "" for row in range(connectfour.BOARD_ROWS): string = "" for col in range(connectfour.BOARD_COLUMNS): if gstate.board[col][row] == connectfour.NONE: string = string + " . " if gstate.board[col][row] == connectfour.RED: string = string + " R " if gstate.board[col][row] == connectfour.YELLOW: string = string + " Y " matrix = matrix + string + "\n" display_column_numbers() print(matrix) def display_column_numbers() -> None: ''' Prints only top line of column numbers ''' # subfunction of display_board() string = "" for col in range(connectfour.BOARD_COLUMNS): string = string + (" " + str(col + 1) + " ") print(string) def print_winner(gstate: connectfour.GameState) -> None: ''' Prints winner ''' if connectfour.winner(gstate) == connectfour.RED: print("RED player, is victorious!") elif connectfour.winner(gstate) == connectfour.YELLOW: print("YELLOW player is victorious!") def input_move(turn: int) -> str: '''Requests player move according to int parameter and returns string.''' if turn == connectfour.RED: move = input("RED, your turn:") elif turn == connectfour.YELLOW: move = input("YELLOW, your turn:") else: move = "" return move.strip() def execute_move(gstate: connectfour.GameState) -> GameStateAndMove: ''' Repeatedly calls input_move until valid move, then returns updated GameState and move string.''' while True: attempted_move = input_move(gstate.turn) try: commands = attempted_move.split() column = int(commands[1]) updated_gstate = gstate if commands[0] == 'DROP': updated_gstate = connectfour.drop(gstate, column - 1) d_gstate = connectfour.drop(gstate, column - 1) elif commands[0] == "POP": updated_gstate = connectfour.pop(gstate, column - 1) elif commands[0] not in ["DROP", "POP"]: raise SyntaxError return GameStateAndMove(updated_gstate, attempted_move) except SyntaxError: print('Please provide "DROP" or "POP" followed by a space and a valid column number.') except ValueError: print("Please provide a valid column nubmer.") except IndexError: print('Please provide "DROP" or "POP" followed by a space and a valid column number.') except InvalidMoveError: print("That is an invalid move. Try again.") except GameOverError: #don't need this print("Game is over." + print_winner(gstate)) break
249aca9540d7298b182131de0d812956d9448955
johnnzz/foundations_python
/module4/scratch/assignment4-list-of-tupples.py
2,404
4.1875
4
''' Module 4 Assignment Foundations of Programming: Python 13 July 2016 Instructor: Randal Root Student: John Navitsky Description: Program that asks the user for the name of a household item, and then asks for its estimated value. Ask the user for new entries and store them in the 2 dimensional Tuple. Ask the user, when the program exits, if they would like to save/add the data to a text file called, HomeInventory.txt. ''' # let the user know what we are doing print() print("HOME INVENTORY 2000") print("Enter items into the inventory") inventory=[] # ask for entries until user quits while(True): print() item_name = input("Enter the name of the item or 'exit' to exit: ") # look for an exit request if item_name.lower() == "exit": break # make sure they entered something before proceeding if item_name: # try until they enter a numeric value while(True): # protect against non numeric input try: item_value = float(input("Enter the estimated value of " + item_name + ": ")) # got a numeric value so break out of loop break # caught non numeric input, print msg, try again except: print(" item value must be numeric") # valid entry, write data to file in pipe delimited # format for easier parsing record = (item_name, item_value) inventory.append(record) # don't try to write data if we didn't enter anything if inventory: print() print("would you like to save these records?") save_data = input("y/n: ") # save the data if save_data.lower() == "y": # open inventory file in append mode in the current directory inventory_file = open("test_inventory.txt", "a") print() # write out the records for record in inventory: # unpack the values for processing (item_name, item_value) = record # give user a warm fuzzy print("...writing: " + item_name + ", " + str(item_value)) # write the entry to the file inventory_file.write(item_name + "|" + str(item_value) + "\n") inventory_file.close() print() print("data saved!") else: print("ok, next time!")
cbe9c4e60e4fffc2c84de038504a4d111f158c95
sagivmis/Casino
/war.py
2,362
3.546875
4
def replay(): again = input("Another game? y or n") while again != "y" and again != "n": again = input("Another game?") if again == "y": return True else: return False def count_cards(cards_list): count = 0 for _ in cards_list: count += 1 return count def to_war(player, opp, playing_deck): #returns 1 for win , 0 for lose at_war = True index = 0 while at_war: for i in range(3): index += 1 player.hand.draw_card_from_deck(playing_deck) opp.hand.draw_card_from_deck(playing_deck) if (player.hand.cards[player.hand.total_cards]) > (opp.hand.cards[opp.hand.total_cards]): at_war = False for i in range(index): player.cards.append(opp.hand.cards[i]) opp.hand.reset_hand_card_array() player.hand.reset_hand_card_array() return 1 if (player.hand.cards[player.hand.total_cards]) > (opp.hand.cards[opp.hand.total_cards]): at_war = False for i in range(index): opp.cards.append(player.hand.cards[i]) opp.hand.reset_hand_card_array() player.hand.reset_hand_card_array() return 0 def run_war(): # CLASSES: # import cfg import casino ## # UTILITIES: # from cfg import show_card ## deck = casino.Deck() print("WELCOME TO WAR \nstart game? \n\t1=Yes \n\t2=No") start_game = int(input()) while start_game == 1: bet = cfg.new_player.new_bet() card = cfg.new_player.hand.draw_card_from_deck(deck) print(f"Your card: ", show_card(card)) oppcard = cfg.opponent.hand.draw_card_from_deck(deck) print(f"Opponent's card: ", show_card(oppcard)) if card.number < oppcard.number: cfg.new_player.lose(bet) print("\nAnother game?\n1=Yes\n2=No") start_game = int(input()) elif card.number == oppcard.number: cfg.new_player.tie(bet) print("Another game?\n\t1=Yes\n\t2=No") start_game = int(input()) else: cfg.new_player.win(bet * 2) print("\nAnother game?\n1=Yes\n2=No") start_game = int(input())
5d9e071c456a242d5648d9ae5ad222e947283dcd
lazzarine/LMS-OFC
/OFC-LMS/firetek/firetek/funçoes.py
329
3.640625
4
count = print class printTest(object): def test (self): a = 5 count(a) pt = printTest() pt.test() #def contar(A): # return [len(x) for x in A] lst = ['teste de python'] #print (contar(lst)) print ('Com lambda') contar = lambda lst: [len(x) for x in lst] print (contar(lst)) teste = list(map(lambda x: x**2, lst))
fb0523aa501cf6abe46f29976ecb0c9b3774bc80
mtyton/SkyTask
/skyphrase/shyphrase.py
784
3.640625
4
def read_file(): """ Simplyb reads the file :return: """ container = [] file = open("skychallenge_skyphrase_input.txt", "r").read() lines = file.split("\n") for line in lines: phrases = line.split(" ") container.append(phrases) return container def check_phrases(phrases): """ Simply checks phareses :param phrases: :return: """ used_words = [] for word in phrases: if word in used_words: return False else: used_words.append(word) return True if __name__ == "__main__": counter = 0 words_list = read_file() for words in words_list: if check_phrases(words): counter += 1 print(counter)
46710e021657795e54522f6820ae99429b93b0bb
DinoSubbu/SmartEnergyManagementSystem
/backend/gasBoiler/hot_water_demand_api.py
3,911
3.65625
4
from datetime import datetime import config import csv import os ############################################### Formula Explanation ############################################## # Formula to calculate Heat Energy required : # Heat Energy (Joule) = Density_Water (kg/l) * Specific_Heat_water (J/Kg/degree Celsius) * Water_Demand (l) * # Temp_Desired - Temp_Current (deg Celsius) # Formula to convert from Heat energy to Power : # Power (Watt) = Heat Energy (Joule) / Time (s) # Example : # Heat Energy required to achieve hot water demand in a hour = 3600 Joule # Power required = No of Joules per second # Assuming time frame of 1 hour = 3600 s # Power = 3600/3600 = 1 J/s = 1 W # (i.e) 1 Joule of energy has to be supplied per second for a duration of 1 hr to meet the demand ################################################################################################################## ############################# Mathematical Constants ################################### DENSITY_WATER = 1 # 1 kg/l SPECIFIC_HEAT_CAPACITY_WATER = 4200 # 4.2KJ/Kg/degree Celsius --> 4200 J/Kg/deg Celsius ######################################################################################## class HotWaterAPI: """ API to calculate power required for meeting hot water demand. Requires hot water demand profile in the form of csv. Attributes ---------- buildingName : string name of the building where gas boiler is installed and hot water has to be supplied noOfOccupants : int number of occupants in a building desiredTempWater : float desired temperature of hot water. Reads from global config file currentTempWater : float current temperature of tap water. Reads from global config file demandProfile : dictionary hourly demand profile for a building hotWaterDemand : float amount of hot water (in litres) needed at the current hour of the day ThermalPowerDHW : float power (in Watts) needed to meet the hot water demand at the current hour of the day Methods ------- getHotWaterProfile() based on the building name and no of occupants, selects the hot water demand profile for the entire day getCurrentHotWaterDemand() returns the hot water demand (in litres) for the current hour getThermalPowerDHW(buildingName) returns power required (in Watt) for hot water demand """ def __init__(self, noOfOccupants = 4): self.noOfOccupants = noOfOccupants self.desiredTempWater = config.DESIRED_TEMPERATURE_WATER self.currentTempWater = config.CURRENT_TEMPERATURE_WATER self.hotWaterDemand = 0 def getHotWaterProfile(self): currentDirectory = os.path.abspath(os.path.dirname(__file__)) pathCsv = os.path.join(currentDirectory, "dhw_demand_profiles/" + self.buildingName + ".csv") with open(pathCsv) as hotWaterProfilecsv: hotWaterCsvReader = csv.reader(hotWaterProfilecsv) demandProfile = [row for idx, row in enumerate(hotWaterCsvReader) if idx==self.noOfOccupants-1] demandProfile = demandProfile[0] demandProfile = {i:float(demandProfile[i]) for i in range(24)} return demandProfile def getCurrentHotWaterDemand(self): currentHour = datetime.now().hour return(self.demandProfile[currentHour]) def getThermalPowerDHW(self, buildingName): self.buildingName = buildingName self.demandProfile = self.getHotWaterProfile() self.hotWaterDemand = self.getCurrentHotWaterDemand() heatEnergy = DENSITY_WATER * SPECIFIC_HEAT_CAPACITY_WATER * self.hotWaterDemand * \ (self.desiredTempWater - self.currentTempWater) self.ThermalPowerDHW = heatEnergy / 3600 return(self.ThermalPowerDHW)
a374a6044fc3d896da1bf7b3a533a78f09700c1f
AnkusManish/Machine-Learning
/Week4/Pandas/Program_2.py
327
3.9375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 15 19:30:13 2019 @author: ankusmanish """ # Write a Python program to convert a Panda module Series to Python list and it's type import pandas as pd data = pd.Series(data = [1,2,3,4,5,6,7,8,9,10]) print(type(data)) data = list(data) print(type(data))
368358b20c77b6b4005559a5853e57f2e87a8b64
ahernot/UE11-equations-differentielles
/legacy/code_anatole.py
5,438
3.65625
4
from typing import Callable import numpy as np def solve_euler_explicit(f: Callable, x0: float, dt: float, t0: float, tf: float): """ This function applies an explicit Euler scheme to numerically calculate the points of a function x defined by its first derivative function f, using a set time step, on a set time interval. :param f: The derivative function of x, as f(t, x) :param x0: The initialisation point (= x(t0)) :param dt: The calculation time step :param t0: The initial time (left bound of the time interval) :param tf: The final time (right bound of the time interval) :returns: The array of time points and the array of values of the x function """ # Initialise the arrays for time and points time_array = np.arange(t0, tf, dt) points_array = np.empty_like(time_array) # Get the number of time points time_len = time_array.shape[0] # Fill the initial value points_array[0] = x0 for time_index in range(1, time_len): # Get the previous point x_previous = points_array[time_index - 1] # Calculate the time delta between both calculations time_previous = time_array[time_index - 1] time_current = time_array[time_index] time_delta = time_current - time_previous # Calculate the approximation function for the integral (rectangle approximation on the left) gradient_diff = time_delta * f(time_previous, x_previous) # Calculate x_current x_current = x_previous + gradient_diff # Add to the points array points_array[time_index] = x_current return time_array, points_array ### Newton function from the UE11-calcul-differentiel GitHub repository def Newton(F:Callable, x0:float, y0:float, eps:float=eps, N:int=N) -> tuple: """ This function solves the equation F(x,y) = 0 around (x0,y0) using the Newton algorithm. :param F: The function to solve for — it must necessarily have a multi-dimensional image in a np.ndarray type :param x0: The initial x-axis coordinate :param y0: The initial y-axis coordinate :param eps: The acceptable precision of the algorithm :param N: The maximum number of iterations (will raise an error if exceeded) :returns: The solution to the equation F(x,y) = 0, to a precision of eps """ # 0. Troubleshooting types (ugly) x0, y0 = float(x0), float(y0) # 1. Defining the X0 point X0 = np.array([x0, y0]) # 2. Generating the jacobian matrix of F (n-dimensional derivative) jacF = DFunc.jacobian(F) # 3. Running the method in a loop to refine the calculation for iter_counter in range(N): # 3.1. Inverting F's jacobian matrix try: jacF_inv = npy.linalg.inv( jacF( *(X0.tolist()) ) ) except npy.linalg.linalg.LinAlgError: raise ValueError('The function to solve for has got a singular jacobian matrix in the desired point.') # 3.2. Dot product between jacF and F(X0) F_dot = npy.dot( jacF_inv, F( *(X0.tolist()) ) ) # 3.3. Computing the new X point X = X0 - F_dot # 3.4. Exiting the function once the desired precision is reached if npy.linalg.norm( X - X0 ) <= eps: return tuple(X.tolist()) # 3.5. Performing end-of-loop actions X0 = X.copy() # 4. Raising an error when no solution is found and the max number of iterations is exceeded raise ValueError(f'No convergence in {N} steps.') eps = 10**-7 # to change later, maybe def solve_euler_implicit(f: Callable, x0: float, dt: float, t0: float, tf: float, itermax:int=100): """ This function applies an implicit Euler scheme to numerically calculate the points of a function x defined by its first derivative function f, using a set time step, on a set time interval. :param f: The derivative function of x, as f(t, x) :param x0: The initialisation point (= x(t0)) :param dt: The calculation time step :param t0: The initial time (left bound of the time interval) :param tf: The final time (right bound of the time interval) :param itermax: The maximum number of iterations for solving the equation using the Newton algorithm :returns: The array of time points and the array of values of the x function """ # Initialise the arrays for time and points time_array = np.arange(t0, tf, dt) points_array = np.empty_like(time_array) # Get the number of time points time_len = time_array.shape[0] # Fill the initial value points_array[0] = x0 for time_index in range(1, time_len): # Get the previous point x_previous = points_array[time_index - 1] # Calculate the time delta between both calculations time_previous = time_array[time_index - 1] time_current = time_array[time_index] time_delta = time_current - time_previous # Calculate the function to solve for using the Newton algorithm def F(X, _): return x_previous - X + time_delta * f(time_current, X) # Calculate x_current x_current = Newton(F=F, x0=x_previous, y0=0, eps=eps, N=itermax) [0] # intialise around the previous point # Add to the points array points_array[time_index] = x_current return time_array, points_array
f51a87c5d2d47c61268cbd355f84e68b233e5e91
ma-shamshiri/Mosh
/Sentence.py
1,008
3.859375
4
from pprint import pprint sentence = "This is a common interview question" dictionary = {letter: sentence.count(letter) for letter in sentence} # print(dictionary) # sorted_dictionary = sorted(key=lambda item: item[1], dictionary) # sorted_dictionary = dictionary.sort(key=lambda item: item[1]) # my = dict(("a"=1), ("b"=2), ("c"=56), ("d"=14), ("e"=13)) # print(my) # # my2 = sorted(my, key=lambda item: item[1]) # print(sorted(my, key=lambda item: item[1])) a = dict(a=2) # print(a) b = {'a': 2, 'b': 33, 'c': 22, 'd': 12, 'e': 442, 'f': 22, 'g': 32} # print(b) c = dict(a=2, b=3, v=4, c=2, x=2, s=2, w=2, q=2) # print(c) d = [("a", 2), ("b", 3), ("v", 4), ("c", 2), ("x", 2), ("s", 2), ("w", 2), ("s", 2)] # print(d) # print() # print(sorted(d, key=lambda item: item[1])) # print(sorted(b.items(), key=lambda item: item[0])) h = {letter: sentence.count(letter) for letter in sentence} sorted_h = sorted(h.items(), key=lambda item: item[1], reverse=True) print(h) pprint(sorted_h, width=10)
ebd0753e540e27e54cc19a3adc3bc95f5e4303de
DraperHXY/PythonLearning
/com/draper/generate_def/first/field2.py
532
3.75
4
""" 内嵌函数不起作用 因为嵌套作用域中的变量被调用才查找,所以实际上指向了相同的值 """ def count(): fs = [] for i in range(1, 4): def f(): return i * i fs.append(f) return fs f1 = count() for i in f1: print(i()) def count1(): fs = [] for i in range(1, 4): def f(i): def g(): return i * i return g fs.append(f(i)) return fs # f1, f2, f3 = count1() # print(f1(), f2(), f3())
4dc7c796604ecc3472ba65ba13421ddad8aca943
inwk6312winter2019/classroomtask1-Mavullu-Surya-Raghava-Nallamatti
/lab3/l3t10.py
170
3.609375
4
def histogram(string): d=dict() for c in string: k=d.get(c,0) print(k) ''' if c not in d: d[c]=1 else: d[c]+=1 return d''' histogram('hello how are you')
63c48f5a3fe36522cd955d20ee56f9c10ff63d51
berinhard/forkinrio_exercises
/exercicios/parte_1/parte_1_1_test.py
877
3.71875
4
#-*- coding: utf-8 -*- import unittest from parte_1_1 import fahrenheit_to_celsius from parte_1_1 import celsius_to_fahrenheit class TestConversaoEscalas(unittest.TestCase): def test_fahrenheit_to_celsius_one(self): self.assertEqual(fahrenheit_to_celsius(68), 20) def test_fahrenheit_to_celsius_one(self): self.assertEqual(fahrenheit_to_celsius(-14), -25.555555555555557) def test_fahrenheit_to_celsius_one(self): self.assertEqual(fahrenheit_to_celsius(0), -17.77777777777778) def test_celsius_to_fahrenheit_one(self): self.assertEqual(celsius_to_fahrenheit(30), 86) def test_celsius_to_fahrenheit_two(self): self.assertEqual(celsius_to_fahrenheit(-15), 5) def test_celsius_to_fahrenheit_three(self): self.assertEqual(celsius_to_fahrenheit(0), 32) if __name__ == '__main__': unittest.main()
573a4b16b922499c5051225c4f2b072f808d6a32
matheusfelipeog/jogos-terminal
/Jogo do Numero Magico/jogoDoNumeroMagico.py
1,625
3.9375
4
# Importando seletor aleatório em determinado intervalo from random import randrange # Importando modúlo que manipula o sistema from os import system system('cls||clear') # Método sendo usado para limpar a tela do prompt/terminal # passando como parâmetro cls (Limpa no windows) e clear (linux) # Guarda numero aleatório numeroMagico = randrange(1, 101) # Número de tentativas restantes numeroTentativas = 7 print('NÃO É PERMITIDO:\n- DIGITOS NÃO NÚMERICOS;\n- NÚMEROS OU ESPAÇOS.') print('\nHumm... Eu pensei em um número de 1 a 100, você tem que adivinhar\n' + 'ele em menos de 7 rodadas, está preparado?') # Inicia o Jogo while True: # Verifica se a quantidade de rodadas restantes acabou if (numeroTentativas == 0): print('Você perdeu!') break # Verifica se a tentativa inserida é válida while True: tentativa = input('\nDigite o número que você acha que é: ') if not tentativa.isdigit(): print('NÃO É PERMITIDO:\n- DIGITOS NÃO NÚMERICOS;\n- NÚMEROS OU ESPAÇOS.\n') else: tentativa = int(tentativa) break # Jogar Vence if (tentativa == numeroMagico): print('Parabéns, você Venceu!!!') break # Número sugerido é muito baixo e diminui número de tentativas elif (tentativa < numeroMagico): print('Seu número é muito baixo.') numeroTentativas -= 1 # Número sugerido é muito alto e diminui número de tentativas else: print('Seu número é muito alto.') numeroTentativas -= 1
4b130db9066095299381ee5ba3baff79f4105dcc
jiankangliu/baseOfPython
/PycharmProjects/02_Python官方文档/一、Python初步介绍/02_Python核心对象、变量、输入和输出/2.4编程项目.py
1,024
4.09375
4
#1找零钱 strMoney=input("Enter amount of change:") money=int(strMoney) Quarters=money//25 money=money%25 Dimes=money//10 money=money%10 Nickels=money//5 money=money%5 Cents=money print("Quarter: ",Quarters,"\t","Dimes: ",Dimes,"\n","Nickels: ", Nickels,"\t","Cents: ",Cents,sep="") #2汽车贷款 loan=float(input("Enter amount of loan:")) rate=float(input("Enter interest rate (%):")) years=float(input("Enter number of years:")) payment=(rate/1200)/(1-(1+rate/1200)**(-12*years))*loan print("Monthly payment: ${0:.2f}".format(payment)) #3债券收益 faceValue=float(input("Enter face value of bond: ")) interestRate=float(input("Enter coupon interest rate: ")) currentMarketPrice=float(input("Enter current market price: ")) untilMaturity=float(input("Enter years until maturity: ")) a=(faceValue-currentMarketPrice)/untilMaturity b=(faceValue+currentMarketPrice)/2 intr=faceValue*interestRate YTM=(intr+a)/b print("Approximate YTM: {0:.2%}".format(YTM)) #单位价格
7ecdfbeb5539e013a4e9aa29f584932fe3542344
AM0511-kee/workspace
/namespacing.py
562
4.1875
4
"""name spacing means unique name for every object in python""" """there are three types of name spacind they are build in name spacing,local namespacing,global name spacing""" var=10 def name_spacing(): global var var=var+1 print(var) name_spacing() var="string" def name_spacing(): var=11 print("inner scope variable=",var) print("outter scope variable=",var) name_spacing() def outer_scope(): var="kevin" def inner_scope(): var="Aravind" print(var) inner_scope() print("outer_var:",var) outer_scope()
55f52e412cd94524c305db13967811ae0556e672
HanPong/PythonPractise
/LottoNumbers.py
929
3.875
4
#编写一个程序决定输入的数字是否涵盖了1到99之间的数 isCovered=99*[False]#创建了99个初始化为false的布尔类型列表 endOfInput=False while not endOfInput: #Read numbers as a string from the console s=input("Enter a line of numbers separated by spaces: ") items=s.split()#把字符串s按照空格分开 lst=[eval(x)for x in items]#将item中的元素转换成数字并储存在1st数组中 for number in lst: if number==0: endOfInput=True else: isCovered[number-1]=True#如果这个数字为0,则endOfInput为True,如果这个数字不为0,则设置isCovered对应的值为True #check whether all numbers is covered allCovered=True for i in range(99): if not isCovered[i]: allCovered=False break if allCovered: print("The tickets cover all numbers") else: print("The tickets don't cover all numbers")
d9d8579a52a70607e42aa35aa9797232e1fb5dd6
minus9d/programming_contest_archive
/agc/003/b/b.py
272
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- N = int(input()) ans = 0 carry = 0 for n in range(N): a = int(input()) if carry and a > 0: ans += 1 a -= 1 ans += a // 2 if a % 2 == 1: carry = 1 else: carry = 0 print(ans)
f84cb4f84081acf104912f7da38bf02c20a20467
vcaitite/hangman
/read_txt_archive.py
441
3.625
4
from pathlib import Path import random path = Path('./word_list.txt') def archive_lines(): if path.is_file(): with open(path, 'r') as f: lines = (f.readlines()) return lines else: raise Exception("Word list archive doesn't exist 😞") def read_random_word(): lines = archive_lines() n_words = len(lines) word_line = random.randint(0, n_words) return lines[word_line]
b45908acb4df26a763550a31843fe69743ba7e3d
theangi/hackerrank
/security/02_inverse_function.py
155
4
4
def print_inverse_function(): _ = input() values = input().split() for i, _ in enumerate(values): print(values.index(str(i + 1)) + 1)
fcaba3cde5e08bdc5368596f20cef04524249506
AdhwaithMenon601/Resource-Allocation-Bot-
/envs/custom_env/ResourceAlloc.py
2,234
3.875
4
import numpy as np import sys import matplotlib.pyplot as plt from matplotlib import style import gym from gym import utils from gym.envs.toy_text import discrete """ The actions are as follows - 0 : Add to M1 1 : Add to M2 2 : Add to M3 3 : Do nothing """ #Render is not required for the given function class ResourceAlloc(gym.Env): def __init__(self, m1, m2, m3, n): self.m1 = m1 self.m2 = m2 self.m3 = m3 self.n = n self.cur_state = (0,0,0) #self.state_space = [] """ for i in range(n): for j in range(n): for k in range(n): self.state_space.append((i,j,k)) """ def find_min_time(self, x, y, z): return (self.m1 * x) + (self.m2 * y) + (self.m3 * z) def reset(self): #To reset the evnironment #Set the current state to (0,0,0) and rewards to normal self.cur_state = (0,0,0) return self.cur_state def step(self, action): #Take in the given action provided given state done = False (x,y,z) = self.cur_state #print('The x y z are ',x,y,z) #print('The values are ',x,y,z) reward = self.find_min_time(x,y,z) my_sum = x + y + z #print('The action is ',action) #print('The sum is ',my_sum) if (my_sum == (self.n - 1)): reward = 1/reward reward *= 100 done = True else : reward = -1 #Our basic reward function done = False #Changing the values of the states #Will try and implement a smarter version of this if (action == 0): x += 1 elif (action == 1): y += 1 elif (action == 2): z += 1 if (x > (self.n+1)) or (y > (self.n+1)) or (z > (self.n+1)): done = False x = 0 y = 0 z = 0 next_state = (x,y,z) self.cur_state = (x,y,z) #Once again checking for equal sum #Only in case it does not work new_sum = x + y + z if (new_sum != self.n): done = False return next_state, reward, done
ca716ace666d02529d8e0a99fafbb19e47bafcf4
zhanjw/leetcode
/codes_auto/543.diameter-of-binary-tree.py
799
3.734375
4
# # @lc app=leetcode.cn id=543 lang=python # # [543] diameter-of-binary-tree # # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def diameterOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int """ def recursion(node): if not node: return 0,0 max_len_left,deep_left = recursion(node.left) max_len_right,deep_right = recursion(node.right) manx_len = max(max_len_left, max_len_right, deep_left+deep_right) deep = max(deep_left,deep_right) + 1 return manx_len,deep return recursion(root)[0] # @lc code=end
c3bcbe95d793d9ee9d48513ec17a661258e792a7
kschultze/Learning-Python
/Assignment_2/diaphantine3_rev1.py
860
3.734375
4
# -*- coding: utf-8 -*- """ 07/26/16 @Schultze Script to calculate chicken nuggets combinations Using an iterated version of diaphantine2_rev1.py, this code finds the largest value for n for which no combination of A, B, and C exist. """ A = 6 B = 9 C = 20 isPossible = () for n in range(1,200): maxA = n//A maxB = n//B maxC = n//C match = False for numA in range(0,maxA + 1): for numB in range(0,maxB + 1): for numC in range(0,maxC + 1): total = numA*A + numB*B + numC*C if total == n: match = True if match: isPossible += (1,) else: isPossible += (0,) if sum(isPossible[-6:]) == 6: print ('Largest number of McNuggets that cannot be bought in exact quantity: ' + str(n-6)) break
a73ad754dcd74111852714e6533bb3ef9fc60baa
Jens2/Similarity-and-Symmetry
/final/fastgraphs.py
2,525
3.53125
4
from final.basicgraphs import vertex, graph, GraphError, edge class FastVertex(vertex): def __init__(self, graph, label=0): self._graph = graph self._label = label self._inclist = [] self._colornum = 1 def getLabel(self): return self._label def setLabel(self, n): self._label = n def setGraph(self, G): self._graph = G def inclist(self): return self._inclist def addToInclist(self, edge): self._inclist.append(edge) def getDegree(self): return len(self.inclist()) def setColornum(self, num): self._colornum = num def updateColornumByOne(self): self._colornum += 1 def getColornum(self): return self._colornum class FastGraph(graph): def addObjVertex(self, node): self._V.append(node) def addvertex(self, label=-1): """ Add a vertex to the graph. Optional argument: a vertex label (arbitrary) """ if label == -1: label = self._nextlabel self._nextlabel += 1 u = FastVertex(self, label) self._V.append(u) return u def addedge(self, tail, head): """ Add an edge to the graph between <tail> and <head>. Includes some checks in case the graph should stay simple. """ if self._simple: if tail == head: raise GraphError('No loops allowed in simple graphs') for e in self._E: if (e._tail == tail and e._head == head): raise GraphError( 'No multiedges allowed in simple graphs') if not self._directed: if (e._tail == head and e._head == tail): raise GraphError( 'No multiedges allowed in simple graphs') if not (tail._graph == self and head._graph == self): raise GraphError( 'Edges of a graph G must be between vertices of G') e = edge(tail, head) # //// tail.addToInclist(e) head.addToInclist(e) # \\\\ tail.updateColornumByOne() head.updateColornumByOne() # //// self._E.append(e) return e def adj(self, u, v): """ Returns True iff vertices <u> and <v> are adjacent. """ for tupel in v.inclist(): if tupel.head() == u or tupel.tail() == u: return True return False
173746433e541bc580cc10572d649b72b8194cd5
kmcgrady/streamlit-example
/streamlit_app.py
652
3.59375
4
import streamlit as st import pandas as pd with st.echo("below"): st.write( "Once a single column is selected, there is no going back. You can add a second in the multiselct, but it won't change anything. Rerunning does not help. Your only hope is to refresh the page." ) df = pd.DataFrame(data=[[1, 4, 7], [2, 5, 8], [3, 6, 9]], columns=["a", "b", "c"]) st.subheader("original dataframe") st.write(df) columns = st.multiselect(label="Select columns to average", options=df.columns) df["Average"] = df[columns].mean(axis=1) st.subheader("dataframe with average column") st.write(df)
9a41c9a514d61a35306de193da9bb97ada3153cb
FelixWessel/SimpleSnakeGame
/SimpleSnakeGame.py
5,653
4.0625
4
# This is a work in progress - not finished and not working yet import pygame import sys from random import randint pygame.init() #Definition of variables for the game run = True # As long as run equals true the game runs screen_width = 600 # Setting the width of the game window screen_height = 600 # Setting the height of the game window square_x_pos = 60 # The initial x-position of the snake head at start of the game square_y_pos = 60 # The initial y-position of the snake head at start of the game square_dimension_w_h = 20 # Setting the hight and width of snake's building blocks rows = ((screen_height - square_dimension_w_h) / square_dimension_w_h) # Rows on the screen columns = ((screen_width - square_dimension_w_h) / square_dimension_w_h) # Colums on the screen snake_head = [square_x_pos, square_y_pos] # The initial position of our snake's head at start of the game snake_body = [[square_x_pos, square_y_pos], [(square_x_pos + square_dimension_w_h), square_y_pos], [(square_x_pos + (2 * square_dimension_w_h)), square_y_pos]] # The initial position of our snake's body at start of the game food_x_pos = (randint(0, columns) * square_dimension_w_h) # Setting the x position of food food_y_pos = (randint(0, rows) * square_dimension_w_h) # Setting the y position of food food = [food_x_pos, food_y_pos] direction = "LEFT" # The initial direction the snake is going to at the start of the game clock = pygame.time.Clock() # Definition of a timer to control the game's speed fps = 5 # Speed of the game (used by clock) step = square_dimension_w_h # Defines how far the snake moves with each step turns = 0 # Counting the number of turns our snake made score = 0 # Counting the number of food the snake has eaten RED = pygame.Color(255, 0, 0) # Variable that stores the red color for snake body GREEN = pygame.Color(0, 255, 0) # Variable that stores the green color for food ORANGE = pygame.Color(255, 69, 0) # Orange color for snake head # Defining our game window game_window = pygame.display.set_mode((screen_width, screen_height)) # This is the main loop of our SimpleSnakeGame while run: # Here we check for inputs and exit the game if we close the game window for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # Check which key has been pressed and setting the direction variable # We also check the current direction and make sure that snake is not running into itself pressed_key = pygame.key.get_pressed() if pressed_key[pygame.K_UP] and direction != "DOWN": direction = "UP" turns += 1 if pressed_key[pygame.K_DOWN] and direction != "UP": direction = "DOWN" turns += 1 if pressed_key[pygame.K_LEFT] and direction != "RIGHT": direction = "LEFT" turns += 1 if pressed_key[pygame.K_RIGHT] and direction != "LEFT": direction = "RIGHT" turns += 1 # Change the movement of the snake depending on the "direction" variable if direction == "LEFT" and snake_head[0] == 0: snake_head[0] = screen_width snake_head[0] -= step elif direction == "LEFT": snake_head[0] -= step if direction == "RIGHT" and snake_head[0] == (screen_width - square_dimension_w_h): snake_head[0] = (0 - square_dimension_w_h) snake_head[0] += step elif direction == "RIGHT": snake_head[0] += step if direction == "UP" and snake_head[1] == 0: snake_head[1] = screen_height snake_head[1] -= step elif direction == "UP": snake_head[1] -= step if direction == "DOWN" and snake_head[1] == (screen_height - square_dimension_w_h): snake_head[1] = (0 - square_dimension_w_h) snake_head[1] += step elif direction == "DOWN": snake_head[1] += step # This line draws the food at random positions on the screen pygame.draw.rect(game_window, GREEN, (food[0], food[1], square_dimension_w_h, square_dimension_w_h)) # This part makes the snake move forward; It is checked if the snake ate some food. If this is not the case # the last element of the array is popped of; It the snake ate food the else part increments the fps variable, adds # a point to the score and updates food at a new random x and y position snake_body.insert(0, list(snake_head)) if snake_head != food: snake_body.pop() else: score += 1 food[0] = (randint(0, columns)) * square_dimension_w_h food[1] = (randint(0, rows)) * square_dimension_w_h fps += 0.5 for segment in snake_body[1:]: if segment == snake_head: run = False # Drawing the snake head on the screen based on the updated postion pygame.draw.rect(game_window, ORANGE, (snake_head[0], snake_head[1], square_dimension_w_h, square_dimension_w_h)) # Drawing the whole snake body on the screen except for the snake head for segment in snake_body[1:]: pygame.draw.rect(game_window, RED, (segment[0], segment[1], square_dimension_w_h, square_dimension_w_h)) pygame.display.update() game_window.fill((0, 0, 0)) # Setting the game of the speed clock.tick(fps) pygame.quit()
f8b786347bd9afac79a0cc913b628390bd564aa1
wcsodw1/Computer-Vision
/CV_Pyimage/Module 1 CV Basic Technical/chp_1_4_Image preproccesing/David_1_4_4_flipping.py
900
3.71875
4
# python David_1_4_4_flipping.py --image "../../../CV-PyImageSearch Gurus Course/Dataset/data/girl.JPG" import argparse import cv2 # 1.Preprocessing # 1.1 construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="Path to the image") args = vars(ap.parse_args()) # 1.2 load the image and show it image = cv2.imread(args["image"]) image = cv2.resize(image, (400,600), interpolation=cv2.INTER_CUBIC) cv2.imshow("Original", image) # 2.flipping # 2.1 flip the image horizontally flipped = cv2.flip(image, 1) cv2.imshow("Flipped Horizontally", flipped) # 2.2 flip the image vertically flipped = cv2.flip(image, 0) cv2.imshow("Flipped Vertically", flipped) # 2.3 flip the image along both axes flipped = cv2.flip(image, -1) cv2.imshow("Flipped Horizontally & Vertically", flipped) cv2.waitKey(0)
170811c5bdbe01274b4a31432d9e3e6ee8794717
SPK44/Weekly-Programming-Challenge
/december2016/ddides.py
239
3.828125
4
#!/usr/bin/env python def missing_num(nums): return list(filter(lambda x: x not in nums, range(1, max(nums)+1))).pop(0) if __name__ == '__main__': assert missing_num([7,8,10,3,6,5,1,2,9]) == 4 assert missing_num([1,3]) == 2
cb5c87f24300a2dcc9e8c14c2470ccb543566c74
athul-santhosh/Leetcode
/202 Happy Number.py
893
3.5
4
def getDigits(self, n: int) -> list: res = [] while n: d, m = divmod(n, 10) res.append(m) n = d return res def isHappy(self, n: int) -> bool: s = set() while 1: s.add(n) get_sum = sum(map(lambda x: x*x, self.getDigits(n))) n = get_sum if n == 1: return True if n in s: return False def isHappy(self, n: int) -> bool: def squaresum(num): result = 0 while num > 0: result += pow((num % 10),2) num = num // 10 return result seen = [] while squaresum(n) not in seen: sum1 = squaresum(n) if sum1 == 1: return True else: seen.append(sum1) n = sum1 return False
2daeec9789ebd793d1b2af379a0628132f92b84f
OutJeck/tic-tac-toe
/game.py
1,584
3.953125
4
"""Realizes main module for the tic tac toe game.""" from board import Board, IncorrectPosition from btree import BTree def main(): """Realizes tic tac toe game.""" board = Board() print(draw_example()) print("Enter a pair of coordinates separated by space from 0 to 2 " "(Example of inputs above)") while board.check(): print(board) move = input(">>> ").strip().split() try: x, y = [int(value) for value in move] board.move(x, y) except ValueError: print('Please enter valid coordinates, not letters or other symbols!') continue except IncorrectPosition as err: print(err) continue if board.check() == 'X': print(board) print("Congrats! You won!!!") break tree = BTree(board) try: y, x = tree.best_move() except TypeError: break board.move(x, y) if board.check() == 'O': print(board) print("Ha-ha, loser! You lost to AI!!!") break if board.check() == 'XO': print(board) print("Sorry, not today. It's just a draw!") def draw_example(): """Draws all possible moves""" string = '' for i in range(3): for j in range(3): string += f"{j} {i}" + ' ┃ ' string = string[:-2] + '\n' string += '━━━━╋━━━━━╋━━━━\n' string = string[:-16] return string if __name__ == '__main__': main()
b9f52c9599ac280a6011464b904bb622891cada3
Nmewada/hello-python
/60_practice.py
181
3.875
4
''' Write a python function to print the first n lines of the following pattern. *** ** * #For n = 3''' n = 3 for i in range(n): print("*" * (n-i)) # Prints * n-i times
c948e89a119a922303357a3a55c9b375f3d6758c
venkatkorapaty/MultiSetSkipList
/multiset.py
10,893
4
4
from skiplist import * class MultiSet(): def __init__(self): ''' Initiates the MultiSet with a SkipList ''' self.sl = SkipList() def __contains__(self, e): '''(MultiSet, Object) -> bool Takes in an element and a MultiSet, checks if the element is contained within the MultiSet ''' if self.sl.search_vert(e) is not None: return True return False def count(self, e): '''(MultiSet, Object) -> int Takes in a MultiSet and an element, and returns the amount of times that element occurs in the MultiSet ''' return self.sl.occurrences(e) def insert(self, e): '''(MultiSet, Object) -> NoneType Takes in a MultiSet and an element, and inserts the element into the MultiSet ''' self.sl.insert(e) def remove(self, e): '''(MultiSet, Object) -> NoneType Takes in a MultiSet and an element, and removes the element if it is within the MultiSet, otherwise it does nothing ''' self.sl.remove(e) def clear(self): '''(MultiSet) -> NoneType Takes in a MultiSet and empties it of all elements ''' self.sl = SkipList() def __len__(self): '''(MultiSet) -> int Takes in a MultiSet and returns the total amount of elements ''' return len(self.sl) def __repr__(self): '''(MultiSet) -> str Takes in a MultiSet and returns a string representation of that MultiSet ''' return 'MultiSet([' + self.sl.level_string() + '])' def __eq__(self, other, self_current=None): '''(MultiSet, MultiSet) -> bool Takes in two MultiSets and checks if they have the same amount of each element, returns True if they do, False otherwise ''' # if the lenght is not the same, then two MultiSets can't be equal if len(self) is not len(other): return False # retrieves the bottom level of self if self_current is None: self_current = self.sl.bottom_level() # if the next node is not a tail if not isinstance(self_current.next_node, TailNode): # checks if the amount of times a value that occurs in self # also occurs in other, then continues recursing through the set data = self_current.next_node.data if self.count(data) == other.count(data): return self.__eq__(other, self_current.next_node) # returns false if the amount of values of each one is different # among the two sets else: return False # the end of the set has been reached, meaning they are equal return True def __le__(self, other, self_current=None): '''(MultiSet, MultiSet) -> bool Takes in two MultiSets, checks if self is a subset of other, meaning if all the elements in self are also in other ''' # retrieves the bottom level of self if self_current is None: self_current = self.sl.bottom_level() # if the next node is a tail, it has either reached the end of a set # or the the set has no values, either way self is a subset of other if isinstance(self_current.next_node, TailNode): return True # checks if the occurrence of a value is less than or equal to than # that of other, if true, then it continues recursion elif self.count(self_current.next_node.data) <= other.count( self_current.next_node.data): return self.__le__(other, self_current.next_node) # other wise false, and self is not a subset of other else: return False def __sub__(self, other): '''(MultiSet, MultiSet) -> MultiSet Takes in two MultiSets, subtracts all values in other from self and returns a new MultiSet ''' # creates a MultiSet to return ms = MultiSet() # gets the bottom levels for the SkipLists of the MultiSets self_current = self.sl.bottom_level() other_current = other.sl.bottom_level() # interates through the level adding all of the values in self # into the MultiSet while not isinstance(self_current.next_node, TailNode): ms.insert(self_current.next_node.data) self_current = self_current.next_node # iterates through the level subtracting any values in self that # are in other while not isinstance(other_current.next_node, TailNode): if other_current.next_node.data in ms: ms.remove(other_current.next_node.data) other_current = other_current.next_node return ms def __isub__(self, other, other_current=None): '''(MultiSet, MultiSet) -> NoneType This takes in two Multisets, removes all the elements that are in other from self and mutates self instead of returning a new MultiSet ''' # starts from the head of the bottom level of MultiSet's skiplist if other_current is None: other_current = other.sl.bottom_level() # if the next node on the bottom level is not a tail node if not isinstance(other_current.next_node, TailNode): # if the next node's element is in self, it removes it from self if other_current.next_node.data in self: self.remove(other_current.next_node.data) # recurses to next node return self.__isub__(other, other_current.next_node) return self def __add__(self, other): '''(MultiSet, MultiSet) -> MultiSet Takes in two MultiSets and adds the elements of both the MultiSets and returns it in a new MultiSet ''' # creates a new MultiSet to return ms = MultiSet() # retrieves the bottom level of the SkipLists of both MultiSets self_current = self.sl.bottom_level() other_current = other.sl.bottom_level() # iterates and adds the value of other into the new MultiSet while not isinstance(other_current.next_node, TailNode): ms.insert(other_current.next_node.data) other_current = other_current.next_node # iterates and adds the value of self into the new MultiSet while not isinstance(self_current.next_node, TailNode): ms.insert(self_current.next_node.data) self_current = self_current.next_node return ms def __iadd__(self, other): '''(MultiSet, MultiSet) -> NoneType Takes in two MultiSets and updates self such that all the elements in other are also in self ''' # finds the bottom level of the SkipList in other MultiSet other_current = other.sl.bottom_level() # iterates until it reaches the end of the set while not isinstance(other_current.next_node, TailNode): # adds every value thats in other, into self self.insert(other_current.next_node.data) # moves onto the next node other_current = other_current.next_node return self def __and__(self, other, self_current=None, ms=None): '''(MultiSet, MultiSet) -> MultiSet Takes in two MultiSets and returns a new MultiSet that contains the intersection of self and other ''' # initialize the MultiSet if ms is None: ms = MultiSet() # get the bottom level of self if self_current is None: self_current = self.sl.bottom_level() # if the next node is not a tail node if not isinstance(self_current.next_node, TailNode): # finds the amount of times the value is in both MultiSets self_amount = self.count(self_current.next_node.data) other_amount = other.count(self_current.next_node.data) # checks if the value exists in both sets more than 0 and if the # the value has not already been inserted into MultiSet if self_amount > 0 and other_amount > 0 and \ self_current.next_node.data not in ms: # finds the amount each Multiset has the values self_amount = self.count(self_current.next_node.data) other_amount = other.count(self_current.next_node.data) # if self has more of the values than other if self_amount >= other_amount: # inserts the value the amount of times it exists by the # amount other has the value while other_amount > 0: other_amount -= 1 ms.insert(self_current.next_node.data) # recurses through the rest of the MultiSets return self.__and__(other, self_current.next_node, ms) # if other has more of the values than self else: # inserts the value the amount of times it exists by the # amount self has the value while self_amount > 0: self_amount -= 1 ms.insert(self_current.next_node.data) # recurses through the rest of the MultiSets return self.__and__(other, self_current.next_node, ms) # if the value isnt in both MultiSets, continue recursing else: return self.__and__(other, self_current.next_node, ms) else: return ms def __iand__(self, other, self_current=None): '''(MultiSet, MultiSet) -> NoneType Takes in two MultiSets and updates self so that it only contains the intersection of self and other ''' self = self & other return self def isdisjoint(self, other, self_current=None): '''(MultiSet, MultiSet) -> bool Takes in two MultiSets and returns true iff the MultiSets have no elements in common ''' # retrieves the bottom of the SkipList in the self MultiSet if self_current is None: self_current = self.sl.bottom_level() # if the next node is not a tail node if not isinstance(self_current.next_node, TailNode): # if both of them have the same value, returns false if self_current.next_node.data in other: return False # else it continues recursing through the MultiSet else: return self.isdisjoint(other, self_current.next_node) # It has reached the end of the set, meaning none of the values # are shared between the sets, returning True return True
373384c8242147b888a0974c925f8f40eb34966f
weightedEights/projectEuler
/weightedEights/prob20/projectEuler.prob20.py
818
3.984375
4
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function """ n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! """ """ Approach is this: """ import math def main(): loadprob() parseShit() displayResult() def loadprob(): # with open(file, 'r') as fin: # # listVals = [map(int, num.split()) for num in fin] # # return listVals[::-1] pass def parseShit(): pass def displayResult(): numStr = str(math.factorial(100)) numSum = [int(c) for c in numStr if c != "0"] print(sum(numSum)) if __name__ == main(): main()
5b18f8f04839a1f608bc08a93cad91f53bd38873
Abhipanda4/PyTorch-Examples
/regression.py
1,337
3.59375
4
import torch from torch.autograd import Variable import torch.nn.functional as F import matplotlib.pyplot as plt torch.manual_seed(0) # Dummy training data x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1) y = x.pow(2) + 0.1 * torch.randn(x.size()) x, y = Variable(x), Variable(y) # print(x) # print(y) # a 1 hidden layer neural network class Net(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output): super(Net, self).__init__() self.hidden = torch.nn.Linear(n_feature, n_hidden) self.out = torch.nn.Linear(n_hidden, n_output) def forward(self, x): x = F.elu(self.hidden(x)) output = self.out(x) return output net = Net(n_feature=1, n_hidden=10, n_output=1) optimizer = torch.optim.Adam(net.parameters(), lr=0.4) loss_fn = torch.nn.SmoothL1Loss() num_iter = 200 losses = [] for t in range(num_iter): prediction = net(x) loss = loss_fn(prediction, y) optimizer.zero_grad() loss.backward() optimizer.step() if (t + 1) % 10 == 0: losses.append(loss.data[0]) print("Timestep: " + str(t + 1) + ", loss = " + str(loss.data[0]) + "....") # plt.plot(losses) # plt.show() plt.scatter(x.data.numpy(), y.data.numpy()) plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=2) plt.savefig("./Figures/regression_out.png")
05e489475d96fd2432943b150c099329360bd2c0
aadityamp01/mathpy
/Sequence generation/Traingular sequence.py
313
3.890625
4
class Mathematics : def __init__(self,n): self.n=int(n); def triang(self): i=1; while i<(self.n+1.0): t=(i*(i+1))/2; if i!=self.n: print(t,end=", "); i=i+1; else: print(t); return;
d48176c5f2ec54bfbd56968a494750c987cdc7b0
vertocode/python-course-challenges
/Mundo 1/desafio05.py
151
4.03125
4
print('Calculador de antecessor e sucessor') n = int(input('Número: ')) print('O antecessor de {} é {} \nO sucessor de {} é {}'.format(n,n-1,n,n+1))
1c7896d1455482a825a93034df4520a35d05dd82
gopikm/chainercv
/chainercv/evaluations/eval_pck.py
1,497
3.546875
4
import numpy as np def eval_pck(pred, expected, alpha, L): """Calculate PCK (Percentage of Correct Keypoints). This function calculates number of vertices whose positions are correctly pred. A pred keypoint is correctly matched to the ground truth if it lies within Euclidean distance :math:`\\alpha \\cdot L` of the ground truth keypoint, where :math:`L` is the size of the image and :math:`0 < \\alpha < 1` is a variable we control. :math:`L` is determined differently depending on the context. For example, in evaluation of keypoint matching for CUB dataset, :math:`L=\\sqrt{h^2 + w^2}` is used. Args: pred (~numpy.ndarray): An array of shape :math:`(K, 2)` :math:`N` is the number of keypoints to be evaluated. The two elements of the second axis corresponds to :math:`y` and :math:`x` coordinate of the keypoint. expected (~numpy.ndarray): Same kind of array as :obj:`pred`. This contains ground truth location of the keypoints that the user tries to predict. alpha (float): A control variable :math:`\\alpha`. L (float): A size of an image. The definition changes from the tasks to task. Returns: float """ m = pred.shape[0] n = expected.shape[0] assert m == n difference = np.linalg.norm(pred[:, :2] - expected[:, :2], axis=1) pck_accuracy = np.mean(difference <= alpha * L) return pck_accuracy
4a194dd2ecbfb72ac09cd2b146442e896063b93e
avivko/pythonWS1819
/practiceFromWorksheet.py
2,777
3.734375
4
import random def part_one_one(n): for i in range(0, n): print(2 ** i) def part_one_two_version_one(n): biggest = 0 for i in range(0, n): if biggest <= n: biggest = 2 ** i else: biggest = biggest / 2 return round(biggest) def part_one_two_version_two(n): biggest = 1 one_bigger = 1 while one_bigger <= n: biggest = one_bigger one_bigger = one_bigger * 2 return biggest # sum numbers def part_one_three(n): summe = 0 for i in range(0, n): summe = summe + i return summe # make table of multiplication def part_one_four(n): table = [] for i in range(1, n + 1): column = [] for j in range(1, n + 1): column.append(i * j) table.append(column) return table # check for prime number def part_one_five(n): assert ((isinstance(n, int) or (isinstance(n, float) and n.is_integer())) and n > 0), "Invalid input" int(n) for i in range(2, n): if n % i == 0: is_prime = False return is_prime if n == 1: is_prime = False else: is_prime = True return is_prime # check for primes under n def part_one_six(n): for i in range(1, n + 1): if part_one_five(i): print(i) # makes a table with * at desired spots. n is size of table def part_one_seven(n): table = [] for j in range(1, n + 1): columns = [] for i in range(1, n + 1): if j % i == 0: columns.append("*") else: columns.append("") table.append(columns) print(columns) return table # addition function def part_two_one(a, b): return a + b # sqrt def part_two_two(n): return n ** 2 # returns the hypotenuse for a,b right angle triangle def part_two_three(a, b): return ((a ** 2) + (b ** 2)) ** 0.5 # returns sum of 1/n series def part_two_four(n): harm_num = 1 for i in range(2, n + 1): harm_num = harm_num + 1 / i return harm_num # return list of harmonic numbers for a list l def part_two_five(l): list_of_harm = [] for x in l: list_of_harm.append(part_two_four(x)) return list_of_harm # returns avg of array l def part_two_six(l): summe = 0 for x in l: summe += x return summe/len(l) # switch two index values for list l, and two indexes a,b def part_two_seven(l, a, b): la_old = l[a] l[a] = l[b] l[b] = la_old return l # randomize array index values def part_two_eight(l): for x in range(len(l)): lx_old = l[x] randomindex = random.randrange(0, len(l)) l[x] = l[randomindex] l[randomindex] = lx_old return l
f82005125b24817fde62d458cb6817f7aae27d6b
BenTildark/sprockets-d
/DTEC501-Lab8-2/lab8-2_q1.py
1,146
4.53125
5
""" Write a program to ask the user to enter their first and last names and mobile number. Store the user entered data in a dictionary and display as below. Hint. Treat the mobile number as a string. Example Please enter your given name: dave Please enter your surname: bracken Please enter your mobile number: 0225555555 First name: Dave Last name: Bracken Mobile number: 0225555555 """ # Auth: Michael Devenport # Email: croxleyway@gmail.com first_name_prompt = "Please enter your given name: " last_name_prompt = "Please enter your surname: " mob_prompt = "Please enter your mobile number: " first_name_statement = "First name: {}" last_name_statement = "Last name: {}" mob_statement = "Mobile number: {}" first_name = input(first_name_prompt).strip().capitalize() last_name = input(last_name_prompt).strip().capitalize() mob_number = input(mob_prompt).strip() user_credentials = {} user_credentials.update({ 'first': first_name, 'last': last_name, 'mob': mob_number }) print(first_name_statement.format(user_credentials['first'])) print(last_name_statement.format(user_credentials['last'])) print(mob_statement.format(user_credentials['mob']))
3458b8f1a8806d078d221482e7eb47f20ecdf88f
guangyi/Algorithm
/step_recursive.py
1,251
3.640625
4
''' Created on Mar 9, 2013 @author: zhouguangyi2009 ''' import sets def step_count(n): dic = {} if n == 1: steps = ['1'] dic[1] = steps return steps if n == 2: steps = ['11','2'] dic[2] = steps return steps if n == 3: steps = ['111','12','21','3'] dic[3] = steps return steps else: step_n = [] for i in range(1,n): for step_i in step_count(i): for step_ni in step_count(n-i): step_n.append(step_ni + step_i) dic[n] = sets.Set(step_n) print(dic[n]) return sets.Set(step_n) #step_count(5) def count_path(x,y): m = 0 n = 0 step = 0 if (x == 0) or (y == 0): step = 1 else: while True: if (m == x) & (n == y): return step elif m == x : step = step + 1 return step elif n == y: step = step + 1 return step else: m = m + 1 n = n + 1 step = step + 2 return step a = count_path(2,4) print a
da5aa11146cdd6601b9b40b4ad3fe76d7f824e9c
prem-pratap/Python-Tkinter-Tutorial
/tkinter6.py
362
4.0625
4
#Binding functions to button from tkinter import * start=Tk() def callme(): print("Hey Dude!!!!") def second(event): print("Second Method") button=Button(start,text="Click me",command=callme) button2=Button(start,text="SecondMethod") button2.bind("<Button-1>",second)#Function is called on left mouse click button.pack() button2.pack() start.mainloop()
215a0fb36f83b54fc7476b6224d8ca22e931a7e3
DaniGodin/LeafModeling
/AlgoLeaf/particle_transportation/leaf_object.py
2,373
3.640625
4
""" This module implement the class Leaf and Venation Point """ import numpy as np from pylab import * from matplotlib import collections as mc import matplotlib.pyplot as plt from matplotlib.patches import Ellipse class Leaf: """ This object decribe the leaf shape attributes: shape: parametric descrption of the leaf shape petiole: coordinate of the petiole point #for some species it will be a list of petioles (reed) venation: VenationPoint structure containing recursively treepoints, representing the venations of the leaf """ shape = "basic" petiole = (0, 0) venation = None ax = None def __init__(self, shape, petiole, venations, ax): self.shape = shape self.petiole = petiole self.venation = VenationPoint(petiole, venations) self.ax = ax def display_venation(self): if self.venation: line = [[self.petiole, self.venation.coord]] lc = mc.LineCollection(line, linewidths=self.venation.PhotoEnergy * 0.8, color='black') self.ax.add_collection(lc) self.venation.display_venation(self.ax) self.ax.autoscale() def display_petiole(self): plot(self.petiole[0], self.petiole[1], 'bo') def display_shape(self): self.shape.set_alpha(0.1) self.shape.set_facecolor("Green") self.ax.add_artist(self.shape) class VenationPoint: """ This object represent a venation point attributes: coord: coordinate of the point childrens: list of the point directly connected to this one PhotoEnergy: quantity of PhotoEnergy going through this point """ coord = None children = None PhotoEnergy = 1 def __init__(self, point, children): self.coord = point self.children = children self.compute_energy() def display_venation(self, ax): if self.children: for elt in self.children: line = [self.coord, elt.coord] lc = mc.LineCollection([line], linewidths=0.08 * elt.PhotoEnergy, color='black') ax.add_collection(lc) elt.display_venation(ax) def compute_energy(self): energy = 0 for child in self.children: energy += child.PhotoEnergy self.PhotoEnergy = max(energy, 1)
01b66278d10fc883ea9f752ada16b78c8ab9993e
jGallicchio/HW8
/binarytree.py
4,406
3.609375
4
from fractions import Fraction import itertools import sys ops = ['+', '-', '*', '/'] d = {'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6' : 6, '7': 7, '8': 8, '9': 9, '0': 10, 'J': 11, 'Q': 12, 'K': 13} class BNode: def __init__(self, element): self.element = element self.left = None self.right = None def addleft(self, leftnode): self.left = leftnode def addright(self, rightnode): self.right = rightnode def evaluate(self): ## Add your code here if self.element == ops[3] and self.right.element == 0: return 0 else: if not self.left and not self.right: return d[self.element] elif self.element == ops[0]: return self.left.evaluate() + self.right.evaluate() elif self.element == ops[1]: return self.left.evaluate() - self.right.evaluate() elif self.element == ops[2]: return self.left.evaluate() * self.right.evaluate() elif self.element == ops[3]: return self.left.evaluate() / self.right.evaluate() def display(self): ## Add your code here if not self.left and not self.right: return str(d[self.element]) elif self.element in ops: return '(' + self.left.display() + self.element + self.right.display() + ')' def evaluatefive(ops, cards): s = set() # Tree #1 node1 = BNode(ops[0]) node2 = BNode(ops[1]) node3 = BNode(ops[2]) node1.addleft(node2) node1.addright(node3) node4 = BNode(cards[0]) node5 = BNode(cards[1]) node6 = BNode(cards[2]) node7 = BNode(cards[3]) node2.addleft(node4) node2.addright(node5) node3.addleft(node6) node3.addright(node7) if node1.evaluate() == 24: s.add(node1.display()) # Tree #2 ## Add your code here node12 = BNode(ops[0]) node22 = BNode(ops[1]) node32 = BNode(ops[2]) node42 = BNode(cards[0]) node52 = BNode(cards[1]) node62 = BNode(cards[2]) node72 = BNode(cards[3]) node12.addleft(node22) node12.addright(node72) node22.addleft(node32) node22.addright(node62) node32.addleft(node42) node32.addright(node52) if node12.evaluate() == 24: s.add(node12.display()) #tree #3 ## Add your code here node13 = BNode(ops[0]) node23 = BNode(ops[1]) node33 = BNode(ops[2]) node43 = BNode(cards[0]) node53 = BNode(cards[1]) node63 = BNode(cards[2]) node73 = BNode(cards[3]) node13.addleft(node23) node13.addright(node73) node23.addleft(node43) node23.addright(node33) node33.addleft(node53) node33.addright(node63) if node13.evaluate() == 24: s.add(node13.display()) #tree #4 ## Add your code here node14 = BNode(ops[0]) node24 = BNode(ops[1]) node34 = BNode(ops[2]) node44 = BNode(cards[0]) node54 = BNode(cards[1]) node64 = BNode(cards[2]) node74 = BNode(cards[3]) node14.addleft(node44) node14.addright(node24) node24.addleft(node34) node24.addright(node74) node34.addleft(node54) node34.addright(node64) if node14.evaluate() == 24: s.add(node14.display()) #tree #5 ## Add your code here node15 = BNode(ops[0]) node25 = BNode(ops[1]) node35 = BNode(ops[2]) node45 = BNode(cards[0]) node55 = BNode(cards[1]) node65 = BNode(cards[2]) node75 = BNode(cards[3]) node15.addleft(node45) node15.addright(node25) node25.addleft(node55) node25.addright(node35) node35.addleft(node65) node35.addright(node75) if node15.evaluate() == 24: s.add(node15.display()) return s s = list(input()) if len(s) != 4: sys.exit() for i in range(len(s)): if s[i] not in d.keys(): sys.exit() results = set() s1 = [0, 1, 2, 3] for L in list(itertools.permutations([0, 1, 2, 3], 4)): for i in range(4): s1[i] = s[L[i]] ops1 = [ops[0], ops[0], ops[0]] for i in range(len(ops)): for j in range(len(ops)): for k in range(len(ops)): ops1[0] = ops[i] ops1[1] = ops[j] ops1[2] = ops[k] results = results | evaluatefive(ops1, s1) for result in results: print(result) print(str(len(results)) + " solutions.")
ba1175394d2562d42e4d73631debba07c4ab18b7
Beardocracy/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/tests/test_models/test_rectangle.py
6,769
3.609375
4
#!/usr/bin/python3 ''' This module tests the rectangle class ''' import unittest import sys from models.rectangle import Rectangle from models.base import Base class TestRectangle(unittest.TestCase): ''' This is a unittest for class rectangle ''' def setUp(self): ''' Resets the class variable''' Base._Base__nb_objects = 0 def test_type(self): ''' Tests if type is correct ''' a = Rectangle(5, 5) self.assertEqual(type(a), Rectangle) self.assertTrue(isinstance(a, Base)) self.assertTrue(issubclass(Rectangle, Base)) def test_id_assignment(self): ''' Tests if id assignment works ''' r1 = Rectangle(10, 5) self.assertEqual(r1.id, 1) r2 = Rectangle(10, 5, 0, 0, 98) self.assertEqual(r2.id, 98) r3 = Rectangle(10, 5, 0, 0) self.assertEqual(r3.id, 2) def test_hwxy_assignment(self): ''' tests to see if variable assignment works ''' r1 = Rectangle(10, 5, 3, 4) self.assertEqual(r1.width, 10) self.assertEqual(r1.height, 5) self.assertEqual(r1.x, 3) self.assertEqual(r1.y, 4) r2 = Rectangle(1, 5) self.assertEqual(r2.width, 1) self.assertEqual(r2.height, 5) self.assertEqual(r2.x, 0) self.assertEqual(r2.y, 0) def test_input_validation(self): ''' tests for input validation exceptions and messages''' with self.assertRaisesRegex(TypeError, 'width must be an integer'): r1 = Rectangle('hi', 5) with self.assertRaisesRegex(TypeError, 'height must be an integer'): r2 = Rectangle(5, 'hi') with self.assertRaisesRegex(TypeError, 'x must be an integer'): r3 = Rectangle(5, 5, 'hi', 5) with self.assertRaisesRegex(TypeError, 'y must be an integer'): r4 = Rectangle(5, 5, 0, 'hi') with self.assertRaisesRegex(ValueError, 'width must be > 0'): r5 = Rectangle(-5, 5) with self.assertRaisesRegex(ValueError, 'height must be > 0'): r6 = Rectangle(5, -5) with self.assertRaisesRegex(ValueError, 'x must be >= 0'): r7 = Rectangle(5, 5, -1, 5) with self.assertRaisesRegex(ValueError, 'y must be >= 0'): r8 = Rectangle(5, 5, 5, -5) def test_area(self): ''' Tests for correct output of area method ''' r1 = Rectangle(10, 5) self.assertEqual(r1.area(), 50) r2 = Rectangle(5, 5, 1, 1) self.assertEqual(r2.area(), 25) def test_display(self): ''' Tests for correct output of display method ''' r1 = Rectangle(3, 2) r2 = Rectangle(2, 4) r3 = Rectangle(2, 3, 2, 2) r4 = Rectangle(3, 2, 1, 0) orig_stdout = sys.stdout with open('test_rectangle.txt', 'w') as f: sys.stdout = f r1.display() with open('test_rectangle.txt', 'r') as f: self.assertEqual(f.read(), '###\n###\n') with open('test_rectangle.txt', 'w') as f: sys.stdout = f r2.display() with open('test_rectangle.txt', 'r') as f: self.assertEqual(f.read(), '##\n##\n##\n##\n') with open('test_rectangle.txt', 'w') as f: sys.stdout = f r3.display() with open('test_rectangle.txt', 'r') as f: self.assertEqual(f.read(), '\n\n ##\n ##\n ##\n') with open('test_rectangle.txt', 'w') as f: sys.stdout = f r4.display() with open('test_rectangle.txt', 'r') as f: self.assertEqual(f.read(), ' ###\n ###\n') sys.stdout = orig_stdout def test_str(self): ''' Tests the __str__ method override ''' r1 = Rectangle(4, 6, 2, 1, 12) r2 = Rectangle(5, 5, 1) orig_stdout = sys.stdout with open('test_rectangle.txt', 'w') as f: sys.stdout = f print(r1) with open('test_rectangle.txt', 'r') as f: self.assertEqual(f.read(), '[Rectangle] (12) 2/1 - 4/6\n') with open('test_rectangle.txt', 'w') as f: sys.stdout = f print(r2) with open('test_rectangle.txt', 'r') as f: self.assertEqual(f.read(), '[Rectangle] (1) 1/0 - 5/5\n') sys.stdout = orig_stdout def test_update(self): ''' Tests the update method ''' r1 = Rectangle(10, 10, 10, 10) self.assertEqual(r1.id, 1) self.assertEqual(r1.width, 10) self.assertEqual(r1.height, 10) self.assertEqual(r1.x, 10) self.assertEqual(r1.y, 10) r1.update(89) self.assertEqual(r1.id, 89) r1.update(89, 2, width=5) self.assertEqual(r1.id, 89) self.assertEqual(r1.width, 2) r1.update(89, 2, 3) self.assertEqual(r1.id, 89) self.assertEqual(r1.width, 2) self.assertEqual(r1.height, 3) r1.update(89, 2, 3, 4, id=98) self.assertEqual(r1.id, 89) self.assertEqual(r1.width, 2) self.assertEqual(r1.height, 3) self.assertEqual(r1.x, 4) r1.update(89, 2, 3, 4, 5) self.assertEqual(r1.id, 89) self.assertEqual(r1.width, 2) self.assertEqual(r1.height, 3) self.assertEqual(r1.x, 4) self.assertEqual(r1.y, 5) r1.update(height=1) self.assertEqual(r1.id, 89) self.assertEqual(r1.width, 2) self.assertEqual(r1.height, 1) self.assertEqual(r1.x, 4) self.assertEqual(r1.y, 5) r1.update(width=1, x=2) self.assertEqual(r1.id, 89) self.assertEqual(r1.width, 1) self.assertEqual(r1.height, 1) self.assertEqual(r1.x, 2) self.assertEqual(r1.y, 5) r1.update(y=1, width=2, x=3, id=89) self.assertEqual(r1.id, 89) self.assertEqual(r1.width, 2) self.assertEqual(r1.height, 1) self.assertEqual(r1.x, 3) self.assertEqual(r1.y, 1) r1.update(x=1, height=2, y=3, width=4) self.assertEqual(r1.id, 89) self.assertEqual(r1.width, 4) self.assertEqual(r1.height, 2) self.assertEqual(r1.x, 1) self.assertEqual(r1.y, 3) def test_dictionary(self): ''' Tests the dictionary method and using it with update method ''' r1 = Rectangle(10, 2, 1, 9) r1_dict = r1.to_dictionary() control_dict = {'x': 1, 'y': 9, 'id': 1, 'height': 2, 'width': 10} self.assertEqual(r1_dict, control_dict) self.assertEqual(type(r1_dict), dict) r2 = Rectangle(1, 1) r2_dict = r2.to_dictionary() self.assertEqual(str(r2), '[Rectangle] (2) 0/0 - 1/1') r2.update(**r1_dict) self.assertEqual(str(r2), '[Rectangle] (1) 1/9 - 10/2')
8d62f6cba3d5e6b98efa51103b27414b93c721f3
tbhall/DFAs
/src/minimizing-DFA.py
4,733
3.546875
4
#!/bin/python # -*- coding: utf-8 -*- ############################################################################### ### ### ### Description: Read the description of a DFA from a text file, and write ### ### (to standard output) the description of a minimal equivalent DFA ### ### ### ############################################################################### __author__ = "Tyler Hall" __copyright__ = "Copyright 2017" ################### # IMPORTS # ################### import sys from pprint import pprint ################### # GLOBAL VARIABLE # ################### number_of_states,accepting_states,alphabet_table, DFA_table = 0,[],[],[] ################### # FUNCTIONS # ################### def DFA_print(): print("Number of states: " + str(number_of_states)) print("Accepting states: " + "\\".join([str(x) for x in accepting_states])) print("Alphabet: " + alphabet) for value in sorted(DFA_table.itervalues()): print(" ".join([str(x) for x in value])) #Initalizes the DFA def init_DFA_setup(data_file): DFA_file = open(data_file,"r") DFA_data = DFA_file.read() ####### READING DFA FILE SETTING UP TRANSITION MAP ####### DFA_lines = DFA_data.split('\n') line_one = DFA_lines[0] line_two = DFA_lines[1] line_three = DFA_lines[2] lines_four = DFA_lines[3:] # Number of States (from line_one) number_of_states = int(line_one.split(' ')[3]) # Accepting states (from line_two) accepting_states = list(int(i) for i in line_two.split(' ')[2:]) # Alphabet (from line_three) alphabet = line_three[10:] alphabet_table = { } count = 0 for x in alphabet: alphabet_table.update({x:count}) count += 1 # Transitions (from lines_four) DFA_table = { } for x in xrange(int(number_of_states)): list_trans = lines_four[x] list_trans = list(int(i) for i in list_trans.split(' ')) DFA_table.update({x: list_trans}) return number_of_states, accepting_states, alphabet_table, DFA_table #Returns true or false if the state is an accepting one def isAccepting(state): if state not in accepting_states: return False else: return True def break_key(name): a,b = name.split(':') return a,b def main(argv1): ####### READING DFA FILE SETTING UP TRANSITION MAP ####### global number_of_states,accepting_states,alphabet_table, DFA_table table_dict = {} new_states = {} removed_states = [] #If a change is made in table_dict it goes back through all the cells in table change = True number_of_states,accepting_states, alphabet_table, DFA_table = init_DFA_setup(argv1) ###################### MINIMIZING DFA ###################### #initalize table (Dictionary) for x in DFA_table.iterkeys(): for i in range(x+1, number_of_states): key_name = str(x)+ ":" + str(i) if(isAccepting(x) == isAccepting(i)): table_dict.update({key_name: False}) else: table_dict.update({key_name: True}) # Creates Table to final form while change == True: change = False for table_key in sorted(table_dict.iterkeys()): #print(table_key + " " + str(table_dict.get(key_name))) if(table_dict.get(table_key) == False): a,b = break_key(table_key) a_trans = DFA_table.get(int(a)) b_trans = DFA_table.get(int(b)) for alpha_char in sorted(alphabet_table.iterkeys()): value = alphabet_table.get(alpha_char) a_char_state = a_trans[int(value)] b_char_state = b_trans[int(value)] if (a_char_state != b_char_state): if(a_char_state > b_char_state): char_state = str(b_char_state) + ":" + str(a_char_state) else: char_state = str(a_char_state) + ":" + str(b_char_state) if(table_dict.get(char_state) == True): table_dict.update({table_key: True}) change = True break for table_key, table_value in sorted(table_dict.items()): pass #pprint(removed_states) ################### # MAIN # ################### if __name__ == "__main__": if(len(sys.argv) != 1): main(sys.argv[1]) else: print "Please pass one argument"
fba8f796a41c43d442b43240179a28ee8763ed64
broepke/GTx
/part_3/4.5.4_modify_dict.py
1,955
4.53125
5
# Write a function called modify_dict. modify_dict takes one # parameter, a dictionary. The dictionary's keys are people's # last names, and the dictionary's values are people's first # names. For example, the key "Joyner" would have the value # "David". # # modify_dict should delete any key-value pair for which the # key's first letter is not capitalized. For example, the # key-value pair "joyner":"David" would be deleted, but the # key-value pair "Joyner":"david" would not be deleted. Then, # return the modified dictionary. # # Remember, the keyword del deletes items from lists and # dictionaries. For example, to remove the key "key!" from # the dictionary my_dict, you would write: del my_dict["key!"] # Or, if the key was the variable my_key, you would write: # del my_dict[my_key] # # Hint: If you try to delete items from the dictionary while # looping through the dictionary, you'll run into problems! # We should never change the number if items in a list or # dictionary while looping through those items. Think about # what you could do to keep track of which keys should be # deleted so you can delete them after the loop is done. # # Hint 2: To check if the first letter of a string is a # capital letter, use string[0].isupper(). # Write your function here! def modify_dict(a_dict): to_delete = [] for last_names in a_dict.keys(): if not last_names[0].isupper(): to_delete.append(last_names) for names in to_delete: del a_dict[names] return a_dict # Below are some lines of code that will test your function. # You can change the value of the variable(s) to test your # function with different inputs. # # If your function works correctly, this will originally # print (although the order of the keys may vary): # {'Diaddigo':'Joshua', 'Elliott':'jackie'} my_dict = {'Joshua': 'Diaddigo', 'joyner': 'David', 'Elliott': 'jackie', 'murrell': 'marguerite'} print(modify_dict(my_dict))
b3a71e83873a8a34dc8bed1002952f818855e5b0
cauegonzalez/cursoPython
/listaDeExercicios/ex065.py
844
4.1875
4
# coding=UTF-8 # Crie um programa que leia vários números inteiros pelo teclado. # No final da execução, mostre a média entre todos os valores e qual foi o maior e o menor valores lidos. # O programa deve pergutnar ao usuário se ele quer ou não continuar a digitar valores numero = soma = i = menor = maior = 0 continuar = 'S' while continuar != 'N': numero = int(input('Digite um número inteiro qualquer: ')) soma += numero i += 1 if i == 1: menor = maior = numero if numero < menor: menor = numero if numero > maior: maior = numero continuar = input('Deseja continuar a digitar números? [S/N] ').strip().upper()[0] media = soma / i print('\nA média dos {} números digitados é {}'.format(i, media)) print('O menor número é {} e o maior número é {}'.format(menor, maior))
fc4c29c1a674e2be4a0e91e9a06ba2be4d68fa6f
friedlich/python
/19年7月/7.23/垃圾分类.py
3,873
3.578125
4
# 首先,导入所需要的相关模块。 import requests from bs4 import BeautifulSoup from urllib.request import quote import tkinter from tkinter import Tk,Button,Entry,Label,Text,END # 接着,请求爬取网页。 def crawl(word): # -------------加了requests headers headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'} # params = { # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', # 'Accept - Encoding': 'gzip, deflate, br', # 'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,es-US;q=0.6,es;q=0.5', # 'Connection': 'keep-alive', # 'DNT': '1', # 'Host': 'lajifenleiapp.com', # 'Referer':'https://lajifenleiapp.com/', # 'Upgrade - Insecure - Requests': '1', # 'User - Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36', # } url = "http://lajifenleiapp.com/sk/"+quote(word) res0 = requests.get(url,headers=headers) res = BeautifulSoup(res0.text,'html.parser') a=res.find_all(class_="col-md-12")#23 # print(a[0].text) # print('-'*75) # 将爬取得数据进行清洗筛选,从中选取自己需要的数据。 if a[0].text !='未查到完全匹配字段。': b = res.find_all("li") ''' for i in range(10): print(i, '\n',a[i]) ''' # ------------严重错误!!!!!!!!!, IndexError: list index out of range, 从4,5,6,7,8改成了3,4,5,6,7 # print(a[0].text,a[1].text,a[3].text,a[4].text,a[5].text,a[6].text,a[7].text) return "相似物品:\n"+a[0].text.replace("\n"," ").replace("相关查询:","").strip()+"\n\n"+''.join(a[1].text.split())+"\n\n"+a[3].text+"\n"+a[4].text+"\n\n"+a[5].text+"\n"+a[6].text+"\n\n"+a[7].text+"\n"+b[0].text+"\n"+b[1].text else: return word+"可不是什么垃圾,哼,请重新搜索" # 最后,对垃圾分类器界面端的大小、颜色等进行设计。 win = tkinter.Tk() #生成win主窗口 win.title("垃圾分拣查询器") #修改框体的名字 win.geometry("400x400+200+50") #指定主框体大小 win.minsize(310,470) win.maxsize(310,470) result_text1 = Text(win,background = 'azure') #文本框(多行) result_text1.place(x = 10,y = 5,width = 285,height = 70) #place组件可以直接使用坐标来放置组件 # x:组件左上角的x坐标;y:组件左上角的y坐标;width:组件的宽度;height:组件的高度 # result_text1.bind("<Key-Return>","submit1") # 对于按钮组件、菜单组件等可以在创建组件时通过command参数指定其事件处理函数。方法为bind # 事件关联 bind(sequence,func,add) # 这一步并不产生任何作用,是文本框的作用 title_label = Label(win, text=u'垃圾分类查询结果:') #生成标签 title_label.place(x=10, y=100) # 翻译结果 result_text = Text(win, background='light cyan') result_text.place(x=10, y=120, width=285, height=325) def submit1(): content = result_text1.get(0.0, END).strip().replace("\n", " ") #可用set和get方法进行传值和取值 # 把这个值传送给服务器进行翻译 result = crawl(content) result_text.delete(0.0, END) result_text.insert(END, result) def submit(): content = result_text1.get(0.0,END).strip().replace("\n"," ") result = crawl(content) result_text.delete(0.0, END) result_text.insert(END, result) def clean(): result_text1.delete(0.0,END) result_text.delete(0.0,END) submit_btn = Button(win, text=u'查询', command=submit) submit_btn.place(x=205, y=80, width=35, height=25) submit_btn2 = Button(win, text=u'清空', command=clean) submit_btn2.place(x=250, y=80, width=35, height=25) win.mainloop()
dedf504b214dab71077788aea97ede0f75b0e41b
ChrysWillians/exercicios-python3
/ex040.py
467
3.890625
4
print('/' * 30) print('Calcule a média de suas notas:') print('/' * 30) n1 = float(input('Primeira nota: ')) n2 = float(input('Segunda nota: ')) print('/' * 30) media = (n1 + n2) / 2 print('A média de {:.1f} e {:.1f} foi: {:.1f}'.format(n1, n2, media)) print('/' * 30) if media >= 7: print('PARABÉNS, você foi APROVADO!') elif media < 5: print('Você foi REPROVADO!') else: print('Você ficou de RECUPERAÇÃO!') print('/' * 30)
ab9cd49686a7c169a638d9d9a2c7d667a8d9db08
jakemiller13/School
/MITx 6.00.1x - Introduction to Computer Programming Using Python/Problem Set 2_1.py
1,522
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 26 06:23:17 2017 @author: Jake """ def yearlyBalance(balance, annualInterestRate, monthlyPaymentRate): ''' Given a balance, annual interest rate, and monthly payment rate, will calculate credit card balance at end of one year balance: the outstanding balance on the credit card annualInterestRate: annual interest rate as a decimal monthlyPaymentRate: minimum monthly payment rate as a decimal ''' for i in range(0,12): monthlyInterest = annualInterestRate / 12.0 minMonthlyPayment = monthlyPaymentRate * balance monthlyUnpaidBalance = balance - minMonthlyPayment balance = monthlyUnpaidBalance + (monthlyInterest * monthlyUnpaidBalance) return balance print("Remaining balance: " + str(round(yearlyBalance(484, 0.2, 0.04),2))) # Test Case 1: # balance = 42 # annualInterestRate = 0.2 # monthlyPaymentRate = 0.04 # Remaining balance: 31.38 # Test Case 2: # balance = 484 # annualInterestRate = 0.2 # monthlyPaymentRate = 0.04 # Remaining balance: 361.61 ### This is the answer. Above is putting it in function #for i in range(0,12): # monthlyInterest = annualInterestRate / 12.0 # minMonthlyPayment = monthlyPaymentRate * balance # monthlyUnpaidBalance = balance - minMonthlyPayment # balance = monthlyUnpaidBalance + (monthlyInterest * monthlyUnpaidBalance) #print("Remaining balance: " + str(round(balance,2)))
f097bfece015d0746248c7aa3c5a4a0d42f1ce58
CDivyaPrabha/CP1404Practicals
/prac_02/Do-from-scratch exercises/files.py
580
4.03125
4
#First program name = input("Enter your name: ") out_file = open('name.txt', 'w') print(name, file=out_file) out_file.close() #Second Program in_file = open('name.txt', 'r') name = in_file.read().strip() print('Your name is', name) in_file.close() #Third program in_file = open('numbers.rtf', 'r') number1 = int(in_file.readline()) number2 = int(in_file.readline()) print(number1 + number2) in_file.close() #Third program extended in_file = open('numbers.rtf', 'r') total = 0 for line in in_file: number = int(line) total += number print(total) in_file.close()
b1ac105fc041929780978f18f74079696d2dc897
katcreardon/PythonCrashCourse
/Ch09/orderedDict_rewrite.py
894
3.875
4
from collections import OrderedDict glossary = OrderedDict() glossary['dictionary'] = 'a collection of key-value pairs' glossary['key-value pair'] = 'a set of values associated with each other' glossary['conditional statement'] = 'a statement that evaluates to either true or false' glossary['for loop'] = 'allows you to do the same action with every item in a list' glossary['tuple'] = 'an immutable list' glossary['set'] = 'a list where each item must be unique' glossary['variable'] = 'a named item that holds a value' glossary['method'] = 'an action that Python can perform on a piece of data' glossary['whitespace'] = 'any nonprinting character, such as spaces, tabs, and end-of-line symbols' glossary['syntax error'] = "occurs when Python doesn't recognize a section of your program as valid Python code" for word, meaning in glossary.items(): print(word + "\n\t" + meaning + "\n")
bdc9657ff6bec9bb87bb066b6d6c4640ff6549c7
DarrRayr/1_1
/game1.py
424
3.53125
4
import time import math print("Welcome to battle sim") print("") time.sleep(2) bag = [""] health = 100 def wolf_battle(): print("You have ran into a wolf!") wolf_health = 100 descision = 1 if descision == 1: print("Bag | Battle | Run") descision1 = input(" ") if descision1.lower == ("bag"): print(bag) if len(bag) == 0: print("There is nothing in your bag!") descision = 1
1241826d3bc71b88f9d325cd60d551dd9c4730f5
kacou12/les_scripts_cours
/fonction/function4.py
789
3.921875
4
from math import pi,sqrt a=(input("demi grand axe a = ")) b=(input("demi axe moyen b = ")) c=(input("demi petit axe c = ")) d=(input("densité d = ")) def volMasseEllipsoide(a=10,b=8,c=6,d=1): volume = float((4/3)*pi*a*b*c) e=sqrt((a**2-c**2)/a) masse=d*volume return e, volume, masse try: a= float(a) b= float(b) c=float(c) d=float(d) if a>=b>=c: table=volMasseEllipsoide(a,b,c) print("l'enxentricité est : {:.4f}".format(table[0])) print("le volume est : {:.4f}".format(table[1])) print("la masse est : {:.4f}".format(table[2]),"kg") else: print("A doit etre superieur ou egal a B, qui doit etre superieur ou egal a C") except : print("Veillez entrer des nombre")
6d43e0845c603d3da0a851bd1dea18620ee7414d
klakor/nauka_pythona
/slownik.py
322
3.90625
4
samolot = {'name': 'boeing', 'przebieg': 10000, 'typ': 'pasazerski'} #in python3 samolot.items() for key, value in samolot.items(): print("{0} : {1}".format(key, value)) print(samolot['name'] + " jest samolotem " + samolot['typ'] + "m.") # for key in samolot: print("{0}:{1}".format(key, value))
01221f7657f0139ee04c038a8d8a5104d030124a
Purnima124/if-else.py
/num greater than.py
166
4.1875
4
num=int(input("enter the number")) if num>=50: print("num greater than 50") elif num%2==0: print("it is even number") else: print("it is odd number")
250a5df623a7dadac0b75ce3dcb64cd3291daa4d
taehwan920/Algorithm
/baekjoon/2193_i-chin-num.py
178
3.625
4
n = int(input()) cache = [0] * 3 cache[0] = 1 cache[1] = 1 for i in range(2, n): cache[2] = cache[0] + cache[1] cache[0], cache[1] = cache[1], cache[2] print(cache[1])
be17627607362bef4b85efd9d9075fabca591209
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_97/485.py
738
3.859375
4
import string def int_input(): return int(raw_input()) def list_int_input(): return [int(i) for i in raw_input().split()] def count_higher_pairs(num, a, b): num_str = str(num); count = 0; counted_number = {} for i in range(1, len(num_str)): new_num = int(num_str[-i:] + num_str[:-i]) if a <= new_num and new_num <= b and num < new_num and counted_number.has_key(new_num) == False: count += 1 counted_number[new_num] = True while num < b: num *= 10; if num <= b: count += 1 return count def solve(): a, b = list_int_input() answer = 0 for i in range(a, b+1): answer += count_higher_pairs(i, a, b) return answer def main(): for i in range(1, int_input()+1): print 'Case #%d: %s' % (i, solve()) main()
e023c2df1882592401c96db5b8908efd6569e07c
jtenhave/AdventOfCode
/2019/Day6/c.py
956
3.5
4
import re orbitPattern = re.compile("(\w*)\)(\w*)") # Class that represents an orbiting object. class Object: def __init__(self, id): self.id = id self.parent = None # Total number of orbits this object has around the central mass. def totalOrbits(self): if not self.parent: return 0 else: return 1 + self.parent.totalOrbits() # Get the objects. def getObjects(file): with open(file) as input: orbitDefs = input.readlines() objects = {} for orbitDef in orbitDefs: match = orbitPattern.match(orbitDef) parentID = match[1] childID = match[2] if parentID not in objects: objects[parentID] = Object(parentID) if childID not in objects: objects[childID] = Object(childID) parent = objects[parentID] child = objects[childID] child.parent = parent return objects
a20b9d2eac3837b4cc41cf686c73bb4c7d221d7d
ellynnhitran/Fundamentals_C4T4
/Session01/polygon.py
243
4.03125
4
from turtle import * speed(-1) shape("turtle") color("purple") # number = int(input("How many polygons you need?")) # ans = 0 + int(number) # print("I want", ans) n = 5 for i in range(n): forward (100) left(360//n) mainloop()
41635d13e0adeff19398a884b00fc4e7256bcc6c
madhav06/LazyBear_for_DS
/Trees/Implement-binary-heap.py
3,307
4.40625
4
# This is a python program to implement a binary heap. # The program creates a binary max-heap and presents a menu to the user to perform various operations on it. # Strategy: # Create a class BinaryHeap with an instance variable items set to an empty list. # This empty list is used to store the binary heap. # Define methods size, parent, left, right, get, get_max, extract_max, max_heapify, swap and insert. # Methods: # size: returns the number of elements in the heap. # parent: takes an index as argument and returns index of the parent. # left: takes an index as argument and returns the index of its left child. # right: takes an index as argument and returns the index of its right child. # get: takes index as argument and returns the key at the index. # get_max: returns the maximum element in the heap by returning the first element in the list items. # extract_max: returns the maximum element in the heap and removes it. # max_heapify: takes an index as argument and modifies the heap structure at and below the node # ...at this index to make it satisfy the heap property. # swap: takes two index as arguments, and swaps the corresponding elements in the heap. # insert: takes a key as argument and adds that key to the heap. # Program: class BinaryHeap: def __init__(self): self.items = [] def size(self): return len(self.items) def parent(self, i): return (i - 1 )// 2 def left(self, i): return 2*1 + 1 def right(self, i): return 2*i + 2 def get(self, i): return self.items[i] def get_max(self): if self.size() == 0: return None return self.items[0] def extract_max(self): if self.size() == 0: return None largest = self.get_max() self.items[0] = self.items[-1] del self.items[-1] self.max_heapify(0) return largest def max_heapify(self, i): l = self.left(i) r = self.right(i) if (l <= self.size() - 1 and self.get(l) > self.get(i)): largest = l else: largest = i if (r <= self.size() - 1 and self.get(r) > self.get(largest)): largest = r if (largest != i): self.swap(largest, i) self.max_heapify(largest) def swap(self, i, j): self.items[i], self.items[j] = self.items[j], self.items[i] def insert(self, key): index = self.size() self.items.append(key) while (index != 0): p = self.parent(index) if self.get(p) < self.get(index): self.swap(p, index) index = p bheap = BinaryHeap() print('Menu') print('insert<data>') print('max get') print('max extract') print('quit') while True: do = input('What would you like to do? ').split() operation = do[0].strip().lower() if operation == 'insert': data = int(do[1]) bheap.insert(data) elif operation == 'max': suboperation = do[1].strip().lower() if suboperation == 'get': print('Maximum value: {}'.format(bheap.get_max())) elif suboperation == 'extract': print('Maximum valiue removed: {}'.format(bheap.extract_max())) elif operation == 'quit': break
6d585d8785caac2d276a1e1705e37367f3f7c76e
eronekogin/leetcode
/2020/lexicographical_numbers.py
616
3.703125
4
""" https://leetcode.com/problems/lexicographical-numbers/ """ from typing import List class Solution: def lexicalOrder(self, n: int) -> List[int]: rslt = [1] while len(rslt) < n: nextNum = rslt[-1] * 10 while nextNum > n: nextNum //= 10 nextNum += 1 while not nextNum % 10: # Handle case when 199 + 1 = 200, where we need # to restart couting from 2. nextNum //= 10 rslt.append(nextNum) return rslt print(Solution().lexicalOrder(111))
cfe9875e3cd55911eeb26813e0b1bbe14fb7b452
RevanthR/SHC
/linear_reg.py
579
3.609375
4
import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error,r2_score np.random.seed(0) x=np.random.rand(100,1) y=2+3*x+np.random.rand(100,1) regression_model=LinearRegression() regression_model.fit(x,y) y_predicted=regression_model.predict(x) rmse=mean_squared_error(y,y_predicted) r2=r2_score(y,y_predicted) print('Slope:',regression_model.coef_) print('Intercept:', regression_model.intercept_) print('Root Mean Squared Error:', rmse) print('Accuracy',r2) plt.scatter(x,y,s=10)
94ea9a4d02007b71bb72a00377ca547fb07f41e0
caiocotts/ics2017
/Lesson4/8-PoundsToKilos.py
125
3.84375
4
pounds = float(input("Enter the value in pounds: ")) kilos = pounds * 0.454 print(pounds, "pounds is", kilos, "kilograms")
9ad1b861e6aebbddb8a2b9cbee7f0fb2f61eafc5
natarajanct/Leetcode
/28_Implement_strStr()_v1.py
257
3.671875
4
def strStr(self, haystack, needle): if len(needle)==0: return 0 elif needle in haystack: for i in range(len(haystack)): if(haystack[i:i+len(needle)]==needle): return i else: return -1
9c5ffb4ac3710b761c246654ed1e30802ad8f103
ScaredTuna/Python
/BinaryConverter.py
806
4.0625
4
def binary(): num = "" while num == "": print("-----------------------------------------------") num = input("Enter a Binary Number:") i = 0 while i < len(num): if ord(num[i]) != 48 and ord(num[i]) != 49: print("-----------------------------------------------") print("Error: Input is not a Binary Number") i = len(num) num = "" else: i += 1 return num bin = binary() print("-----------------------------------------------") num = 0 i = len(bin) - 1 a = 0 while i >= 0: num += int(bin[i]) * (2 ** a) i -= 1 a += 1 print("For the Binary Number:", bin) print("The Decimal Value is:", num) print("-----------------------------------------------")
c20e24440cbf9126130008a7fecf84f07eed9618
Randdyy/Myfirst-Codes
/zuoye/001/guess.py
1,076
3.65625
4
import random print("我在一百内想了一个数,你猜猜看啊") count=0 ran=random.randint(1, 101) print(ran) while(1): count+=1 user_input=input("please input a number,input q to quit") try: if isinstance(int(user_input),int): if ran < int(user_input) : print("大了,请重新猜") print("您已经玩了{}次了".format(count)) continue elif ran > int(user_input) : print("小了,请重新猜") print("您已经玩了{}次了".format(count)) continue elif ran== int(user_input): print("恭喜你猜对了") print("您一共玩了{}次了".format(count)) user_input2=input("输入y继续玩").lower().strip() if user_input2=="y": count=0 ran=random.randint(1,101) continue else: break except: break
3cd313ae5f5436d447edd59f3e86b0b349109ef1
famaxth/Way-to-Coding
/MCA Exam Preparations/Python/LAB/greaterthan 100 store as over in a list.py
175
4
4
N = int(input("Total numbers : ")) listed=[] for i in range(N): num = input("Enter integers") if int(num)>100: num="over" listed.append(num) print(listed)
58340c8c687d2430ce5b6254d42a8011e47ca052
tatmil-99/digitalcrafts-03-2021
/week2/day2/classWork.py
2,410
4.5625
5
# 1 # Create a User class, that has the ability to print the users name # the ability to print the users age # Create a TempUser class, that has the ability to only print his name. # Create a function that as you to give the user a name, and give the user an age, and will then create the user for you, and print it to the screen. The user will have a choice to either be a temp user or a User # class User: # def __init__(self, name, age): # self.name = name # self.age = age # def printUser(self): # print(self.name) # print(self.age) # class TempUser: # def __init__(self, name): # self.name = name # def printTemp(self): # print(self.name) # users = User("Tate", 23) # users.printUser() # temporary = TempUser("Max") # temporary.printTemp() # def createUser(): # userName = input("What is your name?") # userAge = int(input("What is your age?")) # userType = input("Are you a \"user\" or \"temp\" user?") # if userType == "user": # user = User(userName, userAge) # user.printUser() # elif userType == "temp": # user = TempUser(userName) # user.printTemp() # else: # pass # createUser() # Create a building class # buildilng class will have # height # capacity # sqft # # commercial or residential # commercial # ask the user to create a building (new instance of the building class) # they will enter in height # capacity (people) # sqft # 5 instances of a building # print out the specs of the buildilng everytime a building is made # print statement needs to be a method # Default the building type to commercial specs_list = [] class Building: def __init__(self, height, capacity, sqft, building_type="commercial"): self.height = height self.capacity= capacity self.sqft = sqft self.building_type = building_type def print_building(self): print(self.height) print(self.capacity) print(self.sqft) print(self.building_type) # building = Building(300, 1000, 50000) # building.print_building() def new_building(): construct = "" prompt = print("Please create a new building") specs_height = input("Enter building height: ") specs_capacity = input("Enter building capacity: ") specs_sqft = input("Enter building sqft: ") construct = Building(specs_height, specs_capacity, specs_sqft) construct.print_building() count = 0 while count < 5: new_building() count += 1
42b781d8cf9cdddb0fdbd3d70abe502e9c5f243c
qaalib101/SqliteLab
/hello_db.py
472
4.03125
4
import sqlite3 db = sqlite3.connect('my_first_db.db') db.row_factory = sqlite3.Row cur = db.cursor() cur.execute('create table if not exists phones (brand text, version int)') brand = input('Enter brand of phone') version = int(input('Enter version of phone (as an integer)')) cur.execute('insert into phones values (?, ?)', (brand, version)) for row in cur.execute('select * from phones'): print(row) # cur.execute('drop table phones') db.commit() db.close()
957bb8066849af5c8eddbd946dfdc116ac1fce87
Jimbiscus/Python_Dump
/Exo10.py
137
3.65625
4
from random import randint number = randint(1, 6) if number == 3 or number == 4: print("BOOM") else: print("Rien ne se passe")
787ee025dfc80f312770c890c074dedfad764b1e
elhadjmb/fivedd
/app/core/file.py
523
3.53125
4
""" file: file class (if there are files as features or just to store the file) """ import os.path class File: def __init__(self, path="/"): self.path = r"{}".format(path) # if Checker.path(path) else Exceptions.flag(type=Dictionary.Internal()) self.file_name = os.path.basename(self.path) self.size = os.path.getsize(self.path) self.extension = os.path.splitext(self.path)[1] self.name = self.file_name.replace(self.extension, "") # self.file = open(self.path, "r")
4036fbdb185cfca1e76032fa50733b9bacffa10c
td-dana/data
/dictpt3.py
860
3.640625
4
import json survey = ["What is your name?", "What is your favorite programming language?"] keys = ["name", "language"] list_of_answers = [] done = "No" while done == "No": answers = {} for x in range(len(survey)): response = input(survey[x]+" ") answers[keys[x]] = response list_of_answers.append(answers) done = input("Hey are you done? Yes or No?") #Open file with all past results and apppend them to current listen f = open("file.json", "r") oldData = json.load(f) list_of_answers.extend(oldData) f.close() f = open("file.json", "w") f.write('\n') index = 0 for j in list_of_answers: if (index, len(list_of_answers)-1): json.dump(j,f) f.write('\n') else: json.dump(j,f) f.write('\n') index += 1 f.write(']') f.close()
25b1479b423c65c29f467d046327580254501dde
jh-lau/leetcode_in_python
/01-数据结构/哈希表/706.设计哈希映射.py
3,119
3.875
4
""" @Author : liujianhan @Date : 2020/12/24 20:10 @Project : leetcode_in_python @FileName : 706.设计哈希映射.py @Description : 不使用任何内建的哈希表库设计一个哈希映射 具体地说,你的设计应该包含以下的功能 put(key, value):向哈希映射中插入(键,值)的数值对。如果键对应的值已经存在,更新这个值。 get(key):返回给定的键所对应的值,如果映射中不包含这个键,返回-1。 remove(key):如果映射中存在这个键,删除这个数值对。 示例: MyHashMap hashMap = new MyHashMap(); hashMap.put(1, 1);           hashMap.put(2, 2);         hashMap.get(1);            // 返回 1 hashMap.get(3);            // 返回 -1 (未找到) hashMap.put(2, 1);         // 更新已有的值 hashMap.get(2);            // 返回 1 hashMap.remove(2);         // 删除键为2的数据 hashMap.get(2);            // 返回 -1 (未找到) 注意: 所有的值都在 [0, 1000000]的范围内。 操作的总数目在[1, 10000]范围内。 不要使用内建的哈希库。 """ class Bucket: def __init__(self): self.bucket = [] def get(self, key): for (k, v) in self.bucket: if k == key: return v return -1 def update(self, key, value): found = False for i, kv in enumerate(self.bucket): if key == kv[0]: self.bucket[i] = (key, value) found = True break if not found: self.bucket.append((key, value)) def remove(self, key): for i, kv in enumerate(self.bucket): if key == kv[0]: del self.bucket[i] # 272ms, 18.2MB class MyHashMap(object): def __init__(self): """ Initialize your data structure here. """ # better to be a prime number, less collision self.key_space = 2069 self.hash_table = [Bucket() for i in range(self.key_space)] def put(self, key, value): """ value will always be non-negative. :type key: int :type value: int :rtype: None """ hash_key = key % self.key_space self.hash_table[hash_key].update(key, value) def get(self, key): """ Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key :type key: int :rtype: int """ hash_key = key % self.key_space return self.hash_table[hash_key].get(key) def remove(self, key): """ Removes the mapping of the specified value key if this map contains a mapping for the key :type key: int :rtype: None """ hash_key = key % self.key_space self.hash_table[hash_key].remove(key) # Your MyHashMap object will be instantiated and called as such: # obj = MyHashMap() # obj.put(key,value) # param_2 = obj.get(key) # obj.remove(key)
db9b4ac44fac4bce239013b475d05f47ffc1163e
ehizman/Python_Projects
/src/practice/python iterators.py
1,905
4.03125
4
def reverse_string_generator(string): for i in range(len(string) - 1, -1, -1): yield string[i] def all_even(x): n = 0 while True: if n <= x: yield n n = n + 2 else: break def generator(): """ A simple generator""" n = 1 print("This is the first run") yield n n += 1 print("This is the second run") yield n n += 1 print("This is the third run") yield n # class PowTwo: # # def __init__(self, max=0): # self.max = max # # def __iter__(self): # self.n = 0 # return self # # def __next__(self): # if self.n <= self.max: # result = 2 ** self.n # self.n += 1 # return result # else: # raise StopIteration # if __name__ == "__main__": # object_of_powtwo = PowTwo(4) # iterator = iter(object_of_powtwo) # # while True: # try: # print(next(object_of_powtwo)) # except StopIteration: # break # for i in object_of_powtwo: # print(i) # for item in generator(): # print(item) # # for char in reverse_string_generator("Hello"): # print(char, end='') # # # def fibonnacci_nums(num): # x = 0 # y = 1 # for _ in range(num): # x, y = y, x + y # yield x # # # def square(nums): # for num in nums: # yield num ** 2 # # # print(f'\n{sum(square(fibonnacci_nums(10)))}') # # list_ = [1, 2, 3, 4, 5, 6] # target = 3 # iterable = (target - x for x in list_) # # count = 0 # for x, y in enumerate(list_): # if y in iterable: # print(x, iterable[count]) # break # else: # count += 1 for i in all_even(50): print(i)
540c27f85f263bdf8f1fa064fe8cd1675754c042
bestchanges/hello_python
/sessions/2/oleg_baluev/anagrams.py
2,274
4.09375
4
# The algorithm uses a prefix tree data structure. Each node of the tree is array of two values: # [final_letter, children], where final_letter is a flag telling that there is a word which ends with this node, # children is a dictionary if child nodes identified by the next character in the word. # Check if a specified word is present in the tree def check_presence(source, start_index, sample_len, tree_root): next_node = tree_root[1].get(source[start_index]) if (next_node == None): return False if (sample_len == 1): # Whether the node is final letter return next_node[0] else: # Go to next character recursively next_start_index = (start_index + 1) % len(source) return check_presence(source, next_start_index, sample_len - 1, next_node) # Add a new word into the tree def insert_word(source, start_index, word_len, tree_root): next_node = tree_root[1].get(source[start_index]) if (next_node) == None: # Creating a node for the character next_node = [False, {}] tree_root[1][source[start_index]] = next_node if (word_len == 1): # Marking the node as a final letter next_node[0] = True else: # Adding the rest word part next_start_index = (start_index + 1) % len(source) insert_word(source, next_start_index, word_len - 1, next_node) # Returns a source word shifted using the specified start index def shift(source, start_index): return source[start_index:len(source)] + source[0:start_index] words = ["abc", "def", "cab", "bac", "Макар", "карма", "армак", "ракам", "кабан", "банка", "банк", "камыш", "мышка"] print(words) # Main program root = [False, {}] for word in words: if (type(word) != str or len(word) == 0): continue word = word.lower() # The word has already been handled before, skipping if (check_presence(word, 0, len(word), root)): continue; # Shifting the word consequently and seeing if there are such words in the tree for i in range(1, len(word)): if (check_presence(word, i, len(word), root)): print(word + " <--> " + shift(word, i)) insert_word(word, 0, len(word), root) print('end')
ad766408b5d3f7bc095c184e36b6856faa6a9f21
keiti93/Programming101-1
/week0/Problem-40.py
267
3.9375
4
def char_histogram(string): histogram = {} for ch in string: if ch not in histogram: histogram[ch] = 1 else: histogram[ch] += 1 return histogram print(char_histogram("Python!")) print(char_histogram("AAAAaaa!!!"))
d36418203c08c5dd8a4f91e7aec0dc98d950b975
cclauss/Ten-lines-or-less
/bit_filpper.py
444
3.546875
4
# https://forum.omz-software.com/topic/2943/trying-to-make-an-encrypted-message-system # a poor man's encryption def bit_flipper(s, salt=1): return "".join([chr(ord(x) ^ salt) for x in s]) salt = 1 # try 1, 6, 7 # for instance, salt = 2 gives you an encrypted string with no printable chars # (disappearing ink)! s = "Pythonista rules! ¥€$ īt döèš" print(s) s = bit_flipper(s, salt) print(s) s = bit_flipper(s, salt) print(s)
954208c88ee4518b1d71aa98fd0a40536cf8a481
Racso1993/EjerciciosCondicionales
/supermercado (1).py
350
3.78125
4
#Ejercicio 2 - Supermercado precio = int(input("Escribe el valor total de la compra: ")) numeroescogido = int(input("Digita el numero que escogio: ")) if numeroescogido >= 74: total = precio * 0.20 else: total = precio * 0.15 print(f"El descuento a favor es: ${total}") print(f"El total por pagar incluyendo el descuento es: ${precio-total}")
c799de4c6e0010fcd34d28631d0e0b6093b4b698
ChrisMusson/Problem-Solving
/Project Euler/026_Reciprocal_cycles.py
1,685
3.984375
4
''' A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given: 1/2 = 0.5 1/3 = 0.(3) 1/4 = 0.25 1/5 = 0.2 1/6 = 0.1(6) 1/7 = 0.(142857) 1/8 = 0.125 1/9 = 0.(1) 1/10 = 0.1 Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle. Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part. ''' # My idea is to do long division on 1 / x until a remainder repeats. # Then it must be true that the decimal expansion repeats from that point, # so the number of other remainders found between these 2 occurences of the remainder # must be the cycle length def cycle_length(x): '''returns the cycle length of 1 / x if it contains one''' remainders = set() rem = 1 # start off with 1.0000... in long division while rem > 0: while rem < x: rem *= 10 # multiply by 10 until x goes into rem at least once, as in long division rem %= x # if this remainder has already been seen, the decimal expansion must now start repeating if rem in remainders: return len(remainders) else: remainders.add(rem) # if rem ever becomes 0 then the decimal expansion has terminated, so the cycle length must be 0 return 0 def main(): max_cycle_length = 0 max_x = 0 for x in range(1, 1000): leng = cycle_length(x) if leng > max_cycle_length: max_cycle_length = leng max_x = x return max_x if __name__ == "__main__": print(main()) # Output: 983
fd56d025f9736e9194cd3397ca44a7dd9afb622b
lirlia/AtCoder
/aizu-online-judge/ITP1_6_B.py
404
3.546875
4
n = int(input()) cards = [] v = ["S", "H", "C", "D"] number = list(range(1,14)) for i in v: for num in number: cards.append("{} {}".format(i, num)) my_cards = [] if n == 52: exit(0) for i in range(n): my_cards.append(input()) # https://qiita.com/Toitu_Prince/items/222b50594b4bb7b189ee result = [i for i in cards if i not in my_cards] print("\n".join(map(str, result)))
48c50b5b9afad877b867d0cb1a0f044abb639129
lliradev/Programacion-con-Python
/1. Principios basicos POO/hello.py
350
3.703125
4
songs = ["Red Lights", "Hey Brother", "Don't you worry child", "Gold Skies"] print(songs) print(songs[1]) print(len(songs)) songs.append("Congratulations") print(songs) songs.sort() print(songs) songs.insert(5, "Closer") print(songs) songs.append("Complicated") songs.sort() print(songs) s = "Red Lights" s.lower() print(s)
8015b7dfba6d3fc46191d56e8deef8a3185ea5fa
da-ferreira/uri-online-judge
/uri/2906.py
467
3.578125
4
quantidade = int(input()) emails = set() for i in range(quantidade): email = input() email = list(email.partition('@')) primeira_parte = '' for j in range(len(email[0])): if email[0][j] != '.' and email[0][j] != '+': primeira_parte += email[0][j] else: if email[0][j] == '+': break email[0] = primeira_parte emails.add(''.join(email)) print(len(emails))
81633adb55a7c22aba8fffe6d05d34f8eb9f17e4
NishadSoney/Class---99
/removefiles.py
397
3.53125
4
import time import shutil import os path = input("Enter the folder path") days = 30 days = time.time() doesExist = os.path.exists(path) if(doesExist == True): flcheck = os.path.exists(path) folwalk = os.walk(path) crtime = os.stat(path).st_crtime if(crtime >= days): os.remove(path) shutil.rmtree() else: print("Path does not exist")
8a7f0546ee1706a6aeed8651e46e7b4646cd9615
niezhenchao/Adb_Bat
/class03/example06.py
584
3.859375
4
# -*- coding: utf-8 -*- """ @Time : 2020/10/19 21:38 @Auth : Mr. William 1052949192 @Company :特斯汀学院 @testingedu.com.cn @Function :字典的遍历 """ height = {'youmi': 166, 'will': 185, 'roy': 180, 'tufei': 170, 'kaka': 185} # 需把每个人身高都减1 # # 键的遍历 # for key in height.keys(): # height[key] += 1 # print(height[key]) # # 值的遍历:不能修改内容 # for value in height.values(): # print(value) # 键值对的遍历 for item in height.items(): print(item) for key,value in height.items(): print(','.join((key,str(value))))
b74360aaed9d44d705d74f18f9785b9e62a6a861
Sophorth/mypython_exercise
/ex4.py
681
3.953125
4
print " ------Start Exercise 4, Variable and Name ------" print " " cars = 100 space_in_car = 4.0 drivers = 30 passengers = 90 car_not_driven = cars - drivers car_driven = drivers carpool_capacity = car_driven * space_in_car average_passenger_per_car = passengers / car_driven print "There are ", cars, " cars available." print "There are only", drivers, " drivers available" print "There will be ", car_not_driven, " empty cars today" print "We can transport ", carpool_capacity, " people today" print "We have ", passengers, " to carpool today." print "We need to put about ", average_passenger_per_car, " in each car today." print " " print "-------End of Excersise 4-------"
dc1f0085bea6d00ca495d994dead22baa93bf46b
lecagnois/pyrobotlab
/home/kwatters/DHParamsIK3D.py
2,590
3.59375
4
################################################## # Inverse Kinematics # This is an example to build up a robot arm # using (modified?) DH parameters # then use the InverseKinematics3D service to # compute the forward and inverse kinematics for # the arm. ################################################## from time import sleep from org.myrobotlab.service import InMoovArm from org.myrobotlab.kinematics import DHRobotArm from org.myrobotlab.kinematics import DHLink from org.myrobotlab.kinematics import DHLinkType # Create a robot arm myRobotArm = DHRobotArm() # Lets create a 2 link robot arm # Create the first link in the arm specified by 100,100,0,90 # additionally specify a name for the link which can be used elsewhere. d1 = 100 r1 = 100 theta = 0 alpha = 90 link0 = DHLink("base", d1, r1, theta, alpha) # Create the second link (same as the first link.) d1 = 100 r1 = 100 theta = 0 alpha = 90 link1 = DHLink("link1", d1, r1, theta, alpha) # Add the links to the robot arm myRobotArm.addLink(link0) myRobotArm.addLink(link1) # create the IK3D service. ik3d= Runtime.createAndStart("ik3d", "InverseKinematics3D") # assign our custom DH robot arm to the IK service. ik3d.setCurrentArm(myRobotArm) # print out the current postion of the arm. print ik3d.getCurrentArm().getPalmPosition() # Now, pick a start/end point # and begin moving along a stright line as specified by the start/stop point. # starting point # x , y , z x1 = 100 y1 = 100 z1 = 100 # ending point # x , y , z x2 = 200 y2 = -400 z2 = 100 # how many steps will we take to get there numSteps = 100 # delay between steps (in seconds) (this will control the velocity of the end effector. delay = 0.1 # lets compute how long the path is. # this is the change in x,y,z between the two points # divided up into numSteps, so we know how much to # move in the x,y,z direction for each step. dx = 1.0*(x2 - x1)/numSteps dy = 1.0*(y2 - y1)/numSteps dz = 1.0*(z2 - z1)/numSteps # our starting point for the iteratin # set that to the current x,y,z position curX = x1 curY = y1 curZ = z1 # tell the arm to configure to that point ik3d.moveTo(curX,curY,curZ) # iterate over the 100 steps for i in range(0 , 100): # Increment our desired current position by dx,dy,dz curX+=dx curY+=dy curZ+=dz # tell the ik engine to move to that new point ik3d.moveTo(curX, curY, curZ) # pause for a moment to let the arm arrive at it's destination # smaller delay = faster movement. sleep(delay)
cc5fc2ea309e09d7c60b46a69753a9675e197a91
Coobeliues/pp2_py
/midsummer/d.py
352
3.515625
4
for i in range(int(input())): cnt = 0 s = input().split() if len(s) % 2 == 0 and s[0].istitle() and s[-1].count('3') == 2: for j in range(len(s)): if (j % 2 == 0 and len(s[j]) % 2 != 0) or (j % 2 != 0 and len(s[j]) % 2 == 0): cnt += 1 print('Wow! That is perfect' if cnt == len(s) else 'Seriously?')
0688164d99613e2e3f7b0a979dadcc07962615ad
tamycova/Programming-Problems
/Project_Euler/3.py
712
3.53125
4
# # The prime factors of 13195 are 5, 7, 13 and 29. # # What is the largest prime factor of the number 600851475143 ? def divisible(num, divisor): if num % divisor == 0 and num != divisor: return True def prime(num): divisor = 2 while num > divisor: if divisible(num, divisor): return False divisor += 1 return True def max_prime(num): i = 2 new_num = None while True: if divisible(num, i): new_num = num // i if prime(new_num): return new_num i += 1 NUM = 1000 print(max_prime(NUM)) # w = NUM # for x in range(2, 100000): # if w % x == 0: # w = w / x # print(x)
499179d2284a5945c2593c830f3ddc111f52c7e6
Mikhail713-xph/exp
/calculator.py
821
4.09375
4
a = float(input('Введите значение №1: ')) b = float(input('Введите значение №2: ')) operation = input('Выберите операцию: +, -, /, *, mod, pow, div: ') if operation == '+': print(a + b) elif operation == '-': print(a - b) elif (operation == '/') and (b != 0): print(a / b) elif operation == '/' and b == 0: print('Деление на 0!') elif operation == '*': print(a * b) elif (operation == 'mod') and (b != 0): print(a % b) elif (operation == 'mod') and (b == 0): print('Деление на 0!') elif operation == 'pow': print(pow(a,b)) elif (operation == 'div') and (b != 0): print(a // b) elif (operation == 'div') and (b == 0): print('Деление на 0!') else: print('Выбрнана неверная операция!')
29e18a77024091c8ad965a217855de9b1e292699
aizhansapina/BFDjango
/week1/informatics/While loop/CWe.py
76
3.515625
4
n = int(input()) num = 1 k = 0 while num < n: num *= 2 k += 1 print(k)
a6ec4005fe3c1c871deb5f3206ef3194233413db
idealblack/labs
/utils.py
10,967
3.84375
4
# -*- coding: utf-8 -*- """ Some potentially useful functions you can optionally use in your COMP0088 coding assignments. You are not required to use these functions. If you prefer to write these things your own way, you are welcome to do so. """ import numpy as np import numpy.random import matplotlib import matplotlib.pyplot as plt local_rng = numpy.random.default_rng() # MARK: sampling utilities def make_grid(limits=(-1, 1), num_divisions=10, count=2): """ Generate a grid of all value combinations for `count` variables (parameters or features) where each ranges over the interval specified by `limits` and has `num_divisions` evenly-spaced steps. NB: the last dimension indexes the variables # Arguments limits: a tuple (low, high) specifying the endpoints of the range (same for all vars) num_divisions: how many steps to divide the range into (including endpoints) count: the number of (identically-ranged) variables # Returns X: a (count + 1)-dimensional array, of size num_divisions on the first count dims and size count on the last """ ticks = np.linspace(limits[0], limits[1], num=num_divisions) return np.moveaxis(np.stack(np.meshgrid(*((ticks,) * count), indexing='ij')), 0, -1) def make_random(num_samples=100, limits=(-1, 1), rng=local_rng, count=2): """ Generate a 2D array of uniformly-distributed randomised variable values. NB: the last dimension (of 2) indexes the variables # Arguments num_samples: number of rows to generate limits: tuple (low, high) specifying range of values for all vars rng: an instance of numpy.random.Generator from which to draw random values count: how many vars to generate per sample # Returns: X: a 2 dimensional array of size `num_samples` x `count` (ie, columns are vars and rows are samples) """ scale = limits[1] - limits[0] offset = limits[0] return rng.random((num_samples, count)) * scale + offset def grid_sample(function, count=2, num_divisions=10, limits=(-1,1), rng=local_rng, noise=0): """ Sample a function on a grid, with optional additive Gaussian noise. # Arguments function: the function to sample. it must be able to be called with a single ndarray argument (in which `count` input variables are indexed on the last dimension) and return an appropriately sized array of results. count: the number of variables the function expects in its input array num_divisions: the number of sample points along each variable dimension limits: tuple (low, high) specifying range of values for all vars rng: an instance of numpy.random.Generator from which to draw random values noise: standard deviation of additive Gaussian noise # Returns X: the grid of variable values (indexed on the last dimension) y: an array of the corresponding function values """ X = make_grid(limits, num_divisions, count) y = reshaped_apply(X, function) if noise > 0: y += rng.normal(scale=noise, size=y.shape) return X, y def random_sample(function, count=2, num_samples=100, limits=(-1, 1), rng=local_rng, noise=0): """ Sample a function at random variable values, with optional additive Gaussian noise. # Arguments function: the function to sample. it must be able to be called with a single ndarray argument (in which `count` input variables are indexed on the last dimension) and return an appropriately sized array (vector) of results. count: the number of variables the function expects in its input array num_samples: the total number of points to sample limits: tuple (low, high) specifying range of values for all vars rng: an instance of numpy.random.Generator from which to draw random values noise: standard deviation of additive Gaussian noise # Returns X: a 2D array of variable values, where rows are samples and columns are variables y: an array (vector) of the corresponding function values """ X = make_random(num_samples, limits, rng, count) y = function(X) if noise > 0: y += rng.normal(scale=noise, size=y.shape) return X, y def reshaped_apply(X, func): """ Apply a function to a data array. If X has more than 2 dimensions, all but the last are unwound into matrix rows, and then the results vector y is rewound back into the original shape of those dimensions. The main use case for this is to work with grids generated by `make_grid`. # Arguments X: a table or array of variable values, where the last dimension indexes the values func: a function taking a single 2d array argument and returning a vector # Returns y: a vector or array of function outputs for the features in X, and having a corresponding shape """ rewind = None if len(X.shape) > 2: rewind = X.shape[:-1] X = X.reshape(np.product(rewind), X.shape[-1]) y = func(X) if rewind is not None: y = y.reshape(rewind) return y # MARK: linear model utilities def add_x0(X): """ Prepend a column (or array) of 1s to an array of samples, as a dummy feature representing bias/offset/intercept. # Arguments X: a table or array of variable values, where the last dimension indexes the variables # Returns: X: the table or array with all records prefixed with a constant term x0 """ x0 = np.expand_dims(np.ones(X.shape[:-1], X.dtype), axis=-1) return np.concatenate((x0, X), axis=-1) def affine(X, weights): """ Generic affine function of X computed as X . [weights]^T If the weights vector is 1 longer than the number of features in X, we assume it incudes a bias term in first position, and prepend a corresponding x0 (=1) to X before multiplying. If X has more than 2 dimensions, all but the last are unwound into matrix rows, and then the results vector y is rewound back into the original shape of those dimensions. The main use case for this is to work with grids generated by `make_grid`. # Arguments X: a table or array of variable values, where the last dimension indexes the values weights: a vector of coefficients, either the same length as the last dimension of X, or 1 longer # Returns y: a vector or array of dot products of the input observations with the weights """ if len(weights) == (X.shape[-1] + 1): X = add_x0(X) return reshaped_apply(X, lambda z: z @ weights) # MARK: non-parametric model utilities def vote ( y ): """ Find the class with highest number of predictions in an array. # Arguments y: a vector of predictions # Returns top: the prediction with the highest number of occurrences -- ties are won by the numerically lowest class """ classes, counts = np.unique(y, return_counts=True) return classes[np.argmax(counts)] def gini_impurity ( y ): """ Calculate the Gini impurity for a vector of labels. # Arguments y: a numpy vector of class labels for all set/node elements # Returns g: the Gini impurity value for the vector """ return 1 - np.sum([(np.sum(y==cc)/len(y))**2 for cc in np.unique(y)]) # MARK: plotting utilities def plot_unimplemented ( axes, title='Not implemented', msg='Not implemented' ): """ Display simple message on plots for unanswered questions. # Arguments axes: a Matplotlib Axes object into which to plot title: title for the plot msg: text to display in the plot body # Returns None """ axes.set_title(title) axes.xaxis.set_visible(False) axes.yaxis.set_visible(False) axes.text(0.5, 0.5, msg, horizontalalignment='center',verticalalignment='center', color='grey', fontsize='xx-large', fontweight='black', rotation=30) def plot_classification_map ( axes, classifier, X=None, y=None, limits=(-5, 5), resolution=30, title='Classification Map', legend_loc='upper left', ): """ Utility function to test a trained classifier on a grid and display the "map" of predictions, optionally also plotting the training data points if provided. # Arguments axes: a Matplotlib Axes object into which to plot classifier: a classifier function taking a single array of sample data in standard X format and returning a vector of predicted labels X: an array of sample data, where rows are samples and the single column is the input feature. y: vector of output values corresponding to the rows of X limits: a tuple (low, high) specifying the value range to test for both feature dimensions resolution: number of samples across and down the grid title: a title for the plot legend_loc: where to put the legend, or None to omit it # Returns None """ # colour & marker scheme supports up to 10 classes, though # plots will likely be pretty unintelligible with that many darks = [plt.cm.tab20.colors[2 * ii] for ii in range(10)] lights = [plt.cm.tab20.colors[2 * ii + 1] for ii in range(10)] marks = ['o', 'v', '*', 'x', '+', 's', 'D', '^', 'h', '2'] # this Brewer colour scheme is meant to be accessible, but # class 2 light looks very similar to class 1 under some # simulated colour vision deficiencies, so we fudge it to be # more distinguishable lights[2] = (0.7, 1.0, 0.7) grid = make_grid(limits=limits, num_divisions=resolution) pred_y = reshaped_apply(grid, classifier) if y is None: nclass = int(np.max(pred_y)) + 1 else: nclass = int(np.max([np.max(pred_y), np.max(y)])) + 1 fillmap = matplotlib.colors.ListedColormap(lights[:nclass]) axes.imshow(pred_y.T, origin='lower', extent=limits * 2, cmap=fillmap) if (X is not None) and (y is not None): for cc in np.unique(y): axes.scatter(X[y==cc,0], X[y==cc,1], color=darks[cc], marker=marks[cc], label=cc, alpha=0.8) axes.set_title(title) axes.set_xlabel('$x_1$') axes.set_ylabel('$x_2$') if legend_loc is not None: axes.legend(loc=legend_loc)
e60e4e6a08507f0343e641deba221bc79cb2944f
himmannshu/Tic-Tac-Toe-AI
/tictactoe.py
3,657
3.890625
4
""" Tic Tac Toe Player """ import math import copy X = "X" O = "O" EMPTY = None def initial_state(): """ Returns starting state of the board. """ return [[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]] def player(board): """ Returns player who has the next turn on a board. -> Returns O if the game is over. """ x_count = count_actions(board)[0] o_count = count_actions(board)[1] if x_count == o_count + 1: return O elif x_count == o_count: return X def count_actions(board): """ Returns the number of X's and O's as a tuple. """ x_count = 0 o_count = 0 for row in board: for action in row: if action == X: x_count += 1 elif action == O: o_count += 1 return (x_count, o_count) def actions(board): """ Returns set of all possible actions (i, j) available on the board. """ actions_set = set() actions = () for i in range(3): for j in range(3): if board[i][j] == EMPTY: action = (i,j) actions_set.add(action) return actions_set def result(board, action): """ Returns the board that results from making move (i, j) on the board. Still need to figure out how to raise exceptions. """ new_board = copy.deepcopy(board) turn = player(board) #print(turn) if new_board[action[0]][action[1]] == EMPTY: new_board[action[0]][action[1]] = turn else: print("Illegal Move") return new_board def winner(board): """ Returns the winner of the game, if there is one. """ for i in range(3): if board[i][0] == board[i][1] and board[i][1] == board[i][2]: return board[i][0] if board[0][i] == board[1][i] and board[1][i] == board[2][i]: return board[0][i] if board[0][0] == board[1][1] and board[0][0] == board[2][2]: return board[0][0] if board[0][2] == board[1][1] and board[0][2] == board[2][0]: return board[0][2] return None def terminal(board): """ Returns True if game is over, False otherwise. """ x = count_actions(board)[0] o = count_actions(board)[1] if x + o == 9: return True if winner(board) == X or winner(board) == O: return True return False def utility(board): """ Returns 1 if X has won the game, -1 if O has won, 0 otherwise. """ if winner(board) == X: return 1 elif winner(board) == O: return -1 else: return 0 def minimax(board): """ Returns the optimal action for the current player on the board. """ move = () if terminal(board): return None if player(board) == X: move = maxvalue(board) else: move = minvalue(board) #print(move) return move[1] def maxvalue(board): """ """ if terminal(board): return utility(board), (None, None) v = float("-inf") next_x = () for action in actions(board): #v = max(v, minvalue(result(board, action))) temp = minvalue(result(board, action)) if temp[0] > v: v = temp[0] next_x = action return v, next_x def minvalue(board): """ """ if terminal(board): return utility(board), (None, None) v = float("inf") next_o = () for action in actions(board): temp = maxvalue(result(board, action)) if temp[0] < v: v = temp[0] next_o = action return v, next_o
cd14b77946e673202f64c7befa6d7e4706e4d5eb
wmentzer/Python-Programs
/userInput.py
183
4.28125
4
# Asks user for input and prints to console name = input("Please enter your name: ") print("Your name is: " + name) print(4 * "name") print(str(5) + "name") print(4 * name)
316bacbc2f868d9f288c12f32426ad9954b26e16
ECESeniorDesign/lazy_record
/lazy_record/typecasts.py
166
3.59375
4
"""Functions to convert objects to a type""" def date(datetime): # may get more complexity later return datetime def datetime(datetime): return datetime
5bd43106071a675af17a6051c9de1f0cee0e0aec
abhaj2/Phyton
/cycle-2/3_c.py
244
4.125
4
wordlist=input("Enter your word\n") vowel=[] for x in wordlist: if('a' in x or 'e' in x or 'i' in x or 'o' in x or'u' in x or 'A' in x or 'E' in x or 'I' in x or 'O'in x or"U" in x): vowel.append(x) print(vowel)
d31440ca53d5c511853301b66e838875974e66eb
arunvijay211/pypro
/numberofdigitsofint.py
113
3.640625
4
count=0 N=input() print("Input:") print(N) while N>0: N=N/10 count=count+1 print("Output:") print(count)
357ac7d71898d8bbd4d3384d59e60834757505e6
sodamodo/cs_exercises
/bf_interpreter.py
2,423
4.15625
4
""" > increment the data pointer (to point to the next cell to the right). < decrement the data pointer (to point to the next cell to the left). + increment (increase by one) the byte at the data pointer. - decrement (decrease by one) the byte at the data pointer. . output the byte at the data pointer. , accept one byte of input, storing its value in the byte at the data pointer. [ if the byte at the data pointer is zero, then instead of moving the instruction pointer forward to the next command, jump it forward to the command after the matching ] command. ] if the byte at the data pointer is nonzero, then instead of moving the instruction pointer forward to the next command, jump it back to the command after the matching [ command. """ program_string = '+[,.]' program_list = split(program_string) data_array = [0] data_pointer = 0 instruction_pointer = 0 def increment_bit(data_pointer): if (data_array[data_pointer] == 255): data_array[data_pointer] = 0 instruction_pointer += 1 else: data_array[data_pointer] += 1 instruction_pointer += 1 def decrement_bit(data_pointer): if (data_array[data_pointer] == 0): data_array[data_pointer] = 255 else: data_array[data_pointer] -= 1 def find_close_brakcet(instruction_pointer): search_pointer = instruction_pointer while (program_list[search_pointer] != ']'): search_pointer += 1 return search_pointer + 1 # #### Build jump table # for instruction in program_list: jump_list = [] for instruction in program_list: if (instruction == '['): while (instruction_pointer < len(program_list)): if (program_list[instruction_pointer] == "+"): increment_bit(data_pointer) elif (program_list[instruction_pointer] == "-"): decrement_bit(data_pointer) elif (program_list[instruction_pointer] == ">"): data_array.append(0) data_pointer += 1 elif (program_list[instruction_pointer] == "<"): if (instruction_pointer == 0): continue instruction_pointer -= 1 elif (program_list[instruction_pointer] == "."): print(data_array[data_pointer]) elif (program_list[instruction_pointer] == ","): data_array[data_pointer] = input(">> ") # elif (program_list[instruction_pointer] == "["): # if data_array[data_pointer] == 0: cmd_input = input(">> ")
b9a82797402387d45a6651895c23810ecda57201
Gasangit/primeras-pruebas-python
/cualquiera.py
1,731
3.8125
4
archivo = open("abrir archivos.txt" , "r") #### lista_nom0 = archivo.readline() #se recuperan los datos de la primera línea del archivo lista_nom0 = lista_nom0.rstrip(",") #se quita la última coma del STRING para poder armar la LISTA lista_nom0 = lista_nom0.split(",") #se divide el STRING por comas para que se transforme en LISTA cambiar0 = " " + lista_nom0[0] #agrega un espacio al primer elemento de la LISTA para que quede alineado lista_nom0.remove(lista_nom0[0]) #remueve el primer elemento de la lista lista_nom0.insert(0 , cambiar0) #inserta el primer elemento modificado en CAMBIAR0 #### lista_nom1 = archivo.readline() #lee la segunda linea del archivo lista_nom1 = lista_nom1.split(",") #convierte la linea (que es un STRING) en una LISTA cambiar1 = " " + lista_nom1[0] #agrega un espacio al primer elemento de la LISTA para que quede alineado lista_nom1.remove(lista_nom1[0]) #remueve el primer elemento de la lista lista_nom1.insert(0 , cambiar1) #inserta el primer elemento modificado en CAMBIAR0 #### personas = "Personas:" lugares = "Lugares:" print("") print(personas.title(), lugares.title().rjust(50," ")) print("") for indice in range(0, len(lista_nom0)): #obtiene los numerós de INDICE de todos los elementos de LISTA_NOM0 print(lista_nom0[indice], lista_nom1[indice].rjust(50," ")) #al ejecutar la ITERACIÓN de LISTA_NOM0 en si misma y en LISTA_NOM1 #se obtienen cada uno de los elementos con el mismo número de INDICE #en dos LISTAS diferentes.