blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
36a9ad2d0f4ca22c5db3f2f5b8463664160b5ad7
lucasdavid/artificial
/artificial/utils/priority_queue.py
1,266
4.03125
4
"""Basic Priority Queue""" # Author: Lucas David -- <ld492@drexel.edu> # License: MIT (c) 2016 import heapq import itertools class PriorityQueue: REMOVED = '<removed-e>' def __init__(self): self.priority_queue = [] self.map = {} self.counter = itertools.count() def add(self, entry, priority=0): if entry in self.map: self.remove(entry) count = next(self.counter) node = [priority, count, entry] self.map[entry] = node heapq.heappush(self.priority_queue, node) def get(self, entry): return self.map[entry] def remove(self, entry): node = self.map.pop(entry) node[-1] = self.REMOVED def pop(self): while self.priority_queue: priority, count, entry = heapq.heappop(self.priority_queue) if entry is not self.REMOVED: del self.map[entry] return entry raise KeyError('pop from an empty priority queue') def __contains__(self, item): return item in self.map and self.map[item] != self.REMOVED def __getitem__(self, item): return self.get(item) def __len__(self): return len(self.map) def __bool__(self): return len(self) != 0
8fb9216e58f0d05e13b35f10104d343e664d468b
sczapuchlak/PythonCapstoneLab1
/CamelCase.py
1,122
4.46875
4
# this program takes a users sentence and turns it into camel case # keeps the first letter lowercase print('Please enter a sentence in any sort of case! I will make it camel case for you!') # takes the users input and makes all of it lowercase, and then # capitalizes the first letter in each word sentence = input().lower().title() # checks to see if any letters are anything but letters # displays warning for the user that the camel case may be incorrect for char in sentence: if not char.isalpha(): print('You will not get the desired camelCase since there are symbols!') input('But I shall print for you anyways... press enter') break # replaces the spaces with no spaces to the words are put together sentence = sentence.replace(' ', '') # takes the first letter out and keeps the rest of the sentence firstLetterGone = sentence[1:] # then takes the first letter and lowercases it6 makeFirstLetterLower = sentence[0].lower() # puts the lowercase first letter onto the sentenve again fullSentence = makeFirstLetterLower + firstLetterGone # displays the users sentence print(fullSentence)
007641c44e8d61485fbf976c9e002b26e545d963
codecherry12/Data_Structues_AND_Algorithms
/Queues/DoubleEndedQ.py
1,008
4
4
#double ended queue class deq: def __init__(self): self.data=[] def isempty(self): return len(self.data)==0 def __len__(self): return len(self.data) def enquerear(self,ele): self.data.append(ele) def dequerear(self): if self.isempty(): print('Q is empty') else: return self.data.pop() def enquefront(self,ele): self.data.insert(0,ele) def dequefront(self): if self.isempty(): print("Q is empty") else: return self.data.pop(0) def display(self): if self.isempty(): print("Q is empty") else: for var in self.data: print(var," == " ,end=' ') print() DEQ=deq() print(DEQ.isempty()) DEQ.display() DEQ.dequefront() DEQ.enquefront(10) DEQ.enquefront(11) DEQ.display() DEQ.enquerear(100) DEQ.enquerear(101) DEQ.display() print(DEQ.dequerear()) DEQ.display() print(DEQ.dequefront()) DEQ.display()
7608fdc3cf812565aaa08722945b977a1064f7f5
camano/Aprendiendo_Python
/condicionales/condicionales.py
220
3.8125
4
print("Progama de evaluacion") nota_alumno=input("introdusca algo") def evaluacion(nota): valoracion="Aprobado" if nota<5: valoracion="Suspenso" return valoracion print(evaluacion(int(nota_alumno)))
f2b61798ffe3030f6d56bc70616841965e85b44d
bhushankelkar/machinelearning-resources-ieee-apsit
/linear_regression/simple_linear_regression.py
1,846
4.25
4
# Simple Linear Regression # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd import math # Importing the dataset dataset = pd.read_csv('Salary_Data.csv')#has only 2 columns experience and salary(index 0 and 1) X = dataset.iloc[:, :-1].values #takes all column except last column #(here it takes experience column as input which has index 0) y = dataset.iloc[:, 1].values #Takes column with index 1 as input #(here its the salary column) or you can use the below command also #y = dataset.iloc[:, -1].values #Takes only last column ie. salary column # Splitting the dataset into the Training set and Test set #sklearn.cross_validation is now depreceated. from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0) # Fitting Simple Linear Regression to the Training set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) # Predicting the Test set results y_pred = regressor.predict(X_test) print("Experience Predicted Salary Actual Salary") for i in range(0,7): print(X_test[i]," ",math.trunc(y_pred[i])," ",math.trunc(y_test[i])) #math.trunc decimal values ko whole kardeta hai aur kn # Visualising the Training set results plt.scatter(X_train, y_train, color = 'red') plt.plot(X_train, regressor.predict(X_train), color = 'blue') plt.title('Salary vs Experience (Training set)') plt.xlabel('Years of Experience') plt.ylabel('Salary') plt.show() # Visualising the Test set results plt.scatter(X_test, y_test, color = 'red') plt.plot(X_train, regressor.predict(X_train), color = 'blue') plt.title('Salary vs Experience (Test set)') plt.xlabel('Years of Experience') plt.ylabel('Salary') plt.show()
266eb936ffeeb649bc916180cf6cd20e95e4a230
Shmuco/DI_Bootcamp
/Week4/Day4/Ex_XP_Gold_dice.py
2,099
4.5
4
# Create a function that will simulate the rolling of a dice. Call it throw_dice. It should return an integer between 1 and 6. # Create a function called throw_until_doubles. # It should keep throwing 2 dice (using your throw_dice function) until they both land on the same number, ie. until we reach doubles. # For example: (1, 2), (3, 1), (5,5) → then stop throwing, because doubles were reached. # This function should return the number of times it threw the dice in total. In the example above, it should return 3. # Create a main function. # It should throw doubles 100 times (ie. call your throw_until_doubles function 100 times), and store the results of those function calls (in other words, how many throws it took until doubles were thrown, each time) in a collection. (What kind of collection? Read below to understand what we will need the data for, and this should help you decide which data structure to use). # After the 100 doubles are thrown, print out a message telling the user how many throws it took in total to reach 100 doubles. # Also print out a message telling the user the average amount of throws it took to reach doubles. Round this off to 2 decimal places. # For example: # If the results of the throws were as follows (your code would do 100 doubles, not just 3): # (1, 2), (3, 1), (5, 5) # (3, 3) # (2, 4), (1, 2), (3, 4), (2, 2) # Then my output would show something like this: # Total throws: 8 # Average throws to reach doubles: 2.67. import random def throw_dice(): return random.randint(1,6) def throw_until_doubles(): flag = True counter = 0 while flag: dice1 = throw_dice() dice2 = throw_dice() counter += 1 if dice1 == dice2: flag = False return counter def main(): total = 0 throw_num_li = [] for i in range(0,100): throw_num = throw_until_doubles() throw_num_li.append(throw_num) total += throw_num avg = sum(throw_num_li)/len(throw_num_li) print(f'Total throws: {total}') print(f'Average thows for each double: {avg}') main()
0de4eb030e3fd7e05c631f19f69375996da0a029
wstam88/rofistar_php
/resources/snippets/Python3/Buildin functions/String/rpartition.py
169
4.03125
4
txt = "I could eat bananas all day, bananas are my favorite fruit" # Returns a tuple where the string is parted into three parts x = txt.rpartition("bananas") print(x)
1201c22b11346b91ded6f46f4dffc209ccb8ddc9
shouliang/Development
/Python/PythonBasic/var.py
430
4.25
4
# 变量只需被赋予某一值,不需要声明或者定义数据类型 # 建议使用四个空格来索引 i = 5 print(i) # 下面将发生错误,注意行首有一个空格 # print(i) i = i + 1 print(i) s = '''This is a multi-line string. This is the second line.''' print(s) # 显示行连接: 故结果为:This is a string. This continues the string s = 'This is a string. \ This continues the string ' print(s)
10593144eaefd390e91e0374e89684075e1f31ea
Kunal352000/python_adv
/18_userDefinedFunction46.py
145
3.5625
4
def f1(): x=10#local print(x)#10 f1() def f(): print(x)#error f() """ output:- 10 NameError: name 'x' is not defined """
2cc4ae22ed55c44aaf7fa5521a093ef8e1757af4
mendoza/hotcake
/Btree.py
7,964
3.625
4
from Node import Node import bisect import itertools import operator class BTree(object): BRANCH = LEAF = Node """ Orden: como su palabra lo dice, el orden en el que basamos el arbol """ def __init__(self, order): self.order = order self._root = self._bottom = self.LEAF(self) #Metodo que nos ayuda a llegar hasta un item en especifico , como la root con sus keys def _path_to(self, item): current = self._root llaves = [] #Este getattr nos consigue que es nuestro atributo si es leaf, children etc while getattr(current, "children", None): index = bisect.bisect_left(current.contents, item) #Realizamos un append a las llavez llaves.append((current, index)) #tomamos el length para comparar si cumple con la propiedad if index < len(current.contents) \ and current.contents[index] == item: return llaves current = current.children[index] index = bisect.bisect_left(current.contents, item) llaves.append((current, index)) present = index < len(current.contents) present = present and current.contents[index] == item #Hacemos un return de las llavez una vez verificado que cumple las propiedad return llaves #recibe data , y una lista def _present(self, item, ancestors): last, index = ancestors[-1] return index < len(last.contents) and last.contents[index] == item #Realizamos el insert a nuestro arbol def insert(self, item): # assignamos a current el root para revisar si podemos insertarlo ahi current = self._root #usamos la lista que trae y la mandamos a nuestro metodo a ordenarlo ancestors = self._path_to(item) node, index = ancestors[-1] #Revisamos si es un hijo while getattr(node, "children", None): #al nodo sub la lista de sus hijos , dependiendo su condicion le hacemos split node = node.children[index] #como lo muestra el metodo hay un bisect que biseca la lista index = bisect.bisect_left(node.contents, item) #a la lista que traemos la hacemos un apend en el nodo , del data ancestors.append((node, index)) node, index = ancestors.pop() #finalmente hacemos el incert , mandando como parametro, indice, el data a aguardar y la litsa node.insert(index, item, ancestors) #Aqui realizamos nuestra funcion remove que recibe un dato como es logico def remove(self, item): #le asignamos nuevamente a curret la root principal current = self._root #recorremos la lista haciendo la llamada del meto ancestors = self._path_to(item) #Revisamos si existe ene nuestra lista if self._present(item, ancestors): #si es asi realizamos el pop de la lista ancestros node, index = ancestors.pop() #hace el remove correspondiente node.remove(index, ancestors) else: #En caso de no esncontrarlo , de muestra un mensaje que dice que no encontro lo que deseaba eliminar raise ValueError("%r not in %s" % (item, self.__class__.__name__)) #Nuestro metodo simplemente revisa si el item que recibe como parametro, esta contemplado en el arbol def __contains__(self, item): return self._present(item, self._path_to(item)) #Esta funcion es la que itera entre nuestras llavez y es nuestra recursiva def __iter__(self): #Recibe un nodo como parametro def _recurse(node): #Chequea si es hijo if node.children: #En caso de serlo , llama al item encontrado for child, item in zip(node.children, node.contents): for child_item in _recurse(child): yield child_item yield item for child_item in _recurse(node.children[-1]): yield child_item else: #Si no lo encuentra : for item in node.contents: yield item for item in _recurse(self._root): yield item #Nuestro metodo realiza las operaciones llamando si es necesario a la recursiva def __repr__(self): def recurse(node, accum, depth): accum.append((" " * depth) + repr(node)) for node in getattr(node, "children", []): recurse(node, accum, depth + 1) accum = [] recurse(self._root, accum, 0) return "\n".join(accum) #Sobrecarga de metodos propios del lenguaje #Realiza la carga al arbol @classmethod def bulkload(cls, items, order): tree = object.__new__(cls) tree.order = order #llama al meotod paara las hojas que es diferente al de las hijas o branches leaves = tree._build_bulkloaded_leaves(items) tree._build_bulkloaded_branches(leaves) return tree #A diferencia del metodo anterior este es llamado solo si es en una hoja el trabajo def _build_bulkloaded_leaves(self, items): #Definimos cual es nuestro orden minimo minimum = self.order // 2 leaves, seps = [[]], [] #hace la validacion para saber si es posible que pueda realizar el trabajo , debe ser menor al orden-1 for item in items: if len(leaves[-1]) < self.order: leaves[-1].append(item) else: seps.append(item) leaves.append([]) #Revisa la segunda condicion que le dice cual es el orden minimo, la propiedad if len(leaves[-1]) < minimum and seps: last_two = leaves[-2] + [seps.pop()] + leaves[-1] leaves[-2] = last_two[:minimum] leaves[-1] = last_two[minimum + 1:] seps.append(last_two[minimum]) #Una vez ya con las validaciones pertinentes realiza el return return [self.LEAF(self, contents=node) for node in leaves], seps #Este metodo a diferencia del anterior es para nodos NO hojas y por lo tanto tendra contempladas llamadas recuersivas def _build_bulkloaded_branches(self, (leaves, seps)): #De igual manera definimos cual es el orden minimo minimum = self.order // 2 #aqui guardamos cuantos niveles va sumando nuestro arbol levels = [leaves] while len(seps) > self.order + 1: items, nodes, seps = seps, [[]], [] #Es el mismo proceso de las hojas , eso si identifica que son hojas for item in items: if len(nodes[-1]) < self.order: nodes[-1].append(item) else: seps.append(item) nodes.append([]) #Tambien hace la validacion normal , las de las propiedades que debes estar siempre contempladas if len(nodes[-1]) < minimum and seps: last_two = nodes[-2] + [seps.pop()] + nodes[-1] nodes[-2] = last_two[:minimum] nodes[-1] = last_two[minimum + 1:] seps.append(last_two[minimum]) """ offset: es donde va siendo recorrido nuestro arbol, nos da una posicion dentro de el """ offset = 0 #Enumera los nodos y va recorriendo lo que es el arbol para darle un valor for i, node in enumerate(nodes): children = levels[-1][offset:offset + len(node) + 1] nodes[i] = self.BRANCH(self, contents=node, children=children) offset += len(node) + 1 levels.append(nodes) #por ultimo revisa el nodo NO hoja y manda sus hijos y sus niveles contemplados como parametros self._root = self.BRANCH(self, contents=seps, children=levels[-1])
c4fe96f3f104645abd2707bbe8a2e4865fa7e0e2
NetUnit/Lv-527.PythonCore
/home_work_7_04_09/home_work_7_PSW/Sighn_Up_Password/2_check_psw_loop_for.py
1,215
4
4
import time ''' Using loop for and range() sequence in the main block to check whether a password is strong and satisfy conditions ''' # aforehand prepared answers in oreder to fill check() block def inquiry(): return input('PLEASE PROVIDE A PASSWORD: ') def incorrect_answer(): return print(('Password must contain as many as 6 characters \ including lower-case, upper-case and numeric character').upper()) def heads_up(): return print('BE CAREFUL IT\'S THE LAST TRIAL') def correct_answer(): return print('YOUR PASSWORD IS VALID') # password check function def condition_to_psw(psw): symbols = r'\n$@#' result = any([i.islower() for i in psw]) and any([i.isupper() for i in psw]) and \ any([i.isdigit() for i in psw]) and any([i in psw for i in symbols]) length = len(psw) if 16 > length > 6 and result: return True else: return False def psw_check_loop_for(): for trial in range(3): if condition_to_psw(inquiry()): # == True return correct_answer() elif trial == 1: time.sleep(0.5) heads_up() else: incorrect_answer() psw_check_loop_for()
6f15a443d58247ea8ada1c3caa36bffac4f1d98c
ROYALBEFF/aaaaaa_arcade_game
/aaaaaa/ObstacleHandler.py
1,604
3.796875
4
from aaaaaa.Obstacle import Obstacle import random class ObstacleHandler: def __init__(self): pass @staticmethod def generate_obstacle(state): """ Generate a new obstacle with a probability of obstacle_prob percent. """ p = random.randint(0, 100) if p < state.obstacle_prob: if len(state.obstacles) < 10: state.add_obstacle(Obstacle(state.obstacle_speed)) @staticmethod def update_obstacles(state): """ Update position of obstacle. Remove obstacle from game state if it's out of bounds. :param state: Current game state. """ for obstacle in state.obstacles: obstacle.move() if obstacle.out_of_bounds(): state.remove_obstacle(obstacle) @staticmethod def powerup_obstacles(state): """ Make obstacles faster or appear more often. :param state: Current game state. :return: 'speed' if obstacles become faster, 'prob' if obstacles appear more often. """ # powerup obstacles if player reaches another 10000 points # reset counter state.reset_power_up_obstacles() p = random.randint(0, 100) # with probability of 1/3 increase obstacle speed by 1 if p <= 33: state.increase_obstacle_speed() return "speed" # with probability of 2/3 increase obstacle spawn probability by 1 percent else: state.increase_obstacle_prob() return "prob"
778ea996a187546e9656d515ea0cd9dc51085ddb
bjmarsh/insight-coding-practice
/daily_coding_problem/2020-07-31.py
1,002
4.3125
4
""" Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'. You can assume that the messages are decodable. For example, '001' is not allowed. """ def n_possible_decodings(encoding: str) -> int: # if string is empty, there is one (trivial) decoding if len(encoding) == 0: return 1 # if the string starts with a 0, there are no possible decodings if encoding[0] == '0': return 0 n_possible = 0 # the first digit can be mapped to one of the first 9 letters n_possible += n_possible_decodings(encoding[1:]) # if the first two digits are <=26, then we can combine them into a single letter if len(encoding) >= 2 and int(encoding[:2]) <= 26: n_possible += n_possible_decodings(encoding[2:]) return n_possible if __name__ == "__main__": print(n_possible_decodings('111'))
bbd910ce6b14165d9e2701be9abe91b9b70b74ca
natann4755/JavaAlexRony
/Lessens/lessen 15 p/4.py
943
3.734375
4
class car (object): def __init__(self,a,b=0): self.a=a self.b=b def dd(self): print("a:%s \nb: %s"% (self.a,self.b)) @staticmethod def prin(c): print ("a:%s \nb: %s"% (c.a,c.b)) def __ff(self): print ("jjj") def __cmp__(self, other): if isinstance(other,car): if self.a>other.a: return 1 elif self.a<other.a: return -1 else: return 0 class var(car): def __init__(self,a,b,c): car.__init__(self,a,b) self.c=c def prin(c): print ("a:%s \nb: %s \nc: %s" % (c.a, c.b, c.c)) c= car(22,33) car.kkk=88888 print(c.kkk) c1=car (44.55) print (c.__cmp__(c1)) print c.a c.dd() car.prin(c) d= var(66,7777,88) var.prin(d) class point (object): ("mmmmmm") def __init__(self,x=0,y=0): self.x=x self.y=y p1= point(7,9) print(point.__doc__)
d1c4ccf8b930480ec1c9e0b2bd1d11c58e3ea524
Mohan110594/Greedy-2
/Task_scheduler.py
1,612
3.75
4
// Did this code successfully run on Leetcode : Yes // Any problem you faced while coding this : None // Your code here along with comments explaining your approach: In this problem we first calculate the frequency of the largest occuring element and how many times the freq has occured.Then we using the above two parameters we calculate partitions,emptyslots,pending tasks,Idle task.with the above calculated parameters we can calculate the least number of intervals to finish the given tasks. # Time complexity --> o(n) #space compelxity --> o(1) class Solution(object): def leastInterval(self, tasks, n): """ :type tasks: List[str] :type n: int :rtype: int """ if n==0: return len(tasks) d=dict() for i in tasks: if i not in d: d[i]=1 else: d[i]=d[i]+1 maxi=float("-inf") #creating a dictionary and calculating the max occuring freq and how many times they have occured. for key,value in d.items(): if value>maxi: maxi=value count=1 elif value==maxi: count=count+1 maxfreq=maxi # print(maxfreq) partitions=maxfreq-1 # print(partitions) emptyslots=partitions * (n-(count-1)) # print(emptyslots) pendingtasks=len(tasks)-(maxfreq*count) # print(pendingtasks) idle=emptyslots-pendingtasks if idle<0: idle=0 # print(idle) return len(tasks)+idle
2b0ca4bd33ca78e4130332ee0122109f1a1194be
arpitx165/LeetCode
/LC30-2020/W2/q1.py
529
3.875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None #https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/529/week-2/3290/ class Solution(object): def middleNode(self, head): """ :type head: ListNode :rtype: ListNode """ fast = head while head and fast and fast.next: head = head.next fast = fast.next.next return head
16350bbdd5750887386b229f42715ae05a975983
rtridz/pythonfirst
/07_threads_and_os_env/progs/excel/open_excel.py
194
3.515625
4
import xlrd file = xlrd.open_workbook('file.xls',formatting_info=True) sheet = file.sheet_by_index(0) for rownum in range(sheet.nrows): row = sheet.row_values(rownum) for cell in row: print cell
92019d28127dce99c6b200df29efc25499889dc0
hadoopaws8/home-work-files
/homework_set_element_inserttion_and_deletion_and_checking.py
365
4.09375
4
s=set() n=int(input("enter the number of elements in set: ")) for i in range(n): s.add(int(input("enter next element of set: "))) check=int(input("enter which element you want check: ")) if check in s: print(check,"your element in set so i am deleted from set ") s.discard("check") else: print(check,"element is not present in set")
c681d5fb9b36176e2950555b9075c4d7c79a0e16
Jon-Ting/UH-DA-with-PY-summer-2019
/part02-e01_integers_in_brackets/src/integers_in_brackets.py
647
3.8125
4
#!/usr/bin/env python3 import re def integers_in_brackets(s): mo1 = re.findall(r"\[\s*[+-]?\w*] *\]", s) new_s = [] for i, strings in enumerate(mo1): mo2 = re.search(r"[A-Za-z]", strings) if not mo2: new_s.append(strings.strip("[").strip("]").strip()) new_s = " ".join(new_s) mo3 = re.findall(r' ?[+-]?\d+ ?', new_s) return_list = [int(x) for x in mo3] return return_list def main(): print(integers_in_brackets(" afd [asd] [12 ] [a34] [ -43 ]tt [+12]xxx!")) #print(integers_in_brackets(" afd [asd] [12 ] [a34] [ -43 ]tt [+12]xxx")) if __name__ == "__main__": main()
11ade73d572e6c943dbeaaac14e5cafdb4951200
dskard/challenges
/correlation1/corr.py
1,874
3.671875
4
# https://www.hackerrank.com/challenges/correlation-and-regression-lines-6 # # we could put columns in a dataframe and use the Series' corr() function, # setting the 'method' parameter to 'person': # # r = df['History Scores'].corr(df['Physics Scores'],method='person') # # calculating the person correlation coefficient is described here: # http://www.statisticshowto.com/how-to-compute-pearsons-correlation-coefficients/ import pandas as pd import pytest def pearson_correlation(d,x,y): d['xy'] = d[x] * d[y] d['x2'] = pow(d[x],2) d['y2'] = pow(d[y],2) n = len(d[x]) sxy = d['xy'].sum() sx = d[x].sum() sy = d[y].sum() sx2 = d['x2'].sum() sy2 = d['y2'].sum() top = (n*sxy) - (sx*sy) mid = ((n*sx2)-pow(sx,2))*((n*sy2)-pow(sy,2)) bot = pow(mid,0.5) return 1.0*top/bot def test_pc_1(): df = pd.DataFrame({ 'age' : [43,21,25,42,57,59], 'glucose' : [99,65,79,75,87,81]}) r = pearson_correlation(df,'age','glucose') assert round(r,6) == 0.529809 def pearson_correlation_2(x,y): """incase pandas library is not allowed""" xy = [] x2 = [] y2 = [] for i,j in zip(x,y): xy.append(i*j) x2.append(pow(i,2)) y2.append(pow(j,2)) n = len(x) sxy = sum(xy) sx = sum(x) sy = sum(y) sx2 = sum(x2) sy2 = sum(y2) top = (n*sxy) - (sx*sy) mid = ((n*sx2)-pow(sx,2))*((n*sy2)-pow(sy,2)) bot = pow(mid,0.5) return 1.0*top/bot if __name__ == "__main__": # df = pd.DataFrame({ # 'Physics Scores' : [15,12,8,8,7,7,7,6,5,3], # 'History Scores' : [10,25,17,11,13,17,20,13,9,15]}) # # r = pearson_correlation(df,'Physics Scores','History Scores') p = [15,12,8,8,7,7,7,6,5,3] h = [10,25,17,11,13,17,20,13,9,15] r = pearson_correlation_2(p,h) print "{0:.3f}".format(r)
d514bcf79015b1b51ca0c2f927be5716c5623b01
Adarsh232001/Basic-python-scripts
/guessingNumber.py
691
4.15625
4
#import random package to generate a secrate number import random secretNumber=random.randint(1,10) print('I am thinking of a number could you guess it between 1 and 10') #Ask the player to guess the number 6 times for guessesTaken in range(1,7): print('Take a guess') guess=int(input()) if guess<secretNumber: print('Your guess is low') elif guess>secretNumber: print('Your guess is high') else: break #in this condition the player's guess is correct if guess==secretNumber: print('Good job! You guessed my number in '+str(guessesTaken)+' guesses') else: print('Better luck next time. The number is '+str(secretNumber))
92c4b6e43d217b07e98e82181c6603b736943517
HouPoc/Practice
/data_structure/dt_stc.py
6,042
4.25
4
# #Basic Information node # class Node: #Initial the Node def __init__(self,data): self.data = data self.next = None # #Basic Linked List # class Linked_List: #Initial the Linked List with a Head Node def __init__(self,): self.head = Node('head') self.length = 0 #Overloading Insert function def Insert(self, node, after=None): next_node = self.head current_node = next_node self.length += 1 if after is None: #Insert a Node at the end of the linked list while next_node != None: current_node = next_node next_node = current_node.next current_node.next = node else: #Insert a Nose after a certain Node while next_node.data != after: next_node = next_node.next node.next = next_node.next next_node.next = node #Overloarding Delete function def Delete(self, after=None): next_node = self.head current_node = next_node if after is None: #Delete the last Node of the linked list while next_node.next is not None: current_node = next_node next_node = current_node.next current_node.next = None next_node.data = None if after is not None: #Delete a Node after a certain Node while next_node.data != after: next_node = next_node.next target = next_node.next next_node.next = target.next target.data = None target.next = None #Print out the length of the linked list and all nodes def Check(self): #print ('Lenght of the list {}'.format(self.length)) next_node = self.head.next while next_node is not None: print ('node {}'.format(next_node.data)) next_node = next_node.next # #Merge_Sort # def Merge_Sort(list_head): # Base Case if list_head is None or list_head.next is None: return else: front_half = Node(0) back_half = Node(0) Half(list_head, front_half, back_half) Merge_Sort(front_half) Merge_Sort(back_half) head = Node(0) head = Sort_Merge(front_half, back_half) list_head.data = head.data list_head.next = head.next def Sort_Merge(front, back): #base case result = Node(0) if front == None: result.data = back.data result.next = back.next return result elif back == None: result.data = front.data result.next = front.next return result if front.data < back.data: result.data = front.data result.next = Sort_Merge(front.next, back) else: result.data = back.data result.next = Sort_Merge(front, back.next) return result def Half(source, front_half, back_half): if source is None or source.next is None: front_half = source if source is not None: front_half.data = source.data front_half.next = None back_half = None else: slow = source fast = source.next while fast is not None: fast = fast.next if fast is not None: slow = slow.next fast = fast.next back_half.data = slow.next.data back_half.next = slow.next.next #Ending the frst half by make the mid node point to none slow.next = None front_half.data = source.data front_half.next = source.next #FILO #Basic Stack (array as the form float uMix;uniform float uMix;stack holder)i #Stack is underflow when it is completely empty #Stack is overflow when it is completely full class Stack(): def __init__(self, length): self.root = [] #root is an empty array self.indicator = -1 #Show stack status self.length = length def Push(self, item): if self.indicator != self.length - 1: self.root.append(item) self.indicator += 1 else: print("stack is overflow") def Pop (self): if self.indicator != -1: self.root.pop() self.indicator -= 1 else: print ("stack is underflow") def Check (): print (self.root) print (self.indicator) #FIFO #Basic Queue #Underflow: Queue is Completely empty #Overflow: Queue is Completely full #Operations: Enqueue, Dequeue, Peek, isFull, isEmpty class Queue(): def __init__(self,length): self.root = [] self.indicator = -1 self.length = length def isFull(self): if self.indicator == self.length - 1: print("queue is overflow") return True else: return False def isEmpty(self): if self.indicator == -1: print("queue is underflow") return True else: return False def Enqueue(self, data): if not self.isFull(): self.root.append(data) self.indicator += 1 def Dequeue(self): if not self.isEmpty(): self.root.pop(0) self.indicator -= 1 def Peek(self): print (self.root[0]) def Check(self): print (self.root) print (self.indicator) #Priority Queue in heap (array form) #array[0] is always the root #For array[k], its left child array->[2k], its right child->array[2k+1] #For array[k], its parent->array[k/2] #Each child must be less than its parent. #Each row must be filled before going to the next row #Add an element, then compare with its parent and change position if needed #After Removing the highest priority one, move the last one to the root position. and switch it with its larger child #Operation: Intial, Insert, Remove, Peek
36c407ccfc8e47b2242c242983899bb7ab9e7485
Endkas/TSP
/ClassCities.py
2,503
4.125
4
import numpy as np import random class Cities(object): def __init__(self,n,seed = 10): """ Parameters ---------- n : Number of cities you want to generate seed : The seed you want to use for random.seed(seed=seed), optional. The default is 10. The seed is by default the same for all the different classes,so that with the same number of cities, the matrix of distances is the same. With that we can compare results of different algorithms as it exactly the same numbers in the distances'matrix. At the initizialtion of the object, the method matdist is applied. With this class Cities,we want to create n cities,with latitudes and longitudes. With thoses we can generate a matrix of distances and then apply our different algorithm to solve the Travelling Salesman Prblem. Cities will be the superclass of BruteForce,nearest neighbour and ant classes. """ self.n = n self.seed = seed self.matdist() # at the initilization it apply the method matdis to have the ditance matrix def latlong(self): """ Returns ------- x a lit of latitutes of size n. y a list of longitude of size n. """ self.x = [] self.y = [] random.seed(self.seed) for i in range(self.n): a = random.uniform(0,18) b = random.uniform(0,36) self.x.append(a) self.y.append(b) return self.x,self.y def matdist(self): """ Returns ------- mat This a symmetric matrix of distances,it will be primoridal to apply the TSP problem. coord It is a list of tuples (x,y),you can see it conceptualy as GPS coordinates aka the location of our map. """ self.latlong() self.coord = [] self.mat = np.zeros((self.n,self.n)) for i in range(self.n): self.coord.append((self.x[i],self.y[i])) for j in range(i+1,self.n): la = (self.x[i]-self.x[j])**2 lon = (self.y[i]-self.y[j])**2 self.mat[i,j] = (la + lon)**0.5 self.mat[j,i] = self.mat[i,j] return self.mat,self.coord
26a71c04779db981b1ace63c454f26dea6d69184
MrLarsouille/MrLarsouille
/Exercices/createDictionaryFromClass.py
159
3.65625
4
#Créez unn dictonnaire via le constructeur de la classe dict. mydict = dict() mydict["E01"] = "Lar" mydict["E02"] = "souille" print("mydict:", mydict)
0cd2d54ffdcad0cc7b1933bea479cd9f584daf53
RomanMillan/EjerciciosBucles
/Ej_II_T_6.py
202
4.0625
4
total = 0 acum = 0 numero = input("Enter one number: ") numero2 = input("Enter one number: ") while total < int(numero): acum = acum + int(numero2) total += 1 print("The product is ", str(acum))
8089bbe67a2e7c7e2e9fca0da242e85a2c39817e
gadepall/IIT-Hyderabad-Semester-Courses
/EE2350/Coding Assignment-1/2.1.1j.py
1,343
3.546875
4
# code for simulating y1[n] = x[n] - 2x[n-1] + x[n-2] and y2[n] = x[n] - x[n-1] import numpy as np import matplotlib.pyplot as plt s = int(input("No.of Elements in signal: ")) # Generating the input x = np.ones(s) time = np.arange(s) for i in range(s): x[i] = 0.95 ** i def Filter(S): # Function generator """ y[n] = x[n] - 2x[n-1] + x[n-2] """ s = S.shape[0] Y = np.zeros(s+2) time_output = np.arange(s+2) for i in range(s+2): a,b,c = i,i-1,i-2 if (a < 0 or a > s-1): l = 0 else: l = S[i] if (b < 0 or b > s-1): m = 0 else: m = S[i-1] if (c < 0 or c > s-1): n = 0 else: n = S[i-2] Y[i] = l - 2*m + n return Y,time_output def Backward_Differencing_System(S): # Function of Backward Differencing System """ y[n] = x[n] - x[n-1] """ s = S.shape[0] Y = np.zeros(s+1) time_output = np.arange(s+1) for i in range(s+1): a,b = i,i-1 if (a < 0 or a > s-1): l = 0 else: l = S[i] if (b < 0 or b > s-1): m = 0 else: m = S[i-1] Y[i] = l - m return Y,time_output y1,t1 = Backward_Differencing_System(x) y2,t2 = Filter(x) plt.figure(figsize=(13, 8)) ax = plt.subplot(1, 3, 1) plt.stem(time,x,'r') ax = plt.subplot(1,3,2) plt.stem(t1,y1,'y') ax = plt.subplot(1,3,3) plt.stem(t2,y2,'y') plt.show()
5aa2cb13fd3e0d903bbd412d46191765fc383388
dsocaciu/Books
/ImplementingDerivativesModels/Chapter2/figure210.py
1,068
3.5
4
#Implementing Derivatives Models - Clewlow and Strickland #Chapter 2 #Figure 2.10 #valuation of a European Call in an additive tree from math import exp,pow,sqrt #parameters #precompute constants K = 100 T = 1.0 S = 100 sig = 0.2 r = 0.06 N = 3 dt = round(T/N,4) #.3333 nu = round(r-0.5*pow(sig,2),4) #.04 dxu = round(sqrt(pow(sig,2)*dt + pow(nu*dt,2)),4) #.1162 dxd = -dxu #-.1162 pu = round(.5 + .5*(nu*dt/dxu),4) #.5574 pd = 1-pu #.4426 disc = round(exp(-r*dt),4) #.9802 print(dt) print(nu) print(dxu) print(dxd) print(pu) print(pd) print(disc) #initialize asset price at maturity step N N1 = N+1 St = [0.0] * N1 St[0] = round(S*exp(N*dxd),4) for j in range(1,N1): St[j] = round(St[j-1]*exp(dxu-dxd),4) #print(j) print(str(St)) #initialize option values at maturity C = [0.0] * N1 for j in range(0,N1): C[j] = round(max(0.0, float(St[j]-K)),4) print (str(C)) #step back through the tree for i in range(N,0,-1): for j in range(0,i): #print(j) C[j] = round(disc * (pu* C[j+1] + pd*C[j]),4) print(str(C)) print("European Call: " + str(C[0]))
90ddf339aacc7da57b18d11769b344006a65d303
paolamariselli/Python-Problem-Sets
/Spell Checker/checker.py
1,601
3.9375
4
#!/usr/bin/env python import dictionary import sys import time def sanitize_word(word): """ 1. Transforms the word to lower case 2. Removes any surrounding whitespace 3. Removes any leading or trailing punctuation """ word = word.lower() word = word.strip() punct = set("[]*()-,.:;?!/`\"\'") should_delete = True while should_delete: if len(word) == 0: break should_delete = False if len(word) > 0 and word[-1] in punct: word = word[:-1] should_delete = True if len(word) > 0 and word[0] in punct: word = word[1:] should_delete = True word = word.strip() return word if len(sys.argv) < 3: print "usage: %s dictionary-file text-file" % sys.argv[0] sys.exit(-1) dictionary_name = sys.argv[1] text_file_name = sys.argv[2] start = time.clock() dict = dictionary.load(dictionary_name) if dict is None: print "dictionary load failed" sys.exit(-1) text_file = open(text_file_name, "rb") misspelled = set() num_total = 0 for line in text_file: line = line.replace("-", " ") for word in line.split(): word = sanitize_word(word) if len(word) == 0: continue if not dictionary.check(dict, word): num_total += 1 misspelled.add(word) text_file.close() print misspelled print "dictionary size: %d" % dictionary.size(dict) print "num misspelled: %d" % num_total print "num unique: %d" % len(misspelled) dictionary.unload(dict) stop = time.clock() print "time (s):", stop - start
bf9a4c841e52568473f4c09920d7169146b3cc2d
rmgard/python_deep_dive
/sixthSection/partialFn.py
1,583
4.5
4
''' What if we only want to parameters in my_func()? See how fn() uses my_func, but presets the value of a? ''' def my_func(a, b, c): print(a, b, c) def fn(b, c): return my_func(10, b, c) ''' We can also use functools.partial With partial() you define the vars you don't want to feed into the function. ''' from functools import partial f = partial(my_func, 10) # We can do the same thing using a lambda lambda_f = lambda x, y: my_func(x, y) ''' We can also handle more complex arguments ''' def my_complex_func(a, b, *args, k1, k2, **kwargs): print(a, b, args, k1, k2, kwargs) def complex_f(b, *args, k2, **kwargs): return my_complex_func(10, b, *args, k1='a', k2=k2, **kwargs) complex_f = partial(my_complex_func, 10, k1='a') ''' Handling complex arguments such as power: ''' def pow(base, exponent): return base ** exponent square = partial(pow, exponent=2) cube = partial(pow, exponent=3) ############################################################# # Using mutable types.... Let's look at a list ############################################################# def mutable_func(a, b): print(a, b) a = [1, 2] mutable_f = partial(my_func, a) ############################################################# # Sorting with partials ############################################################# origin = (0, 0) points = [(1, 1), (0, 2), (-3, 2), (0, 0), (10, 10)] dist2 = lambda a, b: (a[0] - b[0])**2 + (a[1] - b[1])**2 net_dist = partial(dist2, origin) basic_sort = sorted(points) key_sort = sorted(points, key=net_dist)
91caec4a8b0f6117f3e8777f61b42639cc845dfd
lzhang007/pytest
/ifstat.py
255
3.515625
4
#!/usr/bin/python #Filename:ifstat.py number=23 guess=raw_input("type a integer:") if guess == number: print'great,you guess it' elif guess > number: print'no,it little lower than number' else: print'no,it little big than number' print'done'
c323d1e4266d6582b7733df2839c4ec40b1f54b5
parshuramsail/PYTHON_LEARN
/paresh26/A6.py
108
3.765625
4
my_list=[1,2,3,4,5,6,7,8,9,10] list_sum=2 for num in my_list: list_sum=list_sum+num print(list_sum)
1ff5e7646ce5087f30689120e3a614462938f1d5
rajeshpg/project_euler_solutions
/python/Euler6.py
359
3.671875
4
""" Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ square = lambda n: n * n squareOfSumOfN = lambda n: square((n*(n+1))/2) sumOfSquareOfN = lambda n: ((n * (n+1) * ((2*n)+1)) / 6) def solution(num): return squareOfSumOfN(num) - sumOfSquareOfN(num)
e74a5618cc78d2a6df279ec2f63f1e929e2137c4
gadodia/Algorithms
/algorithms/Arrays/singleNumber.py
363
3.875
4
''' This problem was recently asked by Facebook: Given a list of numbers, where every number shows up twice except for one number, find that one number. Example: Input: [4, 3, 2, 4, 1, 3, 2] Output: 1 Time: O(n) ''' def singleNumber(nums): dup = 0 for num in nums: dup = dup ^ num return dup print(singleNumber([4, 3, 2, 4, 1, 3, 2])) # 1
aacd16e5c8a43394e186819af9bcfe987a95b517
carden-code/python
/stepik/girls_only.py
788
4.34375
4
# The football team recruits girls from 10 to 15 years old inclusive. # Write a program that asks for the age and gender of an applicant, # using the gender designation m (for male) and f (for female) to determine whether the applicant is eligible to join # the team or not. If the applicant fits, then output "YES", otherwise output "NO". # # Input data format # At the entrance to the program, a natural number is submitted - the age of the applicant and # the letter denoting the sex m (man) or f (woman). # # Output data format # The program should display the text in accordance with the condition of the problem. age = int(input('Enter your age:')) sex = input('Enter your gender ( m - man or f - woman ):') if 10 <= age <= 15 and sex == 'f': print('YES') else: print('NO')
53564278a4ac85ba599801dfc230de06924b3865
ivan-yosifov/python-2019
/4strings.py
503
3.984375
4
######################## # Learn Python 2019 ######################## import os os.system('clear') greetings = "My boss yelled \"Get back to work!\"" print(greetings) first_name = 'Megan' last_name = 'Fox' print(first_name + ' ' + last_name) print(first_name.upper()) print(first_name.lower()) print(first_name.capitalize()) print(first_name.title()) print(first_name.swapcase()) print(len(first_name)) print(first_name[0]) print(first_name[0:3]) # Meg print(first_name.split('g')) # ['Me', 'an']
70a2d311d71c785f99ca9948ff0db0b919018841
v-ivanko/QAlight_Online_G7_
/4-if.py
397
3.96875
4
a = int(input("\nВведите 1 значение: ")) b = int(input("Введите 2 значение: ")) v = int(input("Введите 3 значение: ")) if a > b: print('Свершилось!') elif a < b: print('Да ну!') else: print('А если так?') if a + v > b - v: print('Свершилось!') elif a + v < b - v: print('Да ну!')
153040a0b454f0990925b79dd70eabe20ffd3a25
je-suis-tm/recursion-and-dynamic-programming
/pascal triangle with memoization.py
3,486
4.125
4
# coding: utf-8 # In[1]: def pascal_triangle(n): row=[] #base case if n==1: return [1] else: #calculate the elements in each row for i in range(1,n-1): #rolling sum all the values within 2 windows from the previous row #but we cannot include two boundary numbers 1 in this row temp=pascal_triangle(n-1)[i]+pascal_triangle(n-1)[i-1] row.append((temp)) #append 1 for both front and rear of the row row.insert(0,1) row.append(1) return row # In[2]: def printit(n): rows=[] #the first loop is to concatenate all rows for j in range(1,n+1): row=pascal_triangle(j) #this loop is to reshape the row #insert '' between each element in the row for k in range(1,j+j-1): #if index k is an odd number,insert '' if k%2!=0: row.insert(k,'') #need to add '' to both sides of rows #n-j=((n+n-1)-(j+j-1))/2 #we set the n th row plus n-1 space as the total elements in a row #we minus the reshaped row (j+j-1) #we get the space for both sides #finally we divide it by 2 and add to both sides of the row #we append the styled row into rows rows.append(['']*(n-j)+row+['']*(n-j)) #print out each row for i in rows: print(i) # In[3]: #using memoization global memoization memoization={1:[1]} def mmz(n): global memoization if n not in memoization: row=[] for i in range(1,n-1): #rolling sum all the values within 2 windows from the previous row #but we cannot include two boundary numbers 1 in this row temp=mmz(n-1)[i]+mmz(n-1)[i-1] row.append((temp)) #append 1 for both front and rear of the row row.insert(0,1) row.append(1) memoization[n]=row return memoization[n] # In[4]: def printit_mmz(n): rows=[] #the first loop is to concatenate all rows for j in range(1,n+1): #need to be careful with copy #use list comprehension instead of deepcopy row=[i for i in mmz(j)] #this loop is to reshape the row #insert '' between each element in the row for k in range(1,j+j-1): #if index k is the odd number,insert '' if k%2!=0: row.insert(k,'') #need to add '' to both sides of rows #n-j=((n+n-1)-(j+j-1))/2 #we set the n th row plus n-1 space as the total elements in a row #we minus the reshaped row (j+j-1) #we get the space for both sides #finally we divide it by 2 and add to both sides of the row #we append the styled row into rows rows.append(['']*(n-j)+row+['']*(n-j)) #print out each row for i in rows: print(i) # In[5]: #apparently memoization is faster #7.04 ms ± 325 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) get_ipython().run_line_magic('timeit', 'printit(7)') # In[6]: #1.12 ms ± 10.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) get_ipython().run_line_magic('timeit', 'printit_mmz(7)')
d01b274e5e5b7bb9438b8f309f41a2f6d90de745
frankieliu/problems
/leetcode/python/5/longest-palindromic-substring.py
1,767
3.921875
4
"""5. Longest Palindromic Substring Medium 2762 268 Favorite Share Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb" Accepted 435,975 Submissions 1,680,053 """ class Solution: def longestPalindrome(self, s): """ :type s: str :rtype: str """ slen = len(s) if slen == 0: return "" if slen == 1: return s max_palindrome_len = 0 lbest = 0 rbest = 0 # current index to consider as the seed seed = 0 while True: el = s[seed] print("Considering index", seed, el) lptr = seed rptr = seed # group similar characters together while lptr+1 < slen and s[lptr + 1] == el: lptr += 1 # next seed to consider seed = lptr + 1 cur_len = lptr - rptr + 1 while ( lptr+1 < slen and rptr-1 >= 0 and s[lptr+1] == s[rptr-1] ): lptr += 1 rptr -= 1 cur_len += 2 print("Palindrome:", rptr, lptr, cur_len) if cur_len > max_palindrome_len: max_palindrome_len = cur_len lbest = lptr rbest = rptr if ( seed == slen or slen - seed <= max_palindrome_len // 2 ): break return s[rbest:lbest+1] s = Solution() print(s.longestPalindrome("aaaabaaa"))
af843bbfe30f215c88755019e32b05f826127165
MahdieRad/Assignment-3
/5.py
257
4.15625
4
A=int(input('Enter a Number\n')) B = 1 while True: if A % B == 0: A //= B else: break B += 1 if A == 1: print('This is a Factorial Number :)') else: print('Try Again,This is Not a Factorial Number!')
5e34d754f7e66ab486e97622e4464d460715f146
cjx1996/vscode_Pythoncode
/Study python without teacher/202003102container0.py
1,162
4.53125
5
''' In this file,we will learn the use of containers,which contain list、tuple and dictionary. Of course,we will learn the use of method only can be use in objects. ''' #这是对列表list一些method的尝试使用 '''定义''' a=list() a=[1,2,3,4] a=[] a=[1,2,3,4] colors=['blue','green','yellow'] colors1=['blue','green','yellow'] colors2=['orange','pink','black'] colors3=colors1+colors2 if 'green' in colors: print("'green' is in colors!") if "black" not in colors: print("'black' is not in colors!") print(len(colors3)) guess=input("Guess a color:") if guess in colors3: print("You guessed correctly!") else: print("Wrong!Try again.") #下面是对元组tuple的一些method的使用 '''定义''' a=tuple() a=() '''一些method的使用''' a=(9) b=('9') c=('9',) #type(a) is int;type(b) is str ;type(c) is tuple dys=['1984','Brave New World','Fahrenheit 451'] print(dys[2]) print('1984' in dys) print('Handmaid' not in dys)
c0680fe79a8b87601c64da64e6e194b869d7de54
AnuPriya1237/Books_Collection
/Milstone_project-02/utils/database2.py
1,133
3.78125
4
"""concerned with storing and retrieving books from csv file. csv file format name,author,read """ book_file = 'book.txt' def create_book_table(): with open(book_file,'w') as file: pass #just to mark that file is there def add_books(name, author): with open('book.txt','a') as file: file.write(f" name:{name}, author:{author} ,0\n") def get_all_books(): with open('book.txt','r') as file: line = file.readlines() lines = [li.strip() for li in line] data = lines.split(',') return [ {'name':data[0], 'author':data[1],'read':data[2] } ] def to_read_books(bname): bookie = get_all_books() for book in bookie: if book['name'] == bname: book['read'] = '1' _save_books(bookie) def _save_books(bookie): with open('book.txt','w') as file: for book in bookie: file.write(f"book:{book['name']},author:{book['author']},read:{book['read']}\n") def to_delete_books(bname): bookie = get_all_books() books = [book for book in bookie if book['name'] != bname] _save_books(books)
2efc0326bdbfa63e061ea17f1da1eeefc6816019
m-e-l-u-h-a-n/Information-Technology-Workshop-I
/python assignments/assignment-2/5.py
193
3.546875
4
lst=[(),(),("",),('a','b'),('a','b','c'),('d',)] x=len(lst) l=[] print(type(lst[x-1])) for i in range(x): if isinstance(lst[i], tuple) and len(lst[i]) > 0: l.append(lst[i]) print(l)
92ebae533d4f7e9b2c652cd10a0cf6e0cab6872c
6dec3fb8/pycarproject
/erlthread.py
6,102
3.65625
4
#!/usr/bin/python3 # This module is used to simulate the behavior of Erlang threads. # It is really convenient to handle multi-threading things. # 8 16 24 32 40 48 56 64 72 80 # ruler:-------+-------+-------+-------+-------+-------+-------+-------+-------+ """ Python erlang thread simulate module -------------------------------------------------------------- Basic structure: class ErlThread(threading.Thread): the thread to use. def spawn: create a thread (but not invoking it). def send: send a message (like dict, list, etc) to a thread. def halt: stop a thread by setting an event of that thread """ # Future imports are written before # import. # And the __all__, __version, __author__ are here too. __version__ = '0.1' __author__ = 'HexFaker' __all__ = [ 'ErlThread', 'spawn', 'send', 'halt', ] # Imports import time import threading import queue # Constants and global variables DEFAULT_POLL_INTERVAL = 0.02 # Functions and decorators # for the default behavior. May deprecate. def dummy(env, msg): # debug print("Dummy received msg:", msg) pass # Thread factory. Will not run at creation. def spawn(env=None, name=None, poll_interval = DEFAULT_POLL_INTERVAL, message_handler=dummy, tick_action=None): env = env or {} th = ErlThread( env, name, poll_interval, message_handler, tick_action ) return th # Other important methods. def send(thread, message): """Send the message to the thread and notify the thread to receive the message.""" q = thread.inbox cv = thread.notification with cv: q.put(message) cv.notify() def halt(thread, timeout=None): """ Halt the thread. (DEPRECATED)You need join manually to wait for the thread to end. (update 1) This function will automatically join for you. """ ev = thread.exit_event ev.set() if time is None: thread.join() else: thread.join(timeout) # for precious ticking def ticker(ev, job, *args): job(*args) while not ev.is_set(): pass def halt_ticker(ev): ev.set() # Classes and metaclasses class ErlThread(threading.Thread): """ The erlang-like thread. ------------------------------------------------------------ basic structure: - A queue inbox - An event to tell the thread to check the inbox (or to use an condition) - An event to tell the thread to exit. - An inner lock to makesure that all the polling are atomic (or to use the condition instead) - getters and setters to the inbox, notice_event(or condition) and the exit_event(will use property) """ def __init__(self, env=None, name=None, poll_interval=DEFAULT_POLL_INTERVAL, message_handler=None, tick_action=None): """ Constructor. The parameter are almost the same as Thread. """ # if not args: # args = ([[default_, dummy]],) super(ErlThread, self).__init__(name = name) self._inbox = queue.Queue() self._condition_getmsg = threading.Condition() self._exit_event = threading.Event() self._message_handler = message_handler self._tick_action = tick_action self._poll_interval = poll_interval self._env = env or {} def run(self): while not self._exit_event.is_set(): if self._tick_action is not None: ev = threading.Event() tickth = threading.Thread( target=ticker, args=(ev, self._tick_action, self.env) ) tick_timer = threading.Timer( self._poll_interval, halt_ticker, args=(ev,) ) tickth.start() tick_timer.start() with self._condition_getmsg: result = self._condition_getmsg.wait(self._poll_interval) if result: while not self._inbox.empty(): try: msg = self._inbox.get_nowait() except queue.Empty: # ERR! jump out break else: self._message_handler(self.env, msg) if self._tick_action is not None: tick_timer.join(self._poll_interval) @property def inbox(self): return self._inbox @inbox.setter def inbox(self, value): raise RuntimeError("Cannot change the inbox of a thread!") @property def notification(self): return self._condition_getmsg @notification.setter def notification(self, value): raise RuntimeError("Cannot change the Condition of a thread!") @property def exit_event(self): return self._exit_event @exit_event.setter def exit_event(self, value): raise RuntimeError("Cannot change the exit event of a thread!") @property def env(self): return self._env @env.setter def env(self, value): if isinstance(value, dict): self._env = value else: raise ValueError("Environment should be a dict!") # simple test def _test_2(): env={} def print_msg(env, msg): print("Message:", msg) def tick_test(env): print('Tick') send(env['t1'], 'hello') def send_loop(env, msg): send(msg[0], msg) th1 = spawn( message_handler=print_msg ) th2 = spawn( tick_action=tick_test ) env['t1'] = th1 th2.env = env th1.start() th2.start() time.sleep(0.2) send(th1, 'hello') halt(th1) halt(th2) print(th1.is_alive()) print(th2.is_alive()) # main if __name__ == '__main__': _test_2()
34a8abda0883a707ad73fb669e550b5773431670
molejnik88/python_nauka
/własne pomysły/nauka_klas/electric_car.py
1,121
3.796875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # # electric_car.py # # Copyright 2016 Maciej Olejnik <maciej@maciej-pc> from car import Car class Battery(): """Klasa reprezentująca baterię""" def __init__(self, battery_size): self.battery_size = battery_size def describe_battery(self): """Wyświetla pojemność baterii""" print( "Pojemność baterii wynosi : " + str(self.battery_size) + " kWh." ) def get_range(self): """Na podstawie pojemności akumulatora wyświetla zasięg pojazdu""" if self.battery_size == 70: car_range = 240 elif self.battery_size == 90: car_range = 270 message_b = "Twój zasięg wynosi : " + str(car_range) + " mil." print(message_b) # dziedziczenie - klasa potomna class ElectricCar(Car): """Przedstawia cechy charakterystyczne samochodu elektrycznego""" def __init__( self, make, model, year, odometer_reading = 0, battery_size = 70 ): """Inicjalizacja atrybutów klasy nadrzędnej""" super().__init__(make, model, year, odometer_reading) """Inicjalizacja atrybutów klasy potomnej""" self.battery = Battery(battery_size)
ad361f38a61d5af174ed3584bd67268f3b003196
AmeyLaddad/A-Udacity
/introduction to python (3)/chapter 2/Rating_survey.py
1,529
4.5625
5
def convert_to_numeric(score_input): """ Convert the score to a numerical type.""" a = float (score_input) return a def sum_of_middle_three(s1,s2,s3,s4,s5): """Find the sum of the middle three numbers out of the five given.""" add_all = s1 + s2 + s3 + s4 + s5 final = add_all - max(s1,s2,s3,s4,s5) - min (s1,s2,s3,s4,s5) return final def score_to_rating_string(score): """ Convert the average score, which should be between 0 and 5, into a string rating.""" if (0 <= score < 1): return "Terrible" elif (1 <= score < 2): return "Bad" elif (2 <= score < 3): return "OK" elif (3 <= score < 4): return "Good" elif (4 <= score <= 5): return "Excellent" def scores_to_rating(score1,score2,score3,score4,score5): """ Turns five scores into a rating by averaging the middle three of the five scores and assigning this average to a written rating. """ #STEP 1 convert scores to numbers score1 = convert_to_numeric(score1) score2 = convert_to_numeric(score2) score3 = convert_to_numeric(score3) score4 = convert_to_numeric(score4) score5 = convert_to_numeric(score5) #STEP 2 and STEP 3 find the average of the middle three scores average_score = sum_of_middle_three(score1,score2,score3,score4,score5)/3 #STEP 4 turn average score into a rating rating = score_to_rating_string(average_score) return rating print (scores_to_rating(5,"5",'5',3.0,5.0000))
460c261fff6b824b1fe9eac44d3dd9bc670eb95b
xwmtp/advent-of-code-2020
/Day23/Day23.py
2,310
3.546875
4
# https://adventofcode.com/2020/day/23 input = '219347865' class Cups: def __init__(self, init_circle, init_cup): self.circle = init_circle self.total_cups = len(init_circle) self.min_cup = min(init_circle) self.max_cup = max(init_circle) self.current_cup = init_cup def play(self, rounds): for r in range(rounds): if r >0 and r % 1000000 == 0: print(f"Move {r}...") self.move() return self.circle def move(self): picked_up = self._pick_up_cups() destination = self.get_destination_cup(picked_up) self._place_cups(picked_up, destination) self.current_cup = self.circle[self.current_cup] def get_destination_cup(self, picked_up): cup = self.current_cup while True: cup = cup - 1 if cup < self.min_cup: cup = self.max_cup if cup not in picked_up: return cup def _pick_up_cups(self): picked_up = [] cup = self.current_cup for i in range(3): select_cup = self.circle[cup] picked_up.append(select_cup) cup = select_cup self.circle[self.current_cup] = self.circle[cup] return picked_up def _place_cups(self, picked_up, destination): self.circle[picked_up[-1]] = self.circle[destination] self.circle[destination] = picked_up[0] def cups_to_circle(cups): circle = {} for i, cup in enumerate(cups[:-1]): circle[cup] = cups[i+1] circle[cups[-1]] = cups[0] return circle def circle_to_cups(circle, start_cup): cups = [] cup = start_cup while True: cups.append(cup) cup = circle[cup] if cup == start_cup: break return cups # --- Part 1 --- # init_cups = [int(c) for c in input] init_circle = cups_to_circle(init_cups) game = Cups(init_circle, init_cups[0]) circle = game.play(100) print(''.join([str(c) for c in circle_to_cups(circle, 1)[1:]])) # --- Part 2 --- # init_cups = [int(c) for c in input] + [n for n in range(10, 1000001)] init_circle = cups_to_circle(init_cups) game = Cups(init_circle, init_cups[0]) circle = game.play(10000000) cup_1 = circle[1] cup_2 = circle[cup_1] print(cup_1 * cup_2)
fdb3e30f0ae14aaf00127ce3cd41dfb7c0897356
KeepFreedomNoCare/Anonymous-
/lag.py
712
3.828125
4
#strings print('Hello World') msg = 'Hello World' print(msg) firstName = 'Bilal' lastName = 'Ahmed' fullName = firstName + ' ' + lastName print(fullName) #lists bikes = ['trek', 'redline', 'gaint'] firstBike = bikes[0] lastBike = bikes[-1] for bike in bikes: print(bike) square = [] for x in range(1, 11): square.append(x**2) print(square) square = [x**2 for x in range(1, 11)] print(square) finsher = ['bil', 'mon','pola'] firstTwo = finsher[:2] print(firstTwo) bikez = bikes[:] print(bikez) dim = (1920, 1080) x = 1 if x == 1: print(dim) if 'do' not in bikes: print('trek') dic ={'key1': 1, 'key2': 2} print(dic) print(dic['key1'])
3d1671f924a38ad78eec3e91acb974e5e5becfe4
luohuaizhi/test
/Questions/testFrog.py
529
3.640625
4
# -*-encoding:utf-8-*- import sys end = 0 # 终点 cnt = 0 # 统计组合方式 def jump(start): global cnt for i in [1,2]: cur = start+i if cur >= end: print start print cur cnt += 1 continue jump(cur) def main(n): """ 一只青蛙一次可以跳1阶或者2阶,n阶,有多少种到达终点的方式。(递归) """ global end end = n jump(0) print cnt if __name__ == "__main__": main(int(sys.argv[1]))
c608bd85114516f69c294bb707a3668b92d59424
Kakashi-93/word-guessing
/wordGuessing2.py
5,416
4.15625
4
import random wordList = ['cat', 'car', 'rat', 'dog', 'pan', 'pen', 'fox', 'gun', 'wax'] word = random.choice(wordList) var1 = "_" var2 = "_" var3 = "_" guess = 0 guessCharacter = "" print(""" ******************************************************************* * WELCOME! To the Word Guessing game * * Game Rules: * * 1- There is a word that consist of 3 letters, try to guess * * 2- You will be guessing the letters not the word * * 2- If you made 5 wrong attempts you will lose * * 3- Read the previous rules carefully * ******************************************************************* """) while guess < 10: if guess < 6: guessCharacter = input("What is your guess? ").lower() # if guess is true if guessCharacter == word[0]: var1 = guessCharacter print("*" * 20) print("Your guess is right") print(f"The word is {var1} {var2} {var3}") # check if the word was guessed successfully if var1 == word[0] and var2 == word[1] and var3 == word[2]: print(""" *********************************** * Congratulations you have won! * *********************************** """) break # if guess is true elif guessCharacter == word[1]: var2 = guessCharacter print("*" * 20) print("Your guess is right") print(f"The word is {var1} {var2} {var3}") # check if the word was guessed successfully if var1 == word[0] and var2 == word[1] and var3 == word[2]: print(""" *********************************** * Congratulations you have won! * *********************************** """) break # if guess is true elif guessCharacter == word[2]: var3 = guessCharacter print("*" * 20) print("Your guess is right") print(f"The word is {var1} {var2} {var3}") # check if the word was guessed successfully if var1 == word[0] and var2 == word[1] and var3 == word[2]: print(""" *********************************** * Congratulations you have won! * *********************************** """) break # if guess is wrong! else: guess += 1 print("Sorry, your guess is wrong!") print("*" * 20) print("You can try again ^_^") print(f"You have {5 - guess} attempts left") # if it is the 1st wrong attempt if guess == 1: print( " |\n" " | \n" " |\n" " ") # if it is the 2nd wrong attempt elif guess == 2: print("\n" " |\n" " |\n" " |\n" " |\n" " | \n" " |\n" " ") # if it is the 3rd wrong attempt elif guess == 3: print("\n" " ____\n" " | |\n" " o |\n" " |\n" " |\n" " | \n" " |\n" " ") # if it is the 4th wrong attempt elif guess == 4: print("\n" " ____\n" " | |\n" " o |\n" " /|\ |\n" " |\n" " | \n" " |\n" " ") # if it is the last wrong attempt elif guess == 5: print("\n" " ____\n" " | |\n" " o |\n" " /|\ | GAME OVER\n" " | |\n" " / \ | \n" " |\n" " ") print(""" ************************************************** * Sorry, the 5 attempts are finished * * You can run the game again if you like ^_^ * ************************************************** """) print(f"The word was {word}") break
144b2feb52c917d62433f6ceb38c5237165934f1
ronj1901/ICS_32
/ICS 32 midterm/midterm-practice (1).py
3,788
4.25
4
### If you want to run the code, you should comment out the problems you haven't ### done yet so you can't see the answers for them. ### Hints for each problem are at the bottom of this file ## ### 1. What's the output of the following code? ##try: ## try: ## a = 5 ## b = 7 ## c = "five" ## d = "seven" ## print(a*c) ## print(c+d) ## except: ## print(b*c) ## else: ## print(c*d) ## finally: ## print("first finally") ##except: ## print("second except") ##else: ## print("second else") ##finally: ## print("second finally") ## ####ANSWERS ####fiveseven ## ## 2. Imagine you have 3 modules as seen below ##"first.py" ##import second ##print("1") ##if __name__ == '__main__': ## print("first main") ## ##"second.py" ##import third ##print("2") ##if __name__ == '__main__': ## import first ## print("second main") ## ##"third.py" ##print("3") ##if __name__ == '__main__': ## import second ## print("third main") ## ## What is the output if ## a) first.py is run, ## b) second.py is run, and ## c) third.py is run? ## ## ## 3. What's wrong with the following class? Just try to fix the class, ## don't fix anything in the if name = main block ##class Person: ## def __init__(self, name): ## self.name = name ## self.age = 0 ## def grow_up(self): ## self.age += 1 ## ##if __name__ == '__main__': ## a = Person("Alex") ## a.grow_up() # 4. Write a function that takes a nested list of integers and returns the # minimum. Below is a function definition but you need to fill in the body. # Remember that a nested list of integers means that every element in the list # is either an int or a nested list of ints. ##def find_min(l: list) -> int: ## num_list = [] ## ## for num in l: ## if type(num) == list: ## num_list.append(find_min(num)) ## else: ## num_list.append(num) ## ## return min(num_list) # 5. What does the underscore before a function mean? '''It means that it is a privaate code only for the programmer to use''' # 6. What does the if __name__ == '__main__' statement mean? '''If you want your program to run automatically without importing, use this. or the code under this will ctreate whatever it has as a module''' ## Read all his code examples for review. If you understand everything he ## wrote in his code examples, as well as what you did in projects, ## you should be fine. ## Things to look over that I didn't go in depth about: ## the sockets, protocol, and classes code examples. ## Make sure you're able to write your own classes! ## On Wednesday I'll be going over any questions you might have, so make sure ## to bring them! ## Hints ## 1. Remember what each word means. When do you do the except and else ## blocks? When in doubt, always do finally! ## ## 2. If a module is loaded once through import, it doesn't load again, even if ## the same import is called again. Python is smart enough to remember what ## modules have been loaded already ## ## 3. Remember what we went over in class about classes. What always has to be ## inside a class? There's 2 problems only, but they might be found in multiple ## places ## ## 4. With recursion, always start small. How do you find the minimum of a simple ## list of integers? After you get that, seperate it into the differnt possible ## cases and deal with each seperately.
80be5ec102ef20c78ebbde2f94dabb79949b0ccc
decy20002002/MyPythonCourse
/Ch09/class_inheritance.py
554
4.09375
4
class Parent: def __init__(self, last_name): self.last_name = last_name def print_info(self): print('I am in the ' + self.last_name + ' family') class Child(Parent): pass #use pass if dont want any new properties mom = Parent('Smith') mom.print_info() #--------Ch03 Lab 2 Inheritance------------# class Customer: def __init__(self, name, id): self.name = name self.id = id def print_info(self): print(f"Customer id #{self.id}: {self.name}") c = Customer('Frank',111) c.print_info
51322c427e4a29eaba7ff9d6d52ddcccdb1ad5ef
maci2233/Competitive_programming
/CodeForces/A/610a.py
128
3.625
4
n = int(input()) if n % 2 != 0 or n <= 4: print('0') else: half = n // 2 - 1 quart = n // 4 print(half - quart)
b2ba405bfd170f058379750586bf357bef4d0de5
amymhaddad/exercises_for_programmers_2019
/product_search/main.py
1,336
3.90625
4
"""Return the inventory details for an item in the product inventory""" import sys from product_search import ( validate_item, inventory_details_for_user_item, style_dictionary_items_for_output, return_product_details, ) from data_management import access_json_data from user_input import get_item_name_from_user def main(filename): """ Calls to functions to get valid user input, retrieve inventory details based on input, and return details to user. """ data = access_json_data(sys.argv[1]) item = get_valid_item_input(data) inventory_details = inventory_details_for_user_item(item, data) product_detail_output = style_dictionary_items_for_output(inventory_details) output_for_user = return_product_details(product_detail_output) print(output_for_user) def get_valid_item_input(data): """Prompt user until recieve valid item name""" while True: item_to_search = get_item_name_from_user() product_in_inventory = validate_item(data, item_to_search) if product_in_inventory == True: return item_to_search else: print("Sorry, that product was not found in our inventory.") if __name__ == "__main__": try: main(sys.argv[1]) except IndexError: print("This file is not found.")
ad36f72bd45295257c3250755a58822d425620cd
henrypj/HackerRank
/Strings/TwoCharacters.py
2,082
4.375
4
#!/bin/python3 import sys """ # Description # Difficulty: Easy # # String t always consists of two distinct alternating characters. For example, # if string t's two distinct characters are x and y, then t could be xyxyx or # yxyxy but not xxyy or xyyx. # # You can convert some string s to string t by deleting characters from s. When # you delete a character from s, you must delete all occurrences of it in s. For # example, if s = abaacdabd and you delete the character a, then the string # becomes bcdbd. # # Given s, convert it to the longest possible string t. Then print the length of # string t on a new line; if no string t can be formed from s, print 0 instead. # # Input Format # # The first line contains a single integer denoting the length of s. # The second line contains string s. # # Constraints # # 1 <= |s| <= 1000 # s only contains lowercase English alphabetic letters (i.e. a to z) # # Output Format # # Print a single integer denoting the maximum length of t for the given s; if # it is not possible to form string t, print 0 instead. # # Example 0 # # Given Input: # 10 # beabeefeab # # Output: # 5 # # Explanation: # Test Case 0 # The characters present in s are a, b, e, and f. This means that t must consist # of two of those characters. # # If we delete e and f, the resulting string is babab. This is a valid t as there # are only two distinct characters (a and b), and they are alternating within the # string. # # If we delete a and f, the resulting string is bebeeeb. This is not a valid string # t because there are three consecutive e's present. # # If we delete only e, the resulting string is babfab. This is not a valid string # t because it contains three distinct characters. # # Thus, we print the length of babab, which is 5, as our answer. # # Solution: # """ import string s_len = int(input().strip()) s = input().strip() sList = list(s) charList = [] for i in range(s_len): if s[i] not in charList: charList.append(s[i]) print(charList) print(sList) sStr = str(sList) print(sStr) # Delete chars and test
987195962ee506d2fa25cce58f3275218138cbf0
DavidStoilkovski/python-advanced
/comprehension-advanced/even_matrix.py
317
3.75
4
def read_input(): n = int(input()) matrix = [] matrix = [map(int, input().split(', ')) for _ in range(n)] return matrix def find_even(matrix): find_even = [[el for el in row if el % 2 == 0] for row in matrix] return find_even matrix = read_input() even = find_even(matrix) print(even)
976bc15345b03a17cad2b859840e65158985d875
wrayta/Python-Coding-Bat
/big_diff.py
761
4.09375
4
""" Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array. Note: the built-in min(v1, v2) and max(v1, v2) functions return the smaller or larger of two values. big_diff([10, 3, 5, 6]) → 7 big_diff([7, 2, 10, 9]) → 8 big_diff([2, 10, 7, 2]) → 8 """ def big_diff(nums): maxNum = nums[0] currentMax = nums[0] minNum = nums[0] currentMin = nums[0] i = 0 while i < len(nums): if i + 1 < len(nums): currentMin = min(nums[i], nums[i + 1]) if currentMin < minNum: minNum = currentMin currentMax = max(nums[i], nums[i + 1]) if currentMax > maxNum: maxNum = currentMax i += 1 return maxNum - minNum
4de67534f03ae6ebe4cac6573bdd92f538ba9b15
cuiods/Coding
/Python/mooctest/19_twouniform.py
857
3.515625
4
#-*- coding:utf-8 -*- from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np def uniform_distribution(): fig = plt.figure() #add a 3d subplot ax = fig.gca(projection='3d') #set X,Y,Z X = np.arange(-1, 1, 0.02) Y = np.arange(-1, 1, 0.02) #create coordinate matrices X, Y = np.meshgrid(X, Y) Z1 = np.zeros((100,100)) Z2 = 0 #create surface 1 surf = ax.plot_surface(X, Y, inArea(X,Y), color='b') #create surface 2 surf = ax.plot_surface(X, Y, Z2, color='r') plt.show() def inArea(x,y): r = x**2+y**2 for i in range(len(x)): for j in range(len(y)): if r[i,j]>1: r[i,j] = 0 else: r[i,j] = 1 return r #the code should not be changed if __name__ == '__main__': uniform_distribution()
765793a7f9128b8d6a2f87fb1d323e8887f76133
maiwen/LeetCode
/Python/337. House Robber III.py
1,990
4.09375
4
# -*- coding: utf-8 -*- """ Created on 2018/7/22 20:43 @author: vincent The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night. Determine the maximum amount of money the thief can rob tonight without alerting the police. Example 1: 3 / \ 2 3 \ \ 3 1 Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. Example 2: 3 / \ 4 5 / \ \ 1 3 1 Maximum amount of money the thief can rob = 4 + 5 = 9. Credits: Special thanks to @dietpepsi for adding this problem and creating all test cases. """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def rob(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 val1 = root.val if root.left: val1 += self.rob(root.left.left) + self.rob(root.left.right) if root.right: val1 += self.rob(root.right.left) + self.rob(root.right.right) val2 = self.rob(root.left) + self.rob(root.right) return max(val1, val2) class Solution1: def rob(self, root): """ :type root: TreeNode :rtype: int """ def rob_recr(root): if not root: return 0, 0 else: left_node, left_grand_node = rob_recr(root.left) right_node, right_grand_node = rob_recr(root.right) return max(left_node+right_node, root.val + left_grand_node+right_grand_node), left_node+right_node return max(rob_recr(root))
e757c68767dc5bcf60fb29fafb5d905bd04d555b
CopyOfA/reddit_api_analytics
/some_queries.py
1,169
3.625
4
##which user(s) post in more than 1 subreddit? SQL = "SELECT reddit_authors.author, COUNT(*) FROM reddit_authors JOIN reddit_title_authors USING(author_id) " SQL += "JOIN reddit_titles USING(title_id)" SQL += "GROUP BY reddit_authors.author, reddit_titles.subreddit_id HAVING COUNT(*)>1 ORDER BY COUNT(*) DESC " out = pd.read_sql(sql=SQL, con=connection) print(out) ##how many unique subreddits are represented here? sql = "SELECT reddit_subreddits.subreddit, COUNT(*) from reddit_subreddits JOIN reddit_titles USING(subreddit_id) " sql += "GROUP BY reddit_subreddits.subreddit ORDER BY COUNT(*) DESC" out = pd.read_sql(sql=sql, con=connection) print(out) #the result is heavily weighted by the fact that I gather from new (random sample) and then from 8 specified subreddit ##what time are most of the posts made? sql = "SELECT DATE_PART('hour', reddit_titles.dttm), COUNT(*) FROM " sql += "reddit_titles GROUP BY DATE_PART('hour', reddit_titles.dttm) " sql += "ORDER BY DATE_PART('hour', reddit_titles.dttm)" out = pd.read_sql(sql=sql, con=connection) print(out) #this result is also clearly weighted toward the time at which I get the data from the rss feed
6a598333a6553cd359fe508d7be75a64fc182c5f
DenizSka/CodingNomads
/labs/01_python_fundamentals/01_02_seconds_years.py
405
4.0625
4
''' Write the code to calculate how many seconds are in a year in this file, so you can execute it as a script and receive the output to your console. ''' def seconds(days): seconds_in_hour = 60 * 60 total_hours_in_year = days * 24 total_seconds = seconds_in_hour * total_hours_in_year return total_seconds print(seconds(365)) # python 01_python_fundamentals/01_02_seconds_years.py
4dc2a5a6e47622c4365284c6299f2b702841f2d6
ameernormie/100-days-of-python
/2. Python Fundamentals/Collections/dictionaries.py
919
3.9375
4
""" Basic idea of dictionaries in python Key-value pair Keys must be immutable i.e. strings, numbers and tuples Values can be mutable Never rely on order of items in the dictionary """ # Make from other iterables names_and_ages = [('Alice', 32), ('Ameer', 25), ('Bob', 45)] d = dict(names_and_ages) d # {'Alice': 32, 'Ameer': 25, 'Bob': 45} phonetic = dict(a='alpha', b='beta', c='charlie', d='delta') phonetic # {'a': 'alpha', 'b': 'beta', 'c': 'charlie', 'd': 'delta'} # Copying d = {'key': 'value'} c = d.copy() another_copy = dict(d) # Extend dictionary g = dict(wheat='231233') c.update(g) # Iteration d = {'a': 1, 'b': 2} for k in d: print('key {} and value {}'.format(k, d[k])) for value in d.values(): print('values') for key in d.keys(): print('keys') for key, value in d.items(): print('key and value') # membership in and not in operator
f12297bd038fd403d3d73bac92448a0c2e4830c6
Zzzzz-art/Informatika
/Py charm shool/2.32.py
138
3.546875
4
a = int(input()) b = int(input()) c = int(input()) d = int(input()) N = int(input()) print((a + b + c + d) * 3) print((a + b + c + d) * N)
12e741535a6e2bcbdb61664e7b4e09d94404e690
seen2/Python
/StringHandling/inputOutputStr.py
165
3.75
4
def main(): # take string as input s = input("Enter your name:") # printing string print(f"you entered:{s}") if __name__ == "__main__": main()
4a8ad260a9309c94342dace8eff8d70156a841e7
saumya470/python_assignments
/.vscode/OOPs basics/ClassExample.py
453
3.796875
4
class Employee: def __init__(self,first,last,pay): self.first = first self.last = last self.pay = pay self.email = first + last + '@company.com' def fullname(self): return print(self.first + ' ' + self.last) emp1 = Employee('Corey','Schafer',50000) emp2 = Employee('Ted','Mosbey',60000) emp1.fullname() print(Employee.fullname(emp1)) emp2.fullname()
a532e185dfe70beeb5cfbf6b5350ecbf05b7c7b3
deweysasser/training-example-code
/code/testing/Basic.py
666
3.75
4
# A basic python class class Basic(object): def __init__(self): pass; def fact(self, i): if i < 0: raise Exception("Can't compute factorials of negatives!") if i < 0: raise Exception("Can't compute factorials of negatives!") if i is 1: return 1 return i*self.fact(i-1) def genfact(self, gen): ''' Call fact() on gen.get()''' return self.fact(gen.get()) class Gen(object): def __init__(self): self.value=0 def get(self): self.value += 1 return self.value if __name__ == "__main__": print Basic().fact(40)
9df5baa60d20a77cfe9c969bb78812c1654a4e49
BrettMcGregor/w3resource
/dict1.py
380
4.15625
4
# Write a Python script to sort (ascending and descending) a dictionary by value. import random def create_multiple_lists(name, number): master_dict = {} for i in range(number): master_dict.update({name+str(i): random.randint(0, 1000)}) return master_dict def sort_dict(master_dict): print((master_dict)) sort_dict(create_multiple_lists("item", 5))
4a255c0c790db09a487c09510ac19d6cb83cd301
verdi07/crypto
/ataqueDiccionarioSustSimple.py
2,101
3.625
4
# Ataque de diccionario a la cifra de sustitución simple import pyperclip, sustitucionSimple, detectarEspanol MODO = False def main(): criptograma = input('Criptograma > ') textoLlano = ataque(criptograma) if textoLlano == None: # ataque() devuelve None si no ha encontrado la clave print('El ataque falló.') else: # El texto llano se muestra en la pantalla y se copia al portapapeles print('Mensaje copiado al portapapeles.') print(textoLlano) pyperclip.copy(textoLlano) def alfabetoSustitucion(clave): # crea un alfabeto de sustitución con la clave nuevaClave = '' clave = clave.upper() alfabeto = list(sustitucionSimple.LETRAS) for i in range(len(clave)): if clave[i] not in nuevaClave: nuevaClave += clave[i] alfabeto.remove(clave[i]) clave = nuevaClave + ''.join(alfabeto) return clave def ataque(mensaje): print('Probando con %s posibles palabras del diccionario...' % len(detectarEspanol.PALABRAS_ESPANOL)) print('(Pulsa Ctrl-C o Ctrl-D para abandonar.)') intento = 1 # Prueba de cada una de las claves posibles for clave in detectarEspanol.PALABRAS_ESPANOL: if intento % 100 == 0 and not MODO: print('%s claves probadas. (%s)' % (intento, clave)) clave = alfabetoSustitucion(clave) textoLlano = sustitucionSimple.descifrarMensaje(clave, mensaje) if detectarEspanol.porcentaje_palabras(textoLlano) > 0.20: # Comprueba con el usuario si el texto tiene sentido print() print('Posible hallazgo:') print('clave: ' + str(clave)) print('Texto llano: ' + textoLlano[:100]) print() print('Pulsa S si es correcto, o Enter para seguir probando:') respuesta = input('> ') if respuesta.upper().startswith('S'): return textoLlano intento += 1 return None if __name__ == '__main__': main()
3f21aebc8d357987061ea0ebde328a0b3e88466f
matchallenges/PythonLearning
/PythonTutDocumentation/IntroductionToPython/3.1.3._Lists.py
1,139
4.3125
4
# this code was created while reading the 3.1.3. Lists documentation on the tutorial page # python knows a variety of compound data types, used to group variables together # one of the most versatile is a list squares = [1, 4, 9, 16, 25] print (squares) print (4 * squares) # you can also concatenate lists into one big lists print (squares + [64, 1000]) # unlike strings whihc are immutable, lists are mutable which means you can change it's contents squares[0] = 4000 print (squares) # you can also add elements to the end of a list, by using the append() method squares.append(500) # append 500 to the end of the list print (squares) squares.append(squares[:4]) # you can also append lists to other lists and they will be saved as an individual element (nested list) print (squares) # you can also append, change and delete slices of a list squares[:4] = ['M', 'M', 'M', 'M'] # replace the integers in the list with strings print (squares) squares[:4] = [] print (squares) # delete specific elements squares[:] = [] # we can also clear the list with blank slice # the function len() also applies to lists print (len(squares))
baae0078cd322fd2b3c22a46d8a60a13381f2491
virajPatil11/Skill-India-AI-ML-Scholarship
/solving problems in python/2.readFile.py
329
3.59375
4
#opening input file fin = open("in.txt", "rt") #output file to write the result to fout = open("out.txt", "wt") for line in fin: #read replace the string and write to output file fout.write(line.replace('Today', '01-05-2021').replace('tomorrow','02-05-2021')) #close input and output files fin.close() fout.close()
9f7ca5cddb40450c6b309c135e9fc228a1f8511c
mengsince1986/coding_bat_python
/logic-1/love6.py
447
4.03125
4
def love6(a, b): """ The number 6 is a truly great number. Given two int values, a and b, return True if either one is 6. Or if their sum or difference is 6. Note: the function abs(num) computes the absolute value of a number. >>> love6(6, 4) True >>> love6(4, 5) False >>> love6(1, 5) True """ return 6 in (a, b, a+b, abs(a-b)) if __name__ == '__main__': import doctest doctest.testmod()
1abf4f5341e0dfa3569729c4edb4a078fb9f20f8
Prasad-Medisetti/STT
/My Python Scripts/VALID STRING.py
1,739
4.15625
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 14 14:11:50 2020 @author: hp """ ''' check if a string has all characters with same frequency with one variation allowed.. given a string of lowercase alphabets , find if it can be converted to a valid string by removing 1 or 0 characters . A "valid" string is a string str such that for all distinct characters in str each such character occurs the same number of times in it. Examples: input: string str = "aabbcc" output = valid string input: string str = "abbca" output : make it valid we can make it valid by removing 1 character input: string str = "aabbcd" output: not valid we need to remove at least two characters to make it valid For example: Test Input Result 1 aabbcc valid string 2 abbac make it valid 3 aabbcd not valid not valid ''' # def valid(s): # u # valid = '' # for i in set(s): # if d[i]==2: # valid = 'valid string' # elif list(d.values()).count(1)==1: # valid = 'make it valid' # else: # valid = 'not valid' # return valid # if __name__=="__main__": # s = input() # print(valid(s)) def valid(s): d = dict.fromkeys(s,0) for i in s: d[i] = d.get(i,0) + 1 valid = False c1 = 1 for i in d.keys(): if d[i]==2: valid = True continue elif d[i]==1 and c1>0: valid = True c1 -= 1 continue else: valid = False if valid==True: return 'valid string' elif valid==True and c1>=0: return 'make it valid' else: return 'not valid' if __name__=="__main__": s = input() print(valid(s))
6467208f291239013d00bf05ea8bfdd9b22814d7
rafaxtd/URI-Judge
/AC3/secondChance.py
862
3.6875
4
def getGrades(list, x): for i in range(x): n = float(input()) list.append(n) return list n = int(input()) grades = [] activityGrades = [] lastGrade = [] cont = 0 getGrades(grades, n) getGrades(activityGrades, n) for i in range(n): if grades[i] == 10 or activityGrades[i] < 10: lastGrade.append(grades[i]) elif activityGrades[i] == 10: calc = grades[i] + 2 if calc > 10: calc = 10 lastGrade.append(calc) if grades[i] != lastGrade[i]: cont += 1 print(f'NOTAS ALTERADAS: {cont}') for i in range(n): if grades[i] != lastGrade[i]: print(f'*({(i+1):0>3}) original: {grades[i]:05.2f} | final: {lastGrade[i]:05.2f}') else: print(f'-({(i+1):0>3}) original: {grades[i]:05.2f} | final: {lastGrade[i]:05.2f}')
8abac6f77a60e073a38bceef9a8155c184ec6139
maximile/chess
/chess.py
33,710
3.796875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Chess! Squares are identified by tuples of ints, 0-7. Y axis is up from white's point of view: 7 [ ][ ][ ][ ][ ][ ][ ][ ] 6 [ ][ ][ ][ ][ ][ ][ ][ ] Black's starting side 5 [ ][ ][ ][ ][ ][ ][ ][ ] 4 [ ][ ][ ][ ][ ][ ][ ][ ] 3 [ ][ ][ ][ ][ ][ ][ ][ ] 2 [ ][ ][ ][ ][*][ ][ ][ ] 1 [ ][ ][ ][ ][ ][ ][ ][ ] White's starting side 0 [ ][ ][ ][ ][ ][ ][ ][ ] 0 1 2 3 4 5 6 7 The squared marked * would be identified by tuple (4, 2). There's no board class; just a list of pieces - each piece keeps track of its own position. """ import re import sys import copy import random # Regular expression for a valid grid reference (only used for input) GRID_REF = re.compile(r"^[A-H][1-8]$") # Piece colours WHITE = True BLACK = False # Human-readable colour names COLOR_NAMES = {WHITE: "white", BLACK: "red"} # Square colours DARK = "DARK" LIGHT = "LIGHT" HIGHLIGHTED = "HIGHLIGHTED" # Directions UP = (0, 1) UP_RIGHT = (1, 1) RIGHT = (1, 0) DOWN_RIGHT = (1, -1) DOWN = (0, -1) DOWN_LEFT = (-1, -1) LEFT = (-1, 0) UP_LEFT = (-1, 1) # ANSI color codes ANSI_BEGIN = "\033[%sm" ANSI_END = "\033[0m" ANSI_BG = {DARK: "40", LIGHT: "44", HIGHLIGHTED: "42"} ANSI_FG = {WHITE: "37", BLACK: "31"} class AbstractPiece(object): """Abstract superclass defining a chess piece. Pieces keep track of their own attributes and board position. Subclasses must implement get_valid_moves. """ def __init__(self, color, pos): if not color in (WHITE, BLACK): raise ValueError("Invalid color") self.color = color self.pos = pos self.name = PIECE_NAMES[self.__class__] self.value = PIECE_VALUES[self.__class__] self.has_moved = False def __str__(self): color_string = COLOR_NAMES[self.color] piece_string = PIECE_NAMES[self.__class__] pos_string = get_grid_ref_for_pos(self.pos) return "%s %s at %s" % (color_string.title(), piece_string, pos_string) def __repr__(self): return self.__str__() def get_valid_moves(self, game, testing_check=False): """A list of moves that can legally be made in the given game. Returns a list of positions, e.g. [(1, 2), (3, 4), ...]. Pass 'testing_check=True' to omit moves that can't be used to get out of check (castling). """ raise NotImplementedError() def get_moves_in_direction(self, game, direction): """Find all moves along a given direction. Direction is an offset tuple; e.g. to find all moves to the right pass (1, 0). """ moves = [] # Start from the current position test_move = self.pos # Keep adding the offset until we hit an invalid move while True: test_move = (test_move[0] + direction[0], test_move[1] + direction[1]) # Off the board? No more moves in this direction. if (test_move[0] < 0 or test_move[0] > 7 or test_move[1] < 0 or test_move[1] > 7): break # Hit a piece? Action depends on which color hit_piece = game.get_piece_at(test_move) if hit_piece: if hit_piece.color == self.color: # Same color. It's not a valid move and we can't go # any further. break else: # Different color. It's a valid move and we can't go # any further. moves.append(test_move) break # Didn't hit anything; it's a valid move. moves.append(test_move) return moves def remove_invalid_moves(self, game, moves): """Given a list of potential moves, remove any that are invalid for reasons that apply to all pieces. Reasons: * Not on the board * Taking own piece * Doesn't rescue the King from check """ valid_moves = [] for pos in moves: # Make sure it's actually a move if pos == self.pos: continue # Make sure it's on the board if (pos[0] < 0 or pos[0] > 7 or pos[1] < 0 or pos[1] > 7): # Off the board continue # Make sure it's not taking one of its own pieces taken_piece = game.get_piece_at(pos) if taken_piece and taken_piece.color == self.color: # Taking its own piece continue # TODO: If in check, remove moves that don't rescue the King valid_moves.append(pos) return valid_moves class Pawn(AbstractPiece): def get_valid_moves(self, game, testing_check=False): moves = [] # Get all the possible squares it can move to if self.color == WHITE: forward_one = (self.pos[0], self.pos[1] + 1) forward_two = (self.pos[0], self.pos[1] + 2) take_left = (self.pos[0] - 1, self.pos[1] + 1) take_right = (self.pos[0] + 1, self.pos[1] + 1) elif self.color == BLACK: forward_one = (self.pos[0], self.pos[1] - 1) forward_two = (self.pos[0], self.pos[1] - 2) take_left = (self.pos[0] + 1, self.pos[1] - 1) take_right = (self.pos[0] - 1, self.pos[1] - 1) else: raise RuntimeError("Never reached.") # Can move one square forward if the square is vacant if not game.get_piece_at(forward_one): moves.append(forward_one) # Can move two squares forward from the starting position if ((self.color == WHITE and self.pos[1] == 1) or (self.color == BLACK and self.pos[1] == 6)): if not game.get_piece_at(forward_two): moves.append(forward_two) # Can take diagonally forward for taking_move in take_left, take_right: taken_piece = game.get_piece_at(taking_move) if taken_piece and not taken_piece.color == self.color: moves.append(taking_move) # En passant if game.en_passant_pos in [take_left, take_right]: moves.append(game.en_passant_pos) moves = self.remove_invalid_moves(game, moves) return moves class Knight(AbstractPiece): def get_valid_moves(self, game, testing_check=False): moves = [] # [ ][7][ ][0][ ] # [6][ ][ ][ ][1] # [ ][ ][N][ ][ ] # [5][ ][ ][ ][2] # [ ][4][ ][3][ ] offsets = [(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)] for offset in offsets: moves.append((self.pos[0] + offset[0], self.pos[1] + offset[1])) # Remove obviously invalid moves moves = self.remove_invalid_moves(game, moves) return moves class King(AbstractPiece): def get_valid_moves(self, game, testing_check=False): moves = [] # Clockwise, starting with one square up offsets = [UP, UP_RIGHT, RIGHT, DOWN_RIGHT, DOWN, DOWN_LEFT, LEFT, UP_LEFT] for offset in offsets: moves.append((self.pos[0] + offset[0], self.pos[1] + offset[1])) # Castling - just handle the King move; the rook move will be done # by the game. y_pos = self.pos[1] queen_rook = game.get_piece_at((0, y_pos)) king_rook = game.get_piece_at((7, y_pos)) for rook in queen_rook, king_rook: # Don't worry about castling when testing check. if testing_check: continue if not rook: continue # Can't castle out of check if game.in_check(self.color): continue # Neither the rook nor the king can have moved if self.has_moved or rook.has_moved: continue # Squares between the king and rook must be vacant squares_between = [] if rook.pos[0] < self.pos[0]: # Queen side squares_between = [(1, y_pos), (2, y_pos), (3, y_pos)] else: # King side squares_between = [(5, y_pos), (6, y_pos)] all_squares_vacant = True for square in squares_between: if game.get_piece_at(square): all_squares_vacant = False if not all_squares_vacant: continue # None of the squares in between can put the King in check crosses_check = False for square in squares_between: test_game = copy.deepcopy(game) test_game.move_piece_to(self, square) if test_game.in_check(self.color): crosses_check = True break if crosses_check: continue # Castling on this side is allowed if rook == queen_rook: moves.append((2, self.pos[1])) else: moves.append((6, self.pos[1])) # Remove obviously invalid moves moves = self.remove_invalid_moves(game, moves) return moves class Queen(AbstractPiece): def get_valid_moves(self, game, testing_check=False): moves = [] # All directions are valid directions = [UP, UP_RIGHT, RIGHT, DOWN_RIGHT, DOWN, DOWN_LEFT, LEFT, UP_LEFT] # Keep moving in each direction until we hit a piece or the edge # of the board. for direction in directions: moves.extend(self.get_moves_in_direction(game, direction)) moves = self.remove_invalid_moves(game, moves) return moves class Bishop(AbstractPiece): def get_valid_moves(self, game, testing_check=False): moves = [] # Diagonals only directions = [UP_LEFT, UP_RIGHT, DOWN_LEFT, DOWN_RIGHT] # Keep moving in each direction until we hit a piece or the edge # of the board. for direction in directions: moves.extend(self.get_moves_in_direction(game, direction)) moves = self.remove_invalid_moves(game, moves) return moves class Rook(AbstractPiece): def get_valid_moves(self, game, testing_check=False): moves = [] # Horizontal and vertical only directions = [UP, RIGHT, LEFT, DOWN] # Keep moving in each direction until we hit a piece or the edge # of the board. for direction in directions: moves.extend(self.get_moves_in_direction(game, direction)) moves = self.remove_invalid_moves(game, moves) return moves # Characters to represent pieces SELECTED_PIECE_CHARACTERS = {King: "♚", Queen: "♛", Rook: "♜", Bishop: "♝", Knight: "♞", Pawn: "♟"} PIECE_CHARACTERS = {King: "♔", Queen: "♕", Rook: "♖", Bishop: "♗", Knight: "♘", Pawn: "♙"} # Human readable piece names PIECE_NAMES = {King: "king", Queen: "queen", Rook: "rook", Bishop: "bishop", Knight: "knight", Pawn: "pawn"} # Values for AI PIECE_VALUES = {King: 9999, Queen: 9, Rook: 5, Bishop: 3, Knight: 3, Pawn: 1} class EndGame(Exception): """Raised when the game ends. Message is human-readable and presented to the player. """ pass class Game(object): """Class representing the game state. Board layout is stored as a list of pieces - each piece knows its own position. Other state information (who's turn etc.) is stored in instance variables. """ def __init__(self): """Set up initial state. """ # List of all pieces in the game self._pieces = [] # General state self.color_to_move = WHITE # Number of moves without a pawn move or a take self.idle_move_count = 0 # Setup initial position. First, setup pawns: for x in range(8): self._pieces.append(Pawn(WHITE, (x, 1))) self._pieces.append(Pawn(BLACK, (x, 6))) # Other pieces officer_ranks = {WHITE: 0, BLACK: 7} for color, rank in officer_ranks.items(): self._pieces.append(Rook(color, (0, rank))) self._pieces.append(Knight(color, (1, rank))) self._pieces.append(Bishop(color, (2, rank))) self._pieces.append(Queen(color, (3, rank))) self._pieces.append(King(color, (4, rank))) self._pieces.append(Bishop(color, (5, rank))) self._pieces.append(Knight(color, (6, rank))) self._pieces.append(Rook(color, (7, rank))) # Various state self.last_moved_piece = None self.en_passant_pos = None def get_piece_at(self, pos): """The piece at the given position. """ for piece in self._pieces: if piece.pos == pos: return piece def move_piece_to(self, piece, pos): """Update the piece's position, removing any existing piece. All piece moves should be made with this method, otherwise the game state won't be updated properly. """ # Make sure we're not dealing with a piece from another game: piece = self.get_piece_at(piece.pos) previous_piece = self.get_piece_at(pos) # Check for taking if previous_piece: # Make sure it's a different colour (should be caught elsewhere) if previous_piece.color == piece.color: raise RuntimeError("%s tried to take own %s." % (piece.name.title(), previous_piece.name)) # Make sure it's not a king if previous_piece.__class__ == King: raise RuntimeError("%s took %s!" % (piece, previous_piece)) # Remove the piece self._pieces.remove(previous_piece) # Move the piece old_pos = piece.pos piece.pos = pos # Handle special cases. Pawns: if piece.__class__ == Pawn: # Promotion. TODO: Handle promotion to other officers if (piece.color == WHITE and piece.pos[1] == 7 or piece.color == BLACK and piece.pos[1] == 0): self._pieces.remove(piece) self._pieces.append(Queen(piece.color, piece.pos)) # En passant if piece.pos == self.en_passant_pos: if piece.pos[1] == 2: taken_pawn = self.get_piece_at((piece.pos[0], 3)) elif piece.pos[1] == 5: taken_pawn = self.get_piece_at((piece.pos[0], 4)) else: raise RuntimeError("Messed up en passant.") if not taken_pawn: raise RuntimeError("Messed up en passant again.") self._pieces.remove(taken_pawn) # Castling if piece.__class__ == King: if old_pos[0] - pos[0] == 2: # Queen side castling queen_rook = self.get_piece_at((0, pos[1])) queen_rook.pos = (3, pos[1]) queen_rook.has_moved = True if old_pos[0] - pos[0] == -2: # King side castling king_rook = self.get_piece_at((7, pos[1])) king_rook.pos = (5, pos[1]) king_rook.has_moved = True # Update en passant status if (piece.__class__ == Pawn and piece.pos[1] in [3, 4] and not piece.has_moved): if piece.pos[1] == 3: self.en_passant_pos = ((piece.pos[0], 2)) else: self.en_passant_pos = ((piece.pos[0], 5)) else: self.en_passant_pos = None # Update game state for castling etc. piece.has_moved = True self.last_moved_piece = piece # Alter idle move count - reset if it's a take or a pawn move if piece.__class__ == Pawn or previous_piece: self.idle_move_count = 0 else: self.idle_move_count += 1 def check_endgame(self): """Raises EndGame if the previous move ended the game. """ # See if that's the end of the game if not self.get_valid_moves(self.color_to_move): # In check? That's checkmate if self.in_check(): raise EndGame("Checkmate! %s wins" % COLOR_NAMES[not self.color_to_move].title()) else: raise EndGame("Stalemate!") if self.idle_move_count >= 50: raise EndGame("Draw (fifty idle moves)") def is_piece_at_risk(self, piece): """True if the piece can be taken, otherwise False. """ their_moves = self.get_valid_moves(not piece.color, testing_check=True) for move in their_moves: if self.get_piece_at(move[1]) == piece: # They have a move that could potentially take the piece # on the next turn return True return False def in_check(self, color=None): """If the current player's King is under threat. """ if color is None: color = self.color_to_move # See if any of the other player's moves could take the king our_king = [piece for piece in self._pieces if piece.__class__ == King and piece.color == color][0] if self.is_piece_at_risk(our_king): return True # The king isn't under attack return False def get_pieces(self, color=None): """Pieces with the given color, or all pieces. """ if color is None: return self._pieces return [piece for piece in self._pieces if piece.color == color] def get_valid_moves_for_piece(self, piece, testing_check=False): """Get the moves the given piece can legally make. """ moves = [] # Get every possible move for pos in piece.get_valid_moves(self, testing_check=testing_check): moves.append((piece, pos)) # If we're not worried about putting ourself in check, we're done. if testing_check: return moves # Filter out moves that would put the King in check would_check = [] for move in moves: test_game = copy.deepcopy(self) test_game.move_piece_to(move[0], move[1]) if test_game.in_check(piece.color): would_check.append(move) return [move for move in moves if not move in would_check] def get_valid_moves(self, color, testing_check=False): """All possible moves for the given color. Returns a list of tuples, piece then move. Includes taking the King, so check should be handled separately. Pass testing_check to allow moves that would put the King at risk. """ moves = [] # Get every possible move for piece in self.get_pieces(color): moves.extend(self.get_valid_moves_for_piece(piece, testing_check=testing_check)) return moves def get_coords_for_grid_ref(grid_ref): """Convert traditional coordinates to our coordinates. e.g. A1 -> (0, 0) H8 -> (7, 7) """ x_for_file = {"A": 0, "B": 1, "C": 2, "D": 3, "E": 4, "F": 5, "G": 6, "H": 7} y_for_rank = {"1": 0, "2": 1, "3": 2, "4": 3, "5": 4, "6": 5, "7": 6, "8": 7} file_letter = grid_ref[0] rank_number = grid_ref[1] return (x_for_file[file_letter], y_for_rank[rank_number]) def get_grid_ref_for_pos(coords): """Convert traditional coordinates to our coordinates. e.g. A1 -> (0, 0) H8 -> (7, 7) """ files = ["A", "B", "C", "D", "E", "F", "G", "H"] ranks = ["1", "2", "3", "4", "5", "6", "7", "8"] return (files[coords[0]] + ranks[coords[1]]) def draw_game(game, selected_piece=None): """Print a string that represents the current game state. Uses ANSI color codes to make it readable - game isn't playable without color support in the terminal. """ # Get a string for each rank rank_strings = [] # Get possible moves for selected piece if selected_piece: valid_moves = game.get_valid_moves_for_piece(selected_piece) valid_squares = [move[1] for move in valid_moves] else: valid_squares = [] # Ranks, top to bottom: for y in reversed(range(8)): rank_string = " %i " % (y + 1) for x in range(8): # Get foreground text (must make up two characters) piece = game.get_piece_at((x, y)) if piece: if piece == selected_piece or piece == game.last_moved_piece: piece_char = SELECTED_PIECE_CHARACTERS[piece.__class__] else: piece_char = PIECE_CHARACTERS[piece.__class__] foreground_text = piece_char + " " else: foreground_text = " " # Get background colour if (x, y) in valid_squares: square_color = HIGHLIGHTED elif x % 2 == y % 2: square_color = DARK else: square_color = LIGHT piece_color = WHITE if piece and piece.color == BLACK: piece_color = BLACK begin_code = ANSI_BEGIN % "%s;%s" % (ANSI_BG[square_color], ANSI_FG[piece_color]) rank_string += "%s%s%s" % (begin_code, foreground_text, ANSI_END) rank_strings.append(rank_string) file_labels = " A B C D E F G H" print "\n".join(rank_strings) + "\n" + file_labels def main(): game = Game() # Get the game type print "Let's play chess! Select a game type:" print print "1. Computer vs. computer" print "2. Computer vs. human" print "3. Human vs. computer" print "4. Human vs. human" print while True: option = raw_input("Selection: ").strip() if not option in ["1", "2", "3", "4"]: print "Select an option above (1-4)" continue if option == "1": players = {WHITE: ComputerPlayer(game, WHITE), BLACK: ComputerPlayer(game, BLACK)} elif option == "2": players = {WHITE: ComputerPlayer(game, WHITE), BLACK: HumanPlayer(game, BLACK)} elif option == "3": players = {WHITE: HumanPlayer(game, WHITE), BLACK: ComputerPlayer(game, BLACK)} elif option == "4": players = {WHITE: HumanPlayer(game, WHITE), BLACK: HumanPlayer(game, BLACK)} else: raise RuntimeError("Never reached.") break # Main game loop try: while True: # time.sleep(0.01) draw_game(game) player_to_move = players[game.color_to_move] move = player_to_move.get_move() game.move_piece_to(move[0], move[1]) game.color_to_move = not game.color_to_move game.check_endgame() except EndGame as e: draw_game(game) print e class AbstractPlayer(object): """Abstract superclass representing a player who can make moves at the chess game. get_move must be subclassed; player objects will have this method called repeatedly until the game is over. """ def __init__(self, game, color): self.game = game self.color = color def get_move(self): """Return the move that the player wants to make based on the current game state. """ raise NotImplementedError() class ComputerPlayer(AbstractPlayer): """AI-controlled player. Considers checkmate, checks, captures, retreats and pawn advances. No forward-planning though, so it's extremely basic and easy to beat. """ def get_move(self): if not self.game.color_to_move == self.color: raise RuntimeError("Not my turn!") available_moves = self.game.get_valid_moves(self.color) # Find checking moves checking_moves = [] riskless_checking_moves = [] for move in available_moves: test_game = copy.deepcopy(self.game) test_game.move_piece_to(move[0], move[1]) if test_game.in_check(not self.color): # Check for potential mates if not test_game.get_valid_moves(not self.color): return move checking_moves.append(move) if not test_game.is_piece_at_risk(move[0]): riskless_checking_moves.append(move) # Find taking moves taking_moves = [move for move in available_moves if self.game.get_piece_at(move[1])] # Retreats retreats = {} for move in available_moves: if self.game.is_piece_at_risk(move[0]): test_game = copy.deepcopy(self.game) test_game.move_piece_to(move[0], move[1]) if test_game.is_piece_at_risk(test_game.get_piece_at(move[1])): continue retreats[move] = move[0].value highest_value = -999999 best_retreat = None for move, value in retreats.items(): if value > highest_value: best_retreat = move highest_value = value if best_retreat: return best_retreat # Find riskless taking moves (free material) riskless_taking_moves = [] for move in taking_moves: test_game = copy.deepcopy(self.game) test_game.move_piece_to(move[0], move[1]) if not test_game.is_piece_at_risk(test_game.get_piece_at(move[1])): riskless_taking_moves.append(move) if riskless_taking_moves: return random.choice(riskless_taking_moves) # A check is pretty good if it doesn't cost anything if riskless_checking_moves: return random.choice(riskless_checking_moves) # Find the best value taking move valued_taking_moves = {} for move in taking_moves: our_piece = move[0] their_piece = self.game.get_piece_at(move[1]) move_value = their_piece.value - our_piece.value valued_taking_moves[move] = move_value highest_value = -999999 best_taking_move = None for move, value in valued_taking_moves.items(): if value > highest_value: best_taking_move = move highest_value = value # Find pawn moves pawn_moves = [move for move in available_moves if move[0].__class__ == Pawn] # Good options good_options = [] if pawn_moves: good_options.append(random.choice(pawn_moves)) if checking_moves: good_options.append(checking_moves) if best_taking_move: good_options.append(best_taking_move) if good_options: return random.choice(good_options) # Make any move return random.choice(available_moves) class HumanPlayer(AbstractPlayer): """Represents a human player. Parses command-line input to get the move. """ def get_move(self): """Get command line input to move the piece. """ # Loop until we have a valid move while True: # Print status if self.game.in_check(self.color): check_string = " (You're in check!)" else: check_string = "" print "%s to play.%s" % (COLOR_NAMES[self.color].title(), check_string) # Get user input move_string = raw_input("Your move: ").strip().upper() # Is it an explicit move (from -> to)? explicit_match = re.match(r"([A-H][1-8]).*([A-H][1-8])", move_string) if explicit_match: from_ref = explicit_match.group(1) to_ref = explicit_match.group(2) from_pos = get_coords_for_grid_ref(from_ref) to_pos = get_coords_for_grid_ref(to_ref) piece = self.game.get_piece_at(from_pos) # Validate the move if not piece: print "No piece at %s" % from_ref continue if not piece.color == self.color: print "That's not your %s!" % piece.name continue valid_moves = self.game.get_valid_moves_for_piece(piece) valid_squares = [move[1] for move in valid_moves] if not to_pos in valid_squares: print "That %s can't move to %s!" % (piece.name, to_ref) continue return (piece, to_pos) # Specified a single square if not re.match(r"[A-H][1-8]", move_string): print "That's not a valid move. Examples: 'A8', 'D2D4', etc." continue pos = get_coords_for_grid_ref(move_string) piece_on_target = self.game.get_piece_at(pos) # If it's not one of ours, see if any of our pieces can move there if not piece_on_target or not piece_on_target.color == self.color: valid_moves = self.game.get_valid_moves(self.color) moves_to_target = [move for move in valid_moves if move[1] == pos] if not moves_to_target: action_string = "move there" if piece_on_target: action_string = ("take that %s" % PIECE_NAMES[piece_on_target.__class__]) print "None of your pieces can %s." % action_string continue elif len(moves_to_target) == 2: piece_one = moves_to_target[0][0] piece_two = moves_to_target[1][0] if piece_one.__class__ == piece_two.__class__: print "Two %ss can move there." % piece_one.name else: print ("The %s and the %s can both move there." % (piece_one.name, piece_two.name)) continue elif len(moves_to_target) > 1: print "Lots of pieces can move there." continue elif len(moves_to_target) == 1: return moves_to_target[0] else: raise RuntimeError("Never reached.") # It's one of ours; show where it can move and ask again piece = piece_on_target valid_moves = self.game.get_valid_moves_for_piece(piece) if not valid_moves: print "That %s has nowhere to go!" % piece.name continue # Move the piece draw_game(self.game, selected_piece=piece) input_string = raw_input("Move the %s to: " % piece.name).strip().upper() if not GRID_REF.match(input_string): draw_game(self.game) print "That's not a square!" continue coords = get_coords_for_grid_ref(input_string) valid_squares = [move[1] for move in valid_moves] if coords == piece.pos: draw_game(self.game) print "That %s is already on %s!" % (piece.name, input_string) continue if not coords in valid_squares: draw_game(self.game) print "That %s can't move to %s" % (piece.name, input_string) continue return (piece, coords) if __name__ == "__main__": try: main() except KeyboardInterrupt: print "\nBye!" sys.exit()
5acc2d5fb97ddbaac0ff180869e5a252244cf702
amanjaiswalofficial/100-Days-Code-Challenge
/code/python/day-14/binarysearch.py
1,002
4.125
4
def find(arr,a,b,x): while(a<=b):#while left index is less than right index mid=int(a+ (b-a)/2)#finding middle index for the number if(arr[mid] < x):#if number is less than middle element, then look in the first half of sorted array a=mid+1 elif(arr[mid] > x):#if number is greater than middle element, look in the second half b=mid-1 elif(arr[mid] == x):#if element found, return position return mid return -1#if not found anywhere in the array, return -1 n=int(input('Enter no. of elements:')) arr=[] sortedarr=[] for i in range(n): arr.append(int(input())) x=int(input('Enter number to search in the array:')) print(arr) #creating a copy of the original array sortedarr=arr.copy() sortedarr.sort()#sorting it i=find(sortedarr,0,n-1,x) if(i==-1):#element wasnt found print('Element not found') else:#found, then it's location in the original array print('Element found at position: '+str(int(arr.index(x))+1))
635a89221b0dd475f9daf41b214c2050b281cdec
Csatapathy/Employee-Scheduler
/assign.py
4,415
4.03125
4
import pandas as pd import collections import csv class people: def __init__(self,personID,skillID,name): """ Defining the class for ppl that includes the 3 parameters @params: personID : the ID associated with the person skillID : the array of skills that the person has name : the name of the person """ self.personID=personID self.skillID=skillID self.name=name class task: def __init__(self,taskID,skillID,priority): """ Defining the class for tasks that includes the 3 parameters @params: taskID : the ID associated with the task that needs to be done skillID : the skill ID that is req. to complete the task priority : priority of the task (True: for urgent,False: for less urgent) """ self.taskID=taskID self.skillID=skillID self.priority=priority def add_val_tasks(data_tasks): """ This method returns a list of task values sorted based on priority """ tasks=[] for i in range(len(data_tasks)): taskID=data_tasks.loc[i]['Id'] skillID=data_tasks.loc[i]['SkillRequired'] priority=data_tasks.loc[i]['IsPriority'] tasks.append(task(taskID,skillID,priority)) tasks.sort(key= lambda x:x.priority,reverse=True) return tasks def add_val_ppl(data_ppl): """ This method returns a list of people values """ ppl=[] for i in range(len(data_ppl)): id=data_ppl.loc[i]['Id'] name=data_ppl.loc[i]['Name'] skill=data_ppl.loc[i]['Skills'] ppl.append(people(personID=id,skillID=skill,name=name)) return ppl def addSkills(data,length): """ This returns a dictionary of the list of skills that each person has """ arr={} for i in range(1,length+1): arr[i]=[] for i in range(len(data)): personId=int(data.loc[i]['PersonId']) skillId=int(data.loc[i]['SkillId']) arr[personId].append(skillId) return arr def makeDict(data,skill_num): """ returns a dictionary of skillID vs the list of people that have those skills """ d={} for i in range(1,skill_num[0]+1): d[i]=[] for i in range(len(data)): id=data[i].personID skills=data[i].skillID for i in skills: d[i].append(id) return d def takeInput(ppl,skills,tasks): """ This method takes input from diff files and returns ppl: the list of people with IDs,skills and names tasks: the list of tasks with IDs,skill req and priority skill_num : the max skillID """ data_ppl=pd.read_csv(ppl) data_skills=pd.read_csv(skills) data_tasks=pd.read_csv(tasks) data_ppl['Skills']=addSkills(data_skills,len(data_ppl)).values() skill_num=data_ppl['Skills'].max() ppl=add_val_ppl(data_ppl) tasks=add_val_tasks(data_tasks) return ppl,tasks,skill_num def assign(ppl_data,skills_data,tasks_data): """ assigns the tasks to people and returns an orderedDict of taskID vs the personID and the day assigned """ ppl,tasks,skill_num=takeInput(ppl_data,skills_data,tasks_data) data=makeDict(ppl,skill_num) # makes a dictionary of skills vs personID main_assign={} main_check=[0]*len(tasks) day=1 while (sum(main_check)<len(tasks)): person_assign=[0]*len(ppl) i=0 while (sum(person_assign)<len(ppl)) and (i<len(tasks)): if main_check[i]==0: task_id=tasks[i].taskID skill_req=tasks[i].skillID for x in data[skill_req]: if person_assign[x-1]==0: person_assign[x-1]=1 main_assign[task_id]=[x,day] main_check[i]=1 break i+=1 day+=1 return collections.OrderedDict(sorted(main_assign.items())) def write_csv(data,filename): """ writes to the csv file """ fields=['TaskID','PersonID','Day'] with open(filename,'w',newline='') as file: writer=csv.writer(file) writer.writerow(fields) for row in data: writer.writerow([row,data[row][0],data[row][1]])
b8c25e1e26cfaceefa54cf0e62af13f22e2cfcaf
nancyya/Cortica
/Q2/main.py
5,571
3.734375
4
""" Rush Hour - home assignment""" ''' Created on Mar 22, 2016 @author: nancy yacovzada ''' """ ############################ IMPORTS ############################ """ from time import sleep import numpy as np from datetime import datetime as time """ ################### GLOBAL VARIABLES ############################ """ # Using rushHours as a Set() to represent rush hours time spans: # 1. Every element in the set, acts like a key in a dictionary, represents a minute in a rush hour. # For example, "15.00" is 3PM and "0.59" is 12:59AM. # Values in the set vary from 0.00 to 24.00. 1440 possible values. no duplications. # 2. When the class is initialized, the set is empty (there are no rush hours at all). # 3. A time span is added only once. If exists, not added to the set. # The containment operation ("not in") takes O(1). # 4. isRushHour() complexity - constant time access using the "in" operator. # 5. addTimeSpan() complexity - each "add" takes constant time access. # 6. Size - worst case rushHours is length 60*24=1440. # Bonus question: # How would your solution be different if we changed the definition of "time" to be an integer, representing the time of day in seconds? (answer in words) # Answer: this solution supports the change in definition of "time" to seconds. Worst case the size of rushHours is 86,400. Additional approach is using "interval tree" (see: https://en.wikipedia.org/wiki/Interval_tree) rushHours = set() def addTimeSpan(start_time, end_time): """ Receive time-span (start_time, end_time) that is defined as "Rush Hours" and stores them. Parameters ---------- start_time : str, in format "h.mm". end_time : str, in format "h.mm". Returns ------- Void """ if ( isValidTime(start_time) and isValidTime(end_time) and start_time <= end_time): # Add time-span of rush hours # Insert into "rushHours" all the minutes in the range of [start_time, end_time) for minute in np.arange(roundf(start_time), roundf(end_time), 0.01): minute = roundf(minute) if minute not in rushHours and (minute%1 < 0.6): # An hour has only 60 minute rushHours.add(minute) else: print "start_time:", start_time, "end_time:", end_time, " Not a valid time, behavior is not defined." return def isRushHour(time): """ Answer queries about a specific time of day - whether it is considered a rush hour or not Parameters ---------- time : str, in format "h.mm". Returns ------- isRushHour: boolean """ isRushHour = 0 if isValidTime(time): if time in rushHours: isRushHour = 1 print str(time) + " is a rush hour!" else: print str(time) + " is NOT a rush hour!" else: print str(time) + " - NOT AN VALID HOUR!" return isRushHour def isValidTime(time): """ Time T (float) is a valid time of day if (T>=0.00 and T<24.00)""" isValid = 0 # First, Check if float if(isStrFloat(time)): # Take float with only precision 2 to represent "h.mm" time = roundf(time) # Extract the hour h = int(time) # Extract the minutes m = roundf(time - h) # Validate if (h >= 0 and h < 24 and m >= 0.00 and m < 0.60): isValid = 1 return isValid def isStrFloat(s): try: float(s) return True except ValueError: return False def roundf(f): return round(f,2) ############################## def testInput(): """ A test method """ isRushHour(3.00) #--> False isRushHour(5.00) #--> False addTimeSpan(2.00, 4.00) isRushHour(3.00) #--> True isRushHour(5.00) #--> False addTimeSpan(7.00, 9.00) isRushHour(3.00) #--> True isRushHour(5.00) #--> False isRushHour(7.00) #--> True isRushHour(11.00) #--> False addTimeSpan(8.00, 12.00) isRushHour(3.00) #--> True isRushHour(5.00) #--> False isRushHour(7.00) #--> True isRushHour(11.00) #--> True addTimeSpan(0.01, 1.01) isRushHour(0.01) #--> True isRushHour(0.00) #--> False isRushHour(0.59) #--> True isRushHour(5) #--> False (transforms to 5.00) isRushHour(500) #--> Error isRushHour(5.59) #--> False isRushHour(5.60) #--> Error isRushHour(25.00) #--> Error isRushHour(-25.00) #--> Error addTimeSpan(12.00, 8.00) # Not valid, start_time > end_time! addTimeSpan(21.01, 21.01) isRushHour(21.01) #--> False addTimeSpan(21.01, 21.02) isRushHour(21.01) #--> True addTimeSpan(19, 19.05) #--> (transforms to (10.00, 10.05)) isRushHour(19.00) #--> True ##sleep(60) addTimeSpan(0,24) # All day, 24:00 is not a valid time, behavior is not defined. isRushHour(0.00) #--> False, 24:00 is not a valid time, behavior is not defined. addTimeSpan(0,23.9) # Not valid addTimeSpan(0,23.5) isRushHour(24.00) #--> Not valid query isRushHour(0.00) #--> True' isRushHour(5.59) #--> True return ############################## class Main(): print "STRAT -----> " + str(time.now()) running_time = time.now() testInput() running_time = time.now() - running_time print("FINISH -----> " + str(time.now()) + " Total running time : %s " % str(running_time))
35f8a3c3727abc1cd3342ee717ac3f45debabf2d
rohitjoshi6/CP-Practice
/Codeforces-practice/Word-capitalization.py
106
3.8125
4
str = input() if(len(str)>0 and str[0].islower()): print(str[0].upper()+str[1:]) else: print(str)
1bb13378b1571efd8712f69256c5226eac1ae36f
GreenhillTeacher/Python2021
/multip_input.py
1,104
4.53125
5
#Maria Suarez #6/4/2021 # We are going to print multiplacation tables # Using print statements and a variable # input ---> variable is container that will hold data and an address is assigned to it # variables need to have valid name base = 2 numberBase = "multiplication" base3= 3.5 #print(base + base3) print(1 * base) #multiplication is represented with * print(2 * base) #division / print(3 * base) print(4 * base) print(5 * base) print(6 * base) print(7 * base) print(8 * base) print(9 * base) print(10* base) # when we repeat something we should loop loop with counter for counter in range(1,11): #initial value that included ending value is not included print(counter* base, end=" ") print() base =3 for counter in range(1,11): #initial value that included ending value is not included print(counter* base, end=" ") print() #nested for loop for base in range (2, 10): for counter2 in range(1,11): #initial value that included ending value is not included print(counter2* base, end=" ") print() # multiplication table 2 # 1 x 2 = 2 # 2 x 2 = 4
de315e153698c8c0726e5ae026c303a5350651a1
zhuanganmin/python-study
/Http/urllib1.py
1,021
3.671875
4
#! /usr/bin/python # encoding=utf-8 # -*- coding: UTF-8 -*- import urllib.request import json #import urllib2 在python3中没有urllib2用urllib.request代替 url="https://httpbin.org" #get请求 def get(url): #发送请求 response=urllib.request.urlopen(url,None,timeout=3) data=response.read().decode() jsondata=json.loads(data) print(jsondata["args"]) # fo=open("get.txt","a+",encoding='utf-8') # fo.write(data) # fo.close() def post(url,data): headers={'Content-Type':'application/json'} #创建http请求对象 request=urllib.request.Request(url,headers=headers,data=json.dumps(data).encode(encoding="utf-8")) #发送请求 response=urllib.request.urlopen(request) resultData=response.read().decode() return json.loads(resultData)['data'] pass if __name__ == "__main__" : print("main :") get(url+"/get?a=hello") data={ 'name':'zhuang', 'age' : 34 } resultData=post(url+"/post",data) print(resultData)
d25b4ee8fe7db0f0402412807f10b6989c2e2994
alexisechano/Artificial-Intelligence-1
/searches/GraphLabs/depth_extra.py
2,228
3.796875
4
# Alexis Echano from collections import deque def swap(state, i, j): #swaps two characters in a string str = state[:i] + state[j] + state[i+1:j] + state[i] + state[j+1:] return str def generate_children(state): # creates new list to return later children = [] # finds index of the blank index_of_blank = state.index('_') # booleans to check if the bounds will allow movement canMoveU = True canMoveD = True canMoveL = True canMoveR = True if (index_of_blank <= 2): # top side -- blank cannot move up canMoveU = False if (index_of_blank % 3 == 0): # left side -- blank cannot move left canMoveL = False if ((index_of_blank + 1) % 3 == 0): # right side -- blank cannot move right canMoveR = False if ((index_of_blank) >= 6): # bottom side -- blank cannot move down canMoveD = False # using the booleans above, the newly generated children append to the list if (canMoveU): children.append(swap(state, index_of_blank - 3, index_of_blank)) if (canMoveD): children.append(swap(state, index_of_blank, index_of_blank + 3)) if (canMoveL): children.append(swap(state, index_of_blank - 1, index_of_blank)) if (canMoveR): children.append(swap(state, index_of_blank, index_of_blank + 1)) # returns list of children return children # main def main(): #opens file for writing: text_file = open("num_states_at_depth.txt", 'w') q = deque() goal_state = "_12345678" q.append(goal_state) explored = {} explored[q[0]] = 0 while(len(q) != 0): current = q.popleft() childs = generate_children(current) for c in childs: if c not in explored: explored[c] = explored[current] + 1 temp = [] depths = {} for item in explored.keys(): depth = explored[item] while(explored[item] == depth): temp.append(item) depths[depth-1] = temp for i in depths.keys(): #writes to text file d = i leng = len(depths[i]) text_file.write("@ Depth: " + i + " " + leng + "\n") text_file.close() if __name__ == '__main__': main()
29f119d059163e957546e87c7d34f5dbbea01983
ZQ774747876/AID1904
/untitled/day01/linklist.py
1,326
4.28125
4
""" linklist链表程序实现 重点代码 思路分析: 1.创建节点类,生成节点对象,包含数据和下一个节点的引用 2.链表类,可以生成链表对象,可以对脸表进行数据操作 """ #节点类 class Node(): def __init__(self,data,next): self.data=data self.next=next class Linklist(): """ 建立链表模型 进行链表操作 """ def __init__(self): #初始化一个链表,生成一个头结点,表示链表开始节点 self.head=Node(None) #初始添加一组链表节点 def list_list(self,list_): p=self.head#p为移动变量 for i in list_: p.next=Node(i) p=p.next #遍历链表 def show(self,): p=self.head.next #第一个有效节点 while p is not None: print(p.data,end=' ') p=p.next print() #获取链表长度 def get_length(self): n=0 p=self.head while p.next is not None: n +=1 p=p.next return n #判断链表是否为空 def is_empty(self): if self.get_length()==0: return True else: return False #清空链表 def clear(self): self.head.next=None def append(self,data): node=Node(data) p
1e40509a7a0c2b270289dffda9c2c5e330fff69f
erikvader/dotfiles
/python_utils/.pythonlibs/tabulate.py
2,154
3.8125
4
#!/bin/python from itertools import zip_longest import re LEFT = 0 RIGHT = 1 IGNORE = 2 def _transpose(fields): return [list(x) for x in zip_longest(*fields, fillvalue=None)] def _repeat(x): it = iter(x) last = None while True: try: last = next(it) except StopIteration: pass yield last def _align(c, ls, ml, a): def f(cc, l): if cc is None: return None d = ml - l if d < 0: return cc[:ml] elif a == LEFT: return cc + " "*d elif a == RIGHT: return " "*d + cc else: return cc return [f(cc, l) for cc, l in zip(c,ls)] # TODO: end=None to not join the lines # tabulates fields into a string. # fields: is an iterable of iterables align: is a tuple of alignments # applied in order. The last one is repeated indefinitely # separators: is a tuple of string to put between each column, last is # repeated # widths: is a tuple of fixed column widths. A value of 0 means that # the column gets as wide as needed # lenfun: is a function to calculate the length of every field # end: is a string to join each line with # end_on_last_line: if True will put an end at the end of the table def tabulate(fields, align=(LEFT,), separators=(" ",), widths=(0,), lenfun=len, end='\n', end_on_last_line=False): fields = [[str(ff) for ff in f] for f in fields] cols = _transpose(fields) lens = [[lenfun(cc) if cc else 0 for cc in c] for c in cols] maxlens = (max(c) if w == 0 else w for c,w in zip(lens, _repeat(widths))) cols = (_align(*args) for args in zip(cols, lens, maxlens, _repeat(align))) rows = _transpose(cols) lines = [] for r in rows: l = [] for rr,s in zip(r, _repeat(separators)): if rr is None: break l.append(rr) l.append(s) s = "".join(l[:-1]) lines.append(s.rstrip(" ")) return end.join(lines) + (end if end_on_last_line else "") # calculates len(s) with ANSI escape codes removed def ansiLength(s): return len(re.sub(r"\x1b\[[0-9;:<=>?]*[ !\"#$%&'()*+,\-./]*[a-zA-Z[\]^_`\-~{}|@]", "", s))
c9c5622a7cfbcd71286ebf9f26302fd79a60522c
pinkumbrella14/ThinkfulBootcamp
/Unit1_Lesson5_dictionaries.py
3,107
4.875
5
#dictionaries have different performance implications than working #with lists. This has to do with calling data by key vs calling #data by index...... print("A dictionary in Python is a key: value pair.") print(''' This is an example of setting up a dictionary. stock = { apples: 5, oranges: 2, pears: 11, peaches: 3 } ''') stock = { "apples": 5, "oranges": 2, "pears": 11, "peaches": 3 } print(stock) print(stock["oranges"]) print(stock["peaches"]) print("Creating a new value in the dictionary is also done with [].") print(''' Adding a new item (aka key: value pair) to stock: stock["kiwi"] = 6 ''') stock["kiwi"] = 6 print(stock) print('The del keyword deletes item from dictionary.') print("del stock[\"pears\"] will delete the pears key and its value") del stock["pears"] print(stock) print("Writing 'pears' in stock will give you 'False'") print("pears" in stock) print('Important dictionary methods to keep track of:') print('The .keys() method will return all the keys in the dictionary') print('The .values() method will return all the values in a dictionary') print('The .items() method will return all the key: value pairs in the dicitonary') print(''' You can use the dictionary methods to make a real list from dictionaries! list(stock.keys()) will make a list out the stock dictionary. ''') stock_list = list(stock.keys()) print(stock_list) full_stock_list = list(stock.items()) print(full_stock_list) print(''' Dictionary items are printed in an ARBITRARY order. Use the sorted() function to get a sort. list(sorted(stock.keys())) ''') print(list(sorted(stock.keys()))) #dictionary kata!!! print('Here are the dictionary kata that I complete.') print(''' kata 1: You are fullfilling orders and need an automaric way to check if items in stock. stock = { 'football': 4, 'boardgame': 10, 'leggos': 1, 'doll': 5, } The check include listing a value greater than what is available or listing an item that is not in the dictionary. ''') stock = { 'football': 4, 'boardgame': 10, 'leggos': 1, 'doll': 5, } print(stock) print('Here is the function I wrote to check the orders.') print(''' def fillable(stock, merch, n): try: if stock[merch] >= n: return True else: return False except KeyError: return False ''') def fillable(stock, merch, n): try: if stock[merch] >= n: return True else: return False except KeyError: return False outcome = fillable(stock, 'football', 3) print(outcome) another_outcome = fillable(stock, 'action figure', 0) print(another_outcome) #second kata development print('second kata development') try_data = [["Grae Drake", 98110], ["Bethany Kok"], ["Alex Nussbacher", 94101]] def user_contacts(data): result = {} for datum in data: name = datum[0] try: zip = datum[1] except IndexError: zip = None result[name] = zip print(result) user_contacts(try_data)
cbdc85cab09a2bbc4ca48de62eec8431f153e1eb
brasqo/pythoncrashcourse
/41.py
429
3.828125
4
#4-1 pizzas = ['cheese', 'spinach', 'pepperoni'] dots = "..." for pizza in pizzas: print("I love " + pizza + " on my pizza.") print("I really love me some muh-fuckin' pizza!") print(dots) #4-2 animals = ['cat', 'dog', 'bird'] for animal in animals: print(animal) print(dots) for animal in animals: print("A " + animal + " makes a great pet.") print("Let's be honest. All of these animals would make a great pet!!!")
fe3a3e0d8c18ce36f2aa7220569a6bd15e8edb23
arisend/epam_python_autumn_2020
/lecture_04_test/hw/task_2_mock_input.py
847
3.875
4
""" Write a function that accepts an URL as input and count how many letters `i` are present in the HTML by this URL. Write a test that check that your function works. Test should use Mock instead of real network interactions. You can use urlopen* or any other network libraries. In case of any network error raise ValueError("Unreachable {url}). Definition of done: - function is created - function is properly formatted - function has positive and negative tests - test could be run without internet connection You will learn: - how to test using mocks - how to write complex mocks - how to raise an exception form mocks - do a simple network requests >>> count_dots_on_i("https://example.com/") 59 * https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen """ def count_dots_on_i(url: str) -> int: ...
d0b6da8636642404981e736f1dbda5f1ba61974f
obs145628/py-softmax-regression
/softmaxreg.py
3,082
3.53125
4
''' Softmax regression implementation More informations: - http://ufldl.stanford.edu/tutorial/supervised/SoftmaxRegression/ - https://medium.com/@awjuliani/simple-softmax-in-python-tutorial-d6b4c4ed5c16 ''' import numpy as np import dataset_mnist ''' Compute matrix version of softmax compute the sofmax functon for each row @param x matrix of size (set_len, output_len) @return matrix of size (set_len, output_len) softmax(x)_i = exp(x_i) / (sum_(j=1->output_len) exp(x_j)) ''' def softmax(x): e_x = np.exp(x - np.max(x)) return (e_x.T / e_x.sum(axis=1)).T # only difference ''' Compute cost function @param x matrix of size (set_len, input_len) @param y matrix of size (set_len, output_len) @param w matrix of size (input_len, output_len) @param lbda - coefficient for l2 regularization @return cost value ''' def cost_function(X, y, w, lbda): z = np.dot(X, w) y_hat = softmax(z) res = - np.sum(y * np.log(y_hat)) reg2 = np.sum(w * w) #reg2 = np.dot(x.flatten(), x.flatten()) slower method return res + reg2 def evaluate(X, y, w, lbda): y_hat = softmax(np.dot(X, w)) total = X.shape[0] succ = 0 for i in range(total): succ += dataset_mnist.output_test(y[i], y_hat[i]) perc = succ * 100 / total print('Cost: ' + str(cost_function(X, y, w, lbda))) print('Results: {} / {} ({}%)'.format(succ, total, perc)) ''' Apply stochastic gradient descent on the whole training set of size set_len @param x matrix of size (set_len, input_len) @param y matrix of size (set_len, output_len) @param w matrix of size (input_len, output_len) @param lr - learning rate @param lbda - coefficient for l2 regularization @return matrix (input_len, output_len) updated weights ''' def sgd(X, y, w, lr, lbda): y_hat = softmax(np.dot(X, w)) dW = - np.dot(X.T, y - y_hat) + lbda * w w = w - lr * dW return w ''' @param X_train - matrix (set_len, input_len) matrix of features (training set) @param y_train - matrix (set_len, output_len) matrix of labels (training set) @param x_test - matrix (set_len, input_len) matrix of features (test set) @param y_test - matrix (set_len, output_len) matrix of labels (test set) @param epochs - number of epochs of learning @param lr - learning rate @param lbda - coefficient for l2 regularization @param use_intercept - if true, add a bias to the weights Run the training for several epochs. After each epochs, the wieghts are tested on the training test and the test set ''' def train(X_train, y_train, X_test, y_test, epochs, lr, lbda = 0, use_intercept = False): if use_intercept: X_train = np.hstack((np.ones((X_train.shape[0], 1)), X_train)) X_test = np.hstack((np.ones((X_test.shape[0], 1)), X_test)) w = np.zeros((X_train.shape[1], y_train.shape[1])) #Training for i in range(1, epochs + 1): print('Epoch :' + str(i)) w = sgd(X_train, y_train, w, lr, lbda) print('Train:') evaluate(X_train, y_train, w, lbda) print('Test:') evaluate(X_test, y_test, w, lbda) return w
8364d5713f956006da4ffa81702120c1d9a7ac71
heeseoj/homecoming1
/3주차_과제.py
599
3.765625
4
#1330 A,B=input().split() A=int(A) B=int(B) if A > B: print(">") elif A < B: print("<") else: print("==") #9498 score = int(input()) if 90<=score<=100: print("A") elif 80<=score<90: print("B") elif 70<=score<80: print("C") elif 60<=score<70: print("D") else: print("F") #2753 year = int(input()) if year%4==0 and year%400==0: print("1") elif year%4==0 and year%100!=0: print("1") else: print("0") #14681 A=int(input()) B=int(input()) if A>0 and B>0: print("1") elif A<0 and B>0: print("2") elif A<0 and B<0: print("3") else: print("4")
7745d4950fa371cfc7e0920c623119d8e365fa72
luxwarp/pygtk-playground
/01-hello-world/hello-world.py
1,257
3.890625
4
#!/usr/bin/env python3 import gi gi.require_version("Gtk", "3.0") # require gtk version 3.0 from gi.repository import Gtk class MainWindow(Gtk.Window): ''' The MainWindow class that inherit Gtk.Window ''' def __init__(self): # initialize the window and set a title Gtk.Window.__init__(self, title="Hello world") # create a box container to add multiple widgets. self.box = Gtk.Box(spacing=10) self.add(self.box) # create a label self.greet_label = Gtk.Label(label="Click the button") self.box.pack_start(self.greet_label, True, True, 0) # create a button and connect it clicked to a function. self.greet_button = Gtk.Button(label="Greet") self.greet_button.connect("clicked", self.on_greet_clicked) self.box.pack_start(self.greet_button, True, True, 0) def on_greet_clicked(self, widget): ''' On button clicked, greet the user in window with "Hello you!" ''' self.greet_label.set_text("Hello you!") # create an instance of the window. win = MainWindow() # if close (x) button clicked, close it- win.connect("destroy", Gtk.main_quit) # show the window. win.show_all() # the gtk mainloop. Gtk.main()
a8d9ed160164caede2030a735cbb905936fdc3ad
Vistril/pyproj
/06-counter/counter.py
446
3.984375
4
#Seth Camomile #Period 7 def count(start, end, step): rep = '' for i in range(start, end + (-1 if step < 0 else 1), step): rep += str(i) + ' ' #you still have to add a space at the end just because of the tests return rep def main(): start = int(input("What is the starting number? ")) end = int(input("What is the ending number? ")) step = int(input("How much should I cound by? ")) print(count(start,end,step))
7e1fda60da8e590d08681d9302b83e5ec84ccdeb
whiplashzhao/pyrhon
/testing_groupby_1.py
370
3.53125
4
import pandas as pd import numpy as np df = pd.DataFrame({'key1': ['a', 'a', 'b', 'b', 'a'], 'key2': ['one', 'two', 'one', 'two', 'one'], 'data1': np.random.randn(5), 'data2': np.random.randn(5)}) print(df) grouped = df['data1'].groupby(df['key1']) print(grouped.mean()) means = df['data1'].groupby([df['key2'], df['key1']]).mean() print(means) print(means.unstack())
b7428f082a28a09ab7487f42b91f3cfd4a66788a
AnakinCNX/PythonChallenges
/challenge_24.py
422
3.59375
4
# There are no comments, so I don't know what you are trying to do. def drawline(p, x): for i in range(0, p): print(" ", end=" "), for i in range(0, x): print(".", end=" "), print() return def drawpicture(): drawline(1, 3) drawline(1, 5) drawline(1, 6) drawline(1, 3) drawline(1, 8) drawline(1, 2) drawline(1, 9) drawline(1, 7) return drawpicture()
08be68b0a4ddd0e99b867bf5bef62da84e32872a
GopichandJangili/Python
/general_python.py
1,018
3.515625
4
''' 1. Currently the most widely used multi-purpose, high-level programming language. 2. Python allows programming in Object-Oriented and Procedural paradigms. 3. Python programs generally are smaller than other programming languages like Java. 4. Programmers have to type relatively less and indentation requirement of the language, makes them readable all the time. Python language is being used by almost all tech-giant companies like – Google, Amazon, Facebook, Instagram, Dropbox, Uber… etc. The biggest strength of Python is huge collection of standard library which can be used for the following: Machine Learning GUI Applications (like Kivy, Tkinter, PyQt etc. ) Web frameworks like Django (used by YouTube, Instagram, Dropbox) Image processing (like OpenCV, Pillow) Web scraping (like Scrapy, BeautifulSoup, Selenium) Test frameworks Multimedia Scientific computing Text processing and many more. ''' import numpy as np a = np.array([1,2,3,'a','a',1]) b = np.unique(a) print(a,b)
62c2ff9db360ead0904ad5b43773d316315772cb
kaushik2000/python_programs
/ex_09/counts.py
1,064
4.34375
4
# Counting the no. of words in a line and the most occuring word while True: if input('Word frequency counter:\n(Enter "Exit" to quit) or (Press Enter to continue): ').lower() == 'exit' : print("Exiting....") break counts = dict() line = input("Enter a line: ") words = line.split() print("List of words from the entered line\n", words, "\n") # Getting a list of all words in the line print("Counting....") for word in words : counts[word] = counts.get(word, 0) + 1 print(counts, '\n') # Finding the most occuring word max_count = None max_word = None for word,count in counts.items() : if max_count == None or count > max_count: max_count = count max_word = word elif count == max_count : max_word = max_word + ", " + word print("The word(s) \'{}\'".format(max_word), "occurs the most with", max_count, "occurrences\n") print("------------------------------------------------------------------------------------------------")
3fd30f6343754e3b36675058c1222b6a5a2c1ffe
marturoch/Fundamentos-Informatica
/Pandas/Practica 8 - pandas/3.py
366
4.25
4
#Ejercicio 3 #Realizá un programa que agregue datos a un DataFrame vacío. import pandas as pd #vamos a agregar esto: # {1: [1, 4, 3, 4, 5], 2: [4, 5, 6, 7, 8], 3: [7, 8, 9, 0, 1]} df = pd.DataFrame() df[1] = [1, 4, 3, 4, 5] df[2] = [4, 5, 6, 7, 8] df[3] = [7, 8, 9, 0, 1] print(df) #Devuelve: # 1 2 3 #0 1 4 7 #1 4 5 8 #2 3 6 9 #3 4 7 0 #4 5 8 1
e9677922dc02e67f65ac7008c9b96bde62fbe8a6
felipeAraujo/cryptopals-solutions
/Python/Set 01/challenge03.py
1,212
3.5
4
#-*- coding: utf-8 -*- from Crypto.Util.strxor import strxor_c import re def cg03_single_byte_xor_cipher(value): result = get_more_scored_text(value) return result def get_more_scored_text(value): maximum_score = 0 text_with_maximum_score = ''; text_decoded = value.decode('hex') for code in range(0, 256): text_decoded = fixed_xor(text_decoded, code) score = get_text_score(text_decoded) if score > maximum_score: maximum_score = score text_with_maximum_score = text_decoded return text_with_maximum_score def fixed_xor(value1, char): result = strxor_c(value1, char) return result def get_text_score(text_decoded): score = 0 for char in text_decoded: if char == 'e': score += 5 elif char == 't': score += 4 elif char == 'a': score += 4 elif char == 'o': score += 3 elif char == 'i': score += 3 elif char == 'n': score += 2 elif char == ' ': score += 2 elif char == 's': score += 2 elif char == 'h': score += 2 return score
b5f3f0fbf437baa51baf9408c8dd18666cd049f5
lp2016/New_Algorithm
/newcode_fibonacci.py
459
3.859375
4
# -*- coding:utf-8 -*- class Solution: def Fibonacci(self, n): if n==1 or n ==2 : return 1 return self.Fibonacci(n-1)+self.Fibonacci(n-2) def Fibonacci2(self,n): if n==0: return 0 if n==1 or n ==2 : return 1 f=[0] f.append(1) f.append(1) for i in range(3,n+1): f.append(f[i-1]+f[i-2]) return f[n] print(Solution().Fibonacci2(39))
338f7ed50a0c744093ef49715ba611d36146359f
BillRozy/algorithms
/sort_by_merge.py
2,608
3.609375
4
import numpy as np from collections import deque acc = 0 def inversions(it, array): result, count = merge_count_inversion(array) return count def merge(left, right): result = [] i1 = 0 i2 = 0 count = 0 left_len = len(left) while i1 < left_len and i2 < len(right): if left[i1] > right[i2]: result.append(right[i2]) i2 += 1 count += left_len - i1 else: result.append(left[i1]) i1 += 1 result += left[i1:] result += right[i2:] return result, count def merge_count_inversion(array): if len(array) <= 1: return array, 0 middle = len(array) // 2 left, a = merge_count_inversion(array[:middle]) right, b = merge_count_inversion(array[middle:]) result, c = merge(left, right) return result, (a + b + c) def sort_by_merge(array, start=0, end=None): end = end or len(array) if start < end - 1: middle = (start + end) // 2 return merge(sort_by_merge(array, start, middle), sort_by_merge(array, middle, end))[0] if array: return [array[start]] return [] def sort_by_merge_iterative(array): queue = deque() i = 0 while i < len(array): queue.append([array[i]]) i += 1 while len(queue) > 1: queue.append(merge(queue.popleft(), queue.popleft())) if queue: return queue.popleft() return [] def custom_sort(it=False): if it: return sort_by_merge_iterative return sort_by_merge def main(): n = int(input()) array = list(map(int, input().split(' '))) print(inversions(True, array)) def test(it): global acc zero = [] input0 = [2] input1 = [2, 3, 9, 2, 9] input2 = [2, 3, 5, 10, 12] input3 = [12, 10, 5, 3, 2] input4 = [2, 4] # assert np.array_equal(merge([1, 5], [2, 23]), [1, 2, 5, 23]) # assert np.array_equal(custom_sort(it)(zero), zero) # assert np.array_equal(custom_sort(it)(input0), input0) # assert np.array_equal(custom_sort(it)(input1), sorted(input1)) # assert np.array_equal(custom_sort(it)(input2), sorted(input2)) # assert np.array_equal(custom_sort(it)(input3), sorted(input3)) # assert np.array_equal(custom_sort(it)(input4), input4) assert np.array_equal(custom_sort(it)(list(reversed(input4))), input4) assert 2 == inversions(it, input1) assert 0 == inversions(it, input2) assert 10 == inversions(it, input3) assert 21 == inversions(it, [7, 6, 5, 4, 3, 2, 1]) assert 1 == inversions(it, [1, 2, 3, 5, 4]) if __name__ == '__main__': main()
4ebaef825cd6e6d13a7d6b7939e667c5ea01474c
hustlrr/leetcode
/accepted/Word Search II.py
2,432
3.890625
4
# coding=utf-8 class TrieNode(object): def __init__(self): """ Initialize your data structure here. """ self.childs = {} self.isword = False class Trie(object): def __init__(self): self.root = TrieNode() def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ p = self.root for letter in word: p_next = p.childs.get(letter) if p_next is None: p_next = TrieNode() p.childs[letter] = p_next p = p_next p.isword = True def delwords(self, word): p = self.root nodes_del = [] for letter in word: nodes_del.append((letter, p)) p = p.childs.get(letter) if p is None: # 说明这个单词不存在 return if len(p.childs): p.isword = False # 说明这个单词是其他单词的前缀 else: for letter, node in nodes_del[ ::-1]: del node.childs[letter] if len(node.childs) or node .isword: # 如果和其他单词有共同前缀 ,共同前缀不应该删除 break class Solution(object): def findWords(self, board, words): """ :type board: List[List[str]] :type words: List[str] :rtype: List[str] """ tree = Trie() for word in words: tree.insert(word) row = len(board) col = len(board[0]) if row else 0 directs = [[1, 0], [-1, 0], [0, 1], [0, -1]] visited = [[False for i in range(col )] for j in range(row)] res = [] def dfs(node, px, py, s): if px < 0 or px >= row or py < 0 or py >= col or visited[px][py]: return node = node.childs.get (board[px][py]) if node is None: return s += board[px][py] if node.isword: res.append(s) tree.delwords(s) # 删除已经加入结果的单词可 以避免重复加入 visited[px][py] = True for dx, dy in directs: dfs(node, px + dx, py + dy, s) visited[px][py] = False for px in range(row): for py in range(col): dfs(tree.root, px, py, '') return res
b21266c36d4afe466044b9c5c7271063d37ce125
linkian209/rps-tourney
/classes/game.py
3,902
3.890625
4
"""classes.game This module contains the Game class. """ from classes.player import Player class Game(): """ This class represents a single game in a match. It takes an ID and two players and then determines the winner of the game. Attributes: game_id (int): The ID of the game player1 (Player): Player 1 player1_throw (dict): The choice of player 1 player2 (Player): Player 2 player2_throw (dict): The choice of player 2 winner (str): The name of the winning player game_result (str): Result of the game Methods: play_game(self): Play the game using the inputted game_id and players """ def __init__(self, game_id, player1, player2): """ This method initializes the player with the game_id and players, then plays out the game. Arguments: :param self: This object :param game_id: The game id as an int :param player_1: The first player as a Player :param player_2: The second player as a Player """ self.game_id = game_id self.player1 = player1 self.player2 = player2 self.winner = self.play_game() def play_game(self): """ This method plays out the game. Both players throw then we determine the winner. We then return the name of the winner. Arguments: :param self: This object Returns: str: The name of the winner """ self.player1_throw = self.player1.throw() self.player2_throw = self.player2.throw() # Resolve game # Tie - Easiest if(self.player1_throw['choice'] is self.player2_throw['choice']): self.game_result = 'Tie Game!' return None # Player 1 throws Rock elif(self.player1_throw['choice'] is 1): # Player 1 wins on a Scissors if(self.player2_throw['choice'] is 3): self.game_result = '{} wins!'.format(self.player1.name) return self.player1.name else: self.game_result = '{} wins!'.format(self.player2.name) return self.player2.name # Player 1 throws Scissors elif(self.player1_throw['choice'] is 3): # Player 1 wins on a Paper if(self.player2_throw['choice'] is 2): self.game_result = '{} wins!'.format(self.player1.name) return self.player1.name else: self.game_result = '{} wins!'.format(self.player2.name) return self.player2.name # Player 1 throws Paper else: # Player 1 wins on a Rock if(self.player2_throw['choice'] is 1): self.game_result = '{} wins!'.format(self.player1.name) return self.player1.name else: self.game_result = '{} wins!'.format(self.player2.name) return self.player2.name def __str__(self): """ This method returns the string representation of the game. Arguments: :param self: This object Returns: str: The string representation of the game """ return ''' Game {} --------------- {} threw {}. {} threw {}. {} '''.format( self.game_id, self.player1.name, self.player1_throw['str'], self.player2.name, self.player2_throw['str'], self.game_result) def __repr__(self): """ This method returns a string representation of the game. Arguments: :param self: This object Returns: str: The string representation """ return "<Game - {} v. {} | {} wins>".format(self.player1.name, self.player2.name, self.winner)
9de5cbf4f8d3f323b051f7b81cd0630397657a67
shrikantnarvekar/Algorithims-and-Data-Structures
/binary tree.py
1,664
3.796875
4
class Treenode: def __init__(self,d): self.data=d self.lchild=None self.rchild=None class Mytree: def __init__(self,t): self.root=t def preorder(self,t): if t is not None: print(t.data) self.preorder(t.lchild) self.preorder(t.rchild) def inorder(self,t): if t is not None: self.inorder(t.lchild) print(t.data) self.inorder(t.rchild) def postorder(self,t): if t is not None: self.preorder(t.lchild) self.preorder(t.rchild) print(t.data) def conpreorder(self,t): if t is not None: print(t.data) self.preorder(t.rchild) self.preorder(t.lchild) def coninorder(self,t): if t is not None: self.inorder(t.rchild) print(t.data) self.inorder(t.lchild) def conpostorder(self,t): if t is not None: self.preorder(t.rchild) self.preorder(t.lchild) print(t.data) F=Treenode("F") B=Treenode("B") K=Treenode("K") A=Treenode("A") B=Treenode("B") D=Treenode("D") C=Treenode("C") G=Treenode("G") F.lchild=B F.rchild=K B.lchild=A B.rchild=D D.lchild=C K.lchild=G mt=Mytree(F) print("preorder: ") mt.preorder(F) print("inorder: ") mt.inorder(F) print("postorder: ") mt.postorder(F) print("converse preorder: ") mt.conpreorder(F) print("converse inorder: ") mt.coninorder(F) print("converse postorder: ") mt.postorder(F)