blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
bd1a656c78aa96049d38aa24fdb16299e66609dd
santiago-quinga/Proyectos_Python
/matrix9.py
245
3.765625
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 14 11:13:36 2020 @author: Santiago Quinga """ import numpy as np matrix=np.array([[1,2,3,4,5],[6,7,8,9,10]],dtype=np.int64) print(matrix) print("\n") print("La matriz Tiene: ",matrix.ndim, " dimensiones")
0bf61fd2e18b26a5333a1d7db931f22b5ba0b2a8
LucasLCarreira/Python
/ex004.py
530
4.25
4
# Exercício Python 004: # Faça um programa que leia algo pelo teclado e # mostre na tela o seu tipo primitivo e # todas as informações possíveis sobre ele. a = (input('Digite algo: ')) print('O tipo primitivo deste valor é {}'.format(type(a))) print('É alfabético?',a.isalpha()) print('É numérico?',a.isnumeric()) print('É alfanumérico?',a.isalnum()) print('Só tem espaços?',a.isspace()) print('Está em caixa alta?',a.isupper()) print('Está em caixa baixa?',a.islower()) print('Está capitalizada?',a.istitle())
9e067912c8eb8c8a5c400c8d8b570b35c63e032d
BigBricks/PythonChallenges
/SumNegCountPos.py
233
3.703125
4
def count_positives_sum_negatives(arr): #your code here pos = 0 neg = 0 for x in arr: if x > 0: pos += 1 else: neg += x if arr == []: return [] return [pos, neg]
20b41691fc0593dd0c92bdd689b57e92e23390ad
Lynette-Zhang/Assessment-3
/a3 game.py
3,318
3.515625
4
import pygame, random from pygame.locals import * def print_text(src, font, x, y, text, color=(250,25,200)): imgText = font.render(text, True, color) src.blit(imgText, (x, y)) def game(screen, lives, score): rect_x, rect_y, rect_w, rect_h = 300, 460, 120, 40 ball1_x, ball1_y = random.randint(30, 470), -50 ball2_x, ball2_y = random.randint(30, 470), -50 ball3_x, ball3_y = random.randint(30, 470), -50 vel1_y = 2 vel2_y = 2 vel3_y = 3 white = 255, 255, 255 font = pygame.font.Font(None, 24) while lives: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() if event.type == KEYDOWN: if event.key == K_LEFT: rect_x -= 50 if event.key == K_RIGHT: rect_x += 50 screen.fill(white) if rect_x < 0: rect_x = 0 elif rect_x > 600 - rect_w: rect_x = 600 - rect_w pygame.draw.rect(screen, (30, 0, 0), (rect_x, rect_y, rect_w, rect_h), 0) if ball1_y > 500: lives -= 1 ball1_x, ball1_y = random.randint(30, 470), -50 elif (rect_y - ball1_y) < 30 and ball1_x > rect_x and ball1_x < (rect_x + rect_w): score += 1 vel1_y += score//5 ball1_x, ball1_y = random.randint(30, 470), -50 else: ball1_y += vel1_y pygame.draw.circle(screen, (120, 120, 150), (ball1_x, ball1_y), 30, 0) if ball2_y > 500: lives += 0 ball2_x, ball2_y = random.randint(30, 470), -50 elif (rect_y - ball2_y) < 30 and ball2_x > rect_x and ball2_x < (rect_x + rect_w): score -= 1 vel2_y += score//5 ball2_x, ball2_y = random.randint(30, 470), -50 else: ball2_y += vel2_y pygame.draw.circle(screen, (255, 120, 120), (ball2_x, ball2_y), 30, 0) if ball3_y > 500: lives += 0 ball3_x, ball3_y = random.randint(30, 470), -50 elif (rect_y - ball3_y) < 30 and ball3_x > rect_x and ball3_x < (rect_x + rect_w): score += 3 vel3_y += score//5 ball3_x, ball3_y = random.randint(30, 470), -50 else: ball3_y += vel3_y pygame.draw.circle(screen, (100, 255, 200), (ball3_x, ball3_y), 30, 0) print_text(screen, font, 20, 0, "lives:" + str(lives)) print_text(screen, font, 500, 0, "score:" + str(score)) pygame.display.update() pygame.time.delay(10) return lives, score def main(): pygame.init() pygame.display.set_caption("Watch your Catch") screen = pygame.display.set_mode((600, 500)) lives = 5 score = 0 font2 = pygame.font.Font(None, 24) while True: lives, score = game(screen, lives, score) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() if event.type == MOUSEBUTTONUP: lives = 5 score = 0 screen.fill((255, 255, 255)) print_text(screen, font2, 200, 200, "score:"+str(score)+"...GAME OVER!...") pygame.display.update() main()
4f8847b77e2a7dbff9d2829c889b4d4d23c2ed63
cabrossman/developingInPython
/LSTM3/sequences_vs_states.py
1,548
4.03125
4
from tensorflow.keras.models import Model from tensorflow.keras.layers import Input from tensorflow.keras.layers import LSTM from numpy import array """Return Sequence""" # define model inputs1 = Input(shape=(3, 1)) """ setting return_sequences=True will return a hidden value for each time step This is required when stacking LSTMs You may also need to access the sequence of hidden state outputs when predicting a sequence of outputs with a Dense output layer wrapped in a TimeDistributed layer. """ lstm1 = LSTM(1, return_sequences=True)(inputs1) model = Model(inputs=inputs1, outputs=lstm1) # define input data data = array([0.1, 0.2, 0.3]).reshape((1,3,1)) # make and show prediction -- hidden state print(model.predict(data)) """ Return State Keras provides the return_state argument to the LSTM layer that will provide access to the hidden state output (state_h) and the cell state (state_c). """ inputs1 = Input(shape=(3, 1)) lstm1, state_h, state_c = LSTM(1, return_state=True)(inputs1) model = Model(inputs=inputs1, outputs=[lstm1, state_h, state_c]) # define input data data = array([0.1, 0.2, 0.3]).reshape((1,3,1)) # make and show prediction print(model.predict(data)) """return both state and sequence""" # define model inputs1 = Input(shape=(3, 1)) lstm1, state_h, state_c = LSTM(1, return_sequences=True, return_state=True)(inputs1) model = Model(inputs=inputs1, outputs=[lstm1, state_h, state_c]) # define input data data = array([0.1, 0.2, 0.3]).reshape((1,3,1)) # make and show prediction print(model.predict(data))
6ec43ff02d4ac0f8d3a7333674a6d2032885c416
NikhilPrakashrao/PythonProgramming
/CalculateBMI.py
475
4.28125
4
"""SCOPE: 1:Get the input from user 2:use the input to calculate the Body Mass Index """ height=input("Enter the height in Meters\n") weight=input("Enter the weight in kilograms\n") height=float(height) weight=int(weight) bmi=(weight/(height*height)) print(bmi) if(bmi<16): print("The person is underweight") elif(bmi>16 and bmi<25): print("The person is normal") elif(bmi>25 and bmi<40): print("The person is overweight") else: print("The person is obese")
3c02768e2aec736f2b076f594cd639320671aed2
manueldelatourquintero/weky-bird-en-python
/fisica/Colisiones.py
2,137
3.5625
4
import math from fisica.Punto import Punto class Colisiones: """ Calcula algunas colisiones basicas entre objetos 2D """ def _init_(self, mundo): self.Mundo = mundo def ColisionCirculoRectangulo(self, circulo, rectangulo): """ Comprueba si un circulo colisiona con un rectangulo. No funciona con rectangulos rotados.""" return self.CirculoEnRectangulo(circulo, rectangulo) or \ self.PuntoEnCirculo(rectangulo.Punto0(), circulo) or \ self.PuntoEnCirculo(rectangulo.Punto1(), circulo) or \ self.PuntoEnCirculo(rectangulo.Punto2(), circulo) or \ self.PuntoEnCirculo(rectangulo.Punto3(), circulo) or \ self.PuntoEnRectangulo(Punto(circulo.Centro.X + circulo.Radio, circulo.Centro.Y), rectangulo ) or \ self.PuntoEnRectangulo(Punto(circulo.Centro.X, circulo.Centro.Y + circulo.Radio), rectangulo ) or \ self.PuntoEnRectangulo(Punto(circulo.Centro.X - circulo.Radio, circulo.Centro.Y), rectangulo ) or \ self.PuntoEnRectangulo(Punto(circulo.Centro.X, circulo.Centro.Y - circulo.Radio), rectangulo ) def CirculoEnRectangulo(self, circulo, rectangulo): """ Determina si el centro de un circulo esta dentro de un rectangulo. No funciona con rectangulos rotados.""" return self.PuntoEnRectangulo(circulo.Centro, rectangulo) def PuntoEnRectangulo(self, punto, rectangulo): """ Determina si un punto esta dentro de un rectangulo. No funciona con rectangulos rotados""" return punto.X >= rectangulo.posicion.X and punto.X <= rectangulo.posicion.X + rectangulo.Ancho and punto.Y >= rectangulo.posicion.Y and punto.Y <= rectangulo.posicion.Y + rectangulo.Alto def PuntoEnCirculo (self, punto, circulo): """ Determina si un punto esta dentro de un circulo """ return self.Distancia (punto, circulo.Centro) < circulo.Radio def Distancia(self, punto1, punto2): """ Calcula la distancia entre dos puntos en un espacio 2D""" r1, r2 = punto2.X - punto1.X, punto2.Y - punto1.Y p1, p2 = r1**2, r2**2 return math.sqrt(p1+p2)
f2a75d2f1876ab1d582ba556948a7336b676cc78
Prem-chouhan/fellowshipProgram_PremsinghChouhan
/Programs/datastructure/primenumber.py
551
3.875
4
from datastructure.Utility import prime1 def main(): while True: try: start = int(input("Enter start of the number:- ")) end = int(input("Enter End of the number:- ")) # for i in range(0, 10): prime_num = prime1(start, end) print(f"Prime number in between {start} to {end}") print(prime_num) # start = start + 100 # end = end + 100 except ValueError: print("Sorry....!!! Invalid Input") if __name__ == '__main__': main()
2f2f810576e5526e604e12c8559643d44b48942f
catwang42/Algorithm-for-data-scientist
/valid_palindrome.py
512
3.703125
4
#PROBLEM #maxium remve one char and be palindrome def testPalindrome(): assert validPalindrome('asbcba') is True , "Function error" def validPalindrome(s: str) -> bool: start, end = 0, len(s)-1 while start<end: if s[start] != s[end]: left = s[start+1:end+1] right = s[start:end] return left == left[::-1] or right == right[::-1] #print('left', left) #rint('right',right) start += 1 end -= 1 return True
d819a75c302a40ca4206391e2f7bc8e87bd3544b
bmmtstb/adventofcode
/2022/Day04.py
2,817
3.578125
4
import unittest from typing import Dict, List, Tuple, Set from helper.file import read_lines_as_list Range = Tuple[int, int] RangePair = Tuple[Range, Range] def load_ranges(filepath: str) -> List[RangePair]: """load list from file, get list of two Ranges""" return [( tuple(map(int, range_pair[0].split("-"))), tuple(map(int, range_pair[1].split("-"))) ) for range_pair in read_lines_as_list(filepath=filepath, split=",")] def does_range_fully_contain_range(range_pair: RangePair) -> bool: """return whether r1 does fully contain r2 or vice versa""" r1, r2 = range_pair return (r1[0] >= r2[0] and r1[1] <= r2[1]) or (r2[0] >= r1[0] and r2[1] <= r1[1]) def does_range_overlap(range_pair: RangePair) -> bool: """return whether r1 does overlap with r2""" r1, r2 = range_pair return r2[0] <= r1[0] <= r2[1] or r2[0] <= r1[1] <= r2[1] or r1[0] <= r2[0] <= r1[1] or r1[0] <= r2[1] <= r1[1] def count_fully_containing(ranges: List[RangePair]) -> int: """count all range pairs where one fully contains the other""" return sum(does_range_fully_contain_range(range_pair) for range_pair in ranges) def count_overlapping(ranges: List[RangePair]) -> int: """count all range pairs where one fully contains the other""" return sum(does_range_overlap(range_pair) for range_pair in ranges) class Test2022Day04(unittest.TestCase): test_data = load_ranges("data/04-test.txt") def test_does_range_fully_contain_range(self): for i, contains in [ (0, False), (1, False), (2, False), (3, True), (4, True), (5, True), (6, False), (7, False), (8, False), ]: with self.subTest(msg=f'Pair {i}: {self.test_data[i]}'): self.assertEqual(does_range_fully_contain_range(self.test_data[i]), contains) def test_count_fully_containing(self): self.assertEqual(count_fully_containing(self.test_data), 3) def test_does_range_overlap(self): for i, contains in [ (0, False), (1, False), (2, True), (3, True), (4, True), (5, True), (6, True), (7, True), (8, False), ]: with self.subTest(msg=f'Pair {i}: {self.test_data[i]}'): self.assertEqual(does_range_overlap(self.test_data[i]), contains) def test_count_overlapping(self): self.assertEqual(count_overlapping(self.test_data), 6) if __name__ == '__main__': print(">>> Start Main 04:") puzzle_input = load_ranges("data/04.txt") print("Part 1): ", count_fully_containing(puzzle_input)) print("Part 2): ", count_overlapping(puzzle_input)) print("End Main 04<<<")
6bb7970f618c4c620c3b7d1fa3143cc12d71e6e8
Ashutosh-gupt/HackerRankAlgorithms
/Algorithmic Crush.py
1,690
3.609375
4
""" You are given a list of size N, initialized with zeroes. You have to perform M queries on the list and output the maximum of final values of all the N elements in the list. For every query, you are given three integers a, b and k and you have to add value k to all the elements ranging from index a to b(both inclusive). Input Format First line will contain two integers N and M separated by a single space. Next M lines will contain three integers a, b and k separated by a single space. Numbers in list are numbered from 1 to N. Output Format A single line containing maximum value in the final list. """ __author__ = 'Danyang' class Solution(object): def solve(self, cipher): """ Array, Math, Range Range & Complementary Range [i , j] plus k == [i, +\infty] plus k with [j+1, +\infty] subtract k :param cipher: the cipher """ N, M, queries = cipher qry = [] for query in queries: qry.append((query[0], query[2])) qry.append((query[1] + 1, -query[2])) qry.sort(key=lambda x: (x[0], x[1])) # qry.sort(key=lambda x: x[1]) # secondary attribute maxa = -1 << 32 cur = 0 for q in qry: cur += q[1] maxa = max(maxa, cur) return maxa if __name__ == "__main__": import sys f = open("1.in", "r") # f = sys.stdin N, M = map(int, f.readline().strip().split(' ')) queries = [] for t in xrange(M): # construct cipher queries.append(map(int, f.readline().strip().split(' '))) cipher = N, M, queries # solve s = "%s\n" % (Solution().solve(cipher)) print s,
0c0d5baae7687f50b722f54247f53af00cbc3bfa
Sinoh/CalPoly-CPE-103
/Lab 5/list_queue_tests.py
2,428
3.5
4
import unittest from list_queue import * class TestQueue(unittest.TestCase): def test00_interface(self): test_queue = empty_queue() test_queue = enqueue(test_queue, "foo") peek(test_queue) _, test_queue = dequeue(test_queue) size(test_queue) is_empty(test_queue) def test_reverse(self): test0 = Pair(1,Pair(2,Pair(3))) result1 = Pair(3, Pair(2, Pair(1))) self.assertEqual(reverse(test0), result1) def test_empty_queue(self): self.assertEqual(empty_queue(), Queue()) def test_enqueue(self): test0 = Queue() test1 = Queue(Pair(1)) test2 = Queue(Pair(2, Pair(1))) test3 = Queue(Pair('A', Pair(2, Pair(1)))) self.assertEqual(enqueue(test0, 1), test1) self.assertEqual(enqueue(test1, 2), test2) self.assertEqual(enqueue(test2, 'A'), test3) def test_dequeue(self): test4 = Queue(None, Pair(1, Pair(2, Pair('A')))) test3 = Queue(Pair('A', Pair(2, Pair(1)))) test2 = Queue(Pair(2, Pair(1)), None) test1 = Queue(Pair(1), None) test0 = Queue() self.assertEqual(dequeue(test4), ('A', test2)) self.assertEqual(dequeue(test3), ('A', test2)) self.assertEqual(dequeue(test2), (2, test1)) self.assertEqual(dequeue(test1), (1, test0)) self.assertRaises(IndexError, lambda: dequeue(test0)) def test_peek(self): test0 = Queue(Pair(1, Pair(2, Pair('A')))) test1 = Queue() test2 = Queue(Pair(1, Pair(2, Pair('A'))), Pair('A', Pair(2, Pair(1)))) self.assertEqual(peek(test0), 'A') self.assertEqual(peek(test2), 'A') self.assertRaises(IndexError, lambda: peek(test1)) def test_size(self): test0 = Queue(Pair(1, Pair(2, Pair('A')))) test1 = Queue() self.assertEqual(size(test0), 3) self.assertEqual(size(test1), 0) def test_is_empty(self): test0 = Queue(Pair(1, Pair(2, Pair('A')))) test1 = Queue() self.assertFalse(is_empty(test0)) self.assertTrue(is_empty(test1)) def test_queue(self): test0 = Queue(Pair(1, Pair(2, Pair('A')))) test1 = Queue(Pair(1, Pair(2, Pair('A')))) self.assertEqual(repr(test0), '1, 2, A, None, None') self.assertTrue(test0 == test1) self.assertFalse(test1 == None) if __name__ == "__main__": unittest.main()
65d24accfee45199e65672a065f015a335c9592d
us19861229c/Meu-aprendizado-Python
/ExPyBR/ExESPy010.py
251
3.953125
4
""" 10. Faça um Programa que peça a temperatura em graus Celsius, transforme e mostre em graus Farenheit. """ celcs = float(input("Digite o grau em Celcius: ")) faren = (celcs * 9)/ 5 + 32 print(f"O grau {celcs:.1f}ºC corresponde a {faren}ºF")
47124ad31f35c8246feac9cc6e6c8d7e23e35421
aditi0330/Codecademy-Python-for-Data-Science
/Pandas/Modifying_dataframes.py
1,807
4.03125
4
# Modifying dataframes import pandas as pd df = pd.DataFrame([ [1, '3 inch screw', 0.5, 0.75], [2, '2 inch nail', 0.10, 0.25], [3, 'hammer', 3.00, 5.50], [4, 'screwdriver', 2.50, 3.00] ], columns=['Product ID', 'Description', 'Cost to Manufacture', 'Price'] ) # Add columns here df['Sold in Bulk?'] = ['Yes', 'Yes', 'No', 'No'] print(df) df['Is taxed?'] = 'Yes' print(df) df['Margin'] = df.Price - df['Cost to Manufacture'] #New column df['Lowercase Name'] = df.Name.apply(lower) #return first and last letter of string mylambda = lambda str: str[0]+str[-1] mylambda = lambda x: "Welcome to BattleCity!" if x >= 13 else "You must be over 13" get_last_name = lambda x: x.split()[-1] df['last_name'] = df.name.apply(get_last_name) #If we use apply without specifying a single column and add the argument axis=1, the input to our lambda function will be an entire row, not a column. total_earned = lambda row: (row.hourly_wage * 40) + ((row.hourly_wage * 1.5) * (row.hours_worked - 40)) if row.hours_worked > 40 else row.hourly_wage * row.hours_worked df['total_earned'] = df.apply(total_earned, axis = 1) print(df) # Rename columns here df.columns = ['ID', 'Title', 'Category', 'Year Released', 'Rating'] print(df) # Rename columns here df.rename(columns={ 'name' : 'movie_title' }, inplace=True) orders['shoe_source'] = orders.shoe_material.apply(lambda x: \ 'animal' if x == 'leather'else 'vegan') orders['salutation'] = orders.apply(lambda row: \ 'Dear Mr. ' + row['last_name'] if row['gender'] == 'male' else 'Dear Ms. ' + row['last_name'], axis=1)
034c70b0c8549ca7c7da84b728fe45ac10d0a7c2
HusseinSahib/Egyption-fraction-calculator
/Egyption calculator.py
4,598
4.125
4
#Author: Hussein Sahib #Course: Introduction to programming 142 #Date: December 10 2016 #Program informarion: This program is a Egyption fraction calculator, #it takes a pizza number and number of students then outputs the Egyption fraction for pizza over student. #for extra credit I added a function called extracredit that will give the user, the nearest number practical number if students are are not practical number. import itertools def factor(students): # This function takes the numbers of students and returns it's factors factorList = [] # This for loop will calculate the factors of students. for num in range(1,students+1): dfactor = students / num intfactor = students // num if dfactor == intfactor: factorList.append(num) return factorList def sumsOfSublists(lst): #This function takes the factorList from the number students and out puts the sum of the sublists (sumList) sumList = [] # This for loop sum of the sub List for i in range(2, len(lst)+1): zlist = list(itertools.combinations(lst,i)) for el in zlist: sumList.append(sum(el)) return sorted(sumList) def fraction(factorList,students,pizza): # This function takes in the factor list of students, the number students and the number pizza and returns a print statment for the Egyption fractions. count = 0 strList = [] division = 0 factorList = factorList[::-1] # reverses the List # This for loop will subtract the sublists of the factorList and then append the resulr to strList for num in factorList: if (pizza - num) >= 0: division = int(students/num) strList.append(division) pizza = pizza - num # This for loop will look at each character and prints it in the form of 1/n for char in strList: count += 1 if count == 1: print('1/{} '.format(char), end = '') else: print('+ 1/{} '.format(char), end = '') print() #prints empty line (I used print in this function instead of return because I think it is a shorter way to do it) def extracredit(students): #This function takes in the number of students if it is not a practical number and returns the nearest practical number. count = 0 #This for loop will go throug range student into 100 number bigger than student and then resets count every time it goeses through the loop for num in range(students+1, students+100): count = 0 #This for loop checks if num is a practical number and return it if it is a practical number for char in range(1, num+1): if char in (sumsOfSublists(factor(num)) + factor(num)): count += 1 if count == num: return num def main(): # this is the main function. print('Welcome !') print('We calculate Egiption fractions') repeat = 'y' # this while loop will keep the program going until the user decides to stop. while repeat == 'y': count = 0 pizza = int(input("Enter pizzas: ")) students = int(input("Enter students: ")) if students > pizza and students >= 0 and pizza >= 0 and students == int(students) and pizza == int(pizza): print("Denominator factors: {}".format(factor(students))) # this for loop checks if this student is a practical num then it prints for num in range(1, students+1): if num in (sumsOfSublists(factor(students)) + factor(students)): count += 1 if count == students: # this if it is practical number ELSE print("Students are practical number") fraction(factor(students),students,pizza) else : # it prints this and print("Students are not practical number") print("{} is the nearest practical number".format(extracredit(students))) # runs this function with print statment else: print("You enter invalid pizza or student number") repeat = (input("Do you want to repeat the program? Enter y for yes, anything for no: ")).lower() print('Thank you for using our calcullator, please come again :) ') main() # call main function
830b532d426f9dcf7a5d9f628e145fc217dd24d2
CodeHemP/CAREER-TRACK-Data-Scientist-with-Python
/17_Cleaning Data in Python [Part - 2]/4_cleaning-data-for-analysis/06_custom-functions-to-clean-data.py
2,060
4.15625
4
''' Custom functions to clean data You'll now practice writing functions to clean data. The tips dataset has been pre-loaded into a DataFrame called tips. It has a 'sex' column that contains the values 'Male' or 'Female'. Your job is to write a function that will recode 'Male' to 1, 'Female' to 0, and return np.nan for all entries of 'sex' that are neither 'Male' nor 'Female'. Recoding variables like this is a common data cleaning task. Functions provide a mechanism for you to abstract away complex bits of code as well as reuse code. This makes your code more readable and less error prone. As Dan showed you in the videos, you can use the .apply() method to apply a function across entire rows or columns of DataFrames. However, note that each column of a DataFrame is a pandas Series. Functions can also be applied across Series. Here, you will apply your function over the 'sex' column. INSTRUCTIONS 100XP INSTRUCTIONS 100XP -Define a function named recode_sex() that has one parameter: sex_value. -If sex_value equals 'Male', return 1. -Else, if sex_value equals 'Female', return 0. -If sex_value does not equal 'Male' or 'Female', return np.nan. NumPy has been pre-imported for you. -Apply your recode_sex() function over tips.sex using the .apply() method to create a new column: 'sex_recode'. Note that when passing in a function inside the .apply() method, you don't need to specify the parentheses after the function name. -Hit 'Submit Answer' and take note of the new 'sex_recode' column in the tips DataFrame! ''' import pandas as pd import re tips = pd.read_csv('../_datasets/tips.csv') # Define recode_sex() def recode_sex(sex_value): # Return 1 if sex_value is 'Male' if sex_value == 'Male': return 1 # Return 0 if sex_value is 'Female' elif sex_value == 'Female': return 0 # Return np.nan else: return np.nan # Apply the function to the sex column tips['sex_recode'] = tips.sex.apply(recode_sex) # Print the first five rows of tips print(tips.head())
e413a655a2c9f9ecadd04e0d4b7debf7bc9667f0
ZMbiubiubiu/SwordOffer
/reverse_number.py
888
4
4
""" Flow++ 实习生面试题 """ from functools import reduce # 使用str的内置方法 def reverse1(num:int): # 保存符号 symbal = 1 if num >=0 else -1 num = abs(num) return symbal * int(str(num)[::-1]) # 不使用str方法,使用reduce规约方法 def reverse2(num:int): symbal = 1 if num>= 0 else -1 num = abs(num) tmp = [] while num: tmp.append(num % 10) num //= 10 # 注意这里必须是 // 除法! return symbal * reduce(lambda x,y: 10*x+y, tmp) # 一次循环的方法 def reverse3(num:int): symbal = 1 if num>= 0 else -1 num = abs(num) tmp = 10 sum = 0 while num: sum = sum*tmp + (num % 10) num //= 10 return symbal * sum if __name__ == "__main__": num = 1234 # result = reverse1(num) result = reverse2(num) # result = reverse3(num) print(result)
d1103e1c80899e8c045201219fa7ef8ef50609a4
jonfang/cmpe273-fall17-ChatBot
/hotel.py
1,122
3.796875
4
class Hotel: def __init__(self, name, s, d, l): self.name = name self.dates = {} self.types = {"single": s, "double": d, "luxury": l} def get_name(self): return self.name def book_room(self, start, end, room_type): booked = True while end >= start: booked = booked and self.single_book(end, room_type) if booked is False: msg = "Sorry, this " + room_type + " room has been booked in this time frame" return booked, msg end-=1 msg = "Thank you! This " + room_type + " room is booked" return booked, msg def single_book(self, date, room_type): if date not in self.dates: self.dates[date] = {} if room_type not in self.dates[date]: self.dates[date][room_type] = 0 if self.dates[date][room_type] < self.types[room_type]: self.dates[date][room_type]+=1 #print(date , ": " , "Booked") return True else: #print(date , ": " , "No room available") return False
d54ca7b6bc12baf46e932e9d6e242f7c0a39e55d
alqamahjsr/InterviewBit-1
/06_HeapsAndMaps/n_max_pair_combinations.py
1,814
3.515625
4
# N max pair combinations # https://www.interviewbit.com/problems/n-max-pair-combinations/ # # Given two arrays A & B of size N each. # Find the maximum n elements from the sum combinations (Ai + Bj) formed from elements in array A and B. # # For example if A = [1,2], B = [3,4], then possible pair sums can be 1+3 = 4 , 1+4=5 , 2+3=5 , 2+4=6 # and maximum 2 elements are 6, 5 # # Example: # # N = 4 # a[]={1,4,2,3} # b[]={2,5,1,6} # # Maximum 4 elements of combinations sum are # 10 (4+6), # 9 (3+6), # 9 (4+5), # 8 (2+6) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # class MaxHeap(tuple): def __lt__(self, other): return self[0] > other[0] class Solution: # @param A : list of integers # @param B : list of integers # @return a list of integers def solve(self, A, B): from heapq import heappush, heappop A.sort(reverse=True) B.sort(reverse=True) heap, finished = list(), set() heappush(heap, MaxHeap((A[0] + B[0], (0, 0)))) finished.add((0, 0)) ans = [] for i in range(len(A)): s, idx = heappop(heap) ia, ib = idx ans.append(s) if ia + 1 < len(A) and (ia + 1, ib) not in finished: heappush(heap, MaxHeap((A[ia + 1] + B[ib], (ia + 1, ib)))) finished.add((ia + 1, ib)) if ib + 1 < len(B) and (ia, ib + 1) not in finished: heappush(heap, MaxHeap((A[ia] + B[ib + 1], (ia, ib + 1)))) finished.add((ia, ib + 1)) return ans # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # if __name__ == "__main__": s = Solution() print(s.solve([1, 4, 2, 3], [2, 5, 1, 6]))
1def1cbfa639e5509f57a05c2f51356e3bc33384
Mahmoud-Dinah/data-structures-and-algorithms
/python/code_challenges/graph/graph/graph.py
1,875
3.859375
4
class Vertix: def __init__(self,value): self.value = value class Edge: def __init__(self,vertix, weight=1): self.vertix = vertix self.weight = weight class Graph: def __init__(self): self.adjacency_list = {} def add_vertix(self, value): v = Vertix(value) self.adjacency_list[v] = [] return v def add_edges(self, vertix_first, vertix_end, weight=1): nodes = self.adjacency_list.keys() if not vertix_first in nodes and not vertix_end in nodes: return 'vertix not in the graph' elif not vertix_first in nodes: return ' first vertix are not in the graph' elif not vertix_end in nodes: return 'next vertix is not the graph' edge = Edge(vertix_end,weight) self.adjacency_list[vertix_first].append(edge) def get_nodes(self): array = [] for vertix in self.adjacency_list.keys(): array.append(vertix) if len(array) == 0: return None return array def get_neighbors(self,node): array = [] if node in self.adjacency_list : for edge in self.adjacency_list[node]: array.append((edge.vertix, edge.weight)) return array def size(self): return len(self.adjacency_list.keys()) def __str__(self): output = '' for vertix in self.adjacency_list.keys(): output += vertix.value for edge in self.adjacency_list[vertix]: output += ' -> ' + edge.vertix.value output += '\n' return output if __name__ == "__main__": graph = Graph() first = graph.add_vertix('first') second = graph.add_vertix('second') third = graph.add_vertix('third') graph.get_nodes() # print(graph.get_nodes())
1e5f1146e4c05edc8b0953e893476382f65c8049
Krishnaarunangsu/ArtificialIntelligence
/src/datascience/datahandling/csv_reader.py
1,907
3.765625
4
# Implementing class of FileReader from abc import ABC import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from src.datascience.datahandling.file_reader import FileReader class CSVReader(FileReader, ABC): """ class for specific implementation of reading a csv file """ def __init__(self, csv_file): """ :param csv_file: file """ self.csv_file = csv_file def import_data(self) -> object: """ Import csv data :return dataframe_from_csv: dataframe """ dataframe_from_csv = pd.read_csv(self.csv_file, sep=',') return dataframe_from_csv @staticmethod def understand_data(data_frame): """ :param data_frame: :return: """ print(f'DataFrame Information:\n{data_frame.dtypes}') print('*********************************************************') print(f'DataFrame Exploration:\n{data_frame.describe()}') print('*********************************************************') print(f'Top three:\n{data_frame.head(3)}') print('*********************************************************') print(f'Columns:\n{data_frame.columns}') # show the features and label print('*********************************************************') column_list: list = list(data_frame.columns.values) print(f'Column Names:\n{list(data_frame.columns.values)}') # show the features and label print('*********************************************************') print(f'Shape:{data_frame.shape}') # instances vs features + label (4521, 17) for idx, column_name in enumerate(column_list): print(f'column_list[{idx}]->{column_name}') # sns.set(font_scale=1.5) # countplt = sns.countplot(x='y', data=data_frame, palette='hls') # plt.show()
7ba14438299090997ea4726d665326d7e0631a57
maecchi/PE
/pe112.py
798
3.859375
4
#!/usr/bin/env python #-*- coding: utf-8 -*- # # pe112.py - Project Euler # # 数字(リスト)がはずみ数であるか確認 def isBouncy(nums): is_inc, is_dec = False, False for i in range(len(nums) - 1): if nums[i] < nums[i+1]: is_inc = True elif nums[i] > nums[i+1]: is_dec = True # 増加した状態と減少した状態両方ある場合ははずみ数 # 数字が同じ値が続いた場合は変数がどちらもFalseになるので条件を満たさない if is_inc and is_dec: return True return False n = 21780 percent = 0.9 # 27180の値までのはずみ数の総数は求められる count = n * percent while (percent != 0.99): n += 1 nums = map(lambda x :int(x), list(str(n))) if isBouncy(nums): count += 1 percent = float(count)/n print n
f32c71299fc4da3fa86b1600e5d1c61c27f44ee9
bilalsp/enspired
/enspired/coord/_coord.py
658
3.953125
4
class Coord: """Represent a coordinate of old-format plan matrix.""" def __init__(self, x: int, y: int) -> None: """Create a coordinate for plan-matrix cell. Args: x: x-coordinate y: y-coordinate """ self.x = x self.y = y def __repr__(self) -> str: return "Coord({}, {})".format(self.x, self.y) def __eq__(self, coord): return self.x == coord.x and self.y == coord.y def __add__(self, coord): return Coord(self.x + coord.x, self.y + coord.y) def __sub__(self, coord): return Coord(self.x - coord.x, self.y - coord.y)
ce8052789c365baa87ef34e59bc02dfd06b2985d
fp-computer-programming/cycle-3-labs-p22melsheikh
/lab_3-2.py
244
3.984375
4
# Author MEE 09/29/21 x = int(input(" How many points did the team score")) if x >= 15: print("They won the gold!") elif x >= 12: print("They won the silver!") elif x < 9: print(" No Medal") else: print(" They won bronze")
ff289ebb78de5b82e79a7752846a90d8b9af0c5c
RunningShoes/python_lianxice
/5/5.py
213
3.78125
4
filepath='5.txt' letter=[] str='' with open(filepath) as file: f=file.readline() for line in f: str+=line print(str) letter=str.split(' ') for word in letter: print(word) print(len(letter))
b8fd438a1723b11faad19d37aa509c468489533c
anurag9657/Natural-Language-Processing
/nlp_using_regex.py
11,214
3.640625
4
import nltk as n import re from nltk.corpus import stopwords from nltk.stem import * from nltk.tokenize import RegexpTokenizer from collections import Counter # problem 1 # a) funny = 'colorless green ideas sleep furiously'; print(funny.split()) # b) seq = ''; funny = funny.split() for word in funny: seq += (word[1]) print(seq) # c) phrases = funny[0:3] print(phrases) # d) new_phrases = ' ' print(new_phrases.join(phrases)) # e) funny1 = sorted(funny) for word in funny1: print(word) # Problem 2 def split_sent(str1): counts = dict() words = str1.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 for key in sorted(counts): print("%s: %s" % (key, counts[key])) var = input("Please enter a sentence: ") split_sent(var.lower()) # Problem 3 # a) \b(an|a|the)\b # b) (\d+)([+\-*/]\d+)* # Problem 4 str = """ ... austen-emma.txt:hart@vmd.cso.uiuc.edu (internet) hart@uiucvmd (bitnet) ... austen-emma.txt:Internet (72600.2026@compuserve.com); TEL: (212-254-5093) . .. austen-persuasion.txt:Editing by Martin Ward (Martin.Ward@uk.ac.durham) ... blake-songs.txt:Prepared by David Price, email ccx074@coventry.ac.uk ... """ emails = n.re.findall(r'[\w\.-]+@[\w\.-]+', str) for email in emails: # do something with each found email string print(email) # Problem 5 test_str = open('books.txt', 'r').read() def eliminate_duplicate(test_txt): regex = r"^(.*?)$\s+?^(?=.*^\1$)" subst = "" result = re.sub(regex, subst, test_str, 0, re.MULTILINE | re.DOTALL) return result result = eliminate_duplicate(test_str) out = open('books1.txt', 'w+') out.write(result) out.close() # Problem 7 a) OBAMA = [] ROMNEY = [] LEHRER = [] LEHRER.append('LEHRER:') OBAMA.append('OBAMA:') ROMNEY.append('ROMNEY:') test_str = open('debate.txt', 'r').read() out = open('debate11.txt', 'w') # Regex to remove Crosstalk and audience behavior regex_remove = r"\(CROSSTALK\)|\(APPLAUSE\)|\(inaudible\)|\(LAUGHTER\)" subst = "" test_str = re.sub(regex_remove, subst, test_str, 0, re.MULTILINE | re.DOTALL) # regex to identify sentences spoken by Rmoney regex = r"(?<=LEHRER:)(.*?)(?=OBAMA:|ROMNEY:|LEHRER:|© COPYRIGHT)" matches = re.finditer(regex, test_str, re.MULTILINE | re.DOTALL) for matchNum, match in enumerate(matches): matchNum = matchNum + 1 for groupNum in range(0, len(match.groups())): groupNum = groupNum + 1 LEHRER.append(match.group(1)) # out.writelines("%s\n" % l for l in LEHRER) out.writelines(LEHRER) out.writelines("\n") regex1 = r"(?<=OBAMA:)(.*?)(?=OBAMA:|ROMNEY:|LEHRER:)" matches1 = re.finditer(regex1, test_str, re.MULTILINE | re.DOTALL) for matchNum, match in enumerate(matches1): matchNum = matchNum + 1 for groupNum in range(0, len(match.groups())): groupNum = groupNum + 1 OBAMA.append(match.group(1)) out.writelines(OBAMA) out.writelines("\n") regex2 = r"(?<=ROMNEY:)(.*?)(?=OBAMA:|ROMNEY:|LEHRER:)" matches2 = re.finditer(regex2, test_str, re.MULTILINE | re.DOTALL) for matchNum, match in enumerate(matches2): matchNum = matchNum + 1 for groupNum in range(0, len(match.groups())): groupNum = groupNum + 1 ROMNEY.append(match.group(1)) out.writelines(ROMNEY) out.close() # Problem 7 b) # for lehrer test_str = ' '.join(LEHRER) # remove punctuation test_str = re.sub(r'[^\w\s]', '', test_str) # remove capitalization for f in re.findall("([A-Z]+)", test_str): test_str = test_str.replace(f, f.lower()) # remove stop words pattern = re.compile(r'\b(' + r'|'.join(stopwords.words('english')) + r')\b\s*') test_str = pattern.sub('', test_str) # tokenize the words tokenizer = RegexpTokenizer(r'\w+') test_str = tokenizer.tokenize(test_str) print("\nFor Lehrer:\n") # apply porter stemmer stemmer = PorterStemmer() port_stem = [stemmer.stem(prt) for prt in test_str] print("Porter Stemmer:", ' '.join(port_stem)) # apply snowball stemmer stemmer = SnowballStemmer("english") snow_stem = [stemmer.stem(snows) for snows in test_str] print("Snowball Stemmer:", ' '.join(snow_stem)) # apply lancaster stemmer stemmer = LancasterStemmer() lanc_stem = [stemmer.stem(lanc) for lanc in test_str] print("Lancaster Stemmer:", ' '.join(lanc_stem)) # for obama test_str1 = ' '.join(OBAMA) # remove punctuation test_str1 = re.sub(r'[^\w\s]', '', test_str1) # remove capitalization for f in re.findall("([A-Z]+)", test_str1): test_str1 = test_str1.replace(f, f.lower()) # remove stop words pattern = re.compile(r'\b(' + r'|'.join(stopwords.words('english')) + r')\b\s*') test_str1 = pattern.sub('', test_str1) # tokenize the words tokenizer = RegexpTokenizer(r'\w+') test_str1 = tokenizer.tokenize(test_str1) print("\nFor Obama:\n") # apply porter stemmer stemmer = PorterStemmer() port_stem1 = [stemmer.stem(prt) for prt in test_str1] print("Porter Stemmer:", ' '.join(port_stem1)) # apply snowball stemmer stemmer = SnowballStemmer("english") snow_stem1 = [stemmer.stem(snows) for snows in test_str1] print("Snowball Stemmer:", ' '.join(snow_stem1)) # apply lancaster stemmer stemmer = LancasterStemmer() lanc_stem1 = [stemmer.stem(lanc) for lanc in test_str1] print("Lancaster Stemmer:", ' '.join(lanc_stem1)) # for romney test_str2 = ' '.join(ROMNEY) # remove punctuation test_str2 = re.sub(r'[^\w\s]', '', test_str2) # remove capitalization for f in re.findall("([A-Z]+)", test_str2): test_str2 = test_str2.replace(f, f.lower()) # remove stop words pattern = re.compile(r'\b(' + r'|'.join(stopwords.words('english')) + r')\b\s*') test_str2 = pattern.sub('', test_str2) # tokenize the words tokenizer = RegexpTokenizer(r'\w+') test_str2 = tokenizer.tokenize(test_str2) print("\nFor Romney:\n") # apply porter stemmer stemmer = PorterStemmer() port_stem2 = [stemmer.stem(prt) for prt in test_str2] print("Porter Stemmer:", ' '.join(port_stem2)) # apply snowball stemmer stemmer = SnowballStemmer("english") snow_stem2 = [stemmer.stem(snows) for snows in test_str2] print("Snowball Stemmer:", ' '.join(snow_stem2)) # apply lancaster stemmer stemmer = LancasterStemmer() lanc_stem2 = [stemmer.stem(lanc) for lanc in test_str2] print("Lancaster Stemmer:", ' '.join(lanc_stem2)) # Problem 7 c) # 10 most frequent words by lehrer leh_port = [] leh_snow = [] leh_lanc = [] cap_words = [word.lower() for word in port_stem] word_counts = Counter(cap_words) count = 0 for key in sorted(word_counts, key=word_counts.get, reverse=True): if count < 10: leh_port.append(key) count += 1 cap_words = [word.lower() for word in snow_stem] word_counts = Counter(cap_words) count = 0 for key in sorted(word_counts, key=word_counts.get, reverse=True): if count < 10: leh_snow.append(key) count += 1 cap_words = [word.lower() for word in lanc_stem] word_counts = Counter(cap_words) count = 0 for key in sorted(word_counts, key=word_counts.get, reverse=True): if count < 10: leh_lanc.append(key) count += 1 print("\n10 most frequent words by Lehrer") print("Porter stemmer:", leh_port) print("Snowball stemmer:", leh_snow) print("Lancaster stemmer:", leh_lanc) # 10 most frequent words by obama oba_port = [] oba_snow = [] oba_lanc = [] cap_words = [word.lower() for word in port_stem1] word_counts = Counter(cap_words) count = 0 for key in sorted(word_counts, key=word_counts.get, reverse=True): if count < 10: oba_port.append(key) count += 1 cap_words = [word.lower() for word in snow_stem1] word_counts = Counter(cap_words) count = 0 for key in sorted(word_counts, key=word_counts.get, reverse=True): if count < 10: oba_snow.append(key) count += 1 cap_words = [word.lower() for word in lanc_stem1] word_counts = Counter(cap_words) count = 0 for key in sorted(word_counts, key=word_counts.get, reverse=True): if count < 10: oba_lanc.append(key) count += 1 print("\n10 most frequent words by Obama") print("Porter stemmer:", oba_port) print("Snowball stemmer:", oba_snow) print("Lancaster stemmer:", oba_lanc) # 10 most frequent words by romney rom_port = [] rom_snow = [] rom_lanc = [] cap_words = [word.lower() for word in port_stem2] word_counts = Counter(cap_words) count = 0 for key in sorted(word_counts, key=word_counts.get, reverse=True): if count < 10: rom_port.append(key) count += 1 cap_words = [word.lower() for word in snow_stem2] word_counts = Counter(cap_words) count = 0 for key in sorted(word_counts, key=word_counts.get, reverse=True): if count < 10: rom_snow.append(key) count += 1 cap_words = [word.lower() for word in lanc_stem2] word_counts = Counter(cap_words) count = 0 for key in sorted(word_counts, key=word_counts.get, reverse=True): if count < 10: rom_lanc.append(key) count += 1 print("\n10 most frequent words by Romney") print("Porter stemmer:", rom_port) print("Snowball stemmer:", rom_snow) print("Lancaster stemmer:", rom_lanc) # Problem 7 d) print("\nPorter stemmer to stem positive words:") positive_str = open('positive.txt', 'r').read() stemmer = PorterStemmer() post_stem = [stemmer.stem(prt) for prt in positive_str] positive_stem = ''.join(post_stem) print(positive_stem) # Problem 7 e) # For Lehrer print("10 most positive words used by Lehrer:") port_output = ' '.join(port_stem) elem1 = [x for x in port_output.split()] elem2 = [x for x in positive_stem.split()] elem3 = [] for item in elem1: if item in elem2: elem3.append(item) cap_words = [word.lower() for word in elem3] word_counts = Counter(cap_words) count = 0 elem6 = [] for key in sorted(word_counts, key=word_counts.get, reverse=True): # print(key, word_counts[key]) if count < 10: elem6.append(key) count += 1 print(elem6) # For Obama print("10 most positive words used by Obama:") port_output1 = ' '.join(port_stem1) elem1 = [x for x in port_output1.split()] elem2 = [x for x in positive_stem.split()] elem4 = [] for item in elem1: if item in elem2: elem4.append(item) cap_words = [word.lower() for word in elem4] word_counts = Counter(cap_words) count = 0 elem7 = [] for key in sorted(word_counts, key=word_counts.get, reverse=True): if count < 10: #print(key, word_counts[key]) elem7.append(key) count += 1 print(elem7) # For Romney print("10 most positive words used by Romney:") port_output2 = ' '.join(port_stem2) elem1 = [x for x in port_output2.split()] elem2 = [x for x in positive_stem.split()] elem5 = [] for item in elem1: if item in elem2: elem5.append(item) cap_words = [word.lower() for word in elem5] word_counts = Counter(cap_words) count = 0 elem8 = [] for key in sorted(word_counts, key=word_counts.get, reverse=True): if count < 10: #print(key, word_counts[key]) elem8.append(key) count += 1 print(elem8)
a05700e34fc7c5cfa6cc9f4863d00f4e720d36d0
varunkudva/Programming
/AppleStock.py
1,780
4.1875
4
""" Problem: Write an efficient function that takes stock_prices_yesterday and returns the best profit I could have made from 1 purchase and 1 sale of 1 Apple stock yesterday. The values are the price in dollars of Apple stock. A higher index indicates a later time You must buy before you sell. No shorting Algorithmic Pattern: Greedy -- "Scan once" Approach/Solution: For every scanned current price, find the maximum profit that can be obtained from all the previous prices. This can be done by keeping track of the minimum price up till the current price. Update overall maximum profit. Notes: Compexity: Time: O(n) Space: O(n) Source: https://www.interviewcake.com/question/python/stock-price """ import unittest def get_max_profit(stock_prices): if len(stock_prices) < 2: print("Invalid stock price list") return min_price = stock_prices[0] # this is to return negative profit if stockprices # if stock prices are going down all day max_profit = stock_prices[1] - stock_prices[0] for i in range(1, len(stock_prices)): # calculate profit for current price profit = stock_prices[i] - min_price # calculate max profit max_profit = max(max_profit, profit) # calculate new min price min_price = min(min_price, stock_prices[i]) return max_profit class TestMaxProfit(unittest.TestCase): def test_equals(self): test_input = [[10, 7, 5, 8, 11, 9], [10, 9, 8, 7, 6, 5], [4, 11, 23, 5, 6, 90, 11, 24, 55]] expected_output = [6, -1, 86] for input, expected in zip(test_input, expected_output): self.assertEqual(get_max_profit(input), expected) if __name__ == '__main__': unittest.main()
dd46bec4b487e470c088b9bcb0a9410b54c9c3e5
CodeMrSheep/LeetCode
/triangle.py
570
3.71875
4
# Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. # [ # [2], # [3,4], # [6,5,7], # [4,1,8,3] # ] class Solution(object): def minimumTotal(self, triangle): """ :type triangle: List[List[int]] :rtype: int """ result = 0 n = len(triangle) dp = [0]*(n+1) for i in range(n-1,-1,-1): for j in range(0,i+1): dp[j] = min(dp[j],dp[j+1])+triangle[i][j]; return dp[0]
27e8fba14821523b638dd604077acdaebcfa827b
blinerabytyqi/DS_1819_Gr13
/Four Square Cipher.py
4,392
3.671875
4
alphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y'] #letter Z ommited def getData(): #get data from user dataInput = input() data = [] for char in dataInput.upper(): if char.isalpha(): data.append(char) return ''.join(data) def makeMatrix(key): #creates a char array to be used as a matrix matrix = [] counter = 0 alphaCount = 0 if key == '!': for char in alphabet: matrix.append(char) else: for char in key: matrix.append(char) counter += 1 while (counter < 25): if alphabet[alphaCount] not in key: matrix.append(alphabet[alphaCount]) alphaCount += 1 counter += 1 else: alphaCount += 1 return ''.join(matrix) def printMatrix(matrix): #prints the char array as a matrix counter = 0 for x in range(5): print("\n") for y in range(5): print (matrix[counter], end=' ') counter += 1 print("\n\n") def removeDuplicates(str): #removes duplicates from keys result=[] seen=set() for char in str: if char not in seen: seen.add(char) result.append(char) return ''.join(result) #evaluate function: used to determine which index position on the # mirror matrix the key is located def evaluate(ref1, ref2): return ((int(ref1 / 5) * 5) + (ref2 % 5)) #searches for the position index of the message letter in the ref matrix def search (ref, letter): counter = 0 if letter == 'Z': return -1 for char in ref: if ref[counter] == letter: return counter counter += 1 pass #Encryption function #NOTE need to add a case when message last position is even to append original character def encrypt(message , key1, key2): key1 = removeDuplicates(key1) matrix1 = makeMatrix(key1) key2 = removeDuplicates(key2) matrix2 = makeMatrix(key2) refMatrix = makeMatrix('!') print ("*****Key 1 Block*****") printMatrix(matrix1) print ("*****Key 2 Block****") printMatrix(matrix2) print ("****Reference block*****") printMatrix(refMatrix) encrypted = [] counter = 0 set = [] while (counter < len(message)): aPosition = search(refMatrix, message[counter]) if counter != len(message)-1: bPosition = search(refMatrix, message[counter + 1]) if message[counter] != 'Z': set.append(matrix1[evaluate(aPosition,bPosition)]) else: set.append('Z') if counter == len(message) - 1: return ''.join(set) elif message[counter] != 'Z': set.append(matrix2[evaluate(bPosition,aPosition)]) #set.append(matrix1[evaluate(search(refMatrix,message[counter+1]),search(refMatrix,message[counter]))]) else: set.append('Z') counter += 2 #encrypted.append(set) return ''.join(set) # DECRYPTION function #NOTE need to add a case when message last position is even to append original character def decrypt(message , key1, key2): key1 = removeDuplicates(key1) matrix1 = makeMatrix(key1) key2 = removeDuplicates(key2) matrix2 = makeMatrix(key2) refMatrix = makeMatrix('!') #print ("*****Key 1 Block*****") #printMatrix(matrix1) #print ("*****Key 2 Block****") #printMatrix(matrix2) #print ("****Reference block*****") #printMatrix(refMatrix) #encrypted = [] counter = 0 set = [] while (counter < len(message)): aPosition = search(matrix1, message[counter]) if counter != len(message)-1: bPosition = search(matrix2, message[counter + 1]) if message[counter] != 'Z': set.append(refMatrix[evaluate(aPosition,bPosition)]) else: set.append('Z') if counter == len(message) - 1: return ''.join(set) elif message[counter] != 'Z': set.append(refMatrix[evaluate(bPosition,aPosition)]) #set.append(matrix1[evaluate(search(refMatrix,message[counter+1]),search(refMatrix,message[counter]))]) else: set.append('Z') counter += 2 #encrypted.append(set) return ''.join(set) #main function def main(): print ("****** Four Square Cipher *******\n") print ("Enter Key 1: ", end=' ') key1 = getData() print ("\nEnter Key 2: ", end=' ') key2 = getData() print ("\nEnter the message to encrypt (only A-Z):", end=' ') message = getData() enCr = encrypt ( message, key1 , key2) print ("\nEncrypted message: ") print (enCr) print ("\n\nDecrypted message: ") deCr = decrypt ( enCr, key1 , key2) print (deCr) if __name__ == "__main__": main()
99a894692fe8aecd87f1e5d1f86457b11d188068
arwamais/ArwaTest
/BFS.py
900
4.03125
4
""" create a sample graph as a dictionary Where the key is a node and values are next nodes""" graph = { 'a' : ['b', 'c'], 'b' : ['d', 'e'], 'c' : ['f'], 'd' : [], 'e' : ['f','g'], 'f' : [], 'g' : ['a'] } visited = [] # a list of all visited nodes queue = [] # a temporary list def BFS (visited, graph, s_node ): visited.append(s_node) # s_node is the point where we start our visit queue.append(s_node) while queue: s= queue.pop(0) print (s, end =' ') for next in graph[s]: #visit neighbours of graph[s] if next not in visited: visited.append(next) # if not visited, visit it queue.append (next) # and added to the queue to visit its neighbours print('BFS') BFS(visited, graph, 'a') print()
995e7b273bda99491ff79ee609d080de27911ba2
PranavBharadwaj-1328/SPOJ
/mul.py
207
3.71875
4
def multiply(): n = int(input()) n1 = [] n2 = [] for i in range(0,n): x,y = input().split() n1.append(int(x)) n2.append(int(y)) for i in range(0,n): print(n1[i]*n2[i]) multiply()
a9e9667b811c3f4eeb18c3ef2ba738255a71cc7e
joaovicentefs/cursopymundo2
/aulas/aula16b.py
369
3.921875
4
lanche = ('Hamburger', 'Suco', 'Pizza', 'Pudim') '''for comida in lanche: print(f'Eu vou comer {comida}') print('Comi muito!')''' '''for c in range(0, len(lanche)): print(f'Eu vou comer {lanche[c]}') print('Comi Muito!')''' for pos, comida in enumerate(lanche): # Essa é outra maneira de mostrar o index da Tupla print(f'Eu voou comer {comida} na posição {pos}')
96c4cea09752b5648bb3e16d1c1873422cafb688
rtmonteiro/python
/learning free_code_camp/list.py
456
3.796875
4
lucky_numbers = [4, 8, 5, 9, 12] friends = ["Kevin", "Karen", "Kim", "Kade", "Kuzko"] friends.append("Karol") #adiciona no final friends.insert(1, "Kelly") #adiciona aonde quiser friends.remove("Kim") #remove friends.clear() #limpa tudo friends.pop() #elimina o último friends.index("Kevin") #caça a posição do que quiser friends.count("Kuzao") #conta quantos "" tem na lista friends.sort() friends.reverse() friends2 = friends.copy() print(friends)
db48dcba6bb933cbb77f7b862fda119d32f50a19
ToshikiShimizu/AtCoder
/ARC/001/a.py
257
3.625
4
#coding:utf-8 from collections import Counter n = int(input()) c = list(str(input())) if (Counter(c).most_common()[0][1]==n): least = str(0) else: least = str(Counter(c).most_common()[-1][1]) print (str(Counter(c).most_common()[0][1]) + " " + least)
281b23c5428e0ee5a2db7c2c121ccd318e8ebef8
rdaniela00/proyectos
/python/herencia.py
1,318
3.6875
4
class vehiculos(): def __init__(self, marca, modelo): self.marca=marca self.modelo=modelo self.enmarcha=False self.acelera=False self.frena=False def arrancar(self): self.enmarcha=True def acelearar(self): self.acelera=True def detener(self): self.frena=True def estado(self): print("marca:", self.marca, "\n modelo:", self.modelo, "\n en marcha:", self.enmarcha, "\n en aceleracion", self.acelera,"\n en freno:", self.frena) class furgoneta(vehiculos): def carga(self, cargar): self.cargado=cargar if (self.cargado): return "la furgoneta esta cargafa" else: return"la furgoneta n esta cargada" class moto(vehiculos): hcaballito="" def caballito(self): self.hcaballito="voy haciendo caballito" def estado(self): print("marca:", self.marca, "\n modelo:", self.modelo, "\n en marcha:", self.enmarcha, "\n en aceleracion", self.acelera,"\n en freno:", self.frena, "\n", self.hcaballito) class vElectricos(): def __init__(self): self.autonimia=100 def cargarenergia(self): self.cargando=True class Vbicicleta(vehiculos,vElectricos): pass mibici=Vbicicleta("marips", "hola") mimoto=moto("italika", "CBR") mimoto.caballito() mimoto.estado() mifurgoneta=furgoneta("chevi", "gissaaoa") mifurgoneta.arrancar() mifurgoneta.estado() print(mifurgoneta.carga(True))
bbb439bf93b457f72f3a00924fbdb72e87792a35
Raj6713/Project1
/Graphs/python_scripts/mrl_exponential.py
815
3.9375
4
#Write a program which will create the graph for the mean residual life function and will show it on the screen. import matplotlib.pyplot as plt import numpy as np import math x=np.arange(1e-10,10,0.1) sigma1=2 sigma2=1 sigma3=0.5 sigma4=0.2 y1=[(sigma1*math.exp(-xi/sigma1))/(math.exp(-xi/sigma1)) for xi in x] y2=[(sigma2*math.exp(-xi/sigma2))/(math.exp(-xi/sigma2)) for xi in x] y3=[(sigma3*math.exp(-xi/sigma3))/(math.exp(-xi/sigma3)) for xi in x] y4=[(sigma4*math.exp(-xi/sigma4))/(math.exp(-xi/sigma4)) for xi in x] plt.plot(x,y1) plt.plot(x,y2) plt.plot(x,y3) plt.plot(x,y4) plt.legend(['sigma=2','sigma=1','sigma=0.5','sigma4=0.2'],loc='upper left') plt.xlabel('X-axis') plt.ylabel('$mrl(x)=\sigma*exp(-x/\sigma)/exp(-x/\sigma)$') plt.title('mean residual life for exponential distribution') plt.show()
51a3b795585f4d63f383292a6b0609e6ea94612f
Venky1313/venky-python
/second day.py
59
3.515625
4
x=input("Enter name") y=int(input("Enter age")) print(x,y)
753fd4063bfe966ba037eb542be47ad389111369
ksooklall/Python-Projects
/Pramp/Finding_Duplictes.py
1,103
4.09375
4
""" Given two sorted array find of unequal extreme lengths return all duplicates """ # Since both arry are sorted use binary search on the larger to find # T: O(n*log(m)) <> O(m*log(n)) where log(x) x smallest # S: O(1) def find_duplicates(arr1,arr2): # Determine which array is larger smallest, largest = (arr1,arr2) if len(arr1)<len(arr2) else (arr2,arr1) duplicates = [] # Create an empty array for duplicates for i in smallest: # Go through the smallest list left = 0 right = len(largest)-1 while left<=right: # Apply binary search middle = (right+left)//2 if largest[middle] == i: duplicates.append(i) if largest[middle] > i: right = middle - 1 else: left = middle + 1 return duplicates if len(duplicates)>0 else -1 # Return -1 if none if __name__ == '__main__': arr1 = [1,2,12,23,32,46,57,62,73,84,95,101] arr2 = [1,2,53,56,95] print(find_duplicates(arr1,arr2)) # Ans = [1,2,95]
449cbb57428491d527aa378b3b3937541f063b12
kouddy3004/learnPython
/BasicPython/basicProgramming/genericConcept/thread.py
553
3.59375
4
from threading import * import time class PrintMessage(Thread): lock=Lock() def __init__(self,message): Thread.__init__(self) self.message=message def run(self): for i in range(5): print(str(i)+" time "+self.message) time.sleep(1) startTime=time.perf_counter() messages=["Hello","HI"] objs=[PrintMessage(i) for i in messages] for obj in objs: obj.start() for obj in objs: obj.join() endTime=time.perf_counter() print("Time Taken to complete "+str((int)(endTime-startTime))+"s")
f3bb3a8472197b928b660368854f850f57d2134a
lollocat3/Coding-Challenges
/palindrome.py
529
3.90625
4
import math import numpy as np def digit_finder(num, index): return ((num%10**index)-(num%(10**(index-1))))/(10**(index -1)) def isPalindrome(x): if x < 0: return False for i in range(int(math.floor(len(str(int(x)))/2))): if int(digit_finder(x, i+1)) ==int(digit_finder(x, len(str(x))-i)): continue else: return False return True if __name__ == '__main__': while True: num = int(input('input: ')) if num == 0: break print(isPalindrome(num))
d759712d4c18d72b93a030e6e2b9d14640726087
nangunurimanish/pythonpublic1
/2.py
319
3.96875
4
"""number=['manish',2,'3',4,'5',6,] num=[11,12,13] print(number[1]) number.remove(6) number.pop(2) removed=number.pop() print(removed) print(number) nums=[101,256,348,658,452] nums.sort(reverse=True) print(nums)""" """print('maths' in courses )""" import turtle my_turtle=turtle.Turtle() turtle.done()
d85cc01cf4bc7102f77146bb46c7ffa4e152ac23
salman1819/HackerRank-Problem-Solving
/strange_counter.py
623
3.515625
4
#!/bin/python3 import math import os import random import re import sys # Complete the strangeCounter function below. def strangeCounter(t): lst=[1] temp=1 n=0 while t>=temp: # print('t temp n: ', t, temp, n) lst.append(1+3*(1+2*n)) n=1+2*n temp=lst[-1] print('lst: ', lst) inde=len(lst)-2 print('inde: ', inde, lst[inde]) return ((3*(2**inde))-(t-lst[inde])) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) result = strangeCounter(t) fptr.write(str(result) + '\n') fptr.close()
d35235dab167227393873d917bee3b00164184a9
jakemiller13/School
/MITx 6.00.1x - Introduction to Computer Programming Using Python/fancy_divide.py
2,201
3.875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 30 08:56:56 2017 @author: Jake """ def fancy_divide(numbers,index): try: denom = numbers[index] for i in range(len(numbers)): numbers[i] /= denom except IndexError: print("-1") else: print("1") finally: print("0") print('Fancy Divide') fancy_divide([0, 2, 4], 1) print() fancy_divide([0, 2, 4], 4) print() fancy_divide([0, 2, 4], 0) #index error terminates code print() def fancy_divide2(numbers, index): try: denom = numbers[index] for i in range(len(numbers)): numbers[i] /= denom except IndexError: fancy_divide(numbers, len(numbers) - 1) except ZeroDivisionError: print("-2") else: print("1") finally: print("0") print('Fancy Divide 2') fancy_divide2([0, 2, 4], 1) print() fancy_divide2([0, 2, 4], 4) print() fancy_divide2([0, 2, 4], 0) print() def fancy_divide3(numbers, index): try: try: denom = numbers[index] for i in range(len(numbers)): numbers[i] /= denom except IndexError: fancy_divide(numbers, len(numbers) - 1) else: print("1") finally: print("0") except ZeroDivisionError: print("-2") print('Fancy Divide 3') fancy_divide3([0, 2, 4], 1) print() fancy_divide3([0, 2, 4], 4) print() fancy_divide3([0, 2, 4], 0) print() def fancy_divide4(list_of_numbers, index): try: try: raise Exception("0") finally: denom = list_of_numbers[index] for i in range(len(list_of_numbers)): list_of_numbers[i] /= denom except Exception as ex: print(ex) print('Fancy Divide 4') fancy_divide4([0, 2, 4], 0) print() def fancy_divide5(list_of_numbers, index): try: try: denom = list_of_numbers[index] for i in range(len(list_of_numbers)): list_of_numbers[i] /= denom finally: raise Exception("0") except Exception as ex: print(ex) print('Fancy Divide 5') fancy_divide5([0, 2, 4], 0)
eb95409d7b07b2c20b99cdac06230fc329b1ba9f
Ldarrah/edX-Python
/PythonII/3.3.4 Coding Exercise 2 threewhile.py
829
4.34375
4
mystery_int_1 = 2 mystery_int_2 = 3 mystery_int_3 = 4 #You may modify the lines of code above, but don't move them! #When you Submit your code, we'll change these lines to #assign different values to the variables. #Above are three values. Run a while loop until all three #values are less than or equal to 0. Every time you change #the value of the three variables, print out their new values #all on the same line, separated by single spaces. For #example, if their values were 3, 4, and 5 respectively, your #code would print: # #2 3 4 #1 2 3 #0 1 2 #-1 0 1 #-2 -1 0 #Add your code here max_num = max(mystery_int_1, mystery_int_2, mystery_int_3) count = 0 while count < max_num: mystery_int_1 -= 1 mystery_int_2 -= 1 mystery_int_3 -= 1 print(mystery_int_1, mystery_int_2, mystery_int_3) count += 1
09f58f9f75eeb31b292e6f8e674091e34645956b
wanguishan/leetcode
/209.长度最小的子数组.py
1,525
3.53125
4
# -*- coding: utf-8 -*- """ Created on Sun Aug 19 20:18:54 2018 长度最小的子数组: 给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组。 如果不存在符合条件的连续子数组,返回 0。 ---------------------------------------------------------------------------------------- 示例: 输入: s = 7, nums = [2,3,1,2,4,3] 输出: 2 解释: 子数组 [4,3] 是该条件下的长度最小的连续子数组。 @author: Wan G.S """ class Solution: def minSubArrayLen(self, s, nums): """ :type s: int :type nums: List[int] :rtype: int >> 时间复杂度O(n),空间复杂度O(1) """ start = 0 end = -1 sum = 0 res = float('inf') while start < len(nums): if sum < s and end < len(nums)-1: end += 1 sum += nums[end] else: sum -= nums[start] start += 1 if sum >= s: res = min(res, end-start+1) if res > len(nums): return 0 return res def minSubArrayLen_2(self, s, nums): sum = start = 0 res = float('inf') for end, num in enumerate(nums): sum += num while sum >= s: res = min(res, end-start+1) sum -= nums[start] start += 1 if res > len(nums): return 0 return res
e7a0b2926677495bb55511eb6b08c359fb95e99f
erwin-willems/adventofcode
/day3a/solution.py
233
3.5625
4
#!/usr/bin/env python3 list = open("input.txt").readlines() count = 0 pos = 0 # Skip first line list.pop(0) for line in list: pos += 3 if pos>30: pos = pos - 31 if line[pos]=="#": count += 1 print(count)
beac30b9f0dec0e85dfea71ffdd917c92fff8197
robin9804/RoadToDeepLearningKing
/Jinu/week1/problem93.py
406
3.703125
4
print('네 수를 입력하세요 :', end= ' ') a = int(input()) b = int(input()) c = int(input()) d = int(input()) # 어떻게 한 줄에 입력을 다 받지?? aver = float((a + b + c + d) / 4) def aa(x): res = (x - aver) ** 2 return res boonsan = float((aa(a) + aa(b) + aa(c) + aa(d)) / 4) print("평균 : {}".format(aver)) print("분산 : {}".format(boonsan))
0b7be685c0e24091ac9a644ccb358f168a806406
lucascantos/stocks
/src/functions/execution.py
786
3.515625
4
''' Once decided which asset, if the asset is worth it and how much to buy/sell, Theses strategies decide the best way to implement the action ''' import pandas as pd from src.functions.trends import moving_average def twap(df): ''' time weighted average price effect, reduce impact on market avg(open,close,low,high) avg_28days = avg(avg_day[1...28]) if order_price > avg28: return overvalued else: return undervalued Ou seja...dividir meu order de 10**100 em pedaços onde o pedaçoe seja proximo ao avg28 ''' data = { 'daily_twap': df[['close', 'open', 'low', 'high']].mean(axis=1) } data.update({'twap': moving_average(data['daily_twap'],28,None)}) return pd.DataFrame(data) def vwap(df): pass
a0984657e3caa8413657f4bef93402d92eea417f
punchabird/Learn-Python-The-Hard-Way
/my_adventure_game.py
7,130
4.125
4
from textwrap import dedent from sys import exit class Engine(object): def __init__(self, scene_map): self.scene_map = scene_map def play(self): current_scene = self.scene_map.opening_scene() last_scene = self.scene_map.next_scene('finished') while current_scene != last_scene: next_scene_name = current_scene.enter() current_scene = self.scene_map.next_scene(next_scene_name) #something about being sure to print out the last scene current_scene.enter() class Scene(object): def enter(self): print("This scene is not yet configured.") print("Subclass it and implement enter().") class Death(Scene): def enter(self): print("You died!") exit(1) class GameStart(Scene): def enter(self): print(dedent(""" Someone told you that there's a portal to an alternate dimension in this abandoned house at the end of the road in your neighborhood. Not sure what to think but ever the inquisitive type, you decide to check it out. Searching the bedrooms and living room hasn't turned anything up but cobwebs and dust. The last place left is the kitchen... """)) action = input("DO you head to the kitchen?> ") if action == "yes": return 'Kitchen' else: print("You walk out the front door and head home.") exit(1) class Kitchen(Scene): def enter(self): print(dedent(""" It's a pretty small kitchen you've stumbled into. Next to a short countertop with a sink and faucet is an old electric range with oven, as well as a small fridge with a few notes stuck on. Off to the left is the dining table, on top of which sits the remnants of an evening meal, and a small black book. Looks like there's also a door that leads downstairs, just to the right. """)) action = input("Care to look around?> ") if action == "fridge": print(dedent(""" You sift through the notes on the fridge. It looks like there isn't anything of significance - grocery lists, passive-aggressive reminders, phone numbers....and a note that simply says 'Coke 2821'. """)) return 'Kitchen' elif action == "book": print(dedent(""" You flip open the black book on the table. It appears to be a journal of some sort. Written in black ink on cream-colored paper, someone has written the words: UNIVERSE PORTAL all journals to activate it is """)) return 'Kitchen' elif action == "sink": print(dedent(""" Nothing to see here. Just an old sink. """)) return 'Kitchen' elif action == "range": print(dedent(""" Old stovetop. Used recently and still in good shape. """)) return 'Kitchen' elif action == "door": print(dedent(""" Looks like this door leads down into the basement. Time to see what's down there! """)) return 'Basement' else: print(dedent(""" Not quite sure what that means. """)) return 'Kitchen' class Basement(Scene): def enter(self): print(dedent(""" The basement downstairs is surprisingly bare. A ratty green couch occupies the center of the room facing directly opposite a television. Off to the left is a vending machine. """)) action = input("Where do you look?> ") if action == "vending machine": print(dedent(""" You decide to check out the vending machine. """)) return 'SecurityDoor' elif action == "couch": print(dedent(""" Nothing to see except an old green couch - but wait! Jammed in between the cushions you see another black book. Flipping past the first few pages, you find more scribbles. Among them is a single phrase circled in bold red ink: Wednesday my dudes """)) return 'Basement' elif action == "television": print(dedent(""" You try pressing the power button for the television, but nothing comes on. """)) return 'Basement' else: print(dedent(""" Not quite sure what that means. Try something else. """)) return 'Basement' class PortalRoom(Scene): def enter(self): global FailedAttempts FailedAttempts = 0 print(dedent(""" The vending machine turned secret door swung wide to reveal a hidden passageway. At the end of the tunnel is a room with a large ring in the center, large enough to fit a house through.)) Just a few feet in front of the portal is a console with a computer screen and keyboard. You turn it on and the following words light up: UNIVERSE PORTAL ACTIVATION PROTOCOL ENTER PASSPHRASE IN TERMINAL """)) SelfDestruct = False while True: action = input("> ") if action == "It is Wednesday my dude": print(dedent(""" Holy shit! it looks like that was the correct action. The portal lights up and starts humming loudly. A bright green vortex begins spinning in the center of the ring... """)) return 'PortalEnd' elif action != "It is Wednedsay my dude" and not SelfDestruct: print(dedent(""" That doesn't appear to be the right passphrase. According to the terminal, you have one more attempt remaining...""")) SelfDestruct = True elif action != "It is Wednesday my dude" and SelfDestruct: print(dedent(""" Looks like you might have tried the code too many times. The console makes a loud beeping noise, then you're engulfed in a flash of light and hear a bang... """)) return 'Death' class PortalEnd(Scene): def enter(self): print(dedent(""" As the green vortex expands, you feel an unseen force tugging you towards its center. Lifted off your feet, you are sucked through the portal.... """)) return 'Death' class SecurityDoor(Scene): def enter(self): print(dedent(""" You find yourself standing in front of what appears to be a vending machine. Something isn't quite right about how it sits on the floor, though. The way it's placed feels like it swings on a hinge - almost like a door? Maybe thumbing a code into the keypad could work. """)) action = input("> ") if action == "2821": print(dedent(""" You type in the code '2821', and cross your fingers. The vending machine lets out a loud hissing noise, then slowly swings open to reveal a hidden passageway. It's a door! Now that a path is open, you run through to see what's inside. """)) return 'PortalRoom' else: print(dedent(""" You press some numbers on the vending machine, but nothing seems to have happened. Maybe try another? """)) return 'SecurityDoor' class Map(object): scenes = { 'GameStart': GameStart(), 'Kitchen': Kitchen(), 'Basement': Basement(), 'SecurityDoor': SecurityDoor(), 'PortalRoom': PortalRoom(), 'PortalEnd': PortalEnd(), 'Death': Death() } def __init__(self, start_scene): self.start_scene = start_scene def next_scene(self, scene_name): val = Map.scenes.get(scene_name) return val def opening_scene(self): return self.next_scene(self.start_scene) a_map = Map('GameStart') a_game = Engine(a_map) a_game.play()
618f42d39cf54e4060230196364b5d92f4d3f909
JKLee6470/Deep_learning_from_scratch-
/computational_graph/mul_layer.py
936
4.28125
4
#곱셈 계층과 덧셈 계층의 구현 class MulLayer: def __init__(self): self.x = None self.y = None #순전파시의 x 와 y의 값을 전역변수로 저장하는 것은, backpropagation시 x 와 y를 사용하기 때문! def forward(self,x,y): self.x = x self.y = y out = x * y return out def backward(self, dout): dx = dout * self.y dy = dout * self.x return dx, dy apple = 100 apple_num = 2 tax = 1.1 #계층 mul_apple_layer = MulLayer() mul_tax_layer = MulLayer() #forward propagation apple_price = mul_apple_layer.forward(apple, apple_num) total_price = mul_tax_layer.forward(apple_price, tax) print(total_price) #back propagation dprice = 1 #상류에서 오는 신호값. dapple_price, dtax = mul_tax_layer.backward(dprice) dapple, dapple_num = mul_apple_layer.backward(dapple_price) print(dapple, dapple_num, dtax)
073dcb8168623d2dfdfb65d2bb0432149fb4b180
gbuchdahl/term_blackjack
/card.py
842
3.90625
4
import typing class Card: def __init__(self, num: int, suit: str): self.num = num self.suit = suit # a function that translates card numbers to names def get_name(self) -> str: if self.num == 11: return "J" if self.num == 12: return "Q" if self.num == 13: return "K" if self.num == 1: return "A" else: return str(self.num) def get_value(self) -> int: if self.num == 11 or self.num == 12 or self.num == 13: return 10 if self.num == 1: return 11 else: return self.num def get_suit(self) -> str: return self.suit # driver function for testing if __name__ == "__main__": print(Card(12, "c").print_little()) print(Card(1, "h"))
36a4194e13d5637f85cf7dc691cb861d9891b836
rongzhen-chen/optimization
/optimization.py
10,944
3.640625
4
import time, random, math import numpy as np import matplotlib.pyplot as plt def getminutes(t): x = time.strptime(t,'%H:%M') return x[3]*60+x[4] def printschedule(r): for d in range(len(r)/2): name = people[d][0] origin = people[d][1] out = flights[(origin,destination)][r[2*d]] ret = flights[(destination,origin)][r[2*d+1]] # print 'Name: {0}; Orig: {1}; Depart: from {2} to {3}; Price: {4}; Return: from {5} to {6}; Price: {7}.'.format(name, origin, out[0], out[1], out[2], ret[0], ret[1], ret[2]) print '%10s%10s %5s-%5s $%3s %5s-%5s $%3s' % (name,origin,out[0],out[1],out[2], ret[0],ret[1],ret[2]) def schedulecost(sol): totalprice=0 latestarrival=0 earliestdep=24*60 for d in range(len(sol)/2): # Get the inbound and outbound flights origin=people[d][1] outbound=flights[(origin,destination)][int(sol[2*d])] returnf=flights[(destination,origin)][int(sol[2*d+1])] # Total price is the price of all outbound and return flights totalprice+=outbound[2] totalprice+=returnf[2] # Track the latest arrival and earliest departure if latestarrival<getminutes(outbound[1]): latestarrival=getminutes(outbound[1]) if earliestdep>getminutes(returnf[0]): earliestdep=getminutes(returnf[0]) # Every person must wait at the airport until the latest person arrives. # They also must arrive at the same time and wait for their flights. totalwait=0 for d in range(len(sol)/2): origin=people[d][1] outbound=flights[(origin,destination)][int(sol[2*d])] returnf=flights[(destination,origin)][int(sol[2*d+1])] totalwait+=latestarrival-getminutes(outbound[1]) totalwait+=getminutes(returnf[0])-earliestdep # Does this solution require an extra day of car rental? That'll be $50! if latestarrival>earliestdep: totalprice+=50 return totalprice+totalwait def randomoptimize(domain,costf,maxiter): best = 999999999 bestr = None for i in range(maxiter): # creat a random solution r = [random.randint(domain[i][0],domain[i][1]) for i in range(len(domain))] cost = costf(r) if cost < best: best = cost bestr = r return r def hillclimb(domain,costf): # Create a random solution sol=[random.randint(domain[i][0],domain[i][1]) for i in range(len(domain))] # Main loop while 1: # Create list of neighboring solutions neighbors=[] for j in range(len(domain)): # One away in each direction if sol[j]>domain[j][0]: neighbors.append(sol[0:j]+[sol[j]-1]+sol[j+1:]) if sol[j]<domain[j][1]: neighbors.append(sol[0:j]+[sol[j]+1]+sol[j+1:]) # See what the best solution amongst the neighbors is current=costf(sol) best=current for j in range(len(neighbors)): cost=costf(neighbors[j]) if cost<best: best=cost sol=neighbors[j] # If there's no improvement, then we've reached the top if best==current: break return sol def randomhillclimb(domain,costf,n): listSol=[] listCost=[] for i in range(5): # Create a random solution sol=[random.randint(domain[i][0],domain[i][1]) for i in range(len(domain))] # Main loop while 1: # Create list of neighboring solutions neighbors=[] for j in range(len(domain)): # One away in each direction if sol[j]>domain[j][0]: neighbors.append(sol[0:j]+[sol[j]-1]+sol[j+1:]) if sol[j]<domain[j][1]: neighbors.append(sol[0:j]+[sol[j]+1]+sol[j+1:]) # See what the best solution amongst the neighbors is current=costf(sol) best=current for j in range(len(neighbors)): cost=costf(neighbors[j]) if cost<best: best=cost sol=neighbors[j] # If there's no improvement, then we've reached the top if best==current: break listSol.append(sol) listCost.append(costf(sol)) print(listSol) print(listCost) indexFinal=listCost.index(min(listCost)) print(listSol[indexFinal]) return listSol[indexFinal] def pltFigs(): plt.figure(1) temp=np.linspace(0.0, 1E4, num=1000) diffDL=100 plt.plot(temp,np.exp(-diffDL/temp),'-o') plt.xlabel('Temperature') plt.ylabel('exp(-(highcost-lowcost)/temperature)') plt.title('highcost-lowcost=100 (fixed value)') # plt.savefig('fig1.png') plt.figure(2) diffDL=np.linspace(-10.0, 1E4, num=1000) temp=100 plt.plot(diffDL,np.exp(-diffDL/temp),'-o') plt.xlabel('highcost-lowcost') plt.ylabel('exp(-(highcost-lowcost)/temperature)') plt.title('temperature=100 (fixed value)') # plt.savefig('fig2.png') plt.show() def annealingoptimize(domain,costf,T=10000.0,cool=0.95,step=1): # Initialize the values randomly vec=[(random.randint(domain[i][0],domain[i][1])) for i in range(len(domain))] while T>0.1: # Choose random one of the indices i=random.randint(0,len(domain)-1) # dir can be among -1, 0, 1 dir=random.randint(-step,step) # Create a new list with one of the values changed vecb=vec[:] vecb[i]+=dir # Control the values in the range if vecb[i]<domain[i][0]: vecb[i]=domain[i][0] elif vecb[i]>domain[i][1]: vecb[i]=domain[i][1] # Calculate the current cost and the new cost # Calculate the probability p ea=costf(vec) eb=costf(vecb) p=np.exp(-(eb-ea)/T) # Core of algorithm if (eb<ea or random.random()<p): vec=vecb # Decrease the temperature T=T*cool return vec def geneticoptimize(domain, costf, popsize=50, step=1, mutprob=0.2, elite=0.2, maxiter=100): # two methods to contruct new vec def mutate(vec): i = random.randint(0,len(domain)-1) if random.random()<0.5 and vec[i]>domain[i][0]: return vec[0:i]+[vec[i]-step]+vec[i+1:] elif vec[i]<domain[i][1]: return vec[0:i]+[vec[i]+step]+vec[i+1:] def crossover(r1,r2): i=random.randint(1,len(domain)-2) return r1[0:i]+r2[i:] pop=[] costV=[] for i in range(popsize): vec=[random.randint(domain[i][0],domain[i][1]) for i in range(len(domain))] pop.append(vec) topelite=int(elite*popsize) for i in range(maxiter): scores=[(costf(v),v) for v in pop if v!=None] scores.sort() ranked=[v for (s,v) in scores] # Select the topelite number of vectors pop=ranked[0:topelite] # Reconstruct popsize number of vectors while len(pop)<popsize: if random.random()<mutprob: c=random.randint(0,topelite) pop.append(mutate(ranked[c])) else: c1=random.randint(0,topelite) c2=random.randint(0,topelite) pop.append(crossover(ranked[c1],ranked[c2])) costV.append(scores[0][0]) return scores[0][1],costV people=[('Seymour','BOS'),('Franny','DAL'),('Zooey','CAK'),('Walt','MIA'),('Buddy','ORD'),('Les','OMA')] destination='LGA' flights={} for line in file('schedule.txt'): origin, dest, depart, arrive, price = line.strip().split(',') flights.setdefault((origin,dest),[]) #save all "origin, dest" and "dest, origin" flights[(origin, dest)].append((depart,arrive,int(price))) domain=[(0,9)]*(len(people)*2) print("domain={0}".format(domain)) ''' #############################################################' s=[1,4,3,2,7,3,6,3,2,4,5,3] print('solution list:{}'.format(s)) print('cost function returns:{}'.format(schedulecost(s))) print('-----------schdule---------') print(printschedule(s)) #############################################################' print('-----------random optimization----------') listIter=[10,100,1000,10000,100000] list_ro=[] for ele in listIter: s=randomoptimize(domain,schedulecost,ele) list_ro.append(schedulecost(s)) plt.plot(listIter,list_ro,'-o') plt.title('Random Optimization') plt.xlabel('Number of Iteration') plt.ylabel('Cost Function') plt.savefig('random_opt.png', bbox_inches='tight') #############################################################' print('-----------hillclimb----------') list_hc=[] for ele in range(100): s=hillclimb(domain,schedulecost) list_hc.append(schedulecost(s)) x=np.linspace(1,100,100) plt.plot(x,list_hc,'-o') plt.title('Hill Climbing') plt.xlabel('Number of Execution') plt.ylabel('Cost Function') plt.savefig('hillclimb_opt.png', bbox_inches='tight') #############################################################' print('-----------randomhillclimb----------') list_rhc=[] for ele in range(100): s=randomhillclimb(domain,schedulecost,5) list_rhc.append(schedulecost(s)) x=np.linspace(1,100,100) plt.plot(x,list_rhc,'-o') plt.title('random-restart Hill Climbing (5 times searching)') plt.xlabel('Number of Execution') plt.ylabel('Cost Function') plt.savefig('randomhillclimb_opt.png', bbox_inches='tight') #pltFigs() #############################################################' print('-----------annealing----------') list_ann1=[] list_ann2=[] valueT=[1000.,5000.,10000.,50000.,100000.] valueC=[0.2,0.5,0.7,0.9,0.99] for i in range(len(valueT)): s1=annealingoptimize(domain,schedulecost,T=valueT[i], cool=0.95) s2=annealingoptimize(domain,schedulecost,T=10000.0, cool=valueC[i]) list_ann1.append(schedulecost(s1)) list_ann2.append(schedulecost(s2)) plt.figure(1) plt.plot(valueT,list_ann1,'-o') plt.title('Annealing varying T, cool=0.95') plt.xlabel('Temperature (T)') plt.ylabel('Cost Function') plt.savefig('anneal_opt_varyingT.png', bbox_inches='tight') plt.figure(2) plt.plot(valueC,list_ann2,'-o') plt.title('Annealing varying Cool, T=10000') plt.xlabel('Cool rate (Cool)') plt.ylabel('Cost Function') plt.savefig('anneal_opt_varyingC.png', bbox_inches='tight') ''' #############################################################' print('-----------genetic----------') numiter=100 x=np.linspace(1,numiter,numiter) list_genopt=[] list_costV=[] for i in range(numiter): s,costV=geneticoptimize(domain,schedulecost,maxiter=numiter) list_genopt.append(schedulecost(s)) list_costV.append(costV) plt.figure(1) plt.plot(x,list_genopt,'-o') plt.title('Genetic Algorithm') plt.xlabel('Number of Execution') plt.ylabel('Cost Function') plt.savefig('gen_opt_1.png', bbox_inches='tight') plt.figure(2) for ele in list_costV: plt.plot(x,ele,'-o') plt.title('Genetic Algorithm') plt.xlabel('Number of Iteration within the Algorithm') plt.ylabel('Cost Function') plt.savefig('gen_opt_2.png', bbox_inches='tight')
7a190365f3f04192a07a0375c6c4262540df27d8
Fernando-Rodrigo/Exercicios
/Ex073.py
968
4.1875
4
"""Crie uma tupla preenchida com os 20 primeiros colocados do Campeonato Brasileiro de Futebol, na ordem de colocação. Depois mostre: a) Apenas os 5 primeiros colocados. b) Os últimos 4 colocados da tabela. c) Uma lista com os times em ordem alfabética. d) Em que posição está o time da Chapecoense.""" times = ('Flamengo', 'Internacional', 'Atlétivo-MG', 'São Paulo', 'Fluminense', 'Grêmio', 'Palmeiras', 'Santos', 'Athletico-PR', 'Bragantino', 'Ceará', 'Corinthians', 'Atlético-GO', 'Bahia', 'Sport', 'Fortaleza', 'Vasco', 'Goiás', 'Coritiba', 'Botafogo') print('Os cinco primeiros colocados da tabela são:') for i in range(0,5): print(f' {i + 1}º {times[i]}') print('Os quatro ultimos colocados da tabela são:') for i in range(16,20): print(f' {i + 1}º {times[i]}') print(f'Os times da lista ordenados em ordem alfabética é {sorted(times)}') print(f'O time do São Paulo está em {times.index("São Paulo") + 1}ª posição.')
a9d574ddddec5ac23c3fa6f9bf95517048ef2eb9
qeedquan/challenges
/poj/3048-max-factor.py
1,371
4.0625
4
#!/usr/bin/env python """ Description To improve the organization of his farm, Farmer John labels each of his N (1 <= N <= 5,000) cows with a distinct serial number in the range 1..20,000. Unfortunately, he is unaware that the cows interpret some serial numbers as better than others. In particular, a cow whose serial number has the highest prime factor enjoys the highest social standing among all the other cows. (Recall that a prime number is just a number that has no divisors except for 1 and itself. The number 7 is prime while the number 6, being divisible by 2 and 3, is not). Given a set of N (1 <= N <= 5,000) serial numbers in the range 1..20,000, determine the one that has the largest prime factor. Input * Line 1: A single integer, N * Lines 2..N+1: The serial numbers to be tested, one per line Output * Line 1: The integer with the largest prime factor. If there are more than one, output the one that appears earliest in the input file. Sample Input 4 36 38 40 42 Sample Output 38 Hint OUTPUT DETAILS: 19 is a prime factor of 38. No other input number has a larger prime factor. Source USACO 2005 October Bronze """ from sympy import * def prestige(a): r, m = 0, 0 for v in a: p = max(primefactors(v)) if m < p: r, m = v, p return r def main(): assert(prestige([36, 38, 40, 42]) == 38) main()
f5e5abcf3ff826f1a5837ba63601d81f44f89b59
geonsoo/HCDE310
/Homeworks/hw1/hw1.py
1,821
3.921875
4
# Geon Soo Park # HCDE 310 # HW1 lst = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] #fname = "test.txt" fname = "/Users/CalebP/CourseFiles/Homeworks/hw2/hw2feed.txt" #fname = raw_input("Please enter a file name: ") numChars = 0 numLines = 0 numWords = 0 file_name = open(fname, 'r') for line in file_name.readlines(): numLines += 1 for word in line.split(): numWords += 1 for chr in line: numChars += len(chr) # output code below is provided for you; you should not edit this print numChars, 'characters' print numLines, 'lines' print numWords, 'words' #fname = "test.txt" fname = "/Users/CalebP/CourseFiles/Homeworks/hw2/hw2feed.txt" #fname = raw_input("Please enter a file name: ") numChars = 0 numLines = 0 numWords = 0 file_name = open(fname, 'r') for line in file_name.readlines(): numLines += 1 for word in line.split(): numWords += 1 for chr in line: numChars += len(chr) # output code below is provided for you; you should not edit this print numChars, 'characters' print numLines, 'lines' print numWords, 'words' otherlst = ['a','b','c','d','e','f','g'] s = "This is a test string for HCDE 310" #Exercise 1 (working with a list): #a.Print the first element of lst print lst[0] #b.Print the last element of otherlst print otherlst[-1] #c.Print the first five elements of lst print lst[0:5] #d.Print the fifth element of otherlst print otherlst[4] #e.Print the number of items in lst print len(lst) #Exercise 2 (working with a string): #a.Print the first four characters of s print s[0:4] #b.Using indexing, print the substring "test" from s print s.split()[3] #c.Print the contents of s starting from the 27th character (H) print s[26:] #d.Print the last three characters of s print s.split()[-1] #e.Print the number of characters in s print len(s)
f96a10aaea7b842b1caf389433576aae9ed46ce0
saurabhsisodia/Project_Euler
/smallest_multiple.py
261
3.578125
4
from math import gcd from collections import defaultdict d=defaultdict(int) def lcm(a,b): g=gcd(a,b) return (a*b)//g l=lcm(1,2) d[1]=1 d[2]=l for _ in range(3,41): l=lcm(_,l) d[_]=l #print(d[20]) t=int(input()) while t>0: n=int(input()) print(d[n]) t-=1
ecef4209f34ada4bee73608c84380f2605c8caf4
mgcristino/Toastmasters
/runChangeDate.py
2,509
3.625
4
#!/usr/bin/python # # Change File Date import argparse import os.path, time, datetime dateFormat = "%Y-%m-%d %H:%M:%S" def is_valid_date(parser, arg): """ Check if arg is a valid file that already exists on the file system. Parameters ---------- parser : argparse object arg : str Returns ------- arg """ try: return datetime.datetime.strptime(arg, dateFormat) except ValueError: parser.error("This is the incorrect date string format. It should be YYYY-MM-DD HH:MM:SS") def is_valid_file(parser, arg): """ Check if arg is a valid date format. Parameters ---------- parser : argparse object arg : str Returns ------- arg """ arg = os.path.abspath(arg) if not os.path.exists(arg): parser.error("The file %s does not exist!" % arg) else: return arg def get_parser(): """Get parser object for script xy.py.""" from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument("-f", "--file", dest="changeFile", type=lambda x: is_valid_file(parser, x), help="File", metavar="FILE", required=True) parser.add_argument("-d", "--date", dest="newDate", type=lambda x: is_valid_date(parser, x), help="New Date using format YYYY-MM-DD HH:MM:SS", metavar="Date", required=True) return parser def printf (format,*args): sys.stdout.write (format % args) def fileExists (file_path): return os.path.exists(file_path) def main(): args = get_parser().parse_args() fileName = args.changeFile print("Last modified: %s" % time.ctime(os.path.getmtime(fileName))) #print("Created: %s" % time.ctime(os.path.getctime(fileName))) modTime = time.mktime(args.newDate.timetuple()) os.utime(fileName, (modTime, modTime)) print("Last modified: %s" % time.ctime(os.path.getmtime(fileName))) #print("Created: %s" % time.ctime(os.path.getctime(fileName))) if __name__ == "__main__": try: main() except KeyboardInterrupt: print('\n')
dbb476461a9685bbb576ba1ad308f90beef3e608
RRedwards/coursework
/05-Principles-Python/a0_2048.py
5,433
3.5625
4
""" Clone of 2048 game. """ import poc_2048_gui import random # Directions, DO NOT MODIFY UP = 1 DOWN = 2 LEFT = 3 RIGHT = 4 # Offsets for computing tile indices in each direction. # DO NOT MODIFY this dictionary. OFFSETS = {UP: (1, 0), DOWN: (-1, 0), LEFT: (0, 1), RIGHT: (0, -1)} def merge(line): """ Helper function that merges a single row or column in 2048 """ result = [] placeholder = 0 last_tile_merged = False for item in line: result.append(0) # merging logic if placeholder > 0\ and item == result[placeholder - 1]\ and item > 0\ and last_tile_merged == False: result[placeholder - 1] += item last_tile_merged = True # sliding logic elif item > 0: result[placeholder] = item placeholder += 1 last_tile_merged = False return result def mk_grid(width, height): """ Initializes grid with 0's """ arr = [ [0 for dummy_col in range(width)]\ for dummy_row in range(height)] return arr class TwentyFortyEight: """ Class to run the game logic. """ def __init__(self, grid_height, grid_width): self.grid_height = grid_height self.grid_width = grid_width self.cells = [] self.reset() top_row = [(0, yyy) for yyy in range(grid_width)] bottom_row = [(grid_height - 1, yyy) for yyy in range(grid_width)] left_col = [(xxx, 0) for xxx in range(grid_height)] right_col = [(xxx, grid_width - 1) for xxx in range(grid_height)] def build_line(start_pos, direction, length): """ builds coordinate list of row or col line from start_pos """ line = [start_pos] for item in range(1, length): line.append((line[item - 1][0] + OFFSETS[direction][0],\ line[item - 1][1] + OFFSETS[direction][1])) return line up_cols = [build_line(item, UP, grid_height) for item in top_row] down_cols = [build_line(item, DOWN, grid_height) for item in bottom_row] left_rows = [build_line(item, LEFT, grid_width) for item in left_col] right_rows = [build_line(item, RIGHT, grid_width) for item in right_col] self.lines = { UP: up_cols,\ DOWN: down_cols,\ LEFT: left_rows,\ RIGHT: right_rows} def reset(self): """ Reset the game so the grid is empty. """ self.cells = mk_grid(self.grid_width, self.grid_height) def __str__(self): """ Return a string representation of the grid for debugging. """ temp = [] for item in self.cells: temp.append(str(item)) return '\n'.join(temp) def get_grid_height(self): """ Get the height of the board. """ return self.grid_height def get_grid_width(self): """ Get the width of the board. """ return self.grid_width def move(self, direction): """ Move all tiles in the given direction and add a new tile if any tiles moved. """ lines_to_move = self.lines[direction] line_values = [[self.get_tile(jjj[0], jjj[1]) for jjj in iii] for iii in lines_to_move] merged_values = [merge(line) for line in line_values] zip_list = [zip(iii[0], iii[1]) for iii in zip(lines_to_move, merged_values)] new_grid = mk_grid(self.grid_width, self.grid_height) for iii in zip_list: for jjj in iii: row = jjj[0][0] col = jjj[0][1] new_grid[row][col] = jjj[1] if self.cells != new_grid: self.cells = new_grid self.new_tile() def new_tile(self): """ Create a new tile in a randomly selected empty square. The tile should be 2 90% of the time and 4 10% of the time. """ if random.randrange(0, 10) > 8: rand_value = 4 else: rand_value = 2 new_pos = self.cell_picker() self.set_tile(new_pos[0], new_pos[1], rand_value) def cell_picker(self): """ Helper function that shuffles empty_cells list and returns first item """ shuffled_list = self.empty_cells() random.shuffle(shuffled_list) return shuffled_list[0] def empty_cells(self): """ Helper function to return list of empty cells """ zeroes = [] for iii in range(self.grid_height): for jjj in range(self.grid_width): if self.cells[iii][jjj] == 0: zeroes.append([iii, jjj]) return zeroes def set_tile(self, row, col, value): """ Set the tile at position row, col to have the given value. """ self.cells[row][col] = value def get_tile(self, row, col): """ Return the value of the tile at position row, col. """ return self.cells[row][col] poc_2048_gui.run_gui(TwentyFortyEight(4, 4))
67ecd8d271d544f71fc4ec3900ee94e884cff378
Zero-opps/CYPPedroRR
/libro/problemas_resueltos/Cap-03/problema3-008.py
528
4.03125
4
NUM= int(input("\nIngresa un número entero positivo: ")) if NUM>0: print(f"\nEl resultado de la conjetura de ULAM en el número {NUM}, es: ") while (NUM!=1): print(f"\n{NUM}") if (-1)**NUM>0: print(f"{NUM}/2 = {NUM/2} ") NUM/=2 else: print(f"({NUM}*3)+1= {NUM*3+1} ") NUM=(NUM*3)+1 print(f"\nEl resultado final de la serie es: '1' .") else: print("\nIngresa un número válido. ") print("-\nFinaliza el programa .")
cd9edd6275b1f68e471d3a70834951fa2281fe6e
JG0328/programacion-ii-python
/queens.py
1,317
3.75
4
class EightQueens: def __init__(self, size): self.size = size self.solutions = 0 self.Start() def Start(self): positions = [-1] * self.size self.PlaceQueen(positions, 0) print("Se han encontrado: " + str(self.solutions) + " soluciones.") def PlaceQueen(self, positions, row): if row == self.size: self.PrintSolution(positions) self.solutions += 1 else: for column in range(self.size): if self.ValidatePlace(positions, row, column): positions[row] = column self.PlaceQueen(positions, row + 1) def ValidatePlace(self, positions, rows, column): for i in range(rows): if positions[i] == column or \ positions[i] - i == column - rows or \ positions[i] + i == column + rows: return False return True def PrintSolution(self, positions): for row in range(self.size): line = "" for column in range(self.size): if positions[row] == column: line += "R " else: line += ". " print(line) print("\n") def Main(): EightQueens(8) Main()
2d8603a4d21955787543691bbeca2bb8858ecb85
Caaddss/livros
/backend.py
2,283
3.609375
4
import sqlite3 import sqlite3 as sql def iniitDB(): database = "minhabiblioteca.db" conn = sqlite3.connect(database) cur = conn.cursor() cur.execute("""CREATE TABLE livros(id INTEGER PRIMARY KEY, titulo TEXT, subtitulo TEXT, editora TEXT, autor1 TEXT, autor2 TEXT, autor3 TEXT, cidade TEXT, ano TEXT, edicao TEXT, paginas TEXT, volume TEXT);""") conn.commit() conn.close() iniitDB() def view(): database = "minhabiblioteca.db" conn = sqlite3.connect(database) cur = conn.cursor() cur.execute("SELECT * FROM livros") for rows in cur.fetchall(): return rows conn.commit() conn.close() def insert (titulo,subtitulo,editora,autor1,autor2,autor3,cidade,ano,edicao,paginas,volume): database = "minhabiblioteca.db" conn = sqlite3.connect(database) cur = conn.cursor() cur.execute("""INSERT INTO livros VALUES(NUll,?,?,?,?,?,?,?,?,?,?,?)""",[titulo,subtitulo,editora,autor1,autor2,autor3,cidade,ano,edicao,paginas,volume]) conn.commit() conn.close() def search(titulo="",subtitulo="",editora="",autor1="",autor2="",autor3="",cidade="",ano="",edicao="",paginas="",volume=""): database = "minhabiblioteca.db" conn = sqlite3.connect(database) cur = conn.cursor() cur.execute("SELECT * FROM livros WHERE titulo=? or subtitulo=? or editora=? or autor1=? or autor2=? or autor3=? or cidade=? or ano=? or edicao=? or paginas=? or volume=?",(titulo,subtitulo,editora,autor1,autor2,autor3,editora,ano,edicao,paginas,volume)) for rows in cur.fetchall(): return rows conn.commit() conn.close() def update(titulo,subtitulo,editora,autor1,autor2,autor3,cidade,ano,edicao,paginas,volume): database = "minhabiblioteca.db" conn = sqlite3.connect(database) cur = conn.cursor() cur.execute("UPDATE livros SET titulo=? or subtitulo=? or editora=? or autor1=? or autor2=? or autor3=? or cidade=? or ano=? or edicao=? or paginas=? or volume=?",(titulo,subtitulo,editora,autor1,autor2,autor3,editora,ano,edicao,paginas,volume,id)) conn.commit() conn.close() def delete(id): database = "minhabiblioteca.db" conn = sqlite3.connect(database) cur = conn.cursor() cur.execute("DELETE FROM livros WHERE id=?",(id,)) conn.commit() conn.close()
b27e94c6e88cf20a267c7a61f2d0241954dca7bb
amirrezamafi/SHAP-integration
/SHAP_integration_v1.py
2,906
3.640625
4
import pandas as pd import numpy as np import shap shap.initjs() def calculate_shap1 (model , data): ''' The input data is a dataframe, consists of only the model`s features columns The shap values by default are toward class_1 Parameters ---------- model: the machine learning model which has been used (ex: RandomForest) data: the dataset which its Shap values is required. data is a dataframe, consists of only the features columns ''' explainer = shap.TreeExplainer(model) shap_values_df = pd.DataFrame(explainer.shap_values(data)[1], columns=((data.columns))) return shap_values_df ''' The function calcule_shap returns a Pandas DataFrame in shape of (number of instance in data , number of features) ''' def calculate_shap2 (model , data, features): ''' The data is a dataframe, consists of all data`s columns (not only the model`s features) Features are specified by a list The shap values by default are toward class_1 Parameters ---------- model: the machine learning model which has been used (ex: RandomForest) data: the dataset which its Shap values is required features: the list of the features of the model ''' explainer = shap.TreeExplainer(model) shap_values_df = pd.DataFrame(explainer.shap_values(data[features])[1], columns=(features)) return shap_values_df ''' The function calcule_shap returns a Pandas DataFrame in shape of (number of instance in data , number of features) ''' def calculate_shap3 (model , data, features, to_class): ''' The data is a dataframe, consists of all data`s columns (not only the model`s features) Features are specified by a list The direction of the shap values (toward class_0 or class_1) must be specified Parameters ---------- model: the machine learning model which has been used (ex: RandomForest) data: the dataset which its Shap values is required features: the list of the features of the model to_class: the class which the Shap values toward it, is required (to_class=0: the output will be the Shap values toward class 0; to_class=1: the output will be the Shap values toward class 1) ''' explainer = shap.TreeExplainer(model) shap_values_df = pd.DataFrame(explainer.shap_values(data[features])[to_class], columns=(features)) return shap_values_df ''' The function calcule_shap returns a Pandas DataFrame in shape of (number of instance in data , number of features) '''
ce5d7e4704fe6e9f70efee21ecc5ecf0794c2708
iCodeIN/data_structures
/sorting/merge_two_sorted.py
1,080
3.625
4
def merge_two_sorted_arrays(A, m, B,n): a, b, write_idx = m - 1, n - 1, m + n - 1 while a >= 0 and b >= 0: if A[a] > B[b]: # fill in at the end A[write_idx] = A[a] a -= 1 else: A[write_idx] = B[b] b -= 1 write_idx -= 1 while b >= 0: A[write_idx] = B[b] write_idx, b = write_idx - 1, b - 1 return A if __name__ == '__main__': # time: O(m+n) # space: O(1) # A contains enough to fit in b, m and n are numbers of initial entires in A and B respectively # key is to start at the end print(merge_two_sorted_arrays([3,13,17,None,None,None,None,None],3,[3,7,11,19],4)) # a=2,b=3,write_idx=6,[3,13,17,None,None,None,None,None] # [3,13,17,None,None,None,19,None],b=2,write_idx=5 # [3,13,17,None,None,17,19,None],a=1,write_idx=4 # [3,13,17,None,13,17,19,None],a=0,write_idx=3 # [3,13,17,11,13,17,19,None],b=1,write_idx=2 # [3,13,7,11,13,17,19,None],b=0,write_idx=1 # [3,3,7,11,13,17,19,None],b=-1,write_idx=0
22025c116d03d1626e8b4c337d035a5c290137ff
fwcd/advent-of-code-2015
/src/day07.py
1,105
3.578125
4
import functools import re def parse_circuit(raw): circuit = dict() @functools.lru_cache def wire(x): try: return int(x) except: return circuit[x]() for x, op, y, dest in re.findall(r'([0-9a-z]+)?\s*([A-Z]+)?\s*(\S+)?\s+->\s+(\w+)\n', raw): if op == 'AND': circuit[dest] = lambda x=x, y=y: wire(x) & wire(y) elif op == 'OR': circuit[dest] = lambda x=x, y=y: wire(x) | wire(y) elif op == 'LSHIFT': circuit[dest] = lambda x=x, y=y: wire(x) << wire(y) elif op == 'RSHIFT': circuit[dest] = lambda x=x, y=y: wire(x) >> wire(y) elif op == 'NOT': circuit[dest] = lambda y=y: ~wire(y) else: circuit[dest] = lambda x=x: wire(x) return circuit with open('resources/day07.txt', 'r') as f: raw = f.read() circuit1 = parse_circuit(raw) part1 = circuit1['a']() print(f"Part 1: {part1}") circuit2 = parse_circuit(raw) circuit2['b'] = lambda: part1 part2 = circuit2['a']() print(f"Part 2: {part2}")
9cf92c3fc95edd2d2bb0178b8472c5be9101003a
vovunku/NeverNote
/task.py
798
3.53125
4
class Task: def __init__(self, date, name, info, complexity, state): # strings, state in lower case self.date = date self.name = name self.info = info self.state = state self.complexity = int(complexity) easy_color = [50, 205, 50] hard_color = [255, 0, 0] self.complexity_rgb = [easy_num + int(self.complexity * (hard_num - easy_num) / 10) for easy_num, hard_num in zip(easy_color, hard_color)] # from lime_green to red def move_right(self): if self.state == "todo": self.state = "doing" elif self.state == "doing": self.state = "done" else: raise ValueError("unable to move") def finish(self): self.state = "finished"
e5d3dc0471a78a81bee10f72f9dbc2ab81808d71
tcarreira/adventofcode
/2020/day-12/solver_1.py
1,488
4.125
4
#!/usr/bin/env python3 import os curdir = os.path.dirname(os.path.realpath(__file__)) # N # W - E # S class Ship: def __init__(self): self.lon = 0 # x self.lat = 0 # y self.direction = 0 # E=0º, N=90º... def get_direction(self): return {0: "E", 90: "N", 180: "W", 270: "S"}[self.direction % 360] def turn(self, direction, degrees): self.direction += { "R": -degrees, "L": degrees, }[direction] def north(self, direction, distance): self.lat += distance def south(self, direction, distance): self.lat -= distance def east(self, direction, distance): self.lon += distance def west(self, direction, distance): self.lon -= distance def forward(self, direction, distance): self.move(self.get_direction(), distance) def move(self, direction, distance): { "R": self.turn, "L": self.turn, "N": self.north, "E": self.east, "S": self.south, "W": self.west, "F": self.forward, }[direction](direction, distance) def main(): ship = Ship() with open(curdir + "/input.txt") as f: for line in f.readlines(): ship.move(line[0], int(line.strip()[1:])) print(f"Position: x={ship.lon} y={ship.lat}") print(f"Manhattan Distance: {abs(ship.lon)+abs(ship.lat)}") if __name__ == "__main__": main()
d136c178450cf488e6ae75cfd62921a0b884cbad
jeevananthanr/Python
/PyBasics/tuples.py
590
3.8125
4
#Tuples #constant/immutable list num_tup=(1,5,'hello','Python',1.5) print num_tup,"->",type(num_tup) num_tup=tuple(range(5,11)) #reassign num_tup=tuple(range(1,11)) print num_tup #num_tup[5]=10 --will throw an error #count print num_tup.count(5) #index print num_tup.index(7) print num_tup.index(7,3) print num_tup.index(7,3,7) #len print len(num_tup) print min(num_tup) print max(num_tup) print sum(num_tup) #slicing print num_tup[1:5] print num_tup[:] print num_tup[4:] print num_tup[:6] print num_tup[::-1] print "------------------------------"
e1e600edfb8923fb855e475ea7963081bd84a07f
jorgeduartejr/Ex-PYTHON
/mundo 2/ex044.py
774
3.96875
4
print('Calculadora de preços') print('--' * 10) valor = float(input('Digite o valor do produto: ')) print('''Escolha uma forma de pagamento: [1] à vista no dinheiro/cheque com 10% de desconto. [2] à vista no cartão com 5% de desconto. [3] em até 2x no cartão (preço normal sem desconto). [4] 3x ou mais no cartao com acréscimo de 20% de juros. ''') opção = int(input('Digite aqui a sua opção: ')) if opção == 1: print('O valor será de {}.' .format(valor - (valor*0.1))) elif opção == 2: print('O valor a ser pago será {}.' .format(valor-(valor*0.05))) elif opção == 3: print('O valor será de {}.' .format(valor)) elif opção == 4: print('O valor será de {}.' .format(valor + (valor*0.2))) else: print('Insira um valor válido')
f606464c72dae12c4825b05b279b73d22e0dd3dc
nlafferty235/iterative-prisoners-dilemma
/1_3_9-10_sourceFiles/Team 3 - Adrian Jacob Ethan.py
1,751
3.734375
4
import random #### # Each team's file must define four tokens: # team_name: a string # strategy_name: a string # strategy_description: a string # move: A function that returns 'c' or 'b' #### team_name = 'E3' strategy_name = 'Trust Meter.' strategy_description = '''Always start with a collude. Next three turns are completly random, no strings attached. Every 5th turn we collude. If they betray on this turn, our trust meter will have a higher probability of betraying. Every 5th turn we collude. If they collude on this turn, our trust meter will have a higher probability of colluding. Trust meter impacts the random choices (after every fifth turn, the following 4 are random.) from this point on. It will still be random, but depending on the opponents choice, we have a higher chance of betrayal/colluding depending on their choice on the every 5th turn. On the 5th iteration of this loop, trust meter resets the data.''' def move(my_history, their_history, my_score, their_score): '''Arguments accepted: my_history, their_history are strings. my_score, their_score are ints. Make my move. Returns c or b.''' if my_history <=4: random.random['c','b'] c_tally, b_tally, errors = trust_meter(my_history, their_history, my_score, their_score) if c_tally > b_tally: return 'c' else: return 'b' def trust_meter(my_history, their_history, my_score, their_score): '''Makes a desicion based on opponent history.''' b_count = 0 c_count = 0 errors = 0 for item in their_history[-5]: if item == 'b': b_count += 1 elif item == 'c': c_count += 1 else: errors += 1 return b_count,c_count,errors
bc49251f67052bdb7c8148da2e395a1377451801
prathamtandon/g4gproblems
/Arrays/rearrange_array_elements.py
790
3.984375
4
import unittest """ Given an array A of size n, where every element is between 0 and n-1, rearrange given array such that A[i] becomes A[A[i]]. Input: 3 2 0 1 Output: 1 0 3 2 """ """ Approach: Frankly, don't really know why it works! 1. Increment each A[i] by (A[A[i]]%n)*n. 2. Divide each A[i] by n. """ def rearrange_array_elements(arr): n = len(arr) for i in range(n): a = arr[i] b = arr[arr[i]] c = a + (b % n)*n arr[i] = c arr = [c / n for c in arr] # To get back original array, do: # arr = [c % n for c in arr] return arr class TestRearrangeArray(unittest.TestCase): def test_rearrange(self): list_of_numbers = [3, 2, 0, 1] self.assertEqual(rearrange_array_elements(list_of_numbers), [1, 0, 3, 2])
d670751b6b6f6e3cc6706a989341dfad82888d9e
dmitryzykovArtis/education
/42.py
1,234
3.5
4
""" Ориентированный граф называется полуполным, если между любой парой его различных вершин есть хотя бы одно ребро. Для заданного списком ребер графа проверьте, является ли он полуполным. Формат входных данных Сначала вводятся числа n ( 1 <= n <= 100) – количество вершин в графе и m ( 1 <= m <= n(n - 1)) – количество ребер. Затем следует m пар чисел – ребра графа. Номера вершин начинаются с 0. Формат выходных данных Выведите «YES», если граф является полуполным, и «NO» в противном случае. """ n, m = list(map(int, input().split(" "))) G = [[0] * n for i in range(n)] for i in range(m): r = list(map(int, input().split(" "))) G[r[0]][r[1]] = 1 def check(G): for i in range(n): for j in range(n): if i != j and G[i][j] < 1 and G[j][i] < 1: return False return True print("YES" if check(G) else "NO")
9950e64291a837adc79494573406ae1c9f463f34
apapiez/clock_challenge
/Alex/tkinterFramework.py
2,984
3.546875
4
# -*- coding: utf-8 -*- """ Created on Sun Apr 16 00:33:52 2017 @author: alexp """ import tkinter as tk import time def labelmaker(_master, _text): return tk.Label(master=_master, text=_text) def callback_adder(_element, _callback): _element["command"] = _callback return class Screen(tk.Frame): """ A screen is defined as a collection of displayable elements which together represent a single contiguous functional unit of display. Screens are constructed using the add elements method, which adds elements to the internal representation of the screen. This screen is then added to the apps list of displayable screens """ def __init__(self, master): self.master = master super(Screen, self).__init__(self.master) self.elements = [] self.callbacks = [] def get_elements(self): return self.elements def add_element(self, _element, _row, _column): element = (_element, _row, _column) self.elements.append(element) return def remove_element(self, _element): self.elements.remove(_element) return def get_callbacks(self): return self.callbacks def add_callback(self, _element, _command): self.callbacks.append(_command) callback_adder(_element, _command) return def remove_callback(self, _element, _callback): self._element["command"] = None self.callbacks.remove(_callback) return class App(tk.Frame): """ The App holds the list of screens and is responsible for any manipulation of those screens, primarily by adding or removing screens from the list of displayable screens (screens) or by invoking the set-active-screen method, which refreshes the elements buffer and populates it with the elements of the new screen """ def __init__(self, master): self.master = master super(App, self).__init__(self.master) self.screens = [] self.active_elements = [] def add_screen(self, screen): self.screens.append(screen) return def remove_screen(self, screen): self.screens.remove(screen) return def set_active_screen(self, screen): #First dispose of any old elements for item in self.active_elements: item[0].grid_forget() #Empty the active elements list self.active_elements = [] #Populate the active elements list with the elements listed #in the individual screens elements list for item in screen.elements: self.active_elements.append(item) #Activate each of the elements now in the active elements list for item in self.active_elements: item[0].grid(row=item[1], column=item[2]) return def ScreenFactory(master): screen = Screen(master) return screen
ee2639c0cf19c34d6e9e8ade7fab6ae2729c7b94
eprj453/algorithm
/PYTHON/BAEKJOON/1316_그룹단어체커.py
584
3.578125
4
ans = 0 alphabets = 'abcdefghijklmnopqrstuvwxyz' for i in range(int(input())): checked = [False] * 26 word = input() # isGroup = True # print(i,"번째") for l in range(len(word)-1): checked[alphabets.index(word[l])] = True # print('{} , {}'.format(word[l], word[l+1])) if word[l] != word[l+1]: # print(checked) if checked[alphabets.index(word[l+1])]: break else: checked[alphabets.index(word[l+1])] = True else: ans += 1 print(ans)
24eec5f0d0bee42161061e8684967bde1705b757
Phoenix-Zura/python-learnings
/4faultycalculator.py
533
4.125
4
op = input("Enter the operation you want to perform:") a = int(input("Enter the number1:")) b = int(input("Enter the number2:")) if op == "*": if a == 45 and b == 3: print("45 * 3 = 555") else: print(a, "*", b, "=", a*b) elif op == "+": if a == 56 and b == 9: print("56 + 9 = 77") else: print(a, "+", b, "=", a+b) elif op == "/": if a == 56 and b == 6: print("56/6 = 4") else: print(a, "/", b, "=", a/b) else: print(a, "-", b, "=", a-b)
2b0640188f973c3ba6358b9bac544f5c712fe92a
KirillRedin/PythonTasks
/Ch2/tax_calc.py
721
4.09375
4
""" Program: tax_calc.py Author: Kirill Redin Last Modified 10.11.2018 This program computes person's tax Pseudocode: gross income = Input gross income number of dependents = Input number of dependents income tax = (gross income - 10000 - number of dependents * 3000) * 0.2 print income tax """ # Initialize the constants TAX_RATE = 0.2 STANDART_DEDUCTION = 10000 ADDITIONAL_DEDUCTION = 3000 #User input gross_income = float(input("Enter your gross income: ")) num_of_dependents = int(input("Enter your number of dependents: ")) #Calculating income tax income_tax = (gross_income - STANDART_DEDUCTION - num_of_dependents * \ ADDITIONAL_DEDUCTION) * TAX_RATE print("Your income tax is:", round(income_tax, 2))
fd25e1cf67132a913359ecbcc5d13eb1374a4f7f
SchlossLab/snakemake_cluster_tutorial
/code/plotcount.py
3,533
3.5
4
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt import sys from collections.abc import Sequence from wordcount import load_word_counts def plot_word_counts(counts, limit=10): """ Given a list of (word, count, percentage) tuples, plot the counts as a histogram. Only the first limit tuples are plotted. """ plt.title("Word Counts") limited_counts = counts[0:limit] word_data = [word for (word, _, _) in limited_counts] count_data = [count for (_, count, _) in limited_counts] position = np.arange(len(word_data)) width = 1.0 ax = plt.gca() ax.set_xticks(position + (width / 2)) ax.set_xticklabels(word_data) plt.bar(position, count_data, width, color='b') def typeset_labels(labels=None, gap=5): """ Given a list of labels, create a new list of labels such that each label is right-padded by spaces so that every label has the same width, then is further right padded by ' ' * gap. """ if not isinstance(labels, Sequence): labels = list(range(labels)) labels = [str(i) for i in labels] label_lens = [len(s) for s in labels] label_width = max(label_lens) output = [] for label in labels: label_string = label + ' ' * (label_width - len(label)) + (' ' * gap) output.append(label_string) assert len(set(len(s) for s in output)) == 1 # Check all have same length. return output def get_ascii_bars(values, truncate=True, maxlen=10, symbol='#'): """ Given a list of values, create a list of strings of symbols, where each strings contains N symbols where N = ()(value / minimum) / (maximum - minimum)) * (maxlen / len(symbol)). """ maximum = max(values) if truncate: minimum = min(values) - 1 else: minimum = 0 # Type conversion to floats is required for compatibility with python 2, # because it doesn't do integer division correctly (it does floor divison # for integers). value_range=float(maximum - minimum) prop_values = [(float(value - minimum) / value_range) for value in values] # Type conversion to int required for compatibility with python 2 biggest_bar = symbol * int(round(maxlen / len(symbol))) bars = [biggest_bar[:int(round(prop * len(biggest_bar)))] for prop in prop_values] return bars def plot_ascii_bars(values, labels=None, screenwidth=80, gap=2, truncate=True): """ Given a list of values and labels, create right-padded labels for each label and strings of symbols representing the associated values. """ if not labels: try: values, labels = list(zip(*values)) except TypeError: labels = len(values) labels = typeset_labels(labels=labels, gap=gap) bars = get_ascii_bars(values, maxlen=screenwidth - gap - len(labels[0]), truncate=truncate) return [s + b for s, b in zip(labels, bars)] if __name__ == '__main__': input_file = sys.argv[1] output_file = sys.argv[2] limit = 10 if len(sys.argv) > 3: limit = int(sys.argv[3]) counts = load_word_counts(input_file) plot_word_counts(counts, limit) if output_file == "show": plt.show() elif output_file == 'ascii': words, counts, _ = list(zip(*counts)) for line in plot_ascii_bars(counts[:limit], words[:limit], truncate=False): print(line) else: plt.savefig(output_file)
3b4e66f095f0d76360cc995def3f53a704fd680c
optimum007/python_learn
/python/cubed.py
132
3.9375
4
def print_num(): num = input("数字を入力してね:") num = int(num) multiple = num ** 3 print(multiple)
5e711a0c2a30500407326392a9f9932cc4284474
gamesbrainiac/Project_Euler
/__3.py
709
3.9375
4
__author__ = 'Nafiul Islam' __title__ = 'Largest prime factor' number_in_question = 600851475143 def largest_prime_factor(number_in_question): """Finds the largest prime factor for the given number Args: number_in_question Returns: largest_prime_factor """ divisor = 2 factors = [] while number_in_question > 1: if number_in_question % divisor == 0: factors.append(divisor) number_in_question /= divisor else: divisor += 1 print("Factors were:") print(factors) return max(factors) if __name__ == "__main__": print("The largest factor: "+ str(largest_prime_factor(600851475143)))
d1c92b8cb12a0d281283f95219f39e09c0ec01ad
KoliosterNikolayIliev/Softuni_education
/Python OOP 2020/OOP_2020_exam_prep/Python OOP - Exam Preparation - 2 April 2020/tests/test_beginner.py
1,143
3.578125
4
import unittest from project.player.beginner import Beginner class TestBeginner(unittest.TestCase): def setUp(self): self.beginner = Beginner("Gosho") def test_beginner_creation(self): self.assertEqual(self.beginner.username, "Gosho") self.assertEqual(self.beginner.health, 50) self.assertEqual(self.beginner.card_repository.__class__.__name__, "CardRepository") def test_set_username_empty_string_ValueError(self): with self.assertRaises(ValueError): self.beginner.username = "" def test_set_health_negative_ValueError(self): with self.assertRaises(ValueError): self.beginner.health = -1 def test_is_dead_True(self): self.beginner.health = 0 result = self.beginner.is_dead self.assertEqual(result, True) def test_take_damage_negative_error(self): with self.assertRaises(ValueError): self.beginner.take_damage(-100) def test_take_damage_for_real(self): self.beginner.take_damage(10) self.assertEqual(self.beginner.health, 40) if __name__ == "__main__": unittest.main()
341e7c8daa12ff25e20ea3a1fc7f6f644cc169aa
Jangwoojin863/python
/실력향상예제62.py
315
3.765625
4
# 실력 향상 예제 62 import random nums = [0 for i in range(10)] for i in range(100): num = random.randint(1, 9) nums[num] += 1 print("%i, " %num, end='') print("\n--------------------------------------------------------------\n") for i in range(1,10): print("%i : %i" %(i, nums[i]))
cc7da2cb7e1fd9ac49cd9700bcf1924becfd2cd9
eric-s-s/dice-tables
/dicetables/eventsbases/protodie.py
2,202
3.59375
4
""" The abstract class for any die represented by a set of events """ from dicetables.eventsbases.integerevents import IntegerEvents class ProtoDie(IntegerEvents): """ This is the basis for all the dice classes. all Die objects need: - get_size() - returns: int > 0 - get_weight() - returns: int >= 0 - weight_info() - returns: str - multiply_str() - returns: str - get_dict() - returns: {int: int > 0} - __repr__ - __str__ """ def __init__(self): super(ProtoDie, self).__init__() def get_size(self) -> int: raise NotImplementedError def get_weight(self) -> int: raise NotImplementedError def get_dict(self): super(ProtoDie, self).get_dict() def weight_info(self) -> str: """return detailed info of how the die is weighted""" raise NotImplementedError def multiply_str(self, number: int) -> str: """return a string that is the die string multiplied by a number. i.e., D6+1 times 3 is '3D6+3' """ raise NotImplementedError def __str__(self): raise NotImplementedError def __repr__(self): raise NotImplementedError def __hash__(self): return hash('hash of {!r}, {}, {}, {}'.format(self, self.get_size(), self.get_weight(), self.get_dict())) def __lt__(self, other): return ( (self.get_size(), self.get_weight(), sorted(self.get_dict().items()), repr(self)) < (other.get_size(), other.get_weight(), sorted(other.get_dict().items()), repr(other)) ) def __eq__(self, other): return (super(ProtoDie, self).__eq__(other) and (self.get_size(), self.get_weight(), repr(self)) == (other.get_size(), other.get_weight(), repr(other)) ) def __le__(self, other): return self < other or self == other def __gt__(self, other): return not self <= other def __ge__(self, other): return self == other or self > other
3d0c88397604eaa13f44860c71a91bcf1118309b
jennysol/PythonIntroduction
/Cursopython/PythonExercicios/ex019.py
270
3.59375
4
import random # random usado para sorteio a1= (input('Digite o nome do aluno 1:')) a2= (input('Digite o nome do aluno 2:')) a3= (input('Digite o nome do aluno 3:')) a4= (input('Digite o nome do aluno 4:')) num= random.randint(1,4) print( ' O escolhido foi o aluno', num)
64ce57f9b8d3b2c60dfab85cbcccaeccec054268
nishantchaudhary12/Starting-with-Python
/Chapter 8/average_number_of_words.py
539
4.03125
4
#average number of words def average_words(length_list): print('The average number of words in a sentence is:', format(sum(length_list)/len(length_list), '.2f')) def main(): file = open('text.txt', 'r') length_list = list() line = file.readline() while line != '': line = line.rstrip('\n') words = line.split(' ') length = len(words) length_list.append(length) line = file.readline() file.close() average_words(length_list) if __name__ == '__main__': main()
821e9b6d831be8822d895c7548a09513b7e49335
RamonCris222/Ramon-Cristian
/questao_22_repeticao.py
501
3.9375
4
def euclides(a, b): if b == 0: return a else: return euclides(b, a % b) a, b = int(input("Forneça dois números inteiros positivos: ")), int(input()) if a > 0 and b > 0: print("O MDC entre %d e %d é %d." % (a, b, euclides(a, b))) # 8 e 10: # euclides(8, 10) # euclides(10, 10 % 8) # euclides(10, 2) # euclides(2, 10 % 2) # euclides(2, 0) # 2 else: print("Erro: é preciso que dois números inteiros e positivos sejam fornecidos.")
1691dbfffb888d02d6bc579e6ef0941665a9e20a
langjity/Python-spider
/firstspider/BlogSpider.py
874
3.53125
4
# 编写第一个网络爬虫 from urllib3 import * from re import * http = PoolManager() disable_warnings() def download(url): result = http.request('GET', url) htmlStr = result.data.decode('utf-8') return htmlStr def analyse(htmlStr): aList = findall('<a[^>]*titlelnk[^>]*>[^<]*</a>',htmlStr) result = [] for a in aList: g = search('href[\s]*=[\s]*[\'"]([^>\'""]*)[\'"]', a) if g != None: url = g.group(1) index1 = a.find(">") index2 = a.rfind("<") title = a[index1 + 1:index2] d = {} d['url'] = url d['title'] = title result.append(d) return result def crawler(url): html = download(url) blogList = analyse(html) for blog in blogList: print("title:",blog["title"]) print("url:",blog["url"]) crawler('https://www.cnblogs.com')
540da150f8350fa723b913850444b14fbf20da51
DanielCasagallo/ejerciciostkinter
/EjerciciosTkinter.py
3,401
3.8125
4
#Ejercicio 1 from tkinter import * root = Tk() etiqueta1= Label(root, text="Hello Tkinter!") etiqueta1.pack() root.mainloop() #Ejercicio2 master = Tk() whatever_you_do = "Whatever you do will be insignificant, but it is very important that you do it. \n(Mahatma Gandhi)" msg = Message(master, text = whatever_you_do) msg.config(bg='lightgreen', font=('times', 24, 'italic')) msg.pack( ) mainloop( ) #Ejercicio 3 class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text="SALIR",fg="red",command=frame.quit) self.button.pack(side=LEFT) self.slogan =Button(frame,text="ENTRAR",command=self.write_slogan) self.slogan.pack(side=LEFT) def write_slogan(self): print("Estamos aprendiendo a usar Tkinter!") root = Tk() app = App(root) root.mainloop() #Ejercicio 4 root = Tk() v = IntVar() Label(root,text="""Choose a programming language:""",justify = LEFT,padx = 20).pack() Radiobutton(root,text="Python",padx = 20,variable=v,value=1).pack(anchor=W) Radiobutton(root,text="Perl",padx = 20,variable=v,value=2).pack(anchor=W) mainloop() #Ejercicio 5 root = Tk() v = IntVar() v.set(1) languages = [("Python",1),("Perl",2),("Java",3),("C++",4),("C",5)] def ShowChoice(): print (v.get()) Label(root,text="""Elija su lenguaje de programación favorito:""",justify = LEFT,padx = 20).pack() for txt, val in languages: Radiobutton(root,text=txt,padx = 30,variable=v,command=ShowChoice,value=val).pack(anchor=W) mainloop() #Ejercicio 6 root = Tk() v = IntVar() v.set(1) languages = [("Python",1),("Perl",2),("Java",3),("C++",4),("C",5)] def ShowChoice(): print (v.get()) Label(root,text="""Escoja un lenguaje de programación:""",justify = LEFT,padx = 20).pack() for txt, val in languages: Radiobutton(root,text=txt,indicatoron =0,width = 20,padx = 20,variable=v,command=ShowChoice,value=val).pack(anchor=W) mainloop() #Ejercicio 7 master = Tk() var1 = IntVar() Checkbutton(master, text="Hombre", variable=var1).grid(row=0, sticky=W) var2 = IntVar() Checkbutton(master, text="Mujer", variable=var2).grid(row=1, sticky=W) mainloop() #Ejercicio 8 master = Tk() def var_states(): print ("male: ",var1.get()) print ("female: ",var2.get()) Label(master, text="Indicar el sexo:").grid(row=0, sticky=W) var1 = IntVar() Checkbutton(master, text="male", variable=var1).grid(row=1, sticky=W) var2 = IntVar() Checkbutton(master, text="female", variable=var2).grid(row=2, sticky=W) Button(master, text='Quit', command=master.quit).grid(row=3, sticky=W, padx=4) Button(master, text='Show', command=var_states).grid(row=4, sticky=W, pady=4) mainloop() #Ejercicio 9 from Tkinter import * master = Tk() Label(master, text="First Name").grid(row=0) Label(master, text="Last Name").grid(row=1) e1 = Entry(master) e2 = Entry(master) e1.grid(row=0, column=1) e2.grid(row=1, column=1) mainloop() #Ejercicio 10 from Tkinter import * def show_entry_fields(): print("First Name: %s\nLast Name: %s" % (e1.get(), e2.get())) master = Tk() Label(master, text="First Name").grid(row=0) Label(master, text="Last Name").grid(row=1) e1 = Entry(master) e2 = Entry(master) e1.grid(row=0, column=1) e2.grid(row=1, column=1) Button(master, text='Quit', command=master.quit).grid(row=3, column=0, sticky=W, pady=4) Button(master, text='Show', command=show_entry_fields).grid(row=3, column=1, sticky=W, pady=4) mainloop()
d7eda712c949a4eb7fe366f496ef9531d3d024fb
chaddymac/learningprojects
/Cats.py
790
4.34375
4
# Given the below class: class Cat: species = "mammal" def __init__(self, name, age): self.name = name self.age = age # 1 Instantiate the Cat object with 3 cats sam = Cat("sam", 10) lam = Cat("lam", 8) dex = Cat("dex", 7) # 2 Create a function that finds the oldest cat # def oldest_cat(*args): # print("hello") # old_age = 0 # for cat in args: # if cat.age > old_age: # old_age = cat.age # return old_age def oldest_cat(*args): return max(*args) # cat_age = oldest_cat(sam.age, lam.age, dex.age) # 3 Print out: "The oldest cat is x years old.". x will be the oldest cat age by using the function in #2 print(f"The oldest cat is {oldest_cat(sam.age, lam.age, dex.age)} years old")
01853602611b58f10d0e44f8de0874069bf7bd92
darraes/coding_questions
/v2/_leet_code_/0024_swap_node_pairs.py
1,909
3.75
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ node = head if node and node.next: swapper = [node.next, node] tail = node.next.next swapper[0].next = swapper[1] swapper[1].next = self.swapPairs(tail) return swapper[0] return head ############################################################### import unittest def from_list(list): idx = 0 while idx < len(list) - 1: list[idx].next = list[idx + 1] idx += 1 return list[0] def print_ll(head): buffer = "" node = head while node: buffer += str(node.val) buffer += " -> " node = node.next print(buffer) def equals_ll(l1, l2): while l1 and l2: if l1.val != l2.val: return False l1 = l1.next l2 = l2.next return l1 is None and l2 is None class TestFunctions(unittest.TestCase): def test_1(self): s = Solution() l1 = from_list([ListNode(1), ListNode(2), ListNode(3), ListNode(4)]) self.assertTrue( equals_ll( from_list([ListNode(2), ListNode(1), ListNode(4), ListNode(3)]), s.swapPairs(l1), ) ) l1 = from_list([ListNode(1), ListNode(2), ListNode(3)]) self.assertTrue( equals_ll( from_list([ListNode(2), ListNode(1), ListNode(3)]), s.swapPairs(l1), ) ) l1 = from_list([ListNode(1), ListNode(2)]) self.assertTrue( equals_ll( from_list([ListNode(2), ListNode(1)]), s.swapPairs(l1), ) ) if __name__ == "__main__": unittest.main()
0930d27eab577fdfbab898860e6fc0b568264e7f
oran2527/holbertonschool-machine_learning
/math/0x00-linear_algebra/14-saddle_up.py
202
3.53125
4
#!/usr/bin/env python3 """ program to multiply two matrices """ import numpy as np def np_matmul(mat1, mat2): """ function to return the mult of two matrices """ return np.matmul(mat1, mat2)
df7c139f2e00d9e5395da0987d0c824c354e6ef1
FMularski/tkinter-tutorial
/file_dialog.py
578
3.546875
4
from tkinter import * from PIL import ImageTk, Image from tkinter import filedialog root = Tk() def open_file(): global img filename = filedialog.askopenfilename(initialdir='./', title='Select a file', filetypes=(('png files', '*.png'), ('all files', '*'))) file_path_label = Label(root, text=filename).pack() img = ImageTk.PhotoImage(Image.open(filename)) img_label = Label(image=img) img_label.pack() open_file_btn = Button(root, text='Open file', command=open_file) open_file_btn.pack() root.mainloop()
e39bf514c02a1eb450d4bf7767eb654c548c52b4
JoshuaQChurch/SW-Arch-7
/Backup - Python v1.0/User.py
2,917
3.671875
4
import database as db from Mailboxlayer import * import sqlite3 class User(): def __init__(self, first, last, email, password, balance, history): self.first = first self.last = last self.email = email self.password = password self.balance = balance self.transactionHistory = [] def updateName(self): self.first = str(raw_input("Firstname: ")) self.last = str(raw_input("Lastname: ")) db.update('name', [self.first, self.last], self.email) def changePassword(self): pass_attempts = 3 new_pass_attempts = 3 old_password = self.password while (pass_attempts > 0): password = raw_input(str("Please enter your old password: ")) if password == old_password: while (new_pass_attempts > 0): password = raw_input(str("Please enter your new password: ")) r_password = raw_input(str("Please enter your new password again: ")) if password == r_password: print("Password successfully updated!") db.update('pass', password, self.email) self.password = password return else: new_pass_attempts = new_pass_attempts - 1 print("\nERROR: Non-matching passwords.") print(str(new_pass_attempts) + " attempts remaining.\n") if (new_pass_attempts == 0): print("ERROR: You have exceeding the maximum attempts. System exiting...\n") sys.exit(-1) else: pass_attempts = pass_attempts - 1 print("ERROR: Non-matching passwords.") print(str(pass_attempts) + " attempts remaining.\n") print("ERROR: You have exceeding the maximum attempts. System exiting...\n") sys.exit(-1) def addFunds(self): attempts = 3 while (attempts > 0): try: funds = float(raw_input("Add funds: ")) self.balance = self.balance + funds db.update('balance', self.balance, self.email) return except ValueError: attempts = attempts - 1 print("ERROR: Please enter a numerical value.") print(str(attempts) + " attempts remaining.\n") if attempts == 0: print("You have failed too many times.") print("Now exiting...\n") exit(-1) def getBalance(self): return float(self.balance) def getHistory(self): row = db.getHistory(self.email) if row == False: print("\n\nThere is no past transaction history.\n") else: row = row.split(';') for i in range(len(row) - 1): row[i] = row[i].split(',') print("\nTransaction") print("-----------") print(" > Transaction Type: " + row[i][0]) print(" > Company: " + row[i][1]) print(" > Symbol: " + row[i][2]) print(" > Timestamp: " + row[i][3]) print(" > Stock Price: $" + row[i][4]) print(" > Amount: " + row[i][5]) def saleHistoryCheck(self, amount, symbol, option): if option == 'owned': return db.saleHistoryCheck(self.email, amount, symbol, option) else: db.saleHistoryCheck(self.email, amount, symbol, option)
e015059464613c73bac0d31449ecc56d25de28da
thewizardplusplus/robot-fan
/robot_fan/interval.py
720
3.75
4
class Interval: def __init__(self, minimum, maximum): self.minimum = minimum self.maximum = maximum def __len__(self): return abs(self.maximum - self.minimum) def get_proportion_by_value(self, value): minimum = min(self.minimum, self.maximum) maximum = max(self.minimum, self.maximum) if value < minimum or value > maximum: raise RuntimeError("the value is out of the interval") return abs(value - self.minimum) / len(self) def get_value_by_proportion(self, proportion): if proportion < 0 or proportion > 1: raise RuntimeError("the proportion is incorrect") return proportion * len(self) + self.minimum
18740161085f569b3db62e172ce82975c6ae1691
bmasoumi/BioInfoMethods
/pattern_count.py
1,434
4.15625
4
# Input: Strings Pattern and Text # Output: The number of times Pattern appears in Text def PatternCount(Pattern, Text): count = 0 # output variable for i in range(len(Text)-len(Pattern)+1): if Text[i:i+len(Pattern)] == Pattern: count = count+1 return count ### DO NOT MODIFY THE CODE BELOW THIS LINE ### import sys lines = sys.stdin.read().splitlines() print(PatternCount(lines[1],lines[0])) ### DO NOT MODIFY THE CODE BELOW THIS LINE ### #import sys #lines = sys.stdin.read().splitlines() #print(PatternCount(lines[1],lines[0])) # Now, set Text equal to the ori of Vibrio cholerae and Pattern equal to "TGATCA" Text = "ATCAATGATCAACGTAAGCTTCTAAGCATGATCAAGGTGCTCACACAGTTTATCCACAACCTGAGTGGATGACATCAAGATAGGTCGTTGTATCTCCTTCCTCTCGTACTCTCATGACCACGGAAAGATGATCAAGAGAGGATGATTTCTTGGCCATATCGCAATGAATACTTGTGACTTGTGCTTCCAATTGACATCTTCAGCGCCATATTGCGCTGGCCAAGGTGACGGAGCGGGATTACGAAAGCATGATCATGGCTGTTGTTCTGTTTATCTTGTTTTGACTGAGACTTGTTAGGATAGACGGTTTTTCATCACTGACTAGCCAAAGCCTTACTCTGCCTGACATCGACCGTAAATTGATAATGAATTTACATGCTTCCGCGACGATTTACCTCTTGATCATCGATCCGATTGAAGATCTTCAATTGTTAATTCTCTTGCCTCGACTCATAGCCATGATGAGCTCTTGATCATGTTTCCTTAACCCTCTATTTTTTACGGAAGAATGATCAAGCTGCTGCTCTTGATCATCGTTTC" Pattern = "TGATCA" # Finally, print the result of calling PatternCount on Text and Pattern. #count=PatternCount(Pattern, Text) print(PatternCount(Pattern, Text)) # Don't forget to use the notation print() with parentheses included!
12a984a4dacd9ff9586ed4982f764bedd13ffa53
Vostbur/cracking-the-coding-interview-6th
/python/chapter_2/08_loop_detect.py
1,304
3.6875
4
# Для кольцевого связного списка реализуйте алгоритм, возвращающий начальный # узел петли. Определение: # Кольцевой связный список — это связный список, в котором указатель следующего # узла ссылается на более ранний узел, образуя петлю. # Пример: # Ввод: A->B->C->D->E->C (предыдущий узел C) # Вывод: C import unittest from LinkedList import LinkedList def loop_detect(ll): fast = slow = ll.start_node while fast and fast.ref: slow = slow.ref fast = fast.ref.ref if fast is slow: break if fast is None or fast.ref is None: return None slow = ll.start_node while fast is not slow: slow = slow.ref fast = fast.ref return fast class Test(unittest.TestCase): def test_loop_detect(self): ll = LinkedList() ll.insert_multiple(1, 2, 3, 4, 5) loop_node = ll.start_node.ref.ref ll.last_node.ref = loop_node result = loop_detect(ll) print(result.item) self.assertEqual(result, loop_node) if __name__ == "__main__": unittest.main()
5fd4cdd45cd898aab04202ff9340d4c7d68b4dc9
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_116/705.py
2,229
3.5625
4
#! /usr/bin/python # -*- coding: utf-8 -*- import logging logging.basicConfig(level=logging.DEBUG) def search_winner(line): for values in ("XT", "OT"): if all(char in values for char in line): return values[0] def solve_case(case): grid = case.split("\n") for line in [grid[i] for i in range(4)] + [[grid[j][i] for j in range(4)] for i in range(4)] + [[grid[i][i] for i in range(4)]] + [[grid[i][3-i] for i in range(4)]]: winner = search_winner(line) if winner: return winner + " won" else: if "." in case: return "Game has not completed" else: return "Draw" def case_line(case_number, cases): """case_number != list index""" return "Case #{}: {}".format(case_number, solve_case(cases[case_number-1])) def set_to_cases(set_): return set_.split("\n")[1:-1] def set_to_cases_blocks(set_): return "\n".join(set_to_cases(set_)).split("\n\n") def solve_set(set_): cases = set_to_cases_blocks(set_) return "\n".join(case_line(i+1, cases) for i in range(len(cases))) test_in = """6 XXXT .... OO.. .... XOXT XXOO OXOX XXOO XOX. OX.. .... .... OOXX OXXX OX.T O..O XXXO ..O. .O.. T... OXXX XO.. ..O. ...O """ test_out = """Case #1: X won Case #2: Draw Case #3: Game has not completed Case #4: O won Case #5: O won Case #6: O won""" def compare_test_case_line(case_number): test_solution_line = case_line(case_number, set_to_cases(test_in)) test_out_line = test_out.split("\n")[case_number] if test_solution_line == test_out_line: logging.info("Test line {} passed".format(case_number)) else: logging.warning("Test line {} failed".format(case_number)) logging.info(test_solution_line) logging.info(test_out_line) test_solution = solve_set(test_in) if test_solution == test_out: logging.info("Test passed") else: logging.warning("Test failed") logging.info(test_solution) logging.info(test_out) problem_letter = "A" attempt = 0 for problem_size in ("small", "large"): if input("Solve {} {}? (y)".format(problem_letter, problem_size)): name = "{}-{}".format(problem_letter, problem_size, attempt) with open(name + ".in") as file_in: with open(name + ".out".format(problem_letter, problem_size), "w") as file_out: print(solve_set(file_in.read()), file=file_out)
e0d5ec70bc483d21e4aab727ddfa0c50f2d47102
CapGalius/Exercicios-python
/mediaaluno.py
1,591
4.09375
4
nome = input("Digite o nome do aluno: ") valid_nota = False while valid_nota == False: nota1 = input("Digite nota da Prova 1: ") try: nota1 = float(nota1) if nota1 <0 or nota1 >10: print("Nota inválida. Use valores entre 0 e 10") else: valid_nota = True except: print("Nota inválida. Use apenas números e separe decimais com '.'") valid_nota = False while valid_nota == False: nota2 = input("Digite nota da Prova 2: ") try: nota2 = float(nota2) if nota2 <0 or nota2 >10: print("Nota inválida. Use valores entre 0 e 10") else: valid_nota = True except: print("Nota inválida. Use apenas números e separe decimais com '.'") valid_faltas = False while valid_faltas == False: faltas = input("Digite o número de faltas: ") try: faltas = int(faltas) if faltas <0 or faltas >20: print("Número de faltas inválido. Use valores entre 0 e 20") else: valid_faltas = True except Exception as e: print("Númro de faltas inválido") media = (nota1+nota2)/2 assid = (20-faltas)/20 if media >= 6 and assid >= 0.7: resultado = "Aprovado" elif media < 6 and assid < 0.7: resultado = "Reprovado por média e por faltas." elif media < 6: resultado = "Reprovado por média." elif assid < 0.7: resultado = "Reprovado por faltas." else: print("Erro") print("Nome: ",nome) print("Média: ",media) print("Assiduidade: ",str(assid*100)+'%') print("Resultado: ", resultado)
9f85456cdef9adf6c6bf4ad63463547bdce7fb22
khushi3030/Master-PyAlgo
/Algebra/Set_Union.py
909
4.46875
4
''' Aim: To find the total number of elements in the union of the entered sets. ''' # getting the size of set 1 n1=int(input().strip()) s1=[] s1o=[] # getting the elements of the set 1 s1o=(input().strip().split()) for i in s1o: s1.append(int(i)) # getting the size of set 2 n2=int(input().strip()) s2=[] s2o=[] # getting the elements of the set 2 s2o=(input().strip().split()) for i in s2o: s2.append(int(i)) # adding both the sets (as of now their data type is list) set_union=s1+s2 # if we convert the list into set data type, then only unique elements will retain print(len(set(set_union))) ''' COMPLEXITY: Time Complexity -> O(N) Space Complexity -> O(N) Sample Input: 5 3 1 4 6 2 5 6 8 3 6 1 Sample Output: 5 Explanation: Elements in the union of both the sets --> [1,2,3,4,6,8] Total count --> 6 Hence, the output is 6. '''
8d404551edb1811ef881cfb2a8a8e8f44dad88cf
MrSamuelLaw/excel_sucks
/web_excel_tools.py
3,861
4.46875
4
#!/usr/bin/env python3 import re import argparse from pathlib import PurePath """allows the user write an excel equation in a .txt file then convert that into a single line equation which can be pasted in the excel function bar. Also allows the user to convert relative references into "indirect" function. see the relative_to_indirect function for more info.""" def cli(): """walks the user through creating a function from a file assuming they have the path to the file""" filepath = input("copy and paste file path, then press enter\n") eqn = format_from_file(str(filepath)) option1 = input('would you like to make the function "indirect"? [Y,N]\n') if option1.upper() == "Y": option2 = input('does this function need to work on every row or column? [row, col]\n') if option2.lower() == "row": print(relative_to_indirect(eqn, row_or_col="row")) elif option2.lower() == "col": print(relative_to_indirect(eqn, row_or_col="col")) else: raise ValueError(f'options are row or "col", "not" {option2}') else: print(eqn) def format_from_file(filepath: str) -> str: """Asks the user to drag and drop file into terminal and returns the flattened text""" path = PurePath(filepath) with open(path, "r") as f: return flatten(str(f.read())) def flatten(text: str) -> str: """Takes all of the Excel logic spread accross multiple lines for readability and returns a single line for pasting into the excel function bar""" results = [] for line in text.splitlines(): line = line.lstrip() line = line.rstrip() results.append(line) return "".join(results) def relative_to_indirect(equation: str, row_or_col: str = "row") -> str: """One of the major problems with web excel is that the cells cannot be locked, and when using relative references, it only takes one accidental copy and paste to ruin, an entire workbook, to prevent this, this function will take a function with relative references and convert them to indirect. For example: LEN(A5), you want to copy and paste this formula to all the rows and have it work for A(any row here) then you would have to write INDIRECT(CONCAT("A", ROW())) which is time consuming and error prone This function saves you the hassle by converting every indirect cell refernece to the INDIRECT format to then be copy and pasted into the cells of a web excel document args: equation: equation to have relative reference converted to indirect. row_or_col: makes either the row or column reference dynamic. i.e. row = "A", ROW() or col = "COL()", 5. valid inputs are "row" or "col" defaults to row """ # define pattern pattern = re.compile(r"[A-Z]{1,3}\d{1,5}") p = re.compile(r"[A-Z]") # define splitting function def split(match: str): idx, span = p.search(match).span() return match[:span], match[span:] if row_or_col == "row": matches = pattern.findall(equation) for m in matches: static, _ = split(m) equation = equation.replace( m, f'INDIRECT(CONCAT("{static}", ROW()))' ) elif row_or_col == "col": matches = pattern.findall(equation) for m in matches: _, static = split(m) equation = equation.replace( m, f'INDIRECT(CONCAT(COLUMN(), "{static}"))' ) else: raise ValueError( f"""row_or_col value is invalid, options are "row" or "col", not {row_or_col}""" ) return equation if __name__ == "__main__": """runs the script""" cli()
365acd418090b8b85611edb13dfbfe430ea076ed
GolamRabbani20/PYTHON-A2Z
/DATA_STRUCTURE_AND_ALGORITHMS/C-Algorithms/B-Sorting/Merge-Sort.py
700
3.8125
4
def MergeSort(x,lb,ub): if lb<ub: mid=(lb+ub)//2 MergeSort(x,lb,mid) MergeSort(x,mid+1,ub) Merge(x,lb,mid,ub) def Merge(x,lb,mid,ub): i=lb j=mid+1 k=lb while(i<=lb and j<=ub): if x[i]<=x[j]: b[k]=x[i] i+=1 else: b[k]=x[j] j+=1 k+=1 if i>mid: while(j<=ub): b[k]=x[j] i+=1 k+=1 else: while i<=mid: b[k]=x[i] i+=1 k+=1 for k in range(lb,ub): x[k]=b[k] print(x) x=[7,6,10,5,9,2,1,15,7] b=[] MergeSort(x,0,len(x)-1)
ddcc40de8cb40e58afa10df07f2d72cbfd66a702
ImLeosky/holbertonschool-higher_level_programming
/0x03-python-data_structures/6-print_matrix_integer.py
245
3.96875
4
#!/usr/bin/python3 def print_matrix_integer(matrix=[[]]): cadena = '' for i in matrix: cadena = cadena + '\n' for a in i: cadena = cadena + "{:d} ".format(a) cadena = cadena[:-1] print(cadena[1:])