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
0112fc65916b0a9cdd174f53d9fe05d72ac70d86
sanskarvijpuria/Basic-Python-Programs
/Addition of two numbers.py
101
3.890625
4
x=int(input("Enter any number")) y=int(input("Enter another number")) z=x+y print("Additon= ",z)
7b1c89c0b035731e592db7f3a0e8e91755faaaf9
stivenan/Tivenan-Math361-B
/Applied/A3_Deflation_Tivenan.py
2,801
3.703125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Apr 19 20:39:42 2019 @author: StephenTivenan """ import numpy as np def add(f,p): r=[] if len(f)==len(p): aa=f bb=p a=len(p) b=len(f) if len(p)>len(f): aa=p bb=f a=len(p) b=len(f) if len(f)>len(p): aa=f bb=p a=len(f) b=len(p) for ii in range(a): for jj in range(b): if ii==jj: aa[ii]=aa[ii]+bb[jj] r.append(aa[ii]) return r def subtract(f,p): r=[] if len(f)==len(p): aa=f bb=p a=len(p) b=len(f) if len(p)>len(f): aa=p bb=f a=len(p) b=len(f) if len(f)>len(p): aa=f bb=p a=len(f) b=len(p) for ii in range(a): for jj in range(b): if ii==jj: aa[ii]=aa[ii]-bb[jj] r.append(aa[ii]) return r def multiplication(x,u): m=[] for ii in range(len(x)): for jj in range(len(u)): b=x[ii]*u[jj] if x[ii]==0: for pp in range(len(x)): t=0 m.append(t) break break m.append(b) return m def DivisionLT(f,p): r=[] if len(f)==len(p): aa=f bb=p a=len(p) b=len(f) if len(p)>len(f): aa=p bb=f a=len(p) b=len(f) if len(f)>len(p): aa=f bb=p a=len(f) b=len(p) l=aa[0]/bb[0] r.append(l) for jj in range(a-b): r.append(0) return r def clean_poly(p): highest_deg = 0 for ii in range(0,len(p)): if np.abs(p[ii]) > 1e-15: break else: highest_deg += 1 del p[:highest_deg] return p ## The function f is from highest degree to lowest degree of the polynomial ## The function g is the polynomial that divides the larger the larger polynomial f and its degree is from highest to lowest def division(f,g): q=[0] m=list(f) r=f quo=[] while r!=[] and len(f)>len(g): f=r a=DivisionLT(f,g) q=add(q,a) quo.append(a[0]) b=multiplication(a,g) r=subtract(r,b) r=clean_poly(r) return print('\nThis is function of life:', m,'\nThis is the divisor:', g,'\nThis is the quotient:', quo,'\nThis is the remainder:',r) division([2,3,4],[2,3]) #for ii in range(1): # r=p # a=DivisionLT(p,w) # print(a) # q=add(q,a) # print(q) # b=multiplication(a,w) # print(b) # r=subtract(r,b) # print(r) # r=clean_poly(r) # print(r)
61de2f8001658aef4b191dc95efa66c1022c235f
jailukanna/Python-Projects-Dojo
/05.More Python - Microsoft/01.lambda_sorter.py
548
3.78125
4
#sorting by function def name_sorter(item): return item['name'] presenters = [ {'name':'Susan', 'age':50}, {'name':'Christopher', 'age':47} ] #sort by name presenters.sort(key=name_sorter) print(presenters) #----------------------------- #Now Using lambda, without explicting declaring a single line function #sort by name ascending presenters.sort(key=lambda item: item['name']) print(presenters) #----------------------------- #sort by length of name ascending presenters.sort(key=lambda item: len(item['name'])) print(presenters)
ec37f915fd7d843bb14205a63211db8068b02d4d
zhudaxia666/shuati
/LeetCode/刷题/字符串/6Z字形变换.py
2,901
3.53125
4
''' 将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。 比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下: L C I R E T O E S I I G E D H N 之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。 请你实现这个将字符串进行指定行数变换的函数: string convert(string s, int numRows); 思路: 我们先假定有 numRows=4 行来推导下,其中 2*numRows-2 = 6 , 我们可以假定为 step=2*numRows-2 ,我们先来推导下规则: 第0行: 0 - 6 - 12 - 18 ==> 下标间距 6 - 6 - 6 ==> 下标间距 step - step - step 第1行: 1 - 5 - 7 - 11 - 13 ==> 下标间距 4 - 2 - 4 - 2 ==> 下标间距step-2*1(行)-2*1(行)-step-2*1(行)-2*1(行) 第2行: 2 - 4 - 8 - 10 - 14 ==> 下标间距 2 - 4 - 2 - 4 ==> 下标间距step-2*2(行)-2*2(行)-step-2*2(行)-2*2(行) 第3行:3 - 9 - 15 - 21 ==> 下标间距间距 6 - 6 - 6 ==>下标间距step - step - step 可以得出以下结论: 起始下标都是行号 第0层和第numRows-1层的下标间距总是step 。 中间层的下标间距总是step-2*行数,2*行数交替。 下标不能超过len(s)-1 ''' def convert(s,numRows): if numRows==1: return s step=numRows*2-2#间隔 index=0#记录s的下标 l=len(s)# add=0#真实的间隔 res='' for i in range(numRows):#i表示行号 index=i add=i*2 while index<l:#产出字符串长度计算下一层 res+=s[index]#当前行的第一个字母 add=step-add#第一次间隔是step-2*i,第二次是2*i index+=step if i==0 or i==numRows-1 else add return res ''' 思路二: 字符串s是以 ZZ 字形为顺序存储的字符串,目标是按行打印。设numRows行字符串分别为 s1,s2,sn,则容易发现,按顺序遍历字符串s时, 每个字符c属于的对应行索引先从s1增加到sn,再从sn减少到s1...如此反复, 算法流程: 按顺序遍历字符串s; res[i] += c:把每个字符c填入对应行 s_i ; i += flag:更新当前字符c对应的行索引; flag = - flag:在达到 ZZ 字形转折点时,执行反向。 复杂度分析: 时间复杂度 O(N)O(N) :遍历一遍字符串s; 空间复杂度 O(N)O(N) :各行字符串共占用 O(N)O(N) 额外空间。 作者:jyd 链接:https://leetcode-cn.com/problems/zigzag-conversion/solution/zzi-xing-bian-huan-by-jyd/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 ''' def converse(s,numRows): if numRows<2: return s res=['' for _ in range(numRows)] i,flag=0,-1 for c in s: res[i]+=c if i==0 or i==numRows-1: flag=-flag i+=flag return ''.join(res)
dc8458dd9ac7c1c620791dfb678268253753db82
KimSoomae/startcamp-1
/day2/code/operators.py
247
3.5625
4
# 산술 연산자 print(3 + 5) print(5 - 3) print(100 * 5) print(100 / 3) print(100 // 3) print(100 % 3) print(2 ** 5) # 비교 연산자 print(5 == 5) print(3 == '3') print(3 != 5) print(3 >= 3) print(5 < 4) print(type(5) == int)
99406295a3708648d1bd2bfef23f0b51e940e90a
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_203/128.py
767
3.609375
4
import re def rotated(original): return list(map(lambda x: "".join(x), zip(*original))) def replace(s): s = re.sub(r'^([?]+([^?]))', lambda m: m.group(2) * len(m.group(1)), s) s = re.sub(r'(([^?])[?]+)', lambda m: m.group(2) * len(m.group(1)), s) return s def solve(cake): cake = list(map(replace, cake)) cake = rotated(cake) cake = list(map(replace, cake)) cake = rotated(cake) return "\n".join(cake) def main(): t = int(input()) for i in range(t): r, c = map(int, input().split()) cake = [] for y in range(r): cake.append(input()) result = solve(cake) print("Case #{}:\n{}".format(i + 1, result)) if __name__ == '__main__': main()
0a75429c666dfedf31853ccd4a8de34fb197bd18
wfsovereign/python_learn_notes
/src/2019-07-17.py
949
3.765625
4
from modules.buildHandsomeProfile import buildHandsomeProfile message = input('hello world, your name: ') print(message) questionnaires = [] while len(questionnaires) < 2: name = input("What's your name : ") place = input('If you could visit one place in the world, where would you go? ') questionnaires.append({'name': name, 'place': place}) print('the result ,', questionnaires) def myPets(name, type): print('name : ', name, ' type : ', type) myPets('duobi', 'dog') myPets(type='dog', name='duobi') def makePizze(*toppings): print('args ,', toppings) makePizze('peperoni') makePizze('mushroom', 'extra cheese') def buildProfile(name, **info): person = {'name': name} for key, value in info.items(): person[key] = value print(person) return person buildProfile('john', gender='male', age='21', career='princes') F = buildHandsomeProfile('F君', gender='male', age='26', career='dreamer') print(F)
27b501ebf25aea985d8cc2d059a77843d505cd7c
skunkwerk/puzzles
/membrane.py
4,136
3.828125
4
#!/usr/bin/env python # Author: Imran Akbar (imran@osg.stanford.edu) # Created: 1/24/2012 ''' Description of Problem: Print for him a path, consisting of a list of positions, starting anywhere in the nucleus, where: Each position is empty Each successive position is only 1 nm away from the one before it The path passes through each position in the nucleus at most once The number of positions visited is equal to the length of Danny Dendrite's genome (the starting and ending positions both count). If no path exists, just print "impossible". Sample Input file: 5 4 8 oxoo xoxo ooxo xooo oxox Sample Output: 1,1 2,1 3,1 3,2 3,3 2,3 1,3 0,3 ''' import sys # could have used a NumPy matrix here, but for compatibility just use lists # Grid coords start at 0,0 and follow matrix notation grid=[] currentPath = [] # stores row, column of visited nodes def readFile(): try: file = open('membrane_input.txt','r') lines = file.readlines() file.close() global grid arguments = lines.pop(0).strip('\n').split(" ") for line in lines: grid.append(list(line.strip('\n'))) return [int(x) for x in arguments] # casts strings to integers except: print "Error reading from file" def squareStatus(row,column,state,rows,columns): if column>=columns or row>=rows or row<0 or column<0: # out of bounds return False else: if grid[row][column]=="o": # free return True if state=="free" else False elif grid[row][column]=="x": # occupied return False if state=="free" else True else: # invalid data raise Exception def traversal(start_row, start_column, rows, columns, length): # tries different starting positions while start_column<columns: start_row = 0 # reset while start_row<rows: result = testPosition(start_row,start_column,length,rows,columns) if result==True: return True elif result==False: backTrack(start_row,start_column,rows,columns) # otherwise, keep searching start_row += 1 start_column += 1 return False # if done searching, return impossible def testPosition(row,column,length,rows,columns): if squareStatus(row,column,"free",rows,columns): # possible starting point currentPath.append([row,column]) # add to path grid[row][column] = "x" # mark as visited if length==1: return True else: # start recursion on nearest neighbors result = testPosition(row+1,column,length-1,rows,columns) if result==True: return True elif result==False: backTrack(row+1,column,rows,columns) result = testPosition(row-1,column,length-1,rows,columns) if result==True: return True elif result==False: backTrack(row-1,column,rows,columns) result = testPosition(row,column+1,length-1,rows,columns) if result==True: return True elif result==False: backTrack(row,column+1,rows,columns) result = testPosition(row,column-1,length-1,rows,columns) if result==True: return True elif result==False: backTrack(row,column-1,rows,columns) return False # couldn't find any path else: # already occupied or out of bounds return "invalid" # different from False, so you know when to backtrack def backTrack(row,column,rows,columns): if squareStatus(row,column,"occupied",rows,columns): # is NOT out of bounds, and IS occupied currentPath.pop() # remove last visited node from path grid[row][column] = "o" # UNmark as visited def printPath(): for coord in currentPath: print str(coord[0]) + "," + str(coord[1]) def main(): rows, columns, length = readFile() if traversal(0,0,rows, columns, length)==True: printPath() else: print "impossible" if __name__ == '__main__': main() sys.exit()
5237f3404d4936b5704be63384da9924bc6c1a52
rktirtho/Python-3
/Datacollection and Processing/week-2/list_comprehension.py
257
3.515625
4
lst = [4,5,25,6,47,42,67,85,35,2,16,7] new_list = [value *2 for value in lst] evens = [value for value in lst if value%2==0] new_quad = [i+2 for i in lst] odds = [i*3 for i in lst if i%2==1] print(new_list) print(new_quad) print(evens) print(odds)
3644151b977a07d3967f78b49975a25b72d8f4ef
TopskiyMaks/PythonBasic_Lesson
/lesson_2/task_4.py
447
3.6875
4
# variant_1 name = input('Ведите имя: ') surname = input('Ведите фамилию: ') city = input('Ведите город проживания: ') print('Вас зовут') print(name) print(surname) # variant_2 # name = input('Ведите имя: ') # surname = input('Ведите фамилию: ') # city = input('Ведите город проживания: ') print('==========') print('Вас зовут', name, surname) print('Вы живите в городе', city)
7f30476bc5fd6d433f86d8475616950b22921e5d
statco19/doit_pyalgo
/ch2/max_of_test.py
216
3.515625
4
from max import max_of t = (4,7,5.6,2,3.14,1) s = "string" a = ["DTS", "AAC", "FLAC"] print(f"max val of {t} is {max_of(t)}") print(f"max val of {s} is {max_of(s)}") print(f"max val of {a} is {max_of(a)}")
f8bf783645bd7f0b055a188e25390cd4650a61af
daniel-reich/ubiquitous-fiesta
/LDQvCxTPv4iiY8B2A_16.py
117
3.59375
4
def same_upsidedown(ntxt): return ntxt == ''.join('6' if c=='9' else '9' if c=='6' else '0' for c in ntxt)[::-1]
2fc6ac6f11009167d8aa2a129ac4a1d14cee4b56
Dochko0/Python
/Python_Fundamentals/04_Lambda_Functions_And_Exercise/task_lists/07_sort_list_using_bubble_sort.py
426
3.609375
4
number_list = list(map(int, input().split())) swap = True while swap: swap = False for i in range (1, len(number_list)): check_left = number_list[i - 1] check_right = number_list[i] if check_left>check_right: num = number_list[i] number_list[i] = number_list[i-1] number_list[i-1] = num swap = True print(' '.join(str(x) for x in number_list))
af4419e5cbc37531fd006f11441c6a1b876f39f0
gbrs/PythonAlgorithmsAndDataStructuresGeekbrains
/les_3_task_8.py
963
3.859375
4
'''8. Матрица 5x4 заполняется вводом с клавиатуры, кроме последних элементов строк. Программа должна вычислять сумму введенных элементов каждой строки и записывать ее в последнюю ячейку строки. В конце следует вывести полученную матрицу. ''' a = [[0 for j in range(4)] for i in range(5)] # организуем ввод for i in range(4): for j in range(4): a[i][j] = float(input("Введите очередное число: ")) print() # вычисляем элементы пятой строки for j in range(4): t = 0 for i in range(4): t += a[i][j] a[4][j] = t # распечатываем получившуюся 'матрицу' for i in range(5): for j in range(4): print(a[i][j], end="\t") print()
774e0b9c1532b0d30bd1a2b09bc6f2a916e6e785
shobhit-nigam/tsip_pydoge
/day5/concurrency/one.py
449
3.578125
4
import threading import time def taskA(): for i in range(3, 0, -1): print(i, "seconds left for task A") time.sleep(1) def taskB(): for i in range(9, 0, -1): print(i, "seconds left for task B") time.sleep(1) ta = threading.Thread(target=taskA) tb = threading.Thread(target=taskB) ta.start() tb.start() for i in range(6, 0, -1): print(i, "seconds left for task main") time.sleep(1)
1a7ebadbf62b5973b5e24c0f97e0571502932ca3
MrHamdulay/csc3-capstone
/examples/data/Assignment_2/mslleb005/question3.py
337
4.25
4
import math # makes the maths library available. a=2 #the first number in the terms n=math.sqrt(2) #the second number in the terms pi=a*(a/n) while n!=2: n= math.sqrt(a + n) pi=pi * a/n print("Approximation of pi:" ,round(pi,3)) r=eval(input("Enter the radius:\n")) Area=pi * r**2 print("Area:" ,round(Area,3))
7793a5bcf85b3330b87a92db9ef4d311e5c11204
GaiYu0/data_structure_assignments
/hw06/facility.py
2,225
3.65625
4
from itertools import combinations import random class Node: def __init__(self, parent=None, children=None, move=None, value=None): self.parent = parent self.children = [] if children is None else children self.move = move self.value = value def append_child(self, child): child.parent = self self.children.append(child) def depth(self): result = 0 node = self while node.parent is not None: node = node.parent result += 1 return result def goto(self, move): for child in self.children: if child.move == move: return child return None def choose_move(root, moves): # TODO random choice node = root for move in moves: children_moves = [child.move for child in node.children] index = children_moves.index(move) node = node.children[index] values = [child.value for child in node.children] player = len(moves) % 2 if player == 0: metric = max else: metric = min optimal = metric(values) index = random.choice([index for index, value in enumerate(values) if value == optimal]) optimal_move = node.children[index].move return optimal_move def to_coordinate(n): X = n % 3 Y = int(n / 3) return X, Y def AP(s): # whether a sequence is an arithmetic progression s = [left + right for left, right in zip(s, s[::-1])] return min(s) == max(s) def judge(moves): if len(moves) < 5: return 0 player = (len(moves) - 1) % 2 player_moves = [move for index, move in enumerate(moves) if index % 2 == player] player_moves.sort() for sequence in combinations(player_moves, 3): coordinates = map(to_coordinate, sequence) X, Y = zip(*coordinates) if AP(X) and AP(Y): return 1 if player == 0 else -1 return 0 def to_string(moves, symbol='XO', line_delimiter='-', column_delimiter='|'): string = [] for i in range(9): try: index = moves.index(i) % 2 string.append(symbol[index]) except: string.append(str(i)) if i % 3 == 2: string.append('\n') return ''.join(string) if __name__ == '__main__': # print(judge([0, 1, 3, 6, 4, 5, 8])) ''' for i in range(9): print(to_coordinate(i)) ''' print(judge([0, 1, 4, 8, 3, 5, 6]))
4c9f5cc31c5bbf937d18e0afacfed783f3b98c1f
raghavai/Roomba-Simulator
/solution_code.py
11,624
3.59375
4
# H1.py # Author: Paul Talaga # Programmer: Aarthi Raghavendra # Co-Worker: Abhyudaya Upadhyay # This file demonstrates how to implement various kinds of Roomba robot agents # and run them in GUI or non-gui mode using the roomba_sim library. # from roomba_sim import * from roomba_concurrent import * from queue import PriorityQueue # Each robot below should be a subclass of ContinuousRobot, RealisticRobot, or DiscreteRobot. # All robots need to implement the runRobot(self) member function, as this is where # you will define that specific robot's characteristics. # All robots perceive their environment through self.percepts (a class variable) and # act on it through self.action. The specific percepts received and actions allowed # are specific to the superclass. See roomba_sim for details. # TunedRobot - Robot that acceps a chromosome parameter and can store limited state # (a single number). Continuous and dynamic environment. # the chromosome will contains the course of actions which it performs # chromosome = String # string will contain - Hurdle-right, degree to turn -82,88,108, 157, which keep on changing on every hurdle, with addition of 0.5 # on dirt perform a suck opration # on no - bump and no- dirt - move forward # HRt82t88t108t157|DS|Forward # # Stupid Robot class TunedRobot1(RealisticRobot): """ The ReflexRobotState robot is similar to the ReflexRobot, but some state is allowed in the form of a number. """ def __init__(self,room,speed, start_location = -1, chromosome = None): super(TunedRobot1, self).__init__(room,speed, start_location) # Set initial state here you may only store a single number. self.state = 0 # Save chromosome value self.degrees = 0 # choromosome value is coming as null and its causing problems def runRobot(self): (bstate, dirt) = self.percepts if(bstate == 'Bump'): self.action = ('TurnRight',135 + self.degrees) elif(dirt == 'Dirty'): self.action = ('Suck',None) else: self.action = ('Forward',None) class TunedRobot(RealisticRobot): """ The ReflexRobotState robot is similar to the ReflexRobot, but some state is allowed in the form of a number. """ def __init__(self,room,speed, start_location = -1, chromosome = None): super(TunedRobot, self).__init__(room,speed, start_location) # Set initial state here you may only store a single number. self.state = 0 # Save chromosome value #print("chromo = ", chromosome) self.degrees = chromosome #print("degrees = ", self.degrees) def runRobot(self): degree = 0 deg = parseChromosome(self.degrees) if(self.state%4 ==0): degree = deg[0] elif(self.state%4 ==1): degree = deg[1] elif(self.state%4 ==2): degree = deg[2] elif(self.state%4 ==3): degree = deg[3] self.state += 1 (bstate, dirt) = self.percepts if(bstate == 'Bump'): self.action = ('TurnRight',degree ) elif(dirt == 'Dirty'): self.action = ('Suck',None) else: self.action = ('Forward',None) def getOldChromosome(rooms, start_location, min_clean): rooms = rooms wallcount = calculatewalls(rooms) print(wallcount ,'wall count') if(wallcount == 0): return 'HRt82t86t132t157|D|F' elif (wallcount > 20): return 'HRt84t88t102t117|D|F' elif(wallcount >50): return 'HRt81t76t142t127|D|F' else : return 'HRt82t86t132t157|D|F' def getChromosome(rooms, start_location, min_clean): ###New function priority = PriorityQueue() #old chromo HRt84t88t102t117|D|F first = 81 second = 84 third = 106 fourth = 121 for k in range(10): testIt = makechromosome(first + k, second + k, third -k, fourth -k) priority.put( (resultValue(rooms, testIt, minclean = 0.20), testIt) ) chromosomerecent = priority.get()[1] print("transferreing chromomsmme ", chromosomerecent) return chromosomerecent def calculatewalls(rooms): countwalls = 0 for i in range(len(rooms)): wallsnumber = len(getWallsValue(rooms[i])) countwalls = countwalls + wallsnumber print('Number of walls ',countwalls) return countwalls def getWallsValue(room): #width = self.getRoomWidth(); #height = self.getRoomHeight(); #dirtyList = self.getDirty() #wallList = rooms[1].getWalls() insidewall = [] countnumberofWalls = 0 width = room.getWidth() height = room.getHeight() walllist = room.getWalls() #for k in range(len(walllist)): while(len(walllist)>0): #print(walllist[k]) (x,y) = walllist.pop() if(not(x == width or x == -1 or y == -1 or y == height)): insidewall.append((x,y)) return insidewall #countnumberofWalls = countnumberofWalls+ len(rooms[i].getWalls()); def testAllMaps2(robot, rooms, numtrials = 10, minclean = 0.95, start_location = -1, chromosome = None): """ Runs the specified robot over the list of rooms, optionally with a specified number of trials per map, and starting location (x,y). Prints status to the screen and returns the average performance over all maps and trials.""" score = 0 for room in rooms: runscore, runstd = runSimulation(num_robots = 1, speed = 1, min_clean = minclean, num_trials = numtrials, room = room, robot_type = robot, start_location = start_location, #debug = True, chromosome = chromosome, ui_enable = False) score += runscore #print("Room %d of %d done (score: %d std: %d)" % (rooms.index(room)+1, len(rooms), runscore, runstd)) #print("Average score over %d trials: %d" % (numtrials * len(rooms), score / len(rooms))) return score / len(rooms) #Results value for a chromosome ''' def resultValue(robot,rooms,chromosome): #robot = TunedRobot startLoc = (5,5) minclean = 0.2 numtrials = 20 chromosome = getChromosome(rooms, startLoc, minclean) result =testAllMaps(TunedRobot, rooms, numtrials, minclean, chromosome ) testAllMaps(TunedRobot, rooms, numtrials = 20, minclean = minClean, chromosome = getChromosome(rooms, startLoc, minClean))) print(result) return result ''' def makechromosome(first,second,third,fourth): firstdegree = str(first) seconddegree = str(second) thirddegree = str(third) fourthdegree = str(fourth) s = 'HR'+'t'+firstdegree+'t'+seconddegree+'t'+thirddegree+'t'+ fourthdegree + '|D|F' #print ("make chromo -- ", s) return s def resultValue(rooms, chromosome, numtrials = 3, minclean = 0.20, startLoc = (5,5) ): result = testAllMaps2(TunedRobot, rooms, numtrials, minclean, start_location = startLoc ,chromosome = chromosome) return result #result =testAllMaps(TunedRobot, rooms, numtrials = 20, minclean = minClean, chromosome = getChromosome(rooms, startLoc, minClean)) #parse chromosome def parseChromosome(s): #s= 'HRt82t86t132t157|D|F' #s= 'HRt84t84t82t87|D|F' a = s.split('|') degree = a[0].split('t') #print(a) #print(degree) first = int(degree[1]) second = int(degree[2]) third = int(degree[3]) fourth = int(degree[4]) return(first,second,third,fourth) ############################################ ## A few room configurations allRooms = [] smallEmptyRoom = RectangularRoom(10,10) allRooms.append(smallEmptyRoom) # [0] largeEmptyRoom = RectangularRoom(10,10) allRooms.append(largeEmptyRoom) # [1] mediumWalls1Room = RectangularRoom(30,30) mediumWalls1Room.setWall((5,5), (25,25)) allRooms.append(mediumWalls1Room) # [2] mediumWalls2Room = RectangularRoom(30,30) mediumWalls2Room.setWall((5,25), (25,25)) mediumWalls2Room.setWall((5,5), (25,5)) allRooms.append(mediumWalls2Room) # [3] mediumWalls3Room = RectangularRoom(30,30) mediumWalls3Room.setWall((5,5), (25,25)) mediumWalls3Room.setWall((5,15), (15,25)) mediumWalls3Room.setWall((15,5), (25,15)) allRooms.append(mediumWalls3Room) # [4] mediumWalls4Room = RectangularRoom(30,30) mediumWalls4Room.setWall((7,5), (26,5)) mediumWalls4Room.setWall((26,5), (26,25)) mediumWalls4Room.setWall((26,25), (7,25)) allRooms.append(mediumWalls4Room) # [5] mediumWalls5Room = RectangularRoom(30,30) mediumWalls5Room.setWall((7,5), (26,5)) mediumWalls5Room.setWall((26,5), (26,25)) mediumWalls5Room.setWall((26,25), (7,25)) mediumWalls5Room.setWall((7,5), (7,22)) allRooms.append(mediumWalls5Room) # [6] ############################################# def TunedTest1(): print(runSimulation(num_robots = 1, min_clean = 0.95, num_trials = 1, room = allRooms[6], robot_type = TunedRobot1, #ui_enable = True, ui_delay = 0.1, chromosome = getChromosome(rooms, startLoc, minClean))) def TunedTest2(): print(runSimulation(num_robots = 1, min_clean = 0.95, num_trials = 1, room = allRooms[6], robot_type = TunedRobot, #ui_enable = True, ui_delay = 0.1, chromosome = 2)) if __name__ == "__main__": # This is an example of how we will test your program. Our rooms will not be those listed above, but similar. #rooms = [allRooms[1]] #rooms = [allRooms[1], allRooms[5]] rooms = allRooms startLoc = (5,5) minClean = 0.20 #chromosome = getChromosome(rooms, startLoc, minClean) #print('some chromosome ',chromosome) # testAllMaps # Concurrent test execution. print("***********************") print("And Stupid robot") print("***********************") #print(concurrent_test(TunedRobot1, rooms, num_trials = 20, min_clean = minClean, chromosome = chromosome)) print(testAllMaps(TunedRobot1, rooms, numtrials = 20, minclean = minClean, chromosome = 'chromosome')) print("***********************") print("And now your robot") print("***********************") #print(concurrent_test(TunedRobot, rooms, num_trials = 20, min_clean = minClean, chromosome = chromosome)) print(testAllMaps(TunedRobot, rooms, numtrials = 20, minclean = minClean, chromosome = getChromosome(rooms, startLoc, minClean))) #print('Test map results ' + testAllMaps(TunedRobot, rooms, numtrials = 20, minclean = minClean, chromosome = getChromosome(rooms, startLoc, minClean))) #print('before the result function',chromosome) #print ("old chromo ", getOldChromosome(rooms, startLoc, minClean)) #result =testAllMaps(TunedRobot, rooms, numtrials = 20, minclean = minClean, chromosome = getOldChromosome(rooms, startLoc, minClean)) # res = resultValue(rooms,chromosome=getChromosome(rooms, startLoc, minClean)) #print(result) # print(res) # This code will be run if this file is called on its own #TunedTest1() #TunedTest2() # This is an example of how we will test your program. Our rooms will not be those listed above, but similar. #rooms = [allRooms[1], allRooms[5]] #startLoc = (5,5) #minClean = 0.2 #chromosome = getChromsome(rooms, startLoc, minClean) # Concurrent test execution. #print(concurrent_test(TunedRobot, rooms, num_trials = 20, min_clean = minClean, chromosome = chromosome))
3d291dd36c2dfed30eac4d207113b0d48c6f8643
ponkotsuMEN/AtCoder
/ABC/171/a.py
66
3.671875
4
s = input() if ord(s) <= 90: print("A") else: print("a")
9a5706749d88a8c9b4eea8612e3f00dc2690ac68
AdamZhouSE/pythonHomework
/Code/CodeRecords/2180/60769/316470.py
1,022
3.5625
4
import functools class mystr: def __init__(self, string, index): self.string = string self.index = index def __eq__(self, other): return self.string == other.string and self.index != other.index def mycmp(x, y): # print(len(x.string)-len(y.string)) return len(x.string) - len(y.string) str1 = input() str2 = input() string1 = [] string2 = [] count = 0 for i in range(len(str1)): for j in range(i + 1, len(str1) + 1): string1.append(mystr(str1[i:j], i)) for i in range(len(str2)): for j in range(i + 1, len(str2) + 1): string2.append(mystr(str2[i:j], i)) string1 = sorted(string1, key=functools.cmp_to_key(mycmp)) string2 = sorted(string2, key=functools.cmp_to_key(mycmp)) for i in range(len(string1)): for j in range(len(string2)): if len(string1[i].string) < len(string2[j].string): break if string1[i].string == string2[j].string and string1[i].index != string2[j].index: count += 1 print(count,end="")
16295336b312c5f7f40697ed310d32a4f603c704
AkarshSimha007/ISE-SEM_5-Labs
/SL_LAB/Part B python/1c.py
379
3.953125
4
def Max(list): if len(list)==1: return list[0] else: m=Max(list[1:]) return m if m>list[0] else list[0] def main(): try: num_list=eval(input("Enter the listof numbers:")) print("the largest number is: ",Max(num_list)) except SyntaxError:print("Enter comma seperated values") except:print("Enter numbers only") main()
35404eeaa702188b7abee2c4c1206354dcb7dbaa
DaiMaDaiMa/PythonStudy
/多任务/生成器的基本使用.py
330
4.0625
4
""" 生成器也是一样迭代器,可以使用next获取值 两种方式: 1.列表推导式 2.函数中使用了yield yield两个作用:1,充当return作用,2.保存程序状态 """ data = (x for x in range(10)) print(data) print(next(data)) def get_num(): yield 10 num = get_num() print(num) print(next(num))
70e3c957c57f44f1a41a28aee6861e9eedc5e6cf
cynnnzhang/Games
/RPS Game.py
5,028
4.25
4
########################################### #Objects: Paint, Wall, Sconce, Window, Art ########################################### #Explanations ########################################### #Paint beats Wall since it covers it #Paint beats Window since spray paint can be used to grafitti it #Wall beats Window since wall is needed to install a window #Wall beats Sconce since will is needed to install a sconce #Sconce beats Art since the art cannot be seen in the night without the artificial light #Sconce beats Paint since the paint colour cannot be seen in the night without the artificial light #Window beats Sconce since it brings in natural light (better than artificial) #Window beats Art since the real art is the natural world outside #Art beats Paint since is is much more artistic and expressive #Art beats Wall since a hole must be drilled to hang up art from random import * playAgain = "yes" while playAgain == "yes": playerScore = 0 compScore = 0 print("") numPlays = int(input("How many times would you like to play?: ")) for x in range(numPlays): playerChoice = input("Enter your move (P, Wa, S, Wi, A): ") while playerChoice not in ["P", "Wa", "S", "Wi", "A"]: print("Please enter a valid option") playerChoice = input("Enter your move (P, Wa, S, Wi, A): ") cpu = choice(["P", "Wa", "S", "Wi", "A"]) print("The computer played", cpu) if playerChoice == cpu: print("You tied this round") print("Your current score is", playerScore) print("The computer's current score is", compScore) elif playerChoice == "P" and cpu == "Wa": print("You won this round!") playerScore = playerScore + 1 print("Your current score is", playerScore) print("The computer's current score is", compScore) elif playerChoice == "P" and cpu == "Wi": print("You won this round!") playerScore = playerScore + 1 print("Your current score is", playerScore) print("The computer's current score is", compScore) elif playerChoice == "Wa" and cpu == "Wi": print("You won this round!") playerScore = playerScore + 1 print("Your current score is", playerScore) print("The computer's current score is", compScore) elif playerChoice == "Wa" and cpu == "S": print("You won this round!") playerScore = playerScore + 1 print("Your current score is", playerScore) print("The computer's current score is", compScore) elif playerChoice == "S" and cpu == "A": print("You won this round!") playerScore = playerScore + 1 print("Your current score is", playerScore) print("The computer's current score is", compScore) elif playerChoice == "S" and cpu == "P": print("You won this round!") playerScore = playerScore + 1 print("Your current score is", playerScore) print("The computer's current score is", compScore) elif playerChoice == "Wi" and cpu == "S": print("You won this round!") playerScore = playerScore + 1 print("Your current score is", playerScore) print("The computer's current score is", compScore) elif playerChoice == "Wi" and cpu == "A": print("You won this round!") playerScore = playerScore + 1 print("Your current score is", playerScore) print("The computer's current score is", compScore) elif playerChoice == "A" and cpu == "P": print("You won this round!") playerScore = playerScore + 1 print("Your current score is", playerScore) print("The computer's current score is", compScore) elif playerChoice == "A" and cpu == "Wa": print("You won this round!") playerScore = playerScore + 1 print("Your current score is", playerScore) print("The computer's current score is", compScore) else: print("Computer won this round") compScore = compScore + 1 print("Your current score is", playerScore) print("The computer's current score is", compScore) print("") print("*" * 20) print("Your total number of wins is", playerScore) print("The computers total number of wins is", compScore) if playerScore == compScore: print("You tied with the computer! Thanks for playing!") elif playerScore > compScore: print("You won the game! Thanks for playing!") else: print("The computer won the game! Thanks for playing!") print("") playAgain = input("Would you like to play again? (yes/no): ")
0c2948879df6449e52e7d5dfe0ab8cdd950db462
LuisTavaresJr/cursoemvideo
/ex22 aula 09.py
332
3.9375
4
nome = str(input('Digite seu nome completo: ')).strip() print(f'Seu nome com todas letras maiúsculas fica {nome.upper()}.') print(f'Seu nome com todas as letras minúsculas fica {nome.lower()}.') print('Seu nome tem {} letras'.format(len(nome) - nome.count(' '))) print('Seu primeiro nome tem {} letras.'.format(nome.find(' ')))
9c75e75293a813de9cacd7e4af532eb226a0bd9b
kolotaev/vakt
/vakt/rules/inquiry.py
2,749
3.5
4
""" All Rules for defining Inquiry elements relations """ from abc import ABCMeta, abstractmethod from ..rules.base import Rule __all__ = [ 'SubjectEqual', 'ActionEqual', 'ResourceIn', 'SubjectMatch', 'ActionMatch', 'ResourceMatch', ] class InquiryMatchAbstract(Rule, metaclass=ABCMeta): """ Base rule for concrete InquiryMatch rule implementations. """ def __init__(self, attribute=None): self.attribute = attribute def satisfied(self, what, inquiry=None): if not inquiry: return False inquiry_value = getattr(inquiry, self._field_name()) if self.attribute is not None: if isinstance(inquiry_value, dict) and self.attribute in inquiry_value: inquiry_value = inquiry_value[self.attribute] else: return False return what == inquiry_value @abstractmethod def _field_name(self): pass class SubjectMatch(InquiryMatchAbstract): """ Rule that is satisfied if the value equals the Inquiry's Subject or it's attribute. For example: resources=[SubjectMatch('nick')] """ def _field_name(self): return 'subject' class ActionMatch(InquiryMatchAbstract): """ Rule that is satisfied if the value equals the Inquiry's Action or it's attribute. For example: resources=[{'ref': ActionMatch('ref_method')}] """ def _field_name(self): return 'action' class ResourceMatch(InquiryMatchAbstract): """ Rule that is satisfied if the value equals the Inquiry's Resource or it's attribute. For example: resources=[ResourceMatch('sub-category')] """ def _field_name(self): return 'resource' class SubjectEqual(Rule): """ Rule that is satisfied if the string value equals the Inquiry's Subject. For example: context={'user': SubjectEqual()} This Rule only works for string-based policies. """ def satisfied(self, what, inquiry=None): return inquiry and isinstance(what, str) and what == inquiry.subject class ActionEqual(Rule): """ Rule that is satisfied if the string value equals the Inquiry's Action. For example: context={'user': ActionEqual()} This Rule only works for string-based policies. """ def satisfied(self, what, inquiry=None): return inquiry and isinstance(what, str) and what == inquiry.action class ResourceIn(Rule): """ Rule that is satisfied if list contains the Inquiry's Resource. For example: context={'user': ResourceIn()} This Rule only works for string-based policies. """ def satisfied(self, what, inquiry=None): return inquiry and isinstance(what, list) and inquiry.resource in what
57729d141a9a1ac4c11664b5223a22907ec24441
giusepper11/Curso-intensivo-Python
/cap 5/5.9 no_users.py
293
3.640625
4
users = [] if users: for user in users: if user == 'admin': print('Ola {}, deseja relatorio de status?'.format(user)) else: print('Ola {}, obrigado por fazer login novamente!'.format(user.title())) else: print('Precisamos de novos usuarios!!')
f7882770b7418f2599ffa404725f7362a7a91a85
dipsuji/Phython-Learning
/practiceset/hk/diagonal_diff_array.py
633
4.03125
4
def diagonalDiff(arr): # Initialize sums of diagonals sumd1 = 0 sumd2 = 0 for i in range(0, len(arr)): for j in range(0, len(arr)): # finding sum of primary diagonal - arr[1][1]+arr[2][2]+arr[3]a[3].... if (i == j): sumd1 += arr[i][j] # finding sum of secondary diagonal - if (i == len(arr) - j - 1): sumd2 += arr[i][j] # Absolute difference of the sums return abs(sumd1 - sumd2); print(diagonalDiff([[15, 2, 4], [4, 5, 6], [10, 8, -12]])) print(diagonalDiff([[12, 2, 4], [4, 15, 6], [10, 8, 16]]))
a2875438167f9a5f5e510bab39d8d594ab27fa9b
rafaelperazzo/programacao-web
/moodledata/vpl_data/33/usersdata/2/9824/submittedfiles/av1_parte3.py
229
3.953125
4
# -*- coding: utf-8 -*- from __future__ import division import math #COMECE AQUI ABAIXO n = input('Digite o valor de n:') pi = 0 for i in range(0,n+1,1): pi = pi + ((-1/3)**i)/(2*i+1) pi = pi*(12**0.5) print ("%.6f" % pi)
781ca45e2a9bb1117fa79952d21382978645cf88
traymihael/nlp100knock
/1/sample3.py
189
3.53125
4
data = 'Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.' data2 = data.split() data3 = [len(word.rstrip('.,')) for word in data2] print(data3)
d21ceb1848171b3a5de8f4da8e829407bf065031
mehmoodkha/MyPythoncode
/string_printing.py
293
4.0625
4
''' Program for string ''' fname=input("Enter first Name: ") lname=input("Enter last Name: ") print("\nName : ",fname.lower(), ", Surname : ",lname.lower()) drint("- ",fname.upper(), lname.upper()) print("--------------------- ---------") print("- ",fname.capitalize(), lname.capitalize())
700d5d09bf1ba029d791d8e55a06a755d6603096
kdrzazga/python-tutorial
/games-anims/crawler/game.py
1,404
3.578125
4
class Field: def __init__(self, x, y): self.x = x self.y = y self.revealed = False class Board: def __init__(self, width, height): self.width = width self.height = height self.fields = [[Field(x, y) for y in range(height)] for x in range(width)] class Player: def __init__(self, x, y, radius=2): self.x = x self.y = y self.radius = radius class Game: def __init__(self, board_width, board_height, player_x, player_y): self.board = Board(board_width, board_height) self.player = Player(player_x, player_y) def start(self): print("Game started!") def reveal(self): for x in range(self.player.x - self.player.radius, self.player.x + self.player.radius + 1): for y in range(self.player.y - self.player.radius, self.player.y + self.player.radius + 1): if 0 <= x < self.board.width and 0 <= y < self.board.height: self.board.fields[x][y].revealed = True for x in range(self.board.width): for y in range(self.board.height): if not (self.player.x - self.player.radius <= x <= self.player.x + self.player.radius and self.player.y - self.player.radius <= y <= self.player.y + self.player.radius): self.board.fields[x][y].revealed = False
0fc7f6aae2a49817dc5f5eaac43878f3f11b9775
rohitpawar4507/Zensar_Python
/File_Handling/Read_line2.py
876
3.984375
4
'''print("Reading the file") f1=open("file2.txt","r") if f1: print("File created successfully") else: print("file is not created") print("Reading the file") # Read the number of character from file #data=f1.read() # Read entire field data = f1.readline() # Read upto 10 character print("The Data in the file is...!") print(data) print(f1.readline()) # read entire line in the file f1.close() print("File is closed..!")''' print("Reading the file") f1=open("file2.txt","r") if f1: print("File created successfully") else: print("file is not created") print("Reading the file") # Read the number of character from file #data=f1.read() # Read entire field data = f1.readlines() # Read multiple line in the form of list print("The Data in the file is...!") print(data) #print(f1.readline()) # read entire line in the file f1.close() print("File is closed..!")
0330d4c6ce97aabd5419f0971a314a521271b86c
harshitasingh12/pythonassignment
/problem09.py
1,753
3.5
4
import unittest import helper_llists as llists def search_linked_list(node, sk): """ ??? Write what needs to be done ??? """ c=0 t=node; while t.next!=None: c=c+1 if t.val==sk: break t=t.next if t.next==None: if t.val==sk: c=c+1 return c class TestSearchLinkedList(unittest.TestCase): def test_01(self): node = llists.create_from_string( '{val:"arun",next:{val:"babu",next:{val:"john",next:{val:"kavya",next:{val:"raheem",next:{val:"surya",next:None}}}}}}') search_key = 'john' nodenumber = 3 self.assertEqual(search_linked_list(node, search_key), nodenumber) def test_02(self): node = llists.create_from_string( '{val:"arun",next:{val:"babu",next:{val:"john",next:{val:"kavya",next:{val:"raheem",next:{val:"surya",next:None}}}}}}') search_key = 'surya' nodenumber = 6 self.assertEqual(search_linked_list(node, search_key), nodenumber) def test_03(self): node = llists.create_from_string( '{val:"arun",next:{val:"balu",next:{val:"john",next:{val:"kavya",next:{val:"raheem",next:{val:"surya",next:None}}}}}}') search_key = 'arun' nodenumber = 1 self.assertEqual(search_linked_list(node, search_key), nodenumber) def test_04(self): node = llists.create_from_string( '{val:"arun",next:{val:"arun madhav",next:{val:"john",next:{val:"kavya",next:{val:"raheem",next:{val:"surya",next:None}}}}}}') search_key = 'arun madhav' nodenumber = 2 self.assertEqual(search_linked_list(node, search_key), nodenumber) if __name__ == '__main__': unittest.main(verbosity=2)
94d793f08f54080b6b2ff63134aecf73e4d4e7e9
MacBook-Pro-gala/supinfo.python
/自学项目/pygamemods.py
318
3.609375
4
def pygamefrom(x, y, x1, y1, w): aa = x1 bb = y1 for a in range(y + 1): pygame.draw.line(screen, (0, 0, 0), (x1, y1), (x1, x * w + y1)) x1 = x1 + w x1 = aa y1 = bb for b in range(x + 1): pygame.draw.line(screen, (0, 0, 0), (x1, y1), (x1 + y * w, y1)) y1 = y1 + w
87dc6bdc105dcbbcf863a438edb8142ea083aade
haliliceylan/hku-come-103-python-lab-2018
/LAB_08/program15.py
560
4.125
4
import turtle def main(): x1 = int(input("x1: ")) y1 = int(input("y1: ")) x2 = int(input("x2: ")) y2 = int(input("y2: ")) x3 = int(input("x3: ")) y3 = int(input("y3: ")) color = input("color: ") triangle(x1, y1, x2, y2, x3, y3, color) def triangle(x1, y1, x2, y2, x3, y3, color): # go to start point turtle.penup() turtle.hideturtle() turtle.goto(x1, y1) turtle.pendown() turtle.showturtle() turtle.pencolor(color) turtle.goto(x2, y2) turtle.goto(x3, y3) turtle.goto(x1, y1) main()
658cc1c512c451e3854c8f747acfbfb2a84a5c3b
margaret254/py_learn
/lists_04/most_frequent_element.py
681
4.15625
4
# Write a program to find the most popular element in an array # Assume that array size is at least 1 # return None if there ain't any # for more info on this quiz, go to this url: http://www.programmr.com/most-frequent-element-1 def find_popular_item(arr_x): counter = 0 num = arr_x[0] if len(arr_x) == 1: return num for i in arr_x: curr_frequency = arr_x.count(i) if curr_frequency > counter: counter = curr_frequency num = i if counter <= 1: return None else: return num if __name__ == "__main__": print(find_popular_item([2]))
dc0948b706a81d6f0ae91f39d4e52d590e48b71f
DongHyunByun/algorithm_practice
/graph/[boj]4195_친구네트워크_mst_dict.py
1,212
3.75
4
import sys T=int(input()) def find(a): if parent[a]==a: return a else: parent[a]=find(parent[a]) return parent[a] def union(a,b): a=find(a) b=find(b) parent[b]=a for t in range(T): F=int(input()) parent={} cntByRoot={} for _ in range(F): a,b=sys.stdin.readline().rstrip().split() if a in parent: isA=True else: isA=False if b in parent: isB=True else: isB=False if isA and isB: rootA=find(a) rootB=find(b) if rootA!=rootB: union(rootA,rootB) cntByRoot[rootA]+=cntByRoot[rootB] print(cntByRoot[rootA]) elif isA and not isB: root=find(a) parent[b]=root cntByRoot[root]+=1 print(cntByRoot[root]) elif not isA and isB: root=find(b) parent[a]=root cntByRoot[root]+=1 print(cntByRoot[root]) else: parent[a]=a parent[b]=a cntByRoot[a]=2 print(cntByRoot[a])
2e802ee23772d4b717fa2630772c8a8d38a7298f
Anustup900/SDP
/Ayushi/Function.py
568
3.875
4
def greet(name): print("hello %s !"%name) print("Its lovely meeting you %s"%name) print("%s Can u come over for dinner?"%name) mylist={'Amay','bron','carry'} for i in mylist: greet(i) def fullname(fname,lname): name=fname.capitalize()+' '+lname.capitalize() print("Hello %s" %name) fullname('Ayushi','Chauhan') fullname('bron','elark') fullname('shon','mendez') def cal(n1,n2): sum=n1+n2 print("sum=%d"%sum) cal(100,1) cal(20,10) cal(200,23) def mcal(n1,n2): sum=n1+n2 return sum s=mcal(2,3) print("sum=%d"%s)
8d40e98c787be71090e0106134f423a406915c5b
LalitKamble/githublearning
/try except.py
5,495
4.03125
4
''' try: a=int(input("Enter the no:")) b=int(input("Enter second no:")) a/b except ZeroDivisionError: print('invalid error') n=int(input("Enter the no :")) for i in range(10): try: c=n/i print(c) except ZeroDivisionError: print("second values is ") ''' ''' try: print(a) except: print("Enter the values") ZeroDivisionError ValueError try: a=int(input('Entert no')) b=int(input("Entert the no")) print(a/b) except ZeroDivisionError: print("second value can not be zero") except ValueError: print("please Entert the digit") ''' ''' constructor function overloading ''' ''' class Emp: def sum(self,a,b): print(a+b) def sum(self,a,b,c): print(a+b+c) a=Emp() a.sum(10,20) a.sum(10,20,30) ''' ''' in python class Emp: def f(self,*a): print(a) b=Emp() b.f(10,20,30,20,20,20,20,20,20,20,20,200,20,32,0,1,'lalit') ''' ''' single Inheristance class Emp: eno=0 ename='' eaddress='' esal=0 def getdetails(self): self.eno=int(input('Entert the name:')) self.ename=input('Entert the name:') self.eaddress=input('Entert the name:') self.esal=float(input('Entert the name:')) class Emp1(Emp): hr=0 def getdetails1(self): self.hr=input("Entert the name") def showDetails(self): print("Enter the eno :",self.eno) print("Enter the eno :",self.ename) print("Enter the eno :",self.eaddress) print("Enter the eno :",self.esal) print("Enter the eno :",self.hr) a=Emp1() a.getdetails() a.getdetails1() a.showDetails() ''' ''' multiple Inheritance class Abc: def add(self,a,b): print("Enter the no :",a+b) class Pqr: def sub(self,a,b): print("Substration:",a-b) class Xyz(Abc,Pqr): def mul(self,a,b): print("Multiplication :",a*b) def div(self,a,b): print("div :",a/b) o=Xyz() o.add(10,20) o.sub(10,20) o.mul(10,20) o.div(10,20) ''' ''' multilevel inheritance class Abc: a=0 class Pqr(Abc): b=0 class Xyz(Pqr): c=0 def get(self): print(self.a, self.b, self.c) o=Xyz() o.a=10 o.b=20 o.c=30 o.get() ''' ''' Data Abstration class Abc: __p=100 o='lalit' def f(self): print("Hiding Data Abstration") a=Abc() a.f() print(a.o) ''' ''' class Emp: def __init__(self,**x): self.x=x def Display(self): print("Entert the name:",self.x) a=Emp(name='lalit',sal='lalit') a.Display() ''' ''' class Emp: a=0 b=0 def __init__(self,a,b): self.a=a self.b=b def Display(self): print("Enter the no:",self.a) print("Enter the no:",self.b) def __add__(self,other): return Emp(self.a+other.a, self.b+other.b) x=Emp() x.Display(10,20) a=20 print("The {:.2f}".format(a)) for i in range(1,5): for j in range(0,5-i-1): print(end=' ') for j in range(1,i+1): print('*',end=" ") print() n=int(input("Enter the name :")) for i in range(n): print(' '*(n-i-1)+(str(i+1)+' ')*(i+1)) a=[1,2,3,4,5,6,7,8,9] v={i for i in a} print(v) ''' from functools import reduce a=[1,2,3,4,5,6,7,8,9,5,2] b=list(map(lambda s:s*s,a)) print(b) b=tuple(filter(lambda a:a%2==0,a)) print(b) b=reduce(lambda x,y:x+y,a) print(b) ''' def outer(func): print("Enter the outer dec") def inner(): print('inner dec') return inner def outer1(func): print("Outer") def inner1(): print("inner dec") return inner dist() dist.inner() a.inner1() a=int(input("Enter the no :")) b=int(input("Enter the no1 :")) c= a if a>b else b print(c) ''' ''' list dict set comphrensation a=[1,2,3,4,5,6,7,8,9] b={i*i for i in a} print(b) for i in range(1,8): for j in range(0,5-i-1): print(end=' ') for j in range(1,i+1): print("*",end=" ") print() n=int(input("Entert the no:")) for i in range(n): print(' '*(n-i-1)+(str(i+1)+' ')*(i+1)) for i in range(11,0,-1): for j in range(0,11-i): print(end=' ') for j in range(0,i): print('*',end=' ') print() for i in range(11,0,-1): for j in range(0,11-i): print(end=' ') for j in range(0,i): print('*',end=' ') print() a={i*i for i in range(1,10)} print(a) from functools import reduce a=[1,2,3,4,5,6,7,8,9,10] k=list(filter(lambda b:b%2==0,a)) print(k) v=list(map(lambda a:a+a,a)) print(v) b=reduce(lambda c,y:c+y,a) print(b) a='lalit is good boy' a=a.split() l=[] for i in a: if i!='lalit': l.append(i) print(l) '''
f9344b38553784caab1ecc90294dc20083ccb9e9
Alexanderlutsyk/TMS
/HW3/3-46.py
246
3.640625
4
print('введи текст который мы закодируем') a = input() i = 0 l =[] l2 =[] for i in a: c = ord(i) + 3 l.append(chr(c)) l=''.join(l) print(l) for k in l: d = ord(k) - 3 l2.append(chr(d)) l2 = ''.join(l2) print(l2)
963e7f9e1313c0ff5d699f93f8a457bbc77ba927
SwarnimThapa/Python7pmWork
/calcalutor.py
1,316
3.53125
4
import os.path if not os.path.exists('db.txt'): fs = open('db.txt', 'w') fs.close() def add(x,y): return x+y def sub(x,y): return x-y def mult(x,y): return x*y def zerofinder(function): def inar(x, y): if y == 0: print("Cannot divide by 0.") exit() else: return function(x, y) return inar @zerofinder def div(x,y): return x/y x = int(input('Enter your first number: ')) z = input("Enter either add, sub, mult, or div. ") y = int(input("Enter your second number: ")) if z == 'add': ans = (f"Result is: {x+y}.") print(ans) handle = open('db.txt', 'a') handle.write(ans) handle.write('\n') handle.close() exit() elif z == 'sub': ans = (f"Result is: {x-y}.") print(ans) handle = open('db.txt', 'a') handle.write(ans) handle.write('\n') handle.close() exit() elif z == 'mult': ans = (f"Result is: {x*y}") print(ans) handle = open('db.txt','a') handle.write(ans) handle.write('\n') handle.close() exit() elif z == 'div': ans = (f"Result is: {x/y}") print(ans) handle = open('db.txt', 'a') handle.write(ans) handle.write('\n') handle.close() exit()
8bb66385e45d8825250e69270a2966bd42bf9e71
BohaoWu/LeetCode
/Leetcode/109.py
711
3.828125
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def sortedListToBST(self, head): arr = [] while(head): arr.append(head.val) head.next return self.buildBST(arr) def buildBST(self, arr): if not arr: return None mid = len(arr)//2 root = TreeNode(arr[mid]) root.left = self.buildBST(arr[:mid]) root.right = self.buildBST(arr[mid + 1:]) return root
2ea194c6598444152570249482f4a716f29a8e4e
screnary/Algorithm_python
/tree_116_connect.py
1,861
3.9375
4
""" 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。 如果找不到下一个右侧节点,则将 next 指针设置为 NULL。 初始状态下,所有 next 指针都被设置为 NULL。 """ # Definition for a Node. class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next class Solution: def connect_bfs(self, root): if root is None: return None queue = [root] while queue: n = len(queue) for i in range(n): node = queue.pop(0) if i < n-1 and queue: # the last node in this layer, do not connect node.next = queue[0] if node.left: queue.append(node.left) if node.right: queue.append(node.right) return root def connect(self, root): """ divide conquer, O(1) space """ if not root or (not root.left and not root.right): return root if root.left and root.right: root.left.next = root.right root.right.next = self.getNextChild(root) if not root.left: root.right.next = self.getNextChild(root) if not root.right: root.left.next = self.getNextChild(root) root.right = self.connect(root.right) root.left = self.connect(root.left) return root def getNextChild(self, root): # search same level neighbor, from parent level nodes while root.next: if root.next.left: return root.next.left if root.next.right: return root.next.right root = root.next return None
ae32ade7b93b0ba73c5bf481155317ab8bbfafe5
LarisaOvchinnikova/Python
/1 - Python-2/11 - dictionaries/HW11/2. Tests results.py
486
3.609375
4
def newtest(r): average = round(sum(r) / len(r), 3) dct = { "h": 0, "a": 0, "l": 0 } for el in r: if el >= 9: dct["h"] += 1 elif el >= 7: dct["a"] += 1 else: dct["l"] += 1 if dct["a"] + dct["l"] == 0: return [average, dct, "They did well"] else: return [average, dct] print(newtest([10, 9, 9, 10, 9, 10, 9])) print(newtest([5, 6, 4, 8, 9, 8, 9, 10, 10, 10]))
85ae00c437a7c1030cd0ae67660a69892d9f7b95
aswinselva03/PythonAlgorithm
/LinkedList/LinkedList.py
6,084
4.09375
4
class Node: def __init__(self, value): self.value = value self.next = None def __repr__(self): return str("Node") def __str__(self): return str({"value":self.value, "next": self.next}) class LinkedList: def __init__(self, value): new_node = Node(value) self.head = new_node self.tail = new_node self.length = 1 def __str__(self): linked_list = "" temp = self.head if temp is None: return "None" for _ in range(0, self.length+1): linked_list += str(temp.value) linked_list += "->" if temp.next is None: linked_list += "None" return linked_list temp = temp.next return linked_list def append(self, value): new_node = Node(value) # if the linked list is empty assign head and tail to new node if self.head is None: self.head = new_node self.tail = new_node # if not, assign, tail.next as new node(now None) and then shift tail to the new node(already new_node.next is None) else: self.tail.next = new_node self.tail = new_node # increment the length of LL and return True(will be used in another function) self.length +=1 return True def pop(self): # if length is 0, return None if self.length == 0: return None # we are using pre and temp, to find the node before tail (if doubly linked list we can do a prev in tail to get that) # here we need to do it ourselves pre = self.head temp = self.head # our goal is to find new tail(since pop removes the last node, node before last node is our new tail) while(temp.next): # until temp.next is not none - temp is not the tail prev = temp # retaining the previous node of tail in prev temp = temp.next prev.next = None self.tail = prev self.length -= 1 # for cases when we have only one node in LL, the node will not be removed from above steps so if self.length == 0: self.head = None self.tail = None return temp # the last element removed should be returned def prepend(self, value): new_node = Node(value) # if LL is empty just assign head and tail to new node if self.length == 0: self.head = new_node self.tail = new_node # else, self.head is the first node, assign self.head to new_node.next and shift self.head as new node else: new_node.next = self.head self.head = new_node self.length += 1 return True def pop_first(self): if self.length == 0: return None # we need to return the removed element so assign temp with self.head temp = self.head # move head to the next node in LL self.head = self.head.next # detach temp by assigning temp.next = None temp.next = None self.length -= 1 if self.length == 0: self.tail = None return temp def get(self,index): # if out of bound if index < 0 or index >= self.length: return None # we need to return node so assign head to temp and loop to get to the index position temp = self.head for _ in range(index): temp = temp.next return temp def set(self, index, value): # use get to get the node at index, if node is not none, set the value temp = self.get(index) if temp: temp.value = value return True return False def insert(self, index, value): # index out of bound if index < 0 or index>self.length: return False # when you have to insert as the first node, do prepend if index == 0: return self.prepend(value) # when you have to insert as the last node, do append if index == self.length: return self.append(value) # Any other position, get the node before index position and swap next values new_node = Node(value) temp = self.get(index -1) new_node.next = temp.next temp.next = new_node self.length += 1 return True def remove(self, index): if index < 0 or index>=self.length: return None if index == 0: return self.pop_first() if index == self.length - 1: return self.pop() prev = self.get(index - 1) temp = prev.next prev.next = temp.next temp.next = None self.length -= 1 return temp def reverse(self): temp = self.head self.head = self.tail self.tail = temp after = temp.next before = None for _ in range(self.length): after = temp.next temp.next = before before = temp temp = after my_linked_list = LinkedList(4) print("appending 2") my_linked_list.append(2) print(my_linked_list) print("popping 2",my_linked_list.pop()) print(my_linked_list) print("prepending 2", my_linked_list.prepend(2)) print(my_linked_list) print("pop_first 2", my_linked_list.pop_first()) print(my_linked_list) print("pop_first 4", my_linked_list.pop_first()) print(my_linked_list) print("appending 2", my_linked_list.append(2)) print("appending 4", my_linked_list.append(4)) print(my_linked_list) print("Get index 2",my_linked_list.get(2)) print("Get index 0",my_linked_list.get(0)) print("set index 0",my_linked_list.set(0,5)) print(my_linked_list) print("set index 2",my_linked_list.set(2,5)) print(my_linked_list) my_linked_list.insert(0, 3) my_linked_list.insert(2,1) print(my_linked_list) my_linked_list.remove(0) print(my_linked_list) print(my_linked_list.reverse()) print(my_linked_list)
a4277c16d821979c04b0aac10fb485134854ebd7
HeavenOfHell221/IA-Go
/Code/MyGoban.py
50,119
3.53125
4
#!/usr/bin/python3 +x # -*- coding: utf-8 -*- ''' This is a class to play small games of GO, natively coded in Python. I tried to use nice data structures to speed it up (union & find, Zobrist hashs, numpy memory efficient ...) Licence is MIT: you can do whatever you want with the code. But keep my name somewhere. (c) Laurent SIMON 2019 -- 2020 Known Limitations: - No early detection of endgames (only stops when no stone can be put on the board, or superKo) - Final scoring does not remove dead stones, and thus may differ from a more smart counting. You may want to end the game only when all the areas are almost filled. References and Code inspirations -------------------------------- I looked around in the web for inspiration. One important source of inspiration (some of my python lines may be directly inspired by him is the fantastic github repo and book (which I bought :)) of Max Pumperla about Deep Learning and the game of Go https://github.com/maxpumperla/deep_learning_and_the_game_of_go I tried to be faster by using more non python data structures (limiting lists and sets), however :) ''' from __future__ import print_function # Used to help cython work well import numpy as np from Modules.aliasesType import * from Modules.string import String from copy import deepcopy def getProperRandom(): ''' Gets a proper 64 bits random number (ints in Python are not the ideal toy to play with int64)''' return np.random.randint(np.iinfo(np.int64).max, dtype='int64') class MyBoard: ''' GO MyBoard class to implement your (simple) GO player.''' __VERSION__ = 2.2 __BLACK = 1 __WHITE = 2 __EMPTY = 0 __BOARDSIZE = 9 # Used in static methods, do not write it __DEBUG = True INF = np.inf NINF = np.NINF ############################################################################ ############################################################################ ''' A set of functions to manipulate the moves from the - internal representation, called "flat", in 1D (just integers) - coord representation on the board (0,0)..(__BOARDSIZE, __BOARDSIZE) - name representation (A1, A2, ... D5, D6, ..., PASS)''' @staticmethod def flatten(coord): ''' Static method that teturns the flatten (1D) coordinates given the 2D coordinates (x,y) on the board. It is a simple helper function to get x*__BOARDSIZE + y. Internally, all the moves are flatten. If you use legal_moves or weak_legal_moves, it will produce flatten coordinates.''' if coord == (-1,-1): return -1 return MyBoard.__BOARDSIZE * coord[1] + coord[0] @staticmethod def unflatten(fcoord): if fcoord == -1: return (-1, -1) d = divmod(fcoord, MyBoard.__BOARDSIZE) return d[1], d[0] @staticmethod def name_to_coord(s): if s == 'PASS': return (-1,-1) indexLetters = {'A':0, 'B':1, 'C':2, 'D':3, 'E':4, 'F':5, 'G':6, 'H':7, 'J':8} col = indexLetters[s[0]] lin = int(s[1:]) - 1 return (col, lin ) @staticmethod def name_to_flat(s): return MyBoard.flatten(MyBoard.name_to_coord(s)) @staticmethod def coord_to_name(coord): if coord == (-1,-1): return 'PASS' letterIndex = "ABCDEFGHJ" return letterIndex[coord[0]]+str(coord[1]+1) @staticmethod def flat_to_name(fcoord): if fcoord == -1: return 'PASS' return MyBoard.coord_to_name(MyBoard.unflatten(fcoord)) ############################################################################ ############################################################################ '''Just a couple of helper functions about who has to play next''' @staticmethod def flip(player): if player == MyBoard.__BLACK: return MyBoard.__WHITE return MyBoard.__BLACK @staticmethod def player_name(player): if player == MyBoard.__BLACK: return "black" elif player == MyBoard.__WHITE: return "white" return "???" ############################################################################ ############################################################################ def __init__(self): ''' Main constructor. InstantiateMyBoard all non static variables.''' self._winner = MyBoard.__EMPTY self._nbWHITE = 0 self._nbBLACK = 0 self._capturedWHITE = 0 self._capturedBLACK = 0 self._strings = {MyBoard.__WHITE: [], MyBoard.__BLACK: []} self._nextPlayer = self.__BLACK self._board = np.zeros((MyBoard.__BOARDSIZE**2), dtype='int8') self._lastPlayerHasPassed = False self._gameOver = False self._stringUnionFind = np.full((MyBoard.__BOARDSIZE**2), -1, dtype='int8') self._stringLiberties = np.full((MyBoard.__BOARDSIZE**2), -1, dtype='int8') self._stringSizes = np.full((MyBoard.__BOARDSIZE**2), -1, dtype='int8') self._empties = set(range(MyBoard.__BOARDSIZE **2)) # Zobrist values for the hashes. I use np.int64 to be machine independant self._positionHashes = np.empty((MyBoard.__BOARDSIZE**2, 2), dtype='int64') for x in range(MyBoard.__BOARDSIZE**2): for c in range(2): self._positionHashes[x][c] = getProperRandom() self._currentHash = getProperRandom() self._passHashB = getProperRandom() self._passHashW = getProperRandom() self._seenHashes = set() self._historyMoveNames = [] self._trailMoves = [] # data structure used to push/pop the moves #Building fast structures for accessing neighborhood self._neighbors = [] self._neighborsEntries = [] self._corners = [] self._cornersEntries = [] for nl in [self._get_neighbors(fcoord) for fcoord in range(MyBoard.__BOARDSIZE**2)] : self._neighborsEntries.append(len(self._neighbors)) for n in nl: self._neighbors.append(n) self._neighbors.append(-1) # Sentinelle self._neighborsEntries = np.array(self._neighborsEntries, dtype='int16') self._neighbors = np.array(self._neighbors, dtype='int8') for nl in [self._get_corners(fcoord) for fcoord in range(MyBoard.__BOARDSIZE**2)] : self._cornersEntries.append(len(self._corners)) for n in nl: self._corners.append(n) self._corners.append(-1) # Sentinelle self._cornersEntries = np.array(self._cornersEntries, dtype='int16') self._corners = np.array(self._corners, dtype='int8') ############################################################################ ############################################################################ ''' Properties ''' @property def currentHash(self) -> int: return self._currentHash @property def nextPlayer(self) -> int: return self._nextPlayer @property def winner(self) -> int: return self._winner @property def EMPTY(self) -> Color: return self.__EMPTY @property def WHITE(self) -> Color: return self.__WHITE @property def BLACK(self) -> Color: return self.__BLACK ############################################################################ ############################################################################ ''' Simple helper function to directly access the board. if b is a MyBoard(), you can ask for b[m] to get the value of the corresponding cell, (0 for Empty, 1 for Black and 2 for White, see MyBoard.__BLACK,__WHITE,__EMPTY values) If you want to have an access via coordinates on the board you can use it like b[MyBoard.flatten((x,y))] ''' def __getitem__(self, key): ''' Helper access to the board, from flatten coordinates (in [0 .. MyBoard.BOARDSIZE**2]). Read Only array. If you want to add a stone on the board, you have to use _put_stone().''' return self._board[key] def __len__(self): return MyBoard.__BOARDSIZE**2 def __str__(self): ''' WARNING: this print function does not reflect the classical coordinates. It represents the internal values in the board.''' toreturn="" for i,c in enumerate(self._board): toreturn += self._piece2str(c) + " " # +'('+str(i)+":"+str(self._stringUnionFind[i])+","+str(self._stringLiberties[i])+') ' if (i+1) % MyBoard.__BOARDSIZE == 0: toreturn += "\n" toreturn += "Next player: " + ("BLACK" if self._nextPlayer == self.__BLACK else "WHITE") + "\n" toreturn += str(self._nbBLACK) + " blacks and " + str(self._nbWHITE) + " whites on board\n" return toreturn ########################################################## ########################################################## ''' Main functions for generating legal moves ''' def is_game_over(self): ''' Checks if the game is over, ie, if you can still put a stone somewhere''' return self._gameOver def legal_moves(self): ''' Produce a list of moves, ie flatten moves. They are integers representing the coordinates on the board. To get named Move (like A1, D5, ..., PASS) from these moves, you can use the function MyBoard.flat_to_name(m). This function only produce legal moves. That means that SuperKO are checked BEFORE trying to move (when populating the returned list). This can only be done by actually placing the stone, capturing strigns, ... to compute the hash of the board. This is extremelly costly to check. Thus, you should use weak_legal_moves that does not check the superko and actually check the return value of the push() function that can return False if the move was illegal due to superKo. ''' moves = [m for m in self._empties if (not self._is_suicide(m, self._nextPlayer) and not self._is_super_ko(m, self._nextPlayer)[0])] moves.append(-1) # We can always ask to pass return moves def weak_legal_moves(self) -> FlattenMoveList: ''' Produce a list of moves, ie flatten moves. They are integers representing the coordinates on the board. To get named Move (like A1, D5, ..., PASS) from these moves, you can use the function MyBoard.flat_to_name(m). Can generate illegal moves, but only due to Super KO position. In this generator, KO are not checked. If you use a move from this list, you have to check if push(m) was True or False and then immediatly pop it if it is False (meaning the move was superKO.''' moves = [m for m in self._empties if (not self._is_suicide(m, self._nextPlayer))] moves.append(-1) # We can always ask to pass return moves def weak_legal_useful_moves(self): ''' Retourne la liste des coups qui ne sont pas des coups suicides ou des yeux. ''' moves = [m for m in self._empties if (not self._is_suicide(m, self._nextPlayer) and not self.is_eye(m, self._nextPlayer))] moves.append(-1) # We can always ask to pass return moves def generate_legal_moves(self): ''' See legal_moves description. This is just a wrapper to this function, kept for compatibility.''' return self.legal_moves() def move_to_str(self, m): ''' Transform the internal representation of a move into a string. Simple wrapper, but useful for producing general code.''' return MyBoard.flat_to_name(m) def str_to_move(self, s): ''' Transform a move given as a string into an internal representation. Simple wrapper here, but may be more complex in other games.''' return MyBoard.name_to_flat(s) def play_move(self, fcoord): ''' Main internal function to play a move. Checks the superKo, put the stone then capture the other color's stones. Returns True if the move was ok, and False otherwise. If False is returned, there was no side effect. In particular, it checks the superKo that may not have been checked before. You can call it directly but the push/pop mechanism will not be able to undo it. Thus in general, only push/pop are called and this method is never directly used.''' if self._gameOver: return if fcoord != -1: # pass otherwise alreadySeen, tmpHash = self._is_super_ko(fcoord, self._nextPlayer) if alreadySeen: self._historyMoveNames.append(self.flat_to_name(fcoord)) return False (nbEmpty, nbSameColor, nbOtherColor, liberties) = self._compute_liberties(fcoord, self._nextPlayer) captured = self._put_stone(fcoord, self._nextPlayer, (nbEmpty, nbSameColor, nbOtherColor)) captured_objet = self._put_stone_object(fcoord, self._nextPlayer, (nbEmpty, nbSameColor, nbOtherColor, liberties)) # captured is the list of Strings that have 0 liberties for fc in captured: self._capture_string(fc) for fc in captured_objet: self._capture_string_object(fc) assert tmpHash == self._currentHash self._lastPlayerHasPassed = False if self._nextPlayer == self.__WHITE: self._nbWHITE += 1 else: self._nbBLACK += 1 else: if self._lastPlayerHasPassed: self._gameOver = True self._winner = self._nextPlayer else: self._lastPlayerHasPassed = True self._currentHash ^= self._passHashB if self._nextPlayer == MyBoard.__BLACK else self._passHashW self._seenHashes.add(self._currentHash) self._historyMoveNames.append(self.flat_to_name(fcoord)) self._nextPlayer = MyBoard.flip(self._nextPlayer) return True def reset(self): self.__init__() ########################################################## ########################################################## ''' Helper functions for pushing/poping moves. You may want to use them in your game tree traversal''' def push(self, m): ''' push: used to push a move on the board. More costly than play_move() but you can pop it after. Helper for your search tree algorithm''' assert not self._gameOver self._pushBoard() return self.play_move(m) def pop(self): ''' pop: another helper function for you rsearch tree algorithm. If a move has been pushed, you can undo it by calling pop ''' hashtopop = self._currentHash self._popBoard() if hashtopop in self._seenHashes: self._seenHashes.remove(hashtopop) ########################################################## ########################################################## def result(self): ''' The scoring mechanism is fixed but really costly. It may be not a good idea to use it as a heuristics. It is the chinese area scoring that computes the final result. It uses the same notation as in chess: Returns: - "1-0" if WHITE wins - "0-1" if BLACK wins - "1/2-1/2" if DEUCE Known problems: dead stones are not removed, so the score only stricly apply the area rules. You may want to keep playing to consolidate your area before computing the scores. ''' score = self._count_areas() score_black = self._nbBLACK + score[0] score_white = self._nbWHITE + score[1] if score_white > score_black: return "1-0" elif score_white < score_black: return "0-1" else: return "1/2-1/2" def compute_score(self): ''' Computes the score (chinese rules) and return the scores for (blacks, whites) in this order''' score = self._count_areas() return (self._nbBLACK + score[0], self._nbWHITE + score[1]) def final_go_score(self): ''' Returns the final score in a more GO-like way.''' score_black, score_white = self.compute_score() if score_white > score_black: return "W+"+str(score_white-score_black) elif score_white < score_black: return "B+"+str(score_black-score_white) else: return "0" def pretty_print(self): if MyBoard.__BOARDSIZE not in [5,7,9]: print(self) return print() print("To Move: ", "black" if self._nextPlayer == MyBoard.__BLACK else "white") print("Last player has passed: ", "yes" if self._lastPlayerHasPassed else "no") print() print(" WHITE ( ● ) has captured %d stones" % self._capturedBLACK) print(" BLACK ( ○ ) has captured %d stones" % self._capturedWHITE) print() print(" WHITE ( ● ) has %d stones" % self._nbWHITE) print(" BLACK ( ○ ) has %d stones" % self._nbBLACK) print() if MyBoard.__BOARDSIZE == 9: specialPoints = [(2,2), (6,2), (4,4), (2,6), (6,6)] headerline = " A B C D E F G H J" elif MyBoard.__BOARDSIZE == 7: specialPoints = [(2,2), (4,2), (3,3), (2,4), (4,4)] headerline = " A B C D E F G" else: specialPoints = [(1,1), (3,1), (2,2), (1,3), (3,3)] headerline = " A B C D E" print(headerline) for l in range(MyBoard.__BOARDSIZE): line = MyBoard.__BOARDSIZE - l print(" %d" % line, end="") for c in range(MyBoard.__BOARDSIZE): p = self._board[MyBoard.flatten((c, MyBoard.__BOARDSIZE - l - 1))] ch = ' ' if p == MyBoard.__WHITE: ch = '●' elif p == MyBoard.__BLACK: ch = '○' elif (l,c) in specialPoints: ch = '+' print(" " + ch, end="") print(" %d" % line) print(headerline) print("hash = ", self._currentHash) ########################################################## ########################################################## ########################################################## ########################################################## ''' Internal functions only''' def _pushBoard(self): currentStatus = [] currentStatus.append(deepcopy(self._strings[MyBoard.__WHITE])) currentStatus.append(deepcopy(self._strings[MyBoard.__BLACK])) currentStatus.append(self._winner) currentStatus.append(self._nbWHITE) currentStatus.append(self._nbBLACK) currentStatus.append(self._capturedWHITE) currentStatus.append(self._capturedBLACK) currentStatus.append(self._nextPlayer) currentStatus.append(self._board.copy()) currentStatus.append(self._gameOver) currentStatus.append(self._lastPlayerHasPassed) currentStatus.append(self._stringUnionFind.copy()) currentStatus.append(self._stringLiberties.copy()) currentStatus.append(self._stringSizes.copy()) currentStatus.append(self._empties.copy()) currentStatus.append(self._currentHash) self._trailMoves.append(currentStatus) def _popBoard(self): oldStatus = self._trailMoves.pop() self._currentHash = oldStatus.pop() self._empties = oldStatus.pop() self._stringSizes = oldStatus.pop() self._stringLiberties = oldStatus.pop() self._stringUnionFind = oldStatus.pop() self._lastPlayerHasPassed = oldStatus.pop() self._gameOver = oldStatus.pop() self._board = oldStatus.pop() self._nextPlayer = oldStatus.pop() self._capturedBLACK = oldStatus.pop() self._capturedWHITE = oldStatus.pop() self._nbBLACK = oldStatus.pop() self._nbWHITE = oldStatus.pop() self._winner = oldStatus.pop() self._strings[MyBoard.__BLACK] = oldStatus.pop() self._strings[MyBoard.__WHITE] = oldStatus.pop() self._historyMoveNames.pop() def _getPositionHash(self, fcoord, color): return self._positionHashes[fcoord][color-1] # Used only in init to build the neighborsEntries datastructure def _get_neighbors(self, fcoord) -> FlattenMoveList: x, y = MyBoard.unflatten(fcoord) neighbors = ((x+1, y), (x-1, y), (x, y+1), (x, y-1)) return [MyBoard.flatten(c) for c in neighbors if self._is_on_board(c[0], c[1])] # Used only in init to build the cornersEntries datastructure def _get_corners(self, fcoord) -> FlattenMoveList: x, y = MyBoard.unflatten(fcoord) corners = ((x+1, y+1), (x-1, y-1), (x-1, y+1), (x+1, y-1)) return [MyBoard.flatten(c) for c in corners if self._is_on_board(c[0], c[1])] # for union find structure, recover the number of the current string of stones def _getStringOfStone(self, fcoord): # In the union find structure, it is important to route all the nodes to the root # when querying the node. But in Python, using the successive array is really costly # so this is not so clear that we need to use the successive collection of nodes # Moreover, not rerouting the nodes may help for backtracking on the structure successives = [] while self._stringUnionFind[fcoord] != -1: fcoord = self._stringUnionFind[fcoord] successives.append(fcoord) if len(successives) > 1: for fc in successives[:-1]: self._stringUnionFind[fc] = fcoord return fcoord def _merge_strings(self, str1, str2): self._stringLiberties[str1] += self._stringLiberties[str2] self._stringLiberties[str2] = -1 self._stringSizes[str1] += self._stringSizes[str2] self._stringSizes[str2] = -1 assert self._stringUnionFind[str2] == -1 self._stringUnionFind[str2] = str1 def _put_stone(self, fcoord, color, allLiberties): (nbEmpty, nbSameColor, nbOtherColor) = allLiberties self._board[fcoord] = color self._currentHash ^= self._getPositionHash(fcoord, color) if self.__DEBUG: assert fcoord in self._empties self._empties.remove(fcoord) currentString = fcoord self._stringLiberties[currentString] = nbEmpty self._stringSizes[currentString] = 1 stringWithNoLiberties = [] # String to capture (if applies) i = self._neighborsEntries[fcoord] while self._neighbors[i] != -1: fn = self._neighbors[i] if self._board[fn] == color: # We may have to merge the strings stringNumber = self._getStringOfStone(fn) self._stringLiberties[stringNumber] -= 1 if currentString != stringNumber: self._merge_strings(stringNumber, currentString) currentString = stringNumber elif self._board[fn] != MyBoard.__EMPTY: # Other color stringNumber = self._getStringOfStone(fn) self._stringLiberties[stringNumber] -= 1 if self._stringLiberties[stringNumber] == 0: if stringNumber not in stringWithNoLiberties: # We may capture more than one string stringWithNoLiberties.append(stringNumber) i += 1 return stringWithNoLiberties def _is_on_board(self,x,y): return x >= 0 and x < MyBoard.__BOARDSIZE and y >= 0 and y < MyBoard.__BOARDSIZE def _is_suicide(self, fcoord, color): opponent = MyBoard.flip(color) i = self._neighborsEntries[fcoord] libertiesFriends = {} libertiesOpponents = {} while self._neighbors[i] != -1: fn = self._neighbors[i] if self._board[fn] == MyBoard.__EMPTY: return False string = self._getStringOfStone(fn) if self._board[fn] == color: # check that we don't kill the whole zone if string not in libertiesFriends: libertiesFriends[string] = self._stringLiberties[string] - 1 else: libertiesFriends[string] -= 1 else: if MyBoard.__DEBUG: assert self._board[fn] == opponent if string not in libertiesOpponents: libertiesOpponents[string] = self._stringLiberties[string] - 1 else: libertiesOpponents[string] -= 1 i += 1 for s in libertiesOpponents: if libertiesOpponents[s] == 0: return False # At least one capture right after this move, it is legal if len(libertiesFriends) == 0: # No a single friend there... return True # Now checks that when we connect all the friends, we don't create # a zone with 0 liberties sumLibertiesFriends = 0 for s in libertiesFriends: sumLibertiesFriends += libertiesFriends[s] if sumLibertiesFriends == 0: return True # At least one friend zone will be captured right after this move, it is unlegal return False def _is_super_ko(self, fcoord, color): ''' Checks if the move leads to an already seen board By doing this, it has to "simulate" the move, and thus it computes also the sets of strings to be removed by the move. Check if it is a complex move (if it takes at least a stone) ''' tmpHash = self._currentHash ^ self._getPositionHash(fcoord, color) assert self._currentHash == tmpHash ^ self._getPositionHash(fcoord, color) i = self._neighborsEntries[fcoord] libertiesOpponents = {} opponent = MyBoard.flip(color) while self._neighbors[i] != -1: fn = self._neighbors[i] if self._board[fn] == opponent: s = self._getStringOfStone(fn) if s not in libertiesOpponents: libertiesOpponents[s] = self._stringLiberties[s] - 1 else: libertiesOpponents[s] -= 1 i += 1 for s in libertiesOpponents: if libertiesOpponents[s] == 0: for fn in self._breadthSearchString(s): assert self._board[fn] == opponent tmpHash ^= self._getPositionHash(fn, opponent) if tmpHash in self._seenHashes: return True, tmpHash return False, tmpHash def _breadthSearchString(self, fc): ''' A partir d'une coordonnée, fabrique une chaine d'une même couleur (dont EMPTY) ''' color = self._board[fc] string = set([fc]) frontier = [fc] while frontier: current_fc = frontier.pop() string.add(current_fc) i = self._neighborsEntries[current_fc] while self._neighbors[i] != -1: fn = self._neighbors[i] i += 1 if self._board[fn] == color and not fn in string: frontier.append(fn) return string def _count_areas(self): ''' Costly function that computes the number of empty positions that only reach respectively BLACK and WHITE stones (the third values is the number of places touching both colours)''' to_check = self._empties.copy() # We need to check all the empty positions only_blacks = 0 only_whites = 0 others = 0 while len(to_check) > 0: s = to_check.pop() ssize = 0 assert self._board[s] == MyBoard.__EMPTY frontier = [s] touched_blacks, touched_whites = 0, 0 currentstring = [] while frontier: current = frontier.pop() currentstring.append(current) ssize += 1 # number of empty places in this loop assert current not in to_check i = self._neighborsEntries[current] while self._neighbors[i] != -1: n = self._neighbors[i] i += 1 if self._board[n] == MyBoard.__EMPTY and n in to_check: to_check.remove(n) frontier.append(n) elif self._board[n] == MyBoard.__BLACK: touched_blacks += 1 elif self._board[n] == MyBoard.__WHITE: touched_whites += 1 # here we have gathered all the informations about an empty area assert len(currentstring) == ssize assert (self._nbBLACK == 0 and self._nbWHITE == 0) or touched_blacks > 0 or touched_whites > 0 if touched_blacks == 0 and touched_whites > 0: only_whites += ssize elif touched_whites == 0 and touched_blacks > 0: only_blacks += ssize else: others += ssize return (only_blacks, only_whites, others) def _piece2str(self, c): if c==self.__WHITE: return 'O' elif c==self.__BLACK: return 'X' else: return '.' ''' Internally, the board has a redundant information by keeping track of strings of stones. ''' def _capture_string(self, fcoord): # The Union and Find data structure can efficiently handle # the string number of which the stone belongs to. However, # to recover all the stones, given a string number, we must # search for them. string = self._breadthSearchString(fcoord) for s in string: if self._nextPlayer == MyBoard.__WHITE: self._capturedBLACK += 1 self._nbBLACK -= 1 else: self._capturedWHITE += 1 self._nbWHITE -= 1 self._currentHash ^= self._getPositionHash(s, self._board[s]) self._board[s] = self.__EMPTY self._empties.add(s) i = self._neighborsEntries[s] while self._neighbors[i] != -1: fn = self._neighbors[i] if self._board[fn] != MyBoard.__EMPTY: st = self._getStringOfStone(fn) if st != s: self._stringLiberties[st] += 1 i += 1 self._stringUnionFind[s] = -1 self._stringSizes[s] = -1 self._stringLiberties[s] = -1 ''' Internal wrapper to full_play_move. Simply translate named move into internal coordinates system''' def _play_named_move(self, m): if m != "PASS": return self.play_move(MyBoard.name_to_flat(m)) else: return self.play_move(-1) def _draw_cross(self, x,y,w): toret = '<line x1="'+str(x-w)+'" y1="'+str(y)+'" x2="'+str(x+w)+'" y2="'+str(y)+'" stroke-width="3" stroke="black" />' toret += '<line x1="'+str(x)+'" y1="'+str(y-w)+'" x2="'+str(x)+'" y2="'+str(y+w)+'" stroke-width="3" stroke="black" />' return toret def _create_svg_representation(self): text_width=20 nb_cells = self.__BOARDSIZE circle_width = 16 border = 20 width = 40 wmax = str(width*(nb_cells-1) + border) board ='<svg height="'+str(text_width+border*2+(nb_cells-1)*width)+'" '+\ ' width="'+str(text_width+border*2+(nb_cells-1)*width)+'" > ' # The ABCD... line board += '<svg height="'+str(text_width)+'" width="' + str(text_width + border*2+(nb_cells-1)*width)+'">' letters = "ABCDEFGHJ" il = 0 for i in range(border+text_width-5, text_width-5+border+nb_cells*width, width): board+= '<text x="'+str(i)+'" y="18" font-size="24" font-color="black">'+letters[il]+'</text>' il += 1 #board += '<rect x=0 y=0 width=20 height=10 stroke="black" />' board += '</svg>' # The line numbers il = 0 board += '<svg width="'+str(text_width)+'" height="' + str(text_width + border*2+(nb_cells-1)*width)+'">' for i in range(border+text_width+7, text_width+7+border+nb_cells*width, width): board+= '<text y="'+str(i)+'" x="0" font-size="24" font-color="black">'+str(9-il)+'</text>' il += 1 #board += '<rect x=0 y=0 width=20 height=10 stroke="black" />' board += '</svg>' # The board by itself board += ' <svg x="'+str(text_width)+'" y="'+str(text_width)+'" height="' + \ str(text_width+width*(nb_cells-1) + 2*border) + '" width="' + \ str(text_width+width*(nb_cells-1) + 2*border) + '" > ' + \ '<rect x="0" y="0" width="'+str(width*(nb_cells-1)+2*border)+'" height="' + str(width*(nb_cells-1)+ 2*border) + '" fill="#B4927A" />\ <line x1="'+str(border)+'" y1="'+str(border)+'" x2="'+str(border)+'" y2="'+ wmax +'" stroke-width="4" stroke="black"/>\ <line x1="' + wmax + '" y1="' + str(border) + '" x2="' + str(border) + '" y2="' + str(border) + '" stroke-width="4" stroke="black"/>\ <line x1="' + wmax + '" y1="' + wmax + '" x2="' + wmax + '" y2="' + str(border) + '" stroke-width="4" stroke="black"/>\ <line x1="' + str(border) + '" y1="' + wmax + '" x2="' + wmax + '" y2="' + wmax + '" stroke-width="4" stroke="black"/>' board += self._draw_cross(border+4*width, border+4*width, width/3) board += self._draw_cross(border+2*width, border+2*width, width/3) board += self._draw_cross(border+6*width, border+6*width, width/3) board += self._draw_cross(border+2*width, border+6*width, width/3) board += self._draw_cross(border+6*width, border+2*width, width/3) for i in range(border+width, width*(nb_cells-2)+2*border, width): board += '<line x1="'+str(i)+'" y1="'+str(border)+'" x2="'+str(i)+'" y2="' + wmax + '" stroke-width="2" stroke="#444444"/>' board += '<line y1="'+str(i)+'" x1="'+str(border)+'" y2="'+str(i)+'" x2="' + wmax + '" stroke-width="2" stroke="#444444"/>' # The stones pieces = [(x,y,self._board[MyBoard.flatten((x,y))]) for x in range(self.__BOARDSIZE) for y in range(self.__BOARDSIZE) if self._board[MyBoard.flatten((x,y))] != MyBoard.__EMPTY] for (x,y,c) in pieces: board += '<circle cx="'+str(border+width*x) + \ '" cy="'+str(border+width*(nb_cells-y-1))+'" r="' + str(circle_width) + \ '" stroke="#333333" stroke-width="3" fill="' + \ ("black" if c==1 else "white") +'" />' board += '</svg></svg>' #'\ <text x="100" y="100" font-size="30" font-color="black"> Hello </text>\ return board ############################################################################ ############################################################################ ############################################################################ ''' Extension du Goban original ''' def nb_stones(self, color:Color) -> int: ''' Retourne ne nombre de pierre appartenant à la couleur {color}. Si la couleur est EMPTY, alors retourne le nombre de cellule vide. ''' if color == MyBoard.__WHITE: return self._nbWHITE elif color == MyBoard.__BLACK: return self._nbBLACK else: return MyBoard.__BOARDSIZE - self._nbWHITE - self._nbBLACK def nb_liberties(self, color:Color) -> int: ''' Retourne le nombre de liberté total qu'une couleur possède. ''' assert color != MyBoard.__EMPTY libs = 0 for s in self._strings[color]: libs += len(s.liberties) return libs def nb_strings(self, color:Color) -> int: ''' Retourne le nombre de string total qu'une couleur possède. ''' assert color != MyBoard.__EMPTY return len(self._strings[color]) def get_liberties(self, color:Color) -> Set[FlattenMove]: ''' Retourne toutes les libertés (en flat) qu'une couleur possède. ''' assert color != MyBoard.__EMPTY strings = set() for s in self._strings[color]: strings |= s.liberties return strings def nb_shared_liberty(self, color:Color, fcoord:FlattenMove) -> Tuple[int, int]: ''' Pour une case vide {fcoord}, donne le nombre de string différent autour de cette case. Suivant la couleur {color}, différencie les strings alliés de celles adverse. ''' assert self._board[fcoord] == MyBoard.__EMPTY nb = 0 nbOp = 0 for s in self._strings[color]: if fcoord in s.liberties: nb += 1 for s in self._strings[MyBoard.flip(color)]: if fcoord in s.liberties: nbOp += 1 return nb, nbOp def is_eye(self, fcoord:FlattenMove, color:Color) -> bool: ''' Vérifie si la cellule {fcoord} est un oeil de la couleur {color}. Un oeil est une cellule vide qui a tous ses voisins de la même couleur. Ensuite soit : - Elle est sur le bord du plateau, alors tous les coins doivent être de la même couleur - Sinon, elle doit avoir au moins 3 coins de la même couleur Les voisins et les coins doivent être de la même couleur également. ''' if self._board[fcoord] != MyBoard.__EMPTY: # Si ce n'est pas une case vide, on retourne return False # On regarde les 4 voisins # Si un voisin est d'une autre couleur que la notre, ce n'est pas un oeil i = self._neighborsEntries[fcoord] while self._neighbors[i] != -1: if self._board[self._neighbors[i]] != color: return False i += 1 off_board_corners = 4 friendly_corners = 0 # On regarde les corners i = self._cornersEntries[fcoord] while self._corners[i] != -1: if self._board[self._corners[i]] == color: friendly_corners += 1 off_board_corners -= 1 i += 1 # Si la cellule {fcoord} est sur le bord du board if off_board_corners > 0: return (off_board_corners + friendly_corners == 4) return (friendly_corners >= 3) def is_useless(self, fcoord:FlattenMove, color:Color) -> bool: ''' Vérifie si jouer une pierre sur la cellule {fcoord} est utile ou non. Un coup dit "inutile" est un coup qui place une pierre sur une cellule déjà acquise (i.e. que l'adversaire ne peut pas placer une pierre dessus). Dans certains cas, on peut être amené à jouer ce genre de coup, pour fusionner des strings par exemple. ''' if self._board[fcoord] != MyBoard.__EMPTY: # Si c'est pas une case vide, on quitte return False i = self._neighborsEntries[fcoord] nb = 0 nbOp = 0 while self._neighbors[i] != -1: if self._board[self._neighbors[i]] == color: nb += 1 elif self._board[self._neighbors[i]] == MyBoard.flip(color): nbOp += 1 i += 1 # Le coup n'est pas inutile s'il y a une pierre adverse (pour peut être capturer) if nbOp == 1 and nb == 3: return False # Le coup est inutile s'il y a déjà 3 ou 4 pierres de notre couleur autour return (nb >= 3) def _get_territory(self, fcoord:FlattenMove) -> FlattenMoveList: ''' Retourne la liste des coordonnées valide suivant la cellule {fcoord}. Un territoire est composé des 8 cellules autour de la cellule {fcoord} et de la cellule {fcoord} elle-même. ''' x, y = MyBoard.unflatten(fcoord) neighbors = [ (x-1, y+1), (x, y+1), (x+1, y+1), (x-1, y), (x, y), (x+1, y), (x-1, y-1), (x, y-1), (x+1, y-1)] return [MyBoard.flatten(c) for c in neighbors if self._is_on_board(c[0], c[1])] def compute_territory(self, color:Color) -> Tuple[int, int, int, int, int]: ''' Pour chaque cellule du plateau, calcul à quel territoire elle partient. Un territoire est définit par la méthode "self._get_territory". Only_Color -> Si la cellule n'a que des voisins de la couleur {color} Only_OtherColor -> Idem mais avec la couleur opposée Color -> Si la cellule a une majorité absolue de voisin de la couleur {color} OtherColor -> Idem mais avec la couleur opposée Dangerous -> La cellule est en conflit (aucun des deux joueurs ne la possède) (regroupe également les territoires neutres, ceux qui n'ont aucune cellule de couleur) ''' nb_territory_only_color = 0 nb_territory_only_otherColor = 0 nb_territory_color = 0 nb_territory_otherColor = 0 nb_territory_dangerous = 0 for fcoord in range(0, 81, 1): #for cell in self._empties: neighbors = self._get_territory(fcoord) nbColor = 0 nbOtherColor = 0 nbEmpty = 0 # Calcul des pierres dans le territoire for fn in neighbors: if self._board[fn] == color: nbColor += 1 elif self._board[fn] == MyBoard.flip(color): nbOtherColor += 1 else: nbEmpty += 1 if (nbColor > 0 and nbOtherColor == 0): # Voisin(s) seulement de notre couleur nb_territory_only_color += 1 elif (nbColor > nbOtherColor + nbEmpty): # Majorité de notre couleur nb_territory_color += 1 elif (nbColor == 0 and nbOtherColor > 0): # Voisin(s) seulement la couleur adverse nb_territory_only_otherColor += 1 elif (nbOtherColor > nbColor + nbEmpty): # Majorité de la couleur adverse nb_territory_otherColor += 1 else: # Dangereux ou neutre nb_territory_dangerous += 1 return (nb_territory_only_color, nb_territory_only_otherColor, nb_territory_color, nb_territory_otherColor, nb_territory_dangerous) def get_data(self, color:Color, otherColor:Color) -> Dict[str, int]: ''' Récupération des données du board. Méthode utilisé dans les heuristiques. Génère un dictionnaire pour accéder facilement aux données. ''' my_nbStones = self.nb_stones(color) other_nbStones = self.nb_stones(otherColor) my_nbLiberties = self.nb_liberties(color) other_nbLiberties = self.nb_liberties(otherColor) my_nbStrings = self.nb_strings(color) other_nbStrings = self.nb_strings(otherColor) (my_nbWeakStrings1, other_nbWeakStrings1) = self.compute_weak_strings_k_liberties(color, 1) (my_nbWeakStrings2, other_nbWeakStrings2) = self.compute_weak_strings_k_liberties(color, 2) (my_nbWeakStrings3, other_nbWeakStrings3) = self.compute_weak_strings_k_liberties(color, 3) (my_nbWeakStrings4, other_nbWeakStrings4) = self.compute_weak_strings_k_liberties(color, 4) data = { 'my_nbStones' : my_nbStones, 'my_nbLiberties' : my_nbLiberties, 'my_nbStrings' : my_nbStrings, 'other_nbStones' : other_nbStones, 'other_nbLiberties' : other_nbLiberties, 'other_nbStrings' : other_nbStrings, 'my_nbWeakStrings1' : my_nbWeakStrings1, 'my_nbWeakStrings2' : my_nbWeakStrings2, 'my_nbWeakStrings3' : my_nbWeakStrings3, 'my_nbWeakStrings4' : my_nbWeakStrings4, 'other_nbWeakStrings1' : other_nbWeakStrings1, 'other_nbWeakStrings2' : other_nbWeakStrings2, 'other_nbWeakStrings3' : other_nbWeakStrings3, 'other_nbWeakStrings4' : other_nbWeakStrings4 } return data ############################################################################ ############################################################################ ############################################################################ ''' Fonctions de gestion des String contenu dans self._strings ''' def _create_string(self, color:Color, liberties:Set[FlattenMove], stones:Set[FlattenMove]) -> String: ''' Création d'un objet String. L'ajoute dans la liste {self._strings[color]}. ''' s = String(color=color, liberties=liberties, stones=stones) self._strings[color].append(s) return s def _merge_string(self, s1:String, s2:String) -> String: ''' Fusionne les String s1 et s2. Supprime S2. ''' s1.liberties |= s2.liberties s1.stones |= s2.stones self._delete_string(s2) return s1 def _delete_string(self, s:String) -> None: self._strings[s.color].remove(s) del s def _find_string(self, fcoord:FlattenMove, color:Color) -> String: ''' A partir d'une cellule {fcoord}, cherche à quelle String elle appartient. ''' for string in self._strings[color]: if fcoord in string.stones: return string assert False def _capture_string_object(self, string:String) -> None: ''' Capture le String {string}. Modifie les String voisins en conséquence. Une fois le String {string} capturé, le supprime. ''' for stone in string.stones: i = self._neighborsEntries[stone] while self._neighbors[i] != -1: fn = self._neighbors[i] cell = self._board[fn] if cell != MyBoard.__EMPTY: s = self._find_string(fn, cell) if s is not string: s.liberties.add(stone) i += 1 self._delete_string(string) def _compute_liberties(self, fcoord:FlattenMove, color:Color) -> Tuple[int, int, int, Set[FlattenMove]]: ''' Pour une cellule {fcoord}, calcul : - Le nombre de voisin de la couleur {color} - Le nombre de voisin adverse - Le nombre de cellule vide - Récupère les coordonnées des libertés de la cellule {fcoord} ''' nbEmpty = 0 nbSameColor = 0 nbOtherColor = 0 liberties = set() i = self._neighborsEntries[fcoord] while self._neighbors[i] != -1: fn = self._neighbors[i] cell = self._board[fn] if cell == MyBoard.__EMPTY: nbEmpty += 1 liberties.add(fn) elif cell == color: nbSameColor += 1 else: nbOtherColor += 1 i += 1 return (nbEmpty, nbSameColor, nbOtherColor, liberties) def compute_weak_strings_k_liberties(self, color:Color, k:int) -> Tuple[int,int]: ''' Compte, pour une couleur donné, le nombre de String qui a exactement {k} liberté. Compte également pour l'adversaire. ''' nbWeakStrings = 0 nbWeakStringsOpponent = 0 for s in self._strings[color]: if len(s.liberties) == k: nbWeakStrings += 1 for s in self._strings[MyBoard.flip(color)]: if len(s.liberties) == k: nbWeakStringsOpponent += 1 return (nbWeakStrings, nbWeakStringsOpponent) def nb_strings(self, color:Color) -> int: ''' Nombre de String du couleur {color} ''' return len(self._strings[color]) def get_strings(self, color:Color) -> List[String]: ''' Retourne la liste des String du joueur {color} ''' return self._strings[color] def _put_stone_object(self, fcoord:FlattenMove, color:Color, allLiberties:Tuple[int, int, int, Set[FlattenMove]]) -> List[String]: ''' Equivalent à self._put_stone, mais pour l'utilisation des objets String. Place une nouvelle pierre aux coordonnées {fcoord} et mets à jour les String des deux joueurs. Retourne la liste des String à capturer. ''' (nbEmpty, nbSameColor, nbOtherColor, lib) = allLiberties stringWithNoLiberties = [] newString = self._create_string(color=color, liberties=lib, stones=set([fcoord])) i = self._neighborsEntries[fcoord] while self._neighbors[i] != -1: fn = self._neighbors[i] cell = self._board[fn] if cell == color: s = self._find_string(fn, cell) s.liberties.discard(fcoord) if s is not newString: newString = self._merge_string(s, newString) elif cell == MyBoard.flip(color): s = self._find_string(fn, cell) s.liberties.discard(fcoord) if len(s.liberties) == 0: if s not in stringWithNoLiberties: stringWithNoLiberties.append(s) i += 1 return stringWithNoLiberties
1a9df29e0bb124dfa1b029851676deb2eef6d098
xiemingzhi/pythonproject
/lang/range-test.py
66
3.71875
4
str = '123' for x in range(len(str)-1, -1, -1): print(str[x])
819d28e241a93fdcdb8918d935330427f45ae761
danakock/exercism-python
/pangram/pangram.py
400
3.953125
4
import re alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',\ 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'} def is_pangram(phrase): phrase = phrase.lower() wordList = re.sub(r'[.!,;?_"[0-9]', ' ', phrase) s = {x for x in wordList if x not in [' ', '-']} if s == alphabet: return True else: return False
76bdd2f9913f9c985d90f267258ad1d188fe6581
KareliaConsolidated/Data-Structures-and-Algorithms
/48_Final/01_TwoNumberSum.py
1,313
4.09375
4
# Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. If any two numbers in the input array sum up to the target sum, the function should return them in an array, in sorted order. If no two numbers sum up to the target sum, the function should return an empty array. Assume that there will be at most one pair of numbers summing up to the target sum. # O(n^2) Time | O(1) Space def twoNumberSum(array, targetSum): for i in range(len(array)-1): firstNum = array[i] for j in range(i+1,len(array)): secondNum = array[j] if firstNum + secondNum == targetSum: return sorted([firstNum, secondNum]) return [] # O(n) Time | O(n) Space def twoNumberSum(array, targetSum): nums = {} for num in array: potentialMatch = targetSum - num if potentialMatch in nums: return sorted([potentialMatch, num]) else: nums[num] = True return [] # O(nlog(n)) Time | O(1) Space def twoNumberSum(array, targetSum): array.sort() left = 0 right = len(array) - 1 while left < right: currentSum = array[left] + array[right] if currentSum == targetSum: return [array[left], array[right]] elif currentSum < targetSum: left += 1 elif currentSum > targetSum: right -= 1 return [] print(twoNumberSum([3, 5, -4, 8, 11, 1, -1, 6], 10))
63772fb79e670e2a34d2a0a4732714cbe2645173
daniel-reich/ubiquitous-fiesta
/9QbhjtbkXp3QZNuDu_7.py
240
3.78125
4
def is_palindrome(n): return str(n) == str(n)[::-1] ​ def generate_palindromes(limit): palindromes = [] for i in range(0,limit+1): if is_palindrome(i): palindromes.append(i) return sorted(palindromes[::-1][:15])
b67b7bead4d78457465f640ae37852cd3d6d08a0
anand1996wani/CompetitiveCoding-Easy
/Subsequence Again.py
1,144
3.921875
4
''' Question : You are provided with a string s and an integer k. You have to find another string t which satisfies the following conditions: 1: t must be a subsequence of s. 2: Every character in t must occur at least k times. 3: The length of t must be as large as possible. 4: If there are multiple strings for t with largest possible length, pick the lexicographically smallest one. For example, let's say the string is s = hackerrank and k = 2. The solution for this is akrrak. Here t is a subsequence of s, it contains the characters a,k and r repeated at least k times. And, it is the only longest possible subsequence that satisfies the conditions. ''' #!/bin/python3 import sys import collections def subsequenceAgain(s, k): # Complete this function d = collections.OrderedDict() for i in s: if i not in d: d.update({i:1}) else: d[i] = d[i] + 1 st = "" for i in s: if(d[i]>=k): st = st + i return st if __name__ == "__main__": s = input().strip() k = int(input().strip()) result = subsequenceAgain(s, k) print(result)
e53b9966d29c21b333a0994bfe81fd1cd197d09b
tjmaxx/upgy-python3-webapp
/www/db.py
303
3.6875
4
import sqlite3 conn = sqlite3.connect('test.db') cursor = conn.cursor() # cursor.execute('insert into user (id,name) values (\'6\',\'a tjmaxx\')') cursor.execute(('select * from user order by name DESC')) value = cursor.fetchall() print([i[1] for i in value]) cursor.close() conn.commit() conn.close()
1fd630f8777814a91df8c2fac4f077f97b8f10a3
TheAragont97/Python
/Actividades/Antonio_Jose_Aragon - RecPY/ej3_AntonioAragon.py
756
4.15625
4
#creamos un método para ver quitarle las vocales a la cadena y devolverlo en mayusculas def devorador(cadena): cadenaCambiada="" #una vez creada la variable auxiliar para meter el resultado final #hacemos un bucle para ver si es vocal o no for y in cadena: #si no lo es entra en este if y mete las consonantes en mayuscula dentro de la variable nueva if(y!='a' and y!='e' and y!='i' and y!='o' and y!='u'): cadenaCambiada+=y.upper() #despues imprimimos el resultado print(cadenaCambiada) #validamos si es correcto lo que el usuario a introducido try: #hacemos que el usuario meta la cadena y se lo pasamos a la función cadena=input("Ingrese una cadena: ") devorador(cadena) except: print("Error, no se han metido los valores correctos")
2dfe1937341f51c34af057f38ce4971ee42d3366
sunilvarma9697/Code-Basics
/Classand Objects.py
307
3.546875
4
#class - class is simply represented as type of an object and its is also called blueprint. #object - object is termed as instance of a class and it has own state. class Computer(object): """docstring for Computer""" def config(self): print("i5, 16GB, 1TB") com1 = Computer() com1.config()
7e5249b5b0c40f81d7baa0b81e214f2f055e26a3
justinglobal/codeguild
/9-farkle.py
2,109
4.03125
4
# this game plays Farkle, or at least a basic version of Farkle # it uses 5 6-sided dice for each 'roll' # User types 'roll' or hits enter to roll dice print('This is a simple Farkle game. Press enter to roll dice.') input() print('Results: ') import random total_score = 0 dice1 = random.randint(1 , 6) dice2 = random.randint(1 , 6) dice3 = random.randint(1 , 6) dice4 = random.randint(1 , 6) dice5 = random.randint(1 , 6) all_dice = [dice1 , dice2 , dice3 , dice4 , dice5] #all_dice = [random.randint(1 , 6) , random.randint(1 , 6) , random.randint(1 , 6) , random.randint(1 , 6) , random.randint(1 , 6)] #all_dice = [1, 1, 1, 1, 1] #can make this shorter #how to count values in a string or list #all_dice_string = str(all_dice) number_of_1s = all_dice.count(1) number_of_2s = all_dice.count(2) number_of_3s = all_dice.count(3) number_of_4s = all_dice.count(4) number_of_5s = all_dice.count(5) number_of_6s = all_dice.count(6) if number_of_1s == 3: total_score = total_score + 1000 #fix one scoring error here if number_of_2s == 3: total_score = total_score + 200 if number_of_3s == 3: total_score = total_score + 300 if number_of_4s == 3: total_score = total_score + 400 if number_of_5s == 3: total_score = total_score + 500 #fix 5 scoring error here if number_of_6s == 3: total_score = total_score + 600 if number_of_1s < 3: total_score = total_score + (number_of_1s * 100) if number_of_5s < 3: total_score = total_score + (number_of_5s * 50) #[, start[, end]] #print('results for each dice' , all_dice) print('results for each dice' , dice1 , dice2 , dice3 , dice4 , dice5) print(all_dice) print(all_dice_string) if total_score > 0: print('Your total score is ' , total_score) else: print('FARKLE!') # # num_6sided_dice = 5#int(input()) # total_dice = num_6sided_dice # total_sum = 0 # # while 0 < num_6sided_dice: # dice = random.randint(1, 6) # total_sum += dice # print(num_6sided_dice, 'dice left to roll, and the value is:' , dice) # num_6sided_dice -= 1 # # print('The average of all die rolls is ', int(total_sum / total_dice))
43422cb0857859d680f87a7b2d115ad59e3117b4
krishnaece1505/Code
/Python Projects/Simple_coolers_using_turtle/Coolers.py
1,229
4.375
4
#------------------------------------------------------------------------------- # Name: Simple Coolers using Python Turtle # # Author: Krishnaswamy Kannan # #------------------------------------------------------------------------------- import turtle def main(): window = turtle.Screen() # create a window to draw coolers = turtle.Turtle() # create a new turtle coolers.left(180) coolers.forward(100) coolers.right(90) # Fill the circle with green color and black line coolers.color("black","green") coolers.begin_fill() #begin color fill coolers.circle(50) coolers.end_fill() #end color fill coolers.right(90) coolers.forward(100) coolers.right(90) # Fill the other circle with green color and black line coolers.color("black","green") coolers.begin_fill() #begin fill coolers.circle(50) coolers.end_fill() #end fill coolers.circle(50,180) coolers.forward(100) coolers.right(180) coolers.forward(100) coolers.circle(-50,180) coolers.left(90) coolers.forward(100) coolers.right(90) coolers.circle(50,180) coolers.right(180) coolers.forward(100) window.exitonclick() if __name__ == '__main__': main()
f2bfa4f5f7d1c9fdc7fda2e642706297499f1e09
jesuslz/AIPy
/Documentation/BuildingMachineLearningSystems/codes/p1-learningNumpy/p1-learningNumpy.py
3,177
4.4375
4
import numpy as np print("version de Numpy: ", np.version.full_version) a = np.array([0,1,2,3,4,5]) print("a = ", a) print("dimension del array a: ", a.ndim) print("shape of a: ", a.shape) #We can now transform this array in to a 2D matrix b = a.reshape((3,2)) print("Matriz hecha a partir de a = b = ", b) print("dimension de la matriz b: ", b.ndim) print("shape of b: ", b.shape) #it avoids copies wherever ppossible b[1][0] = 77 print("b fue modificado: \n b = \n", b) print("como b fue modificado, a tambien \n a = ", a) #ahora crearemos una copia, a y c son copias totalmente independientes c = a.reshape((3,2)).copy() print("copia de a reformada: c = ", c) c[0][0] = -99 print("c modificado: c = ", c) print("vemos que a no se ha modificado a = ", a) #operaciones con a print("a*2 = ", a*2) print("a**2 = ", a**2) '''Contrast that to ordinary Python lists: >> [1,2,3,4,5]*2 [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] >> [1,2,3,4,5]**2 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for ** or pow(): 'list' and int ''' #Indexing print('------Indexing-------') #In addition to normal list indexing, it allows us to use arrays themselves as indices. print("indexando con un array", a[np.array([2,3,4])]) print("a > 4 = ", a > 4) print("a[a > 4] = ", a[a > 4]) #This can also be used to trim outliers. '''As this is a frequent use case, there is a special clip function for it, clipping the values at both ends of an interval with one function call as follows:''' print('la funcion clip() hace lo mismo que lo anterior \n a.clip(0,4) = ', a.clip(0, 4)) print("a = ", a) a[a > 4] = 4 print("a[a > 4] = 4, a = ", a) #handling non-existing values print('------handling non-existing values------') c = np.array([1, 2, np.NAN, 3, 4]) print("c = ", c) print("np.isnan(c) = ", np.isnan(c)) print("c[~np.isnan(c)] = ", c[~np.isnan(c)])#no modifica c print("c = ", c) print("np.mean(c[~np.isnan(c)]) = ", np.mean(c[~np.isnan(c)])) #Comparing runtime behaviors print('-----------------Comparing runtime behaviors------------------') import timeit #normal_py_sec = timeit.timeit('sum(x*x for x in np.arange(1000))', number = 10000) naive_np_sec = timeit.timeit('sum(na*na)', setup = "import numpy as np; na = np.arange(1000)", number = 10000) good_np_sec = timeit.timeit('na.dot(na)', setup = "import numpy as np; na = np.arange(1000)", number = 10000) #print("Normal Python: %f sec" % normal_py_sec) print("Naive NumPy: %f sec" % naive_np_sec) print("Good NumPy: %f sec" % good_np_sec) '''However, the speed comes at a price. Using NumPy arrays, we no longer have the incredible fexibility of Python lists, which can hold basically anything. NumPy arrays always have only one datatype. ''' print('------------Numpy datatype -------------') a = np.array([1,2,3]) print(a.dtype) '''If we try to use elements of different types, NumPy will do its best to coerce them to the most reasonable common datatype:''' print('np.array([1, "stringy"]) = ', np.array([1, "stringy"])) print('np.array([1, "stringy", set([1,2,3])]) = ', np.array([1, "stringy", set([1, 2, 3])]))
1306633a617bd96168ec381b2208e9a2e16d4c77
irennerifire/algorithms
/hw1_1.py
369
4.1875
4
#1. Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь. num = input("Enter some numerical value of 3 digits: ") sum = 0 prod = 1 for i in num: sum += int(i) prod *= int(i) print(f"Sum of digits: {sum}") print(f"Production of digits: {prod}")
020f34faadbf21f01c0b614278e90e946352eb7f
ajnirp/binarysearch
/line-segment.py
420
3.8125
4
# https://binarysearch.com/problems/Line-Segment class Solution: def slope(self, c1, c2): a, b = c1 c, d = c2 return 'inf' if a == c else (d - b) / (a - c) def solve(self, coordinates): if len(coordinates) < 3: return True slope = self.slope(coordinates[0], coordinates[1]) return all(slope == self.slope(c, coordinates[0]) for c in coordinates[2:])
a111f265f54982ff5eebb424b9a20cb6d2052d88
nishesh19/CTCI
/leetCode/countServers.py
984
3.5625
4
class Solution: def countServers(self, grid) -> int: total_count = 0 rows = len(grid) columns = len(grid[0]) row_count = [0 for _ in range(rows)] column_count = [0 for _ in range(columns)] for i in range(rows): for j in range(columns): if grid[i][j]: row_count[i] += 1 column_count[j] += 1 for i in range(rows): for j in range(columns): if grid[i][j] and ((row_count[i] > 1) or (column_count[j] > 1)): total_count += 1 return total_count if __name__ == '__main__': sol = Solution() grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]] print(sol.countServers(grid))
2d3a19e1605de21bedd2b19af3e83ea53f17a2f6
haidfs/LeetCode
/Hot100/合并区间.py
1,520
3.5625
4
# 给出一个区间的集合,请合并所有重叠的区间。 # # 示例 1: # # 输入: [[1,3],[2,6],[8,10],[15,18]] # 输出: [[1,6],[8,10],[15,18]] # 解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6]. # 示例 2: # # 输入: [[1,4],[4,5]] # 输出: [[1,5]] # 解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。 class Solution: def merge(self, intervals: [[int]]) -> [[int]]: intervals.sort() length = len(intervals) if length <= 1: return intervals i = 0 while i < len(intervals) - 1: if intervals[i][0] == intervals[i + 1][0] and intervals[i][1] <= intervals[i + 1][1]: intervals.pop(i) elif intervals[i][1] >= intervals[i + 1][1]: intervals.pop(i + 1) elif intervals[i + 1][0] <= intervals[i][1] <= intervals[i + 1][1]: intervals[i + 1][0] = intervals[i][0] intervals.pop(i) else: i += 1 return intervals def merge2(self, intervals: [[int]]) -> [[int]]: intervals.sort() merged = [] for interval in intervals: if not merged or merged[-1][1] < interval[0]: merged.append(interval) else: merged[-1][1] = max(merged[-1][1], interval[1]) return merged if __name__ == '__main__': # ints = [[0, 1], [1, 3], [2, 6], [8, 10], [15, 18]] ints = [[1, 4], [2, 3]] s = Solution() print(s.merge(ints))
2babddfbc7db980f8f0d374e9e61608a80a0e7f3
sjkirby/search-algorithms-graphical-summary
/py/uninformed_search.py
4,306
3.65625
4
from collections import deque from random import shuffle #returns the integer representation from a state matrix def state_value(state): sum = 0 for x in range(3): for y in range(3): sum = sum*10 + state[x][y] return sum #returns the state matrix from an integer representation def value_state(num): state = [[0 for x in range(3)] for x in range(3)] for i in range(9): state[(8-i)/3][(8-i)%3] = num % 10 num = num / 10 return state #checks if node or its rotations occur in state set def is_new(node,states): if node.value in states: return False for r in range(3): if state_value(rotate_state(node.state)) in states: return False return True #rotates a state def rotate_state(state): return zip(*state[::-1]) #checks if node matches goal state def is_complete(node,goal): return node.value == goal.value #adds state to explored states def add_state(node,states): states.add(state_value(node.state)) #class to abstract node data class Node: def __init__(this,state, parent, depth, pathcost): this.state = state this.parent = parent this.depth = depth this.pathcost = pathcost this.value = state_value(state) #create a node (generally should use makeState) def makeNode(state, parent, depth, pathcost): return Node(state,parent,depth,pathcost) #returns a move state from xy origin and xy target, the result of moving from origin to target def move(state,tx,ty,fx,fy): new_state = [row[:] for row in state] new_state[tx][ty] = new_state[fx][fy] new_state[fx][fy] = 0 return new_state #returns a list of all moves from a node, sorted by a heuristic def moves(node,goal,heuristicsort): state = node.state for x in range(3): for y in range(3): if(state[x][y]==0): tpos = x*3+y out = [] if x!=0: out.append(move(state,x,y,x-1,y)) if x!=2: out.append(move(state,x,y,x+1,y)) if y!=0: out.append(move(state,x,y,x,y-1)) if y!=2: out.append(move(state,x,y,x,y+1)) return heuristicsort(map(lambda x: makeNode(x,node,node.depth+1,node.pathcost+1), out),goal) #unused generic search function def generalSearch(queue, limit, numRuns): if queue == []: return False elif testProcedure(queue[0]): outputProcedure(numRuns, queue[0]) elif limit == 0: print "Limit reached" else: limit -= 1 numRuns += 1 generalSearch(expandProcedure(queue[0], queue[1:len(queue)]), limit, numRuns) #prints the move history def printmoves(node): hist = deque() while node.parent: hist.appendleft(node) node = node.parent hist.appendleft(node) move = 1 print len(hist),'moves total' for n in hist: print "Move",move move+=1 for y in n.state: print ''.join(map(str,y)) print numMoves = 0 #correct search function, with abstraction of append, pop, and next move heuristic sorting def gen_search(state,goal,limit,numRuns,appendf,popf,heuristicsort,output=True): global numMoves states = set() ops = deque() appendf(ops,state) depth = 0 while len(ops) != 0: node = popf(ops) if numRuns == limit: print "Limit reached" return (False,states) if is_complete(node,goal): if output: printmoves(node) return (node.depth,len(states),numRuns) if is_new(node,states): numRuns +=1 numMoves +=1 if numRuns % 1000 == 0: if output: print numRuns,'nodes attempted'#,',len(states),'unique' if len(states) > 110000: if output: print('Search may fail due to Python memory limits') add_state(node,states) for new_node in moves(node,goal,heuristicsort): appendf(ops,new_node) print "Memory limit error" return (False) #a heuristic for a random ordering of next moves def randomorder(node,goal): shuffle(node) return node #create an state (returns a Node with no parent) def makeState(*args): sum = 0 for x in args: if x == "blank": x = 0 sum = sum * 10 + x return Node(value_state(sum),None,0,0) #test DFS per specification, calls gen_search def testDFS(init,goal,limit,output=True): if output: print("DFS") return gen_search(init,goal,limit,0,deque.append,deque.pop,randomorder,output) #test BFS per specification, calls gen_search def testBFS(init,goal,limit,output=True): if output: print("BFS") return gen_search(init,goal,limit,0,deque.appendleft,deque.pop,randomorder,output)
50074b141ddbddbae2f8d3c230fe48901ff9dae6
ramgopal99/StandalonePrograms_Python
/SentenceAnalyser.py
1,771
4.4375
4
# Incorporates tuples, lists and disctionaries - all in a single use case """ Create a program to analyse song lyrics with the followinng three features/functions: - a frequency dictionary that maps strings to integers; Return type is a dictionary, format {word;frequency} - word(s) that appears most often. Return type is a tuple, format (list, int) for ([List of most freq. occoring word(s)],frequency) - words that appear at-least x number of times (x - user input); Return type is a list of tuples, each tuple has format (word,freq) Comment: Not entirely straightforward, but will get the job done """ s = "one two three one one two three three three five six six six six six six" def word_freq(s): s = s.lower() L = s.split(" ") L.sort() song_dict = {} freq = 1 for i in range(len(L)-1): if L[i] == L[i+1]: freq +=1 else: song_dict[L[i]] = freq freq = 1 return song_dict #quick test word_freq(s) def freq_word(s,func): song_dict = word_freq(s) max_list = [] max1 = 0 for i in song_dict.keys(): if song_dict[i]> max1: max1 = song_dict[i] for i in song_dict.keys(): if song_dict[i]== max1: max_list.append(i) return (max_list,max1) #quick test freq_word(s,word_freq) def atleast_x(s,func1,x): #badly named function that returns a list of tuples song_dict = word_freq(s) output_list = [] for i in song_dict.keys(): if song_dict[i]>= x: output_list.append((i,song_dict[i])) return output_list #quick test atleast_x(s,word_freq,4) """ Happy to have written efficient code """
3992a524310ef532776a86d1bd57c3e26aa01ad3
NeelJVerma/Daily_Coding_Problem
/Autocomplete/main.py
1,934
3.6875
4
""" Problem statement: Implement an autocomplete system. That is, given a query string s and a list of words in a dictionary, return all words that have s as a prefix. """ class TrieNode: def __init__(self): self.children = [None] * 26 self.iswordend = False def insert(root, word): crawler = root for i in range(len(word)): idx = get_index(word[i]) if not crawler.children[idx]: crawler.children[idx] = TrieNode() crawler = crawler.children[idx] crawler.iswordend = True def find(root, key): crawler = root for i in range(len(key)): idx = get_index(word[i]) if not crawler.children[idx]: return False crawler = crawler.children[idx] return (crawler and crawler.iswordend) def is_end(root): for i in range(26): if root.children[i]: return False return True def get_index(char): return ord(char) - ord('a') def autocomplete_helper(root, word): word = list(word) if root.iswordend: print(''.join(word)) if is_end(root): return for i in range(26): if root.children[i]: word.append(chr(97 + i)) autocomplete_helper(root.children[i], word) word.pop(-1) def autocomplete(root, word): word = list(word) crawler = root for i in range(len(word)): idx = get_index(word[i]) if not crawler.children[idx]: return crawler = crawler.children[idx] isword = crawler.iswordend isend = is_end(crawler) if isword and isend: print(''.join(word)) return if not isend: wordcopy = word autocomplete_helper(crawler, wordcopy) root = TrieNode() insert(root, 'ab') insert(root, 'abc') insert(root, 'def') insert(root, 'cel') insert(root, 'fed') insert(root, 'npc') insert(root, 'aqr') autocomplete(root, 'a')
93f018f43827ae19774abf590ec3475d5140cd26
mgheeraert/Informatica5
/toets_5WWI2/dronken voeren.py
573
3.75
4
def dronken_voeren(woord): nieuw_woord = woord[0] for i in range(1, len(woord)): #even letter? if i % 2 == 0: nieuw_woord += woord[i].upper() #oneven letter en vorige (even) letter is hoofletterklinker op einde van nieuw woord elif woord[i - 1] in 'aeiouAEIOU': nieuw_woord += woord[i].upper() #elif woord[-1] in 'AEIOU': # nieuw_woord += woord[i].upper() #oneven letter else: nieuw_woord += woord[i].lower() return nieuw_woord print(dronken_voeren('dronkenboer'))
a64f4ddcf00f98633bfa457b33204efe1bd6b4c5
AmberRosanne/HelloYou
/ditbenik.py
2,339
4
4
import time a = True while a == True: print("Hi! Ik ben Amber") jouwNaam = input("Wat is jouw naam? ") print ("Hey, "+ jouwNaam + ". Welkom!") time.sleep(1) print("Ik heb 3 vragen voor je:") time.sleep (1) print("1. Wat is mijn haarkleur?") print("A Bruin \nB Donker Rood \nC Paars \nD Donker Blond") antwoord1 = input("A, B, C of D ") if antwoord1 == "a" or antwoord1 == "A": print("Nope, als de kleur vervaagt word het wel bruin.") elif antwoord1 == "b" or antwoord1 == "B": print("Ja! Helaas vervaagt de kleur wel snel.") elif antwoord1 == "c" or antwoord1 == "C": print("Nope, maar wel in de buurt.") elif antwoord1 == "d" or antwoord1 == "D": print("Nee, dit is mijn echte haarkleur...") else: print("ik begrijp alleen maar a, b, c ofd als antwoord") time.sleep (2) print("Oke, nu vraag 2:") time.sleep (1) print("2. Wat is mijn favoriete eten?") print("A Pizza \nB Sushi \nC Lasagne \nD Stamppot andijvie") antwoord1 = input("A, B, C of D ") if antwoord1 == "a" or antwoord1 == "A": print("Nope, maar pizza is wel lekker!") elif antwoord1 == "b" or antwoord1 == "B": print("Niet mijn nummer 1, maar het is wel lekker.") elif antwoord1 == "c" or antwoord1 == "C": print("Jaa! En al helemaal als mijn moeder hem maakt.") elif antwoord1 == "d" or antwoord1 == "D": print("Nee, maar vind dit ook heel lekker.") else: print("ik begrijp alleen maar a, b, c ofd als antwoord") time.sleep (2) print("Oke, nu de laatste vraag:") time.sleep (1) print("3. Waar woon ik nu?") print("A Alkmaar \nB Haarlem \nC Spaarndam \nD Hoofddorp") antwoord1 = input("A, B, C of D ") if antwoord1 == "a" or antwoord1 == "A": print("Nee, maar ik ben hier wel geboren.") elif antwoord1 == "b" or antwoord1 == "B": print("Niet helemaal,ik heb hier wel 9 jaar gewoont.") elif antwoord1 == "c" or antwoord1 == "C": print("Ja, ik woon hier sinds 4 jaar.") elif antwoord1 == "d" or antwoord1 == "D": print("Nope!") else: print("ik begrijp alleen maar a, b, c ofd als antwoord") print("Yeay je hebt alle vragen gehad! Goed gedaan!") time.sleep(2) break
ea10dd40b0b89330509843c36215aab8859b6cfa
gautamdayal/computational-thinking-club
/dataScienceCourse/week2/problems/nested_loops_ex3.py
233
4.125
4
n = int(input("What is your number? ")) prime = True for factor in range(2, n): if n % factor == 0: prime = False break if prime: print(str(n) + " is a prime!") else: print(str(n) + " is not a prime.")
aa3dee1aa13f690458fc59b9b04f78552d8eb5f7
quantumkisa/python_basics
/6.py
685
3.84375
4
def int_func(my_string): my_list = list(my_string) my_list[0] = my_list[0].upper() my_string = ''.join(my_list) print(my_string) def int_func_2(my_string): my_list = list(my_string) for i in range(len(my_list)): if i == 0: my_list[i] = my_list[i].upper() elif my_list[i] == ' ': my_list[i + 1] = my_list[i + 1].upper() else: continue my_string = ''.join(my_list) print(my_string) my_string = input('ввведите строку с маленькой буквы') my_string_2 = input('ввведите слова через пробел') int_func(my_string) int_func_2(my_string_2)
8c9d174a28fcd5dd07c898459e1b387ad5c6a803
GuilleGG19/PARCIAL1A
/DESCUENTO.py
422
3.875
4
answer=("1") while answer==("1"): answer= input ("Bienvenido, precione 1 para continuar o preciona 2 para salir ") print ("Iniciemos") a = int(answer) if (a == 1): numero= int(input("Escriba un número")) porcentaje = numero * 0.15 resultado= numero - porcentaje print ("Su resultado es ") print (resultado) else: print ("Adios")
33bb4b921dc87a75d4d8b49f8580fb79459d46e5
DKU-STUDY/Algorithm
/programmers/난이도별/level02.짝지어_제거하기/HyeonJeong.py
250
3.578125
4
def solution(s): slist = [s[0]] for x in s[1:]: if slist != [] and x == slist[-1]: slist.pop() continue slist.append(x) return int(slist == []) print(solution("baabaa") == 1, solution("cdcd") == 0)
4b8b29cd738e5258c3931639a37800f90dc249e4
stehrenberg/HomeAutomation
/python_examples/python/demo_exception.py
1,659
4.28125
4
# python exception # see also http://www.tutorialspoint.com/python/python_exceptions.htm from __future__ import print_function, division from time import strftime l = [4,7,5] # list with 3 entries index = 3 # l[index] will raise an exception if index > 2 # handling predefined exceptions try: l[index] = 10 except IndexError, Argument: # KeyError, NameError, ValueError, IOError, ZeroDivisionError, ... #except Exception, Argument: # handling any exception print("IndexError:", Argument) # Argument depends on the type of exception else: print("this block will be executed if there is no exception") finally: print("this block will be executed in any case") # raising exceptions # defining a function that raises an exception def insertList(p_list, p_index, p_value): if p_index > len(p_list)-1: raise IndexError("index too high!!") else: p_list[p_index] = p_value # using the function insertList() try: insertList(l,index,10) except IndexError, Argument: print("IndexError:", Argument) else: print(l) # defining own exceptions class MyException(Exception): # base class Exception def __init__(self,description): self.expr = description def __str__(self): # defines how to convert the description to a string now = strftime("%H:%M:%S") return str(self.expr) + " actual time is " + now # using MyException try: if index > len(l)-1: raise MyException("index too high!!") else: l[index] = 11 except MyException, Argument: print("MyException:", Argument) else: print(l)
f01eff284ea30b9435182341cf6364c72433eaf7
Hausdorffcode/python
/fileRead.py
268
3.921875
4
# -*- coding: cp936 -*- try: filename = raw_input("Enter your file name: ") fobj = open(filename, "r") for eachline in fobj: print eachline, #ÿıѾԴ˻з fobj.close() except IOError, e: print "file open error: ", e
a1446fd759d59326a85e4e6d374ba46de3f516a7
avdata99/programacion-para-no-programadores
/code/01-basics/strings-03.format.py
689
4.21875
4
""" Opciones para concatenar strings con variables """ nombre = 'Pedro' pais = 'Chile' print("Hello world {} de {}!".format(nombre, pais)) # Hello world Pedro de Chile! # valores enumerados print("Valores enumerados. Hello world {0} de {1} ({0}-{1})!".format(nombre, pais)) # Valores enumerados. Hello world Pedro de Chile (Pedro-Chile)! # valores con nombre print("Valores con nombre. Hello world {name} de {country}!".format(name=nombre, country=pais)) # Valores con nombre. Hello world Pedro de Chile! # Estilo C print("Estilo C. Hello world %s de %s !" % (nombre, pais)) # Estilo C. Hello world Pedro de Chile ! # Nueva opcion desde python 3.6 print(f"Hello world {nombre} de {pais}!") # Hello world Pedro de Chile!
e19611286d35bf0bcf296aacd6c02c3ca852dba2
mudambirichard/python
/challenge11.py
198
3.71875
4
def fruit_labeler(thing): if type(thing) == str: return 'apples' elif type(thing) == int: return 'orange' else: return 'banana' print (fruit_labeler('muda'))
87b78d055df8cd5ff12b85faef0e40dba99afd3c
hehlinge42/machine_learning_bootcamp
/day02/ex01/log_loss.py
2,030
3.796875
4
import numpy as np def sigmoid_(x, k=1, x0=0): """ Compute the sigmoid of a scalar or a list. Args: x: a scalar or list Returns: The sigmoid value as a scalar or list. None on any error. Raises: This function should not raise any Exception. """ if isinstance(x, (int, float, list)) == False and type(x) != 'numpy.ndarray': print("Invalid type") return None x = np.asarray(x) return (1 / (1 + np.exp((-k)*(x - x0)))) def log_loss_(y_true, y_pred, m, eps=1e-15): """ Compute the logistic loss value. Args: y_true: a scalar or a list for the correct labels y_pred: a scalar or a list for the predicted labels m: the length of y_true (should also be the length of y_pred) eps: epsilon (default=1e-15) Returns: The logistic loss value as a float. None on any error. Raises: This function should not raise any Exception. """ if isinstance(y_true, (int, float)) == True: y_true = [float(y_true)] if isinstance(y_pred, (int, float)) == True: y_pred = [float(y_pred)] y_true = np.array(y_true) y_pred = np.array(y_pred) if y_true.shape != y_pred.shape or y_true.shape[0] != m: print(y_true.shape) print(y_pred.shape) print(m) return None return ((-1 / m) * (y_true * np.log(y_pred + eps) + (1 - y_true) * np.log(1 - y_pred + eps))).sum() # Test n.1 x = 4 y_true = 1 theta = 0.5 y_pred = sigmoid_(x * theta) m = 1 # length of y_true is 1 print(log_loss_(y_true, y_pred, m)) # 0.12692801104297152 # Test n.2 x = [1, 2, 3, 4] y_true = 0 theta = [-1.5, 2.3, 1.4, 0.7] x_dot_theta = sum([a*b for a, b in zip(x, theta)]) y_pred = sigmoid_(x_dot_theta) m = 1 print(log_loss_(y_true, y_pred, m)) # 10.100041078687479 # Test n.3 x_new = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] y_true = [1, 0, 1] theta = [-1.5, 2.3, 1.4, 0.7] x_dot_theta = [] for i in range(len(x_new)): my_sum = 0 for j in range(len(x_new[i])): my_sum += x_new[i][j] * theta[j] x_dot_theta.append(my_sum) y_pred = sigmoid_(x_dot_theta) m = len(y_true) print(log_loss_(y_true, y_pred, m)) # 7.233346147374828
956f038dbd57bf40766dd1a9571e3697cb91feec
gulyash/AsyaPy
/LR3/LR3_3_Migranova.py
74
3.796875
4
s = 0 for i in range(1, int(input("N: "))+1): s += pow(i, 3) print(s)
c2a10d53abb1d132f79c443566123245f212de0a
faustogomezp/retosciclounomintic2020
/Reto3/tirilla_unaleno.py
1,668
3.859375
4
import math def calcularDescuento(valor_compra): if valor_compra > 150000 and valor_compra <= 300000: porcentaje_descuento = 0.1 elif valor_compra > 300000 and valor_compra <= 700000: porcentaje_descuento = 0.15 else: porcentaje_descuento = 0.2 return valor_compra * porcentaje_descuento def registrarProductos(comando): opcion, producto, cant ,costo_producto = comando.split('&') costo_total=int(cant) * int(costo_producto) return producto, cant, costo_total def impresionTirilla(productos, comando): valor_compra = 0 cliente = comando.split('&')[1] print('Centro Comercial Unaleño') print('Compra más y Gasta Menos') print('NIT: 899.999.063') print(f'Cliente: {cliente}') print('Art Cant Precio') for producto in productos: print(f'{producto[0]} x{producto[1]} ${producto[2]}') valor_compra = valor_compra + producto[2] if valor_compra <= 150000: descuento = 0 else: descuento = float(calcularDescuento(valor_compra)) valor_compra = valor_compra - descuento print(f'Total: ${math.ceil(valor_compra)}') print(f'En esta compra tu descuento fue ${int(descuento)}') print('Gracias por tu compra') print('---') if __name__ == "__main__": comando = input() lista_productos = [] while comando != '3': if comando.split('&')[0] == '1': lista_productos.append(registrarProductos(comando)) elif comando.split('&')[0] == '2': impresionTirilla(lista_productos, comando) lista_productos = [] comando = input() """ impresionTirilla() """
de23c6fb27db3999b8e1fc0c9bd75aee7aa4c717
pramilagm/Data_structure_and_algorithm
/LinkedList/doublyLinkedList/sortedLinkedList.py
1,253
4.125
4
class Node: def __init__(self, data): self.data = data self.next = None class DDL: def __init__(self): self.head = None def sortedInsert(self, new_node): if self.head is None: self.head = new_node self.head.prev = None return elif self.head.data >= new_node.data: new_node.next = self.head new_node.next.prev = new_node self.head = new_node return else: current_node = self.head while current_node.next is not None and current_node.next.data < new_node.data: current_node = current_node.next new_node.next = current_node.next if current_node.next is not None: new_node.next.prev = new_node current_node.next = new_node new_node.prev = current_node def printList(self): prinVal = self.head while prinVal is not None: print(prinVal.data) prinVal = prinVal.next list = DDL() node1 = Node(3) node2 = Node(7) node3 = Node(2) node4 = Node(1) list.sortedInsert(node1) list.sortedInsert(node2) list.sortedInsert(node3) list.sortedInsert(node4) list.printList()
534e8017f88f331c4d6ead6b13ba35708d3dea18
WarrenK-design/Python-GUI-Projects
/useful_code/frames.py
301
3.828125
4
from tkinter import * from PIL import ImageTk,Image root = Tk() root.title('Frames') # Create the frame frame = LabelFrame(root, text="This is my Frame...",padx=5, pady=5) frame.pack(padx=100,pady=100) # Put the button inside of the frame b = Button(frame, text="Click Me") b.pack() root.mainloop()
acafe7d0c1e7acaccb36104070134462d81fd76c
Erick-rick/Python
/Curso em video Python/Aulas/aula9.py
710
3.5625
4
#Manipulação de Texto # # Fatiamento # # frase = 'Curso em Video python' # # frase[9] = V # frase[9:13] = Vide **( não pegando caracter 13, smp um a menos) # frase[9:21:2] = Vdo pto (pulando de 2 em 2) # frase[:5] = Curso (do inicio até o 5) # frase[15:] = python(do 15 ate o final da string) # frase[9::3] = veph (começa do 9 até o final) #Analise # len(frase) > comprimento da frase 21 caracters # frase.count('o') > contar quantas x aparece a letra 'o' na frase # frase.find('deo') > encontra as string 'deo' a posição 11 # frase.find('android') > devolvendo -1 não existe na frase # 'Curso' in frase > Encontra a palavra na frase # #Transformação # frase.replace('Python', 'Android')##
909942004ada2571cdbee2dd2ae1e89342f29506
Ritvik19/CodeBook
/data/HackerRank-Regex/Backreferences To Failed Groups.py
147
3.75
4
import re Regex_Pattern = r"^((\d\d-\d\d-\d\d-\d\d)|(\d{8}))$" # Do not delete 'r'. print(str(bool(re.search(Regex_Pattern, input()))).lower())
de5778b73e7355039476327f416d4eddf14f7ea8
Abdulla-binissa/ColorGame.py
/ColorGame.py
2,414
4
4
import tkinter import random # List of possible colors colors = ['Red', 'Blue', 'Green', 'Pink', 'Black', 'Yellow', 'Orange', 'White', 'Purple', 'Brown'] # Initial player score score = 0 # The game time left, initially 30 seconds timeleft = 30 # Starting game def startGame(event): if timeleft == 30: countdown() # run next color nextColor() # Choose and display next color def nextColor(): # use global variables from above global score global timeleft # If game is in progess if timeleft > 0: # make the text entry box active. e.focus_set() # typed color is correct if e.get().lower() == colors[1].lower(): score += 1 # clear the text box and shuffle colors e.delete(0, tkinter.END) random.shuffle(colors) # change color to type label.config(fg = str(colors[1]), text = str(colors[0])) # update score scoreLabel.config(text = "Score: " + str(score)) # Countdown timer function def countdown(): global timeleft # If game is in progress if timeleft > 0: # decrement the timer timeleft -= 1 # update label timeLabel.config(text = "Time left: " + str(timeleft)) # run every second timeLabel.after(1000, countdown) ###### Driver Code # Create a GUI window root = tkinter.Tk() # Set title and size root.title("ColorGame.py") root.geometry("475x250") # add instructions label instructions = tkinter.Label( root, text = "Type in the COLOR of the words, not the WORD!", font = 'Helvetica 16') instructions.pack() # add score label scoreLabel = tkinter.Label( root, text = "Press enter to start!", font = 'Helvetica 16') scoreLabel.pack() # add a time label timeLabel = tkinter.Label( root, text = "Time left: " + str(timeleft), font = 'Helvetica 16') timeLabel.pack() # add a color display label label = tkinter.Label( root, font = 'Helvetica 60 bold') label.pack() # add text box to type e = tkinter.Entry(root) # run startGame when 'enter' is pressed root.bind('<Return>', startGame) e.pack() # set focus on entry box e.focus_set() # start GUI root.mainloop()
b83c1cd279065226ac7a29c2776a305047dedfb5
hpanwar214/BarCode-Scanner
/Barcode/barcode.py
986
3.765625
4
# Importing library import cv2 from pyzbar.pyzbar import decode # Make one method to decode the barcode code="" def BarcodeReader(): # read the image in numpy array using cv2 img = cv2.imread("Img.jpeg") # Decode the barcode image detectedBarcodes = decode(img) # If not detected then print the message if not detectedBarcodes: print("Barcode Not Detected or your barcode is blank/corrupted!") else: # Traveres through all the detected barcodes in image for barcode in detectedBarcodes: # Locate the barcode position in image (x, y, w, h) = barcode.rect # Put the rectangle in image using # cv2 to heighlight the barcode cv2.rectangle(img, (x-10, y-10), (x + w+10, y + h+10), (255, 0, 0), 2) if barcode.data!="": # Print the barcode data print(barcode.data) print(barcode.type) return barcode.data #Display the image cv2.imshow("Image", img) cv2.waitKey(0) cv2.destroyAllWindows()
5d0a9353ce9d688b65b1fa0d0da824c1ed7f1afa
sourabbanka22/Competitive-Programming-Foundation
/Recursion/interweavingStrings_1.py
988
4
4
def interweavingStrings(one, two, three): # Write your code here. if len(three) != len(one) + len(two): return False return interweavingStringsUtil(0, 0, one, two, three) def interweavingStringsUtil(idxOne, idxTwo, one, two, three): #print("One: "+ one[:idxOne+1] + " Two: "+ two[:idxTwo+1]) idxThree = idxOne + idxTwo if idxThree == len(three): return True if idxOne<len(one) and one[idxOne] == three[idxThree]: if interweavingStringsUtil(idxOne+1, idxTwo, one, two, three): return True if idxTwo<len(two) and two[idxTwo] == three[idxThree]: return interweavingStringsUtil(idxOne, idxTwo+1, one, two, three) return False # print(interweavingStrings("algoexpert", "your-dream-job", "your-algodream-expertjob")) # print(interweavingStrings("aabcc", "dbbca", "aadbbcbcac")) #print(interweavingStrings("aaa", "aaab", "aaabaaa")) print(interweavingStrings("aaab", "aaaaa", "aaaaaaaab"))
f1c083057f5982df6f8b383ddf35032558fd546f
gxsgxs/1808
/08.day/02.奇偶数.py
115
4
4
while True: num = int(input("请输入一个数")) if num%2==0: print("是偶数") else: print("是奇数")
641de9a35aec6637c58174efde6d760ad9284e45
Jagerheat/Introduce
/Introduce-master/Py_Project/Lesson_2/proj_2.py
78
3.546875
4
s1 = "Corovan" s2 = "Vorona" s = s2.replace("Corovan", "Vorona") print(s)
d2367c36f4ab030a729bbfb8b958be27aaeacfd1
drdhaval2785/sumgenerator
/sumgenerator.py
6,086
4.0625
4
import random import sys from datetime import datetime def date_time(): """Generate datetime in string.""" return datetime.now().strftime("%d%m%Y_%H%M%S") def num_to_str(numList): """Generate string from list of numbers.""" result = '' for num in numList: result += str(num) return result def create_sum(length, n, take='take'): """Generate <n> sums of digits <length>.""" result = [] # Generate n sums. for j in range(n): first = [] second = [] # Generate a random number of <length> digits. for i in range(length): first.append(random.randint(0,9)) # Generate a random number of <length> digits. for dig in first: # If take / carry is allowed, second number is purely random. if take == 'take': second.append(random.randint(0,9)) # If take / carry is not allowed, second number is restricted so that its addition does not cross 9. else: second.append(random.randint(0,9-dig)) # Convert from list of numbers to strings. dig1 = num_to_str(first) dig2 = num_to_str(second) # Append to the result. result.append((dig1, dig2)) # Return the result. return result def create_subtraction(length, n, take=True): """Generate <n> subtraction of <length> digits.""" result = [] # Generate n sums. for j in range(n): first = [] second = [] # Random number of <length> digits. for i in range(length): # if the first digit, it can be from 1 to 9 if i == 0: first.append(random.randint(1,9)) else: first.append(random.randint(0,9)) # Random number of <length> digits. for x in range(len(first)): dig = first[x] # The first digit of second number is to remain less than the first digit of the first number, so that the result is not negative. if x == 0: second.append(random.randint(0,dig-1)) # If take / carry is allowed, the second number is random. elif take == 'take': second.append(random.randint(0,9)) # otherwise the second number is less than the first one. else: second.append(random.randint(0,dig)) # Generate digits from list of numbers. dig1 = num_to_str(first) dig2 = num_to_str(second) # Append to the result. result.append((dig1, dig2)) # Return result. return result def create_multiplication(length, n): """Generate <n> multiplication of upto <length> digits.""" result = [] # Generate n sums. for j in range(n): first = [] second = [] # Random number of <length> digits. for i in range(length): # if the first digit, it can be from 1 to 9 if i == 0: first.append(random.randint(1,9)) else: first.append(random.randint(0,9)) # Random number of <length> digits. for x in range(length): second.append(random.randint(0,9)) # Generate digits from list of numbers. dig1 = num_to_str(first) dig2 = num_to_str(second) # Append to the result. result.append((dig1, dig2)) # Return result. return result def pretty_sum(digitTuples, arithmaticOperator, dttm, sumsInARow=5, writeAnswer=False): """Pretty print the sums in html. Show <sumsInARow> sums on a line. """ # If Answers are to be printed (for parents / teachers), append ans to the filename. if writeAnswer: fout = open('math_ans_'+dttm+'.html', 'w') # Otherwise for kids, append que to filename. else: fout = open('math_que_'+dttm+'.html', 'w') # Generic HTML and CSS starting. fout.write('<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta charset="utf-8"/>\n<title>\nMath sum generator</title>\n<style>\ntable, td { border: 2px solid black; padding: 10px; font-size: 35px;}\n td { text-align: right; }\n</style>\n</head>\n<body>\n<table>\n') # Initialize counter counter = 0 # a and b are the numbers for (a, b) in digit_tuples: # At every sumsInARow, insert a new table row. if counter % sumsInARow == 0: startCounter = counter fout.write('<tr>\n') # Generate Sum. summ = '<td>' summ += '<br>' + a + '<br/>' summ += arithmaticOperator + ' ' + b + '<br/>' summ += '----------' + '<br/>' # If answer is to be written, do sum actually and print. if writeAnswer: if arithmaticOperator == '+': summ += str(int(a) + int(b)) + '<br/>' elif arithmaticOperator == '-': summ += str(int(a) - int(b)) + '<br/>' elif arithmaticOperator in ['x', 'X']: summ += str(int(a) * int(b)) + '<br/>' # Else leave a blank line. else: summ += '<br/>' if arithmaticOperator in ['x', 'X']: summ += '<br/>' * (len(b)-1) # Close the td. summ += '</td>' # Write summ to the file. fout.write(summ) # Close the row at specified interval i.e. <sumsInARow>. if counter - startCounter == sumsInARow - 1: fout.write('\n</tr>\n') # Increment counter. counter += 1 # Close HTML. fout.write('</table>\n</body>\n</html>') if __name__ == "__main__": # Operation can be + or - operation = sys.argv[1] # how many digits in the number? digits = int(sys.argv[2]) # Default sums to generate are 20. if len(sys.argv) > 3: sumsToGenerate = int(sys.argv[3]) else: sumsToGenerate = 20 # Default is to allow take / carry. # If there is specific mention of 'notake', take / carry is not allowed. if len(sys.argv) > 4: take = sys.argv[4] else: take = 'take' # Date time in string format. dttm = date_time() # If addition, if operation == '+': # Create sums digit_tuples = create_sum(digits, sumsToGenerate, take) # Write without answers to HTML. pretty_sum(digit_tuples, '+', dttm) # Write with answers to HTML. pretty_sum(digit_tuples, '+', dttm, writeAnswer=True) # If subtraction, elif operation == '-': # Create sums. digit_tuples = create_subtraction(digits, sumsToGenerate, take) # Write without answers to HTML. pretty_sum(digit_tuples, '-', dttm) # Write with answers to HTML. pretty_sum(digit_tuples, '-', dttm, writeAnswer=True) # If multiplication, elif operation in ['x', 'X', '*']: # Create sums. digit_tuples = create_multiplication(digits, sumsToGenerate) # Write without answers to HTML. pretty_sum(digit_tuples, 'X', dttm) # Write with answers to HTML. pretty_sum(digit_tuples, 'X', dttm, writeAnswer=True)
69133d3b848ad915ad25f0dae49d7c71ac0be0b9
shhuan/algorithms
/py/common/QuickSort.py
3,943
4.125
4
# -*- coding: utf-8 -*- """ created by huash06 at 2015-05-04 16:04 """ __author__ = 'huash06' import sys import os import datetime import functools import itertools import collections import random def qsort(arr): if len(arr) <= 1: return arr else: pivot = arr[0] return qsort([x for x in arr[1:] if x < pivot]) + \ [pivot] + \ qsort([x for x in arr[1:] if x >= pivot]) def quickSort(nums, left, right): """ Improvements: 1. Cutoff to insertion sort. As with mergesort, it pays to switch to insertion sort for tiny arrays. The optimum value of the cutoff is system-dependent, but any value between 5 and 15 is likely to work well in most situations. 2. Median-of-three partitioning. A second easy way to improve the performance of quicksort is to use the median of a small sample of items taken from the array as the partitioning item. Doing so will give a slightly better partition, but at the cost of computing the median. It turns out that most of the available improvement comes from choosing a sample of size 3 (and then partitioning on the middle item). :param nums: :param left: :param right: :return: """ if left >= right: return index = partition(nums, left, right) quickSort(nums, left, index-1) quickSort(nums, index, right) return [] def partition(nums, left, right): i, j = left, right pivotId = random.randint(left, right) nums[pivotId], nums[0] = nums[0], nums[pivotId] pivot = nums[left] while i <= j: while i <= j and nums[i] < pivot: i += 1 while i <= j and nums[j] > pivot: j -= 1 if i <= j: nums[i], nums[j] = nums[j], nums[i] # 注意交换后改变i和j,否则可能死循环 i += 1 j -= 1 return i def quickSort_3Way(nums, left, right): """ Entropy-optimal sorting. Arrays with large numbers of duplicate sort keys arise frequently in applications. In such applications, there is potential to reduce the time of the sort from linearithmic to linear. One straightforward idea is to partition the array into three parts, one each for items with keys smaller than, equal to, and larger than the partitioning item's key. Accomplishing this partitioning was a classical programming exercise popularized by E. W. Dijkstra as the Dutch National Flag problem, because it is like sorting an array with three possible key values, which might correspond to the three colors on the flag. Dijkstra's solution is based on a single left-to-right pass through the array that maintains a pointer lt such that a[lo..lt-1] is less than v, a pointer gt such that a[gt+1..hi] is greater than v, and a pointer i such that a[lt..i-1] are equal to v, and a[i..gt] are not yet examined. Starting with i equal to lo we process a[i] using the 3-way compare given us by the Comparable interface to handle the three possible cases: a[i] less than v: exchange a[lt] with a[i] and increment both lt and i a[i] greater than v: exchange a[i] with a[gt] and decrement gt a[i] equal to v: increment i :param nums: :param left: :param right: :return: """ if left >= right: return lt = left gt = right v = nums[lt] i = lt while i <= gt: if nums[i] < v: nums[lt], nums[i] = nums[i], nums[lt] i += 1 lt += 1 elif nums[i] > v: nums[i], nums[gt] = nums[gt], nums[i] gt -= 1 else: i += 1 quickSort_3Way(nums, left, lt-1) quickSort_3Way(nums, gt+1, right) nums = [1, 12, 5, 26, 7, 14, 3, 7, 2] quickSort(nums, 0, len(nums)-1) print(nums) nums = [1, 12, 5, 26, 7, 14, 3, 7, 2] quickSort_3Way(nums, 0, len(nums)-1) print(nums)
65586585c5d70e5961a1fff56040a7a1fed19f17
PedroPenaUSF/3DPrintedStatues
/main.py
432
3.625
4
# Step 1 receive input as integer n, which equals amount statues needed. import math statueNeeded = int(input()) day = 5 statueMax = 16 if statueNeeded < 5: day = statueNeeded if statueNeeded == 4: day = 3 if 5 <= statueNeeded <= 7: day = 4 if statueNeeded >= 8: while math.log2(statueNeeded) > math.log2(statueMax): previousMax = statueMax statueMax = previousMax * 2 day += 1 print(day)
6982a8df70d07c7c68bc80b95dae8c4ea3b1eb7c
z1z22/mypython
/inputdigit.py
300
3.921875
4
def inputdigit(input_str): '''输入数字''' while True: i_str = input(input_str) if i_str.isdigit(): return int(i_str) break elif i_str == 'q' or i_str == 'Q': exit() else: print("Please input digit('Q'uit).")
e083b5deb54e3110eb7f20a890648314c9603ff5
Gnbmario/proyecto
/15_clases.py
772
4.25
4
""" Trabajando con clases y POO (programación orientada a objetos) """ class Thing: pass thing = Thing() class Fruit: def __init__(self): print('objeto fruta iniciado') fruit = Fruit() # argumentos del constructor class Person: """ Estas es la documentación de la clase Person """ COUNTER = 0 def __init__(self, name): self.name = name self.knowledges = [] Person.COUNTER +=1 def __str__(self): return 'Me llamo {} y se: {}'.format(self.name, self.knowledges) def learn(self,what): self.knowledges.append(what) p1 = Person('Mario') p2 = Person('Mary') p3 = Person('David') p1.learn('python') p2.learn('javascript') p3.learn('c#') print(p1) print(p2) print(p3) print(Person.COUNTER)
d44e196e2b5c62adaccfc6f05fbdc636ac3fd8dd
silverwolf2r/book
/bookpdf.py
12,293
3.5625
4
#basically want to have a list of websites and we will google search for a book on these websites. #The search would be title site:onlinereadfreenovel.com from googlesearch import search import requests from bs4 import BeautifulSoup import re import isbnlib import fpdf #---------------------------------------------------- #Finding the book title #---------------------------------------------------- gtitle = input("What is the Title of the Book: ") author = input("Authors Name: ") book = isbnlib.goom(gtitle + ' ' + author) isbn1 = book[0] isbn = str(isbn1) # I want the first 28 characters of str isbn isbn = isbn[13:26] book = isbnlib.meta(isbn) title = book['Title'] author = book['Authors'] print('\n') print('\n') print('Title: ' + str(title) + '\n' + 'Author: ' + str(author)) print('\n ISBN: ' + isbn) #---------------------------------------------------- #Formulate the google query and results #---------------------------------------------------- resultinglinks = [] searching = str(title) + ' "Page 1" site:' x = 0 links = ["onlinereadfreenovel.com", "readonlinefreenovel.com", "novel80.com", "thefreeonlinenovel.com", "readonlinefreebook.com", "lovefreenovels.com", "novel122.com", "www.topbooks2019.com" ] for link in links: query = searching + link result = search(query , num_results=0) resultinglinks.append(result) for results in resultinglinks: x = x + 1 linkresults = str(x) + " " + str(results) print(linkresults) #--------------------------------------------------- #Use the chosen link to download #--------------------------------------------------- chosenlink = input("Which link would you like to download? (enter in a number) ") chosenlink = int(chosenlink) - 1 link = (resultinglinks[chosenlink]) link = str(link).replace("'","") link = str(link).replace("[","") link = str(link).replace("]","") #for each link I need to format a way to download it from that link no matter how odd the link is #DOWNLOAD INFORMATION FOR EACH LINK RIGHT NOW #link1 onlinereadfreenovel.com #-------------------------------------------------textid, Page_next if chosenlink == 0: textid = "textToRead" Nextpage = "page_next" #prep a document for the book to be written too tity = ''.join(filter(str.isalpha, title)) f = open( str(tity) + ".txt", "w") f.write("HERE IS YOUR BOOK: ") f.close() #set for how many iterations this will run for tfoncode = int(200) x = 0 while x < tfoncode + 1: x = x + 1 #Get the html from the webpage res = requests.get(link) text = res.text # Take the text and parses the html out so that it is easy to read soup = BeautifulSoup(text, 'html.parser') title = soup.title.string akt = soup.find(id=textid) text = akt.text #Write the page to the document startpage = int(x) final_product = (str(title) + str(text) ) fp = final_product # tfontext requires parsing everytime f = open( str(tity) + ".txt", "a") # write page to the document f.write(fp) f.close() print(startpage ,"/",tfoncode ) startpage = startpage + 1 #get the next url rinse and repeat for links in soup.find_all(Nextpage,href=True): print(links) link = links #link2 readonlinefreenovel.com #-------------------------------------------------search by classs=content, next-page elif chosenlink == 1: textid = "p" Nextpage = "next-page" #prep a document for the book to be written too tity = ''.join(filter(str.isalpha, title)) f = open( str(tity) + ".txt", "w") f.write("HERE IS YOUR BOOK: ") f.close() #set for how many iterations this will run for tfoncode = int(200) x = 0 while x < tfoncode + 1: x = x + 1 #Get the html from the webpage res = requests.get(link) text = res.text # Take the text and parses the html out so that it is easy to read soup = BeautifulSoup(text, 'html.parser') title = soup.title.string akt = soup.find("div", class_="content") text = akt.text #Write the page to the document startpage = int(x) final_product = (str(title) + str(text) ) fp = final_product # tfontext requires parsing everytime f = open( str(tity) + ".txt", "a") # write page to the document f.write(fp) f.close() print(startpage ,"/",tfoncode ) startpage = startpage + 1 #get the next url rinse and repeat for links in soup.find_all(Nextpage,href=True): print(links) link = links #link3 novel80.com #-------------------------------------------------search by chapter-content, search for Next page elif chosenlink == 2: textid = "p" Nextpage = "Next Page" #prep a document for the book to be written too tity = ''.join(filter(str.isalpha, title)) f = open( str(tity) + ".txt", "w") f.write("HERE IS YOUR BOOK: ") f.close() #set for how many iterations this will run for tfoncode = int(200) x = 0 while x < tfoncode + 1: x = x + 1 #Get the html from the webpage res = requests.get(link) text = res.text # Take the text and parses the html out so that it is easy to read soup = BeautifulSoup(text, 'html.parser') title = soup.title.string akt = soup.find("div", class_="chapter-content") text = akt.text #Write the page to the document startpage = int(x) final_product = (str(title) + str(text) ) fp = final_product # tfontext requires parsing everytime f = open( str(tity) + ".txt", "a") # write page to the document f.write(fp) f.close() print(startpage ,"/",tfoncode ) startpage = startpage + 1 #get the next url rinse and repeat for links in soup.find_all(Nextpage,href=True): print(links) link = links #link4 thefreeonlinenovel.com #Needs Revision #-------------------------------------------------textid <td>, linksy elif chosenlink == 3: textid = "td" Nextpage = "Next Page" print('This link needs revision and will most likely break. Feel free to try but eh...') #prep a document for the book to be written too tity = ''.join(filter(str.isalpha, title)) f = open( str(tity) + ".txt", "w") f.write("HERE IS YOUR BOOK: ") f.close() #set for how many iterations this will run for tfoncode = int(200) x = 0 linksyl = link linksy = (linksyl[-1]) linksy = linksyl.replace(linksy, "") while x < tfoncode + 1: x = x + 1 #Get the html from the webpage res = requests.get(link) text = res.text # Take the text and parses the html out so that it is easy to read soup = BeautifulSoup(text, 'html.parser') title = soup.title.string akt = soup.find(textid) text = akt.text #Write the page to the document startpage = int(x) final_product = (str(title) + str(text) ) fp = final_product # tfontext requires parsing everytime f = open( str(tity) + ".txt", "a") # write page to the document f.write(fp) f.close() print(startpage ,"/",tfoncode ) startpage = startpage + 1 #get the next url rinse and repeat link = str(linksy) + str(x) #link5 readonlinefreebook.com #-------------------------------------------------search for class content_novel, search for class of nextpage elif chosenlink == 4: textid = "p" res = requests.get(link) text = res.text soup = BeautifulSoup(text, 'html.parser') Nextpage = soup.find_all("div", class_="fa fa-angle-right") #prep a document for the book to be written too tity = ''.join(filter(str.isalpha, title)) f = open( str(tity) + ".txt", "w") f.write("HERE IS YOUR BOOK: ") f.close() #set for how many iterations this will run for tfoncode = int(200) x = 0 while x < tfoncode + 1: x = x + 1 #Get the html from the webpage res = requests.get(link) text = res.text # Take the text and parses the html out so that it is easy to read soup = BeautifulSoup(text, 'html.parser') title = soup.title.string akt = soup.find("div", class_="content_novel") text = akt.text #Write the page to the document startpage = int(x) final_product = (str(title) + str(text) ) fp = final_product # tfontext requires parsing everytime f = open( str(tity) + ".txt", "a") # write page to the document f.write(fp) f.close() print(startpage ,"/",tfoncode ) startpage = startpage + 1 #get the next url rinse and repeat for links in Nextpage: print(links) link = links #link6 lovefreenovels.com #-------------------------------------------------search for text class, search for text elif chosenlink == 5: textid = "text" Nextpage = "Next" #prep a document for the book to be written too tity = ''.join(filter(str.isalpha, title)) f = open( str(tity) + ".txt", "w") f.write("HERE IS YOUR BOOK: ") f.close() #set for how many iterations this will run for tfoncode = int(200) x = 0 while x < tfoncode + 1: x = x + 1 #Get the html from the webpage res = requests.get(link) text = res.text # Take the text and parses the html out so that it is easy to read soup = BeautifulSoup(text, 'html.parser') title = soup.title.string akt = soup.find("div", class_="text") text = akt.text #Write the page to the document startpage = int(x) final_product = (str(title) + str(text) ) fp = final_product # tfontext requires parsing everytime f = open( str(tity) + ".txt", "a") # write page to the document f.write(fp) f.close() print(startpage ,"/",tfoncode ) startpage = startpage + 1 #get the next url rinse and repeat for links in soup.find_all(Nextpage,href=True): print(links) link = links #link7 novel122.com #-------------------------------------------------search by classs=chapter-content-p, search by class btn-blue elif chosenlink == 6: textid = "btn-blue" res = requests.get(link) text = res.text soup = BeautifulSoup(text, 'html.parser') Nextpage = soup.find_all("div", class_="next-page") #prep a document for the book to be written too tity = ''.join(filter(str.isalpha, title)) f = open( str(tity) + ".txt", "w") f.write("HERE IS YOUR BOOK: ") f.close() #set for how many iterations this will run for tfoncode = int(200) x = 0 while x < tfoncode + 1: x = x + 1 #Get the html from the webpage res = requests.get(link) text = res.text # Take the text and parses the html out so that it is easy to read soup = BeautifulSoup(text, 'html.parser') title = soup.title.string akt = soup.find("div", class_="chapter-content-p") text = akt.text #Write the page to the document startpage = int(x) final_product = (str(title) + str(text) ) fp = final_product # tfontext requires parsing everytime f = open( str(tity) + ".txt", "a") # write page to the document f.write(fp) f.close() print(startpage ,"/",tfoncode ) startpage = startpage + 1 #get the next url rinse and repeat for links in Nextpage: print(links) link = links #link8 www.topbooks2019.com #-------------------------------------------------textid <p>, linksy elif chosenlink == 7: textid = "p" Nextpage = "Next" #prep a document for the book to be written too tity = ''.join(filter(str.isalpha, title)) f = open( str(tity) + ".txt", "w") f.write("HERE IS YOUR BOOK: ") f.close() #set for how many iterations this will run for tfoncode = int(200) x = 0 linksy = link while x < tfoncode + 1: x = x + 1 #Get the html from the webpage res = requests.get(link) text = res.text # Take the text and parses the html out so that it is easy to read soup = BeautifulSoup(text, 'html.parser') title = soup.title.string akt = soup.find("div", class_="main") text = akt.text #Write the page to the document startpage = int(x) final_product = (str(title) + str(text) ) fp = final_product # tfontext requires parsing everytime f = open( str(tity) + ".txt", "a") # write page to the document f.write(fp) f.close() print(startpage ,"/",tfoncode ) startpage = startpage + 1 #get the next url rinse and repeat link = str(linksy) + "index_" + str(startpage) + ".html" pdf = fpdf.FPDF(format='letter') # Read text file name = (str(tity) + ".txt") with open(name, 'r', encoding='utf-8') as f: txt = f.read() #txt = txt.encode('latin-1', 'replace').decode('latin-1') pdf.add_page() pdf.add_font('DejaVu', '', 'DejaVuSansCondensed.ttf', uni=True) pdf.set_font('DejaVu', '', 12) pdf.multi_cell(0, 5, txt,0,'R') pdf.ln() pdf.cell(0, 5, 'End') pdf.output(str(tity) + ".pdf")
de3abff12ccd40a6769365aeec02314736e55595
sebastians22/COOP2018
/Chapter 3/U03_Ex11_Natural_Numbers.py
1,232
4.34375
4
# U03_Ex11_Natural_Numbers.py # # Author: Sebastian Schaefer # Course: Coding for OOP # Section: A2 # Date: 05 Oct 2018 # IDE: PyCharm # # Assignment Info # Exercise: 11 # Source: Python Programming # Chapter: 3 # # Program Description # This program will find the sum of natural numbers with natural numbers be a user input # # Algorithm (pseudocode) # Print Intro # Eval Input how many times the user wants to print a natural number # Eval Input a natural number # Print all the natural numbers # Print the sum of all the natural numbers # def main(): # Print Intro print("This program will find the sum of natural numbers with natural numbers ") # Eval Input how many times the user wants to print a natural number x = eval(input("How many times would you like to print the program? ")) # Eval Input a natural number y = eval(input("What natural number would you like to print? ")) # Print all the natural numbers for x in range(x): y = (y + 1) # Print the sum of all the natural numbers print("The natural numbers that you have are") for x in range(x): print(y + 1) print("The sum of all of your natural number's is", y) main()
8b96fa8722c030ec974935b2505dcf80429ffcdc
ShanSenanayake/advent_of_code_2020
/src/day_3.py
2,336
3.546875
4
import sys from typing import List def part_one(tree_chart: List[List[bool]], slope) -> int: x_step, y_step = slope x = x_step y = y_step nbr_of_trees = 0 for i in range(len(tree_chart)): if i != y: continue nbr_of_trees = nbr_of_trees + 1 if tree_chart[y][x] else nbr_of_trees x = (x + x_step) % len(tree_chart[i]) y += y_step return nbr_of_trees def parse_lines(lines: List[str]) -> List[List[bool]]: tree_chart = [] for index, line in enumerate(lines): tree_chart.append([x == "#" for x in line.rstrip()]) return tree_chart def test_part_one(): print("testing part one") tree_chart_string = """..##....... #...#...#.. .#....#..#. ..#.#...#.# .#...##..#. ..#.##..... .#.#.#....# .#........# #.##...#... #...##....# .#..#...#.#""" result = part_one(parse_lines(tree_chart_string.split("\n")), (3, 1)) if result == 7: print(" passed") else: print(" failed") def test_part_two(): print("testing part two") tree_chart_string = """..##....... #...#...#.. .#....#..#. ..#.#...#.# .#...##..#. ..#.##..... .#.#.#....# .#........# #.##...#... #...##....# .#..#...#.#""" tree_chart = parse_lines(tree_chart_string.split("\n")) result = part_one(tree_chart, (1, 1)) result *= part_one(tree_chart, (3, 1)) result *= part_one(tree_chart, (5, 1)) result *= part_one(tree_chart, (7, 1)) result *= part_one(tree_chart, (1, 2)) if result == 336: print(" passed") else: print(" failed") def parse_input() -> List[List[bool]]: with open("inputs/day_3_part_1.txt", "r") as fp: return parse_lines(fp.readlines()) def part_two(tree_chart: List[List[bool]]): result = part_one(tree_chart, (1, 1)) result *= part_one(tree_chart, (3, 1)) result *= part_one(tree_chart, (5, 1)) result *= part_one(tree_chart, (7, 1)) result *= part_one(tree_chart, (1, 2)) return result if __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] == "test": test_part_one() test_part_two() else: tree_chart = parse_input() result = part_one(tree_chart, (3, 1)) print("Part 1 result: {}".format(result)) result = part_two(tree_chart) print("Part 2 result: {}".format(result))
138f096af1bbf59cddc37f5b3225731434f20e71
mrisoli/eulerian
/python/problem64.py
320
3.625
4
from math import sqrt def odd(n): a,b = int(sqrt(n)), int(sqrt(n)) m,d,p = 0.0,1.0,0 if a != sqrt(n): while b != 2 * a: m = d * b - m d = (n - m ** 2) / d b = int((a + m) / d) p += 1 return p % 2 == 1 print(len(list(filter(odd, range(10_001)))))
2b1d9d040d0cd1ef5478ad23fdd5804a87b78007
bbli/CS156-Code
/Weight-Decay-Regularization/WeightDecay.py
2,039
3.78125
4
import numpy as np import pandas as pd def datapoints_f(path): ''' This function takes the raw data and changes it into a numpy array and a result_vector, with the array's columns being each datapoint. Assumes path is a string ''' df=pd.read_csv(path,delim_whitespace=True,names=['x','y','result']) data=df.as_matrix() datapoints=data[:,0:2] result_vector=data[:,2] return datapoints,result_vector ########################################################### def input_matrix_f(datapoints): ''' Returns the transformed inputs. Assumes transformed space is 8 dimensional. Also assumes the datapoints' columns are each point in R^2 ''' # Seperating out the x and y values transpose=datapoints.T x1=transpose[0] x2=transpose[1] # Creating the output matrix datapoints_dimensions,datapoints_number=transpose.shape input_matrix=np.ones((8,datapoints_number)) input_matrix[0]=1 input_matrix[1]=x1 input_matrix[2]=x2 input_matrix[3]=x1**2 input_matrix[4]=x2**2 input_matrix[5]=x1*x2 input_matrix[6]=np.abs(x1-x2) input_matrix[7]=np.abs(x1+x2) return input_matrix.T ################################################################# def LinReg_weight_vector_f(input_matrix, result_vector): ''' This function computes the linear regression vector. Assumes rows are different vectors and columns is the dimension of the vector ''' transpose=input_matrix.T inverse_part=np.linalg.inv(np.dot(transpose,input_matrix)) pseudo_inverse=np.dot(inverse_part,transpose) return np.dot(pseudo_inverse,result_vector) ################################################################ def squared_error_f(weight_vector, datapoints, result_vector): ''' This function returns the squared error ''' pred_vector=np.dot(datapoints,weight_vector) norm_vector=np.subtract(pred_vector,result_vector) norm=np.linalg.norm(norm_vector) samples_size=len(result_vector) return (norm**2)/samples_size
e28a7a2eaa4573528d748cc67a6503124f3926b6
alanmaranto/Basico-Algoritmos
/arte5.py
166
3.625
4
import turtle myWindow = turtle.Screen() turtle.speed(2) for i in range(100): turtle.circle(5*i) turtle.circle(-5) turtle.left(i) turtle.exitonclick()
bd7e35dfcb70d3f05862140946cf8197b55ffa16
ismuch/Exos_Andrew
/Exos_td/TD2/exo1_td2.py
139
3.734375
4
a = 0 b = 0 c = 0 d = 0 a = int(input("entrez un entier")) b = int(input("entrez un autre entier")) c = a / b d = a % b print(a, b, c, d)
4cc66b8d8fde8c0e692eeae9c21e1b1cfbdf22f8
shaversj/100-days-of-code
/days/28/program.py
1,822
3.640625
4
import os import csv from data_types import Purchase import statistics def main(): print_header() filename = get_data_file() data = load_file(filename) query_data(data) def print_header(): print('---------------------------------') print(' Real Estate Data Mining App ') print('---------------------------------') print() def get_data_file(): base_folder = os.path.dirname(__file__) return os.path.join(base_folder, 'data', 'SacramentoRealEstateTransactions2008.csv') def load_file(filename): with open(filename, 'r', encoding='utf-8') as fin: reader = csv.DictReader(fin) purchases = [] for row in reader: # p = Purchase() # Creating a static method removes the need to use self and initialize the Class. # Representing the data in a class gives you the ability to make it easier to work with the data. p = Purchase.create_from_dict(row) purchases.append(p) # print(purchases[0].__dict__) return purchases def get_price(z): return z.price def query_data(data): # if data was sorted by price data.sort(key=get_price) # most expensive house? high_purchase = data[-1] print(high_purchase.price) # least expensive house? low_purchase = data[0] print(low_purchase.price) # average price house? ...Using 'statistics'. prices = [] for pur in data: prices.append(pur.price) avg_price = statistics.mean(prices) print(int(avg_price)) # average price of 2 bedroom houses? prices = [] for pur in data: if pur.beds == 2: prices.append(pur.price) avg_two_bedroom_price = statistics.mean(prices) print(int(avg_two_bedroom_price)) main()
1e99fe872196ff5736016980e684f353ba188f2e
jcohenp/DI_Exercises
/W4/D1/ninja/ex_2/ex_1.py
1,580
4.28125
4
# Exercise 1 # Your job is to automate some reports for a carpool application. # On your app, 100 cars are available, every car can accept 4 passengers and a driver, and there will always be more cars than drivers. # Today, there is: # 30 drivers. # 90 passengers waiting for a carpool. # Your report needs to contain: # The number of cars available on your app. # The number of drivers registered on your app. # The number of empty cars today. # The number of passengers that can be transported today. # The average of passengers to put in each car. # Tip: Use python to generate it. #available data num_drivers = 30 num_passengers = 90 num_max_passengers_per_car = 4 num_cars_available = 100 if num_passengers is not None: # report Head: print(f"Cars Available: {num_cars_available}") print(f"Passengers: {num_passengers}") print(f"Drivers Available {num_drivers}") #passengers per car if (num_passengers // 4) < num_drivers: num_required_cars = num_passengers // 4 num_average_passengers = num_passengers / 4 print(f"Average passengers per Car: {num_average_passengers}") print(f"Required cars: {num_required_cars}") if num_required_cars < num_average_passengers: num_spaces_left_in_used_car = (num_average_passengers - num_required_cars)*4 print(f"Spaces left in used car: {num_spaces_left_in_used_car}") else: error = -1 error_msg = "couldn't find number of passengers - we are out of business" print(f"Error {error}, {error_msg}")