blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
155a6195c974de35a6de43dffe7f1d2065d40787
IsaacMarovitz/ComputerSciencePython
/Conversation2.py
1,358
4.15625
4
# Python Homework 09/09/2020 # Inital grade 2/2 # Inital file Conversation.py # Modified version after inital submisions, with error handeling and datetime year # Importing the datetime module so that the value for the year later in the program isn't hardcoded import datetime def userAge(): global user_age user_age = int(input("How old are you? (Please only input numbers) ")) print("\nHey there!", end=" ") user_name = input("What's your name? ") print("Nice to meet you " + user_name) user_age_input_recieved = False while (user_age_input_recieved == False): try: userAge() user_age_input_recieved = True except ValueError: print("Invalid Input") user_age_input_recieved = False # I got this datetime solution from StackOverflow # https://stackoverflow.com/questions/30071886/how-to-get-current-time-in-python-and-break-up-into-year-month-day-hour-minu print("So, you were born in " + str((datetime.datetime.now().year-user_age)) + "!") user_colour = input("What's your favourite colour? ") if user_colour.lower() == "blue": print("Hey, my favourite is blue too!") else: print(user_colour.lower().capitalize() + "'s a pretty colour! But my favourite is blue") print("Goodbye!") input("Press ENTER to exit") # On my honor, I have neither given nor received unauthorized aid # Isaac Marovitz
bf00b432183b7c83bed5de8f1f78ce59322e1889
IsaacMarovitz/ComputerSciencePython
/Minesweeper.py
10,535
3.59375
4
# Isaac Marovitz - Python Homework 02/10/20 # Sources: N/A # Blah blah blah # On my honour, I have neither given nor received unauthorised aid import sys, random, os, time # Declaring needed arrays mineGrid = [] gameGrid = [] # Clear the terminal def clear(): if os.name == "nt": os.system('cls') else: os.system("clear") # Returns all items surrounding an item in a given array def checkSurrounding(givenArray, x, y): returnArray = [] height = len(givenArray) - 1 width = len(givenArray[0]) - 1 if y < height and x > 0: returnArray.append((givenArray[y+1][x-1], y+1, x-1)) if y < height: returnArray.append((givenArray[y+1][x], y+1, x)) if y < height and x < width: returnArray.append((givenArray[y+1][x+1], y+1, x+1)) if x > 0: returnArray.append((givenArray[y][x-1], y, x-1)) if x < width: returnArray.append((givenArray[y][x+1], y, x+1)) if y > 0 and x > 0: returnArray.append((givenArray[y-1][x-1], y-1, x-1)) if y > 0: returnArray.append((givenArray[y-1][x], y-1, x)) if y > 0 and x < width: returnArray.append((givenArray[y-1][x+1], y-1, x+1)) return returnArray # Creates the mineGrid, which is the solved version of the grid that the user doesnt see def createMineGrid(startX, startY): # Create 2D Array if given width and height for _ in range(0, height): tempWidthGrid = [0 for x in range(width)] mineGrid.append(tempWidthGrid) # Place mines in the grid until the mine count equals total mine count totalMineCount = 0 while totalMineCount < mineCount: xPosition = random.randint(0, width-1) yPosition = random.randint(0, height-1) if mineGrid[yPosition][xPosition] != '*': if startX != xPosition and startY != yPosition: mineGrid[yPosition][xPosition] = '*' totalMineCount = totalMineCount + 1 # Sets all the numbers in the grid to the number of mines surrounding that point for y in range(0, height): for x in range(0, width): if mineGrid[y][x] != '*': surroundingMineCount = 0 checkArray = checkSurrounding(mineGrid, x, y) for value in checkArray: if value[0] == '*': surroundingMineCount += 1 mineGrid[y][x] = surroundingMineCount createGameGrid(startX, startY) # Create the gameGrid which stores hidden tiles with 'False', shown tiles with 'True', and flagged tiles with 'f', default it all to 'False' def createGameGrid(startX, startY): for _ in range(0, height): tempWidthGrid = [] for _ in range(0, width): tempWidthGrid.append(False) gameGrid.append(tempWidthGrid) recursiveCheck(startX, startY) # Checks all tiles around a given tile and starts the check if it isn't already shown def recursiveCheck(xPos, yPos): gameGrid[yPos][xPos] = True if mineGrid[yPos][xPos] != '*': if int(mineGrid[yPos][xPos]) == 0: gameGrid[yPos][xPos] = True checkArray = checkSurrounding(gameGrid, xPos, yPos) for value in checkArray: if not value[0]: gameGrid[value[1]][value[2]] = True recursiveCheck(value[1], value[2]) # This checks to see if the win conditions have been met yet by checking if there are any unrevealed non-mine tiles def checkWin(): totalSqauresLeft = 0 for x in range(0, width): for y in range(0, height): if mineGrid[y][x] != '*' and gameGrid[y][x] == False: totalSqauresLeft = totalSqauresLeft + 1 if totalSqauresLeft == 0: return True else: return False # Parses user input coords for each turn and checks for errors def parseUserInput(inputMessage): # Gets input message and splits it into an array inputMessage = inputMessage.strip().split(" ") try: # Gets input coords from input message array xPos = int(inputMessage[0]) - 1 yPos = int(inputMessage[1]) - 1 # If an 'f' is included, toggle the flag on the given square try: if inputMessage[2] == 'f' or inputMessage[2] == 'F': if gameGrid[yPos][xPos] == False: gameGrid[yPos][xPos] = 'F' elif gameGrid[yPos][xPos] == 'F': gameGrid[yPos][xPos] = False else: print("You can't place flags on revealed squares!") time.sleep(1) else: print("Type 'f' to place a flag at the given coordinates!") time.sleep(1) # If no flag is included, check if the given square is a mine and either reveal it or end the game except IndexError: if gameGrid[yPos][xPos] != 'F': recursiveCheck(xPos, yPos) if mineGrid[yPos][xPos] == '*': print("You died!") return else: print("You cannot reveal sqaures with a flag!") time.sleep(1) # Error checking except ValueError: print("Only input intergers for coordinates!") time.sleep(1) except IndexError: print("Only input valid coordinates!") time.sleep(1) if checkWin(): printGrid() print("You won!") else: printGrid() parseUserInput(input("Input coords: ")) # Prints the grid with spacing and unicode box-drawing characters for added aesthetics def printGrid(): clear() print('┌',end='') for x in range(0, width): if x < width-1: print('───┬', end='') else: print('───┐', end='') print('\n', end='') for y in range(0, height): for x in range (0, width): print('│', end='') if gameGrid[y][x] == 'F': print(' ⚑ ', end='') else: if gameGrid[y][x] and mineGrid[y][x] != '*': print(f" {mineGrid[y][x]} ", end='') else: print(' ◼ ', end='') if not (x < width-1): print('│', end='') print('\n',end='') if y < height-1: print('├', end='') else: print('└', end='') for x in range(0, width): if y < height-1: if x < width-1: print('───┼', end='') else: print('───┤', end='') else: if x < width-1: print('───┴', end='') else: print('───┘', end='') print('\n', end='') # Starts the game, gets the starting coords from the user, checks for errors, keeps track of game time, and asks the user if they want to play again def startGame(): global mineGrid, gameGrid clear() print('Welcome to Minesweeper\n') startCoordsReceived = False mineGrid = [] gameGrid = [] # Receive starting coords and check if they're valid while not startCoordsReceived: try: inputMessage = input('Where do you want to start? Input coords (x & y): ') inputMessage = inputMessage.strip().split(' ') xCoord = int(inputMessage[0]) - 1 yCoord = int(inputMessage[1]) - 1 if xCoord < width and yCoord < height: startCoordsReceived = True else: print(f"Width and height must be between 0 and {width} and {height} respectively!") startCoordsReceived = False time.sleep(1) clear() print('Welcome to Minesweeper\n') except IndexError: print("Please input an x AND a y coordinate seperated by a space.") startCoordsReceived = False time.sleep(1) clear() print('Welcome to Minesweeper\n') except ValueError: print("Please only input whole intergers.") startCoordsReceived = False time.sleep(1) clear() print('Welcome to Minesweeper\n') # Record start time and create mine grid startTime = time.time() createMineGrid(xCoord, yCoord) printGrid() parseUserInput(input("Input coords: ")) # When the game finishes, display final time print(f"You played for {round(time.time() - startTime, 2)} seconds!") playAgainReceived = False # Ask the user if they want to play again while not playAgainReceived: try: inputMessage = input('Do you want to play again? (y/n): ') inputMessage = inputMessage.strip().lower() if inputMessage == 'y' or inputMessage == 'yes': playAgainReceived = True startGame() elif inputMessage == 'n' or inputMessage == 'no': playAgainReceived = True input("Press ENTER to exit") else: print("Please input yes or no") time.sleep(1) clear() playAgainReceived = False except ValueError: print("Please input yes or no") time.sleep(1) clear() playAgainReceived = False # Get starting command line argument and check for errors try: width = int(sys.argv[1]) if width < 1 or width > 30: sys.exit("Width must be greater than 0 and less than 30!\nProgram exiting.") except IndexError: sys.exit("Width not given!\nProgram exiting.") except ValueError: sys.exit("Width can only be an interger!\nProgram exiting.") try: height = int(sys.argv[2]) if height < 1 or width > 30: sys.exit("Height must be greater than 0 and less than 30!\nProgram exiting.") except IndexError: sys.exit("Height not given!\nProgram exiting.") except ValueError: sys.exit("Height can only be an interger!\nProgram exiting.") try: mineCount = int(sys.argv[3]) if mineCount < 1 or mineCount > (width * height): sys.exit("Number of mines must be greater than 0 and less than the number of grid squares!\nProgram exiting.") except IndexError: sys.exit("Number of mines not given!\nProgram exiting.") except ValueError: sys.exit("Number of mines can only be an interger!\nProgram exiting.") startGame()
6cad478212cb9a345107e33659dd716f49e674a0
daniromero97/Python
/e025-StringMethods/StringMethods.py
1,049
3.75
4
print("##################### 1 #####################") sequence = ("This is a ", "") s = "test" sentence = s.join(sequence) print(sentence) sequence = ("This is a ", " (", ")") sentence = s.join(sequence) print(sentence) """ output: This is a test This is a test (test) """ print("##################### 2 #####################") sentence = "this is a test" separator = "is a" tuple = sentence.partition(separator) print(tuple) """ output: ('this ', 'is a', ' test') """ print("##################### 3 #####################") sentence = "this is a test, " * 4 separator = "," list = sentence.split(separator) print(sentence) print(list) """ output: this is a test, this is a test, this is a test, this is a test, ['this is a test', ' this is a test', ' this is a test', ' this is a test', ' '] """ print("##################### 4 #####################") sentence = """line 1 line2 line3""" print(sentence) print(sentence.splitlines()) """ output: line 1 line2 line3 ['line 1', 'line2 ', 'line3'] """
00e97c511c9114dd8cb32f68a3ce3323cfd7ebf4
daniromero97/Python
/e004-Tuples/Tuples.py
1,380
3.875
4
print("########################### 1 ############################") my_tuple = ("value 1", "value 2", "value 3", ["value 4.1", "value 4.2"], 5, ("value 6.1", "value 6.2")) print(my_tuple) print(my_tuple[0]) print(my_tuple[-1]) print(my_tuple[2:5]) """ Output: ('value 1', 'value 2', 'value 3', ['value 4.1', 'value 4.2'], 5, ('value 6.1', 'value 6.2')) value 1 ('value 6.1', 'value 6.2') ('value 3', ['value 4.1', 'value 4.2'], 5) """ print("########################### 2 ############################") print(my_tuple.index("value 2")) print(5 in my_tuple) """ Output: 1 True """ print("########################### 3 ############################") print(len(my_tuple)) print(my_tuple.count("value 3")) """ Output: 6 1 """ print("########################### 4 ############################") my_tuple2 = (1, 4, 5, 21, 2) print(min(my_tuple2)) print(max(my_tuple2)) """ Output: 1 21 """ print("########################### 5 ############################") print(my_tuple) l = list (my_tuple) print(l) t = tuple (l) print(t) """ Output: ('value 1', 'value 2', 'value 3', ['value 4.1', 'value 4.2'], 5, ('value 6.1', 'value 6.2')) ['value 1', 'value 2', 'value 3', ['value 4.1', 'value 4.2'], 5, ('value 6.1', 'value 6.2')] ('value 1', 'value 2', 'value 3', ['value 4.1', 'value 4.2'], 5, ('value 6.1', 'value 6.2')) """
ddbeef1a26cb8b570434e5e595dd1421a81a5625
daniromero97/Python
/e013-Encapsulation/OOP.py
728
4.03125
4
class Person(object): def __init__(self, name, height, weight, age): self.__name = name self.__height = height self.__weight = weight self.__age = age def properties(self): print("Name: %s, height: %.2f m, weight: %.1f kg, age: %d years old" % (self.__name, self.__height, self.__weight, self.__age)) def eat(self): print("%s is eating" % self.__name) def drink(self): print("%s is drinking" % self.__name) def sleep(self): print("%s is sleeping" % self.__name) p1 = Person("Gonzalo", 1.78, 74, 25) p1.properties() p1.__name = "Luis" p1.properties() print(p1.__name) # Unresolved attribute reference '__name' for class 'Person'
a5eaef2210158228b7681822194cb4ae04dfd677
daniromero97/Python
/e006-ControlFlowStatements/ControlFlowStatements.py
1,780
3.9375
4
print("########################### 1 ############################") a = 0 while a<5: print(a) a+=1 """ Output: 0 1 2 3 4 """ print("########################### 2 ############################") a = 0 while True: a += 1 print(a) if a == 3: break """ Output: 1 2 3 """ print("########################### 3 ############################") color_list = ['red', 'blue', 'green'] for color in color_list: print(color) """ Output: red blue green """ print("########################### 4 ############################") for num in range(0, 5): print(num) """ Output: 0 1 2 3 4 """ print("########################### 5 ############################") sentence = "I just want you to count the letters" counter = 0 print(len(sentence)) for letter in sentence: if letter == ' ': continue counter+=1 print(counter) """ Output: 36 29 """ print("########################### 6 ############################") sentence = "I just want you to count the letters" counter = 0 print(len(sentence)) for letter in sentence: pass # Incomplete code print(counter) """ Output: 36 0 """ print("########################### 7 ############################") sentence = "Count only the length of the first word" counter = 0 for letter in sentence: counter += 1 if letter == ' ': break else: counter = 0 print("It was not a sentence, it was a word") print(counter) sentence = "Test" counter = 0 for letter in sentence: counter += 1 if letter == ' ': break else: counter = 0 print("It was not a sentence, it was a word") print(counter) """ Output: 6 It was not a sentence, it was a word 0 """
7dcde1f414b5214079c7516810a9d96094538107
daniromero97/Python
/e033-Datetime/Main.py
3,097
3.734375
4
import datetime print("###################### 1 ######################") print(datetime.MINYEAR) """ output: 1 """ print("###################### 2 ######################") print(datetime.MAXYEAR) """ output: 9999 """ print("###################### 3 ######################") print(datetime.date.today()) print("day:", datetime.date.today().day) print("month:", datetime.date.today().month) print("year:", datetime.date.today().year) print("weekday:", datetime.date.today().weekday()) """ output: 2018-11-28 day: 28 month: 11 year: 2018 weekday: 2 """ print("###################### 4 ######################") print(datetime.datetime.now()) print("hour:", datetime.datetime.now().hour) print("minute:", datetime.datetime.now().minute) print("second:", datetime.datetime.now().second) print("microsecond:", datetime.datetime.now().microsecond) print("timestamp():", datetime.datetime.now().timestamp()) """ output: 2018-11-28 12:54:24.378262 hour: 12 minute: 54 second: 24 microsecond: 378290 timestamp(): 1543406064.378299 """ print("###################### 5 ######################") print("weeks:", datetime.timedelta(weeks=1), "--> total seconds:",datetime.timedelta(weeks=1).total_seconds()) print("days:", datetime.timedelta(days=1), "--> total seconds:",datetime.timedelta(days=1).total_seconds()) print("hours:", datetime.timedelta(hours=1), "--> total seconds:",datetime.timedelta(hours=1).total_seconds()) print("minutes:", datetime.timedelta(minutes=1), "--> total seconds:",datetime.timedelta(minutes=1).total_seconds()) print("seconds:", datetime.timedelta(seconds=1), "--> total seconds:",datetime.timedelta(seconds=1).total_seconds()) print("milliseconds:", datetime.timedelta(milliseconds=1), "--> total seconds:",datetime.timedelta(milliseconds=1).total_seconds()) print("microseconds:", datetime.timedelta(microseconds=1), "--> total seconds:",datetime.timedelta(microseconds=1).total_seconds()) print("total:", datetime.timedelta(weeks=1, days=1, hours=1, minutes=1, seconds=1, milliseconds=1, microseconds=1), "--> total seconds:", datetime.timedelta(weeks=1, days=1, hours=1, minutes=1, seconds=1, milliseconds=1, microseconds=1).total_seconds()) """ output: weeks: 7 days, 0:00:00 --> total seconds: 604800.0 days: 1 day, 0:00:00 --> total seconds: 86400.0 hours: 1:00:00 --> total seconds: 3600.0 minutes: 0:01:00 --> total seconds: 60.0 seconds: 0:00:01 --> total seconds: 1.0 milliseconds: 0:00:00.001000 --> total seconds: 0.001 microseconds: 0:00:00.000001 --> total seconds: 1e-06 total: 8 days, 1:01:01.001001 --> total seconds: 694861.001001 """ print("###################### 6 ######################") print(datetime.date.today()) print(datetime.datetime.today().strftime('%d, %b %Y')) print(datetime.datetime.now()) print(datetime.datetime.now().strftime('%d, %b %Y')) print(datetime.datetime.now().strftime('%d/%b/%Y %H:%M:%S')) """ output: 2018-11-28 28, Nov 2018 2018-11-28 13:26:41.492853 28, Nov 2018 28/Nov/2018 13:26:41 """
b574c115fc9c68ca068880dfb5b2a247f985d8c2
xiong-zh/Arithmetic
/sort/radix.py
685
3.84375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020/6/15 # @Author: zhangxiong.net # @Desc : def radix(arr): digit = 0 max_digit = 1 max_value = max(arr) # 找出列表中最大的位数 while 10 ** max_digit < max_value: max_digit = max_digit + 1 while digit < max_digit: temp = [[] for i in range(10)] for i in arr: # 求出每一个元素的个、十、百位的值 t = int((i / 10 ** digit) % 10) temp[t].append(i) coll = [] for bucket in temp: for i in bucket: coll.append(i) arr = coll digit = digit + 1 return arr
774ce49dd157eca63ab05d74c0d542dd33b4f14a
Nyame-Wolf/snippets_solution
/codewars/Write a program that finds the summation of every number between 1 and num if no is 3 1 + 2.py
629
4.5
4
Summation Write a program that finds the summation of every number between 1 and num. The number will always be a positive integer greater than 0. For example: summation(2) -> 3 1 + 2 summation(8) -> 36 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 tests test.describe('Summation') test.it('Should return the correct total') test.assert_equals(summation(1), 1) test.assert_equals(summation(8), 36) others solution: def summation(num): return (1+num) * num / 2 or def summation(num): return sum(range(1,num+1)) or def summation(num): if num > 1: return num + summation(num - 1) return 1
389b09b0bcc2596b3847791765a47127b4f97f13
McBonB/text01_lf
/t.py
1,958
3.65625
4
""" 最远足迹 莫探险队对地下洞穴探索 会不定期记录自身坐标,在记录的间隙中也会记录其他数据,探索工作结束后,探险队需要获取到某成员在探险过程中,对于探险队总部的最远位置 1.仪器记录坐标时,坐标的数据格式为 x,y x和y——》0-1000 (01,2)(1,01) 设定总部位置为0,0 计算公式为x*(x+y)*y """ import re,math s = "abcccc(3,10)c5,13d(1$f(6,11)sdf(510,200)adas2d()(011,6)" #原始字符串 #print(re.findall(r'[^()a-z]+', s)) pattern = re.compile(r'\(([0-9]{1,3},[0-9]{1,3})\)') #提取坐标正则表达式对象 result = re.findall(pattern,s) #查询整个字符串,得出坐标列表 f_result={} #判断是否为合格的十进制整数,且大于0小于500 def isDigit(str1): if len(str1)==3: if str1[0]=='0': return False else: return True if len(str1)==2: if str1[0]=='0': return False else: return True if len(str1)==1: if str1=='0': return False else: return True #遍历得出的坐标列表,求得他距离总部(0,0)的距离,距离为x^2+y^2,并保存到字典f_result for i in result: i=i.split(',') if isDigit(i[0]) and isDigit(i[1]): f_result[','.join(i)]=i[0]*(i[1]+i[0])*i[1] #求得最远距离 a=max(f_result.values()) #最远距离的距离和坐标字典 z_result=[] for i in f_result: if f_result[i]==a: z_result.append(i) #最远距离下,x+y和与坐标 he_result={} #如果最远距离相等,判断谁先到达,规则x+y for i in z_result: i=i.split(',') he_result[','.join(i)]=int(i[0])+int(i[1]) #求得和的最小值 b=min(he_result.values()) #遍历,打印出最小和的坐标 for i in he_result: if he_result[i]==b: print('('+i+')') #print(i,i[0],i[1],isDigit(i[0]),isDigit(i[1]),f_result,a,z_result,z_result[0],he_result)
a1e2cbfe73c8889bca05dd05a02ef1789bb61a68
Bellroute/python_class
/day0911/example2_6.py
304
4.09375
4
def sumDigits(n): result = 0 while(n != 0): result += n % 10 n //= 10 return result def main(): n = int(input('Enter a number between 0 and 1000 : ')) result = sumDigits(n) print('The sum of the digits is', result) if __name__ == "__main__": main()
483a180d35ed99b23cd82163b47fe2f78e18148c
Bellroute/python_class
/day1002/example5_19.py
253
3.703125
4
inputValue = int(input("Enter the number of lines: ")) for i in range(1, inputValue + 1): line = " " for j in range(i, 0, -1): line += str(j) + " " for j in range(2, i + 1): line += str(j) + " " print(line.center(60))
282434fc39e19a79f8ce6b7ca4b142a9a61aed9d
Bellroute/python_class
/someday/factorize.py
457
3.765625
4
import prime def factorize(n): factor = [] while True: m = prime.isPrime(n) if m == n: break n //= m return factor def main(): n = int(input('type any number : ')) result = prime.isPrime(n) if result: print(n, '은 소수야!') else: print(n, '은 ', result, '로 나눠져!') result = factorize(n) print(result) if __name__ == "__main__": main()
d920f009c5aa6209e9daf681197d9de7ca73a1f5
acttx/Python
/Comp Fund 2/Lab4/personList.py
1,811
3.59375
4
import csv from person import Person from sortable import Sortable from searchable import Searchable """ This class has no instance variables. The list data is held in the parent list class object. The constructor must call the list constructor: See how this was done in the Tower class. Code a populate method, which reads the CSV file. It must use: try / except, csv.reader, and with open code constructs. Code the sort method: Must accept a function object and call the function. Code the search method: Must accept a function object and a search item Person object and call the function. Code a __str__ method: Look at the Tower class for help You may want to code a person_at method for debug purposes. This takes an index and returns the Person at that location. """ class PersonList(Sortable, Searchable, list): def __init__(self): super().__init__() def populate(self, filename): try: with open(filename, 'r') as input_file: lines = csv.reader(input_file) emp_list = list(lines) for emp in emp_list: name = emp[0] month = int(emp[1]) day = int(emp[2]) year = int(emp[3]) self.append(Person(name, year, month, day)) except IOError: print("File Not Found. Program Exited.") exit() def person_at(self): for i in range(len(self)): return self.index(i) def sort(self, funcs): funcs(self) def search(self, func, person_obj): return func(self, person_obj) def __str__(self): x = '[' + '] ['.join(str(d) for d in self) return x
e96466aa5575c4b719780a0c2585c270e6f2fb16
acttx/Python
/Comp Fund 2/Lab9/road.py
8,547
3.859375
4
import math from edge import Edge from comparable import Comparable """ Background to Find Direction of Travel: If you are traveling: Due East: you are moving in the positive x direction Due North: you are moving in the positive y direction Due West: you are moving in the negative x direction Due South: you are moving in the negative y direction From any point in a plane one can travel 360 degrees. The 360 degrees can be divided into 4 quadrants of 90 degrees each. The angles run from 0-90 degrees in a counter-clockwise direction through each of the four quadrants defined below: a) East to North: called Quadrant I b) North to West: called Quadrant II c) West to South: called Quadrant III d) South to East: called Quadrant IV The possible directions of travel are Quadrant I: E, ENE, NE, NNE, N Quadrant II: N, NNW, NW, WNW, W Quadrant III: W, WSW, SW, SSW, S Quadrant IV; S, SSE, SE, ESE. E The angle slices in these quadrants correspond to traveling in one of 16 directions: Quadrant I (1): [0.00, 11.25) : 'E' [11.25, 33.75) : 'ENE' [33.75, 56.25) : 'NE' [56.25, 78.75) : 'NNE' [78.75, 90.0) : 'N' Quadrant II (2): [0.00, 11.25) : 'N', [11.25, 33.75) : 'NNW' [33.75, 56.25) : 'NW' [56.25, 78.75) : 'WNW' [78.75, 90.0) : 'W' Quadrant III (3): [0.00, 11.25) : 'W' [11.25, 33.75) : 'WSW' [33.75, 56.25) : 'SW' [56.25, 78.75) : 'SSW' [78.75, 90.0) : 'S' Quadrant IV (4): [0.00, 11.25) : 'S' [11.25, 33.75) : 'SSE' [33.75, 56.25) : 'SE' [56.25, 78.75) : 'ESE' [78.75, 90.0) : 'E' To determine the quadrant, you need to know the relative positions between x1 and x2 and between y1 and y2 a) Quadrant I: (x1 < x2 & y1 <= y2) b) Quadrant II: (x1 >= x2 & y1 < y2) c) Quadrant III:(x1 > x2 & y1 >= y2) d) Quadrant IV: (x1 >= x2 & y1 > y2) To find the direction of travel, you need to find an angle between the line from P1 to P2 and either a) a line parallel to the x-axis OR b) a line parallel to the y-axis In order to find the angle A in radians, which is the angle between the line from P1 to P2, and the line parallel to either the x-axis for Quadrants I and III or the y-axis for Quadrants II and IV, you need to use: angle_A = arctan((y2-y1) / (x2-x1)) The Python math library has a function for this angle_A = math.atan ((y2-y1) / (x2-x1)) This gives the angle in radians. You must convert the angle to degrees. Use the Python math library function: angle_A_deg = math.degrees (angle_A) If the direction is in Quadrants II or IV, then add 90 degrees. To compute the distance, use the distance formula distance = SQRT [(x2-x1)**2 + (y2-y1)**2] The Python math library has a function for this distance = math.sqrt ((x2-x1)**2 + (y2-y1)**2) """ class Road(Edge, Comparable): """ This class represents a Road on a map (Graph) """ def __init__(self, from_city, to_city): """ Creates a new Road New Instance variables: self.direction: str Set Edge instance variable: self weight: float This is the distance stored in miles Call the method comp_direction to set the direction and weight (in miles) """ super().__init__(from_city, to_city) direction, distance = self.comp_direction() self.direction = direction self.weight = distance def get_direction(self): """ Return the direction set in the constructor """ return self.direction def comp_direction(self): """ Compute and return the direction of the Road and the distance between the City vertices Note: Do NOT round any values (especially GPS) in this method, we want them to have their max precision. Only do rounding when displaying values This is called in the constructor """ # Get the points from the GPS coordinates of each City # These are in degrees, change to radians # Point 1 x1 = self.from_vertex.get_X() y1 = self.from_vertex.get_Y() # Point 2 x2 = self.to_vertex.get_X() y2 = self.to_vertex.get_Y() # Convert from degrees to radian x1 = math.radians(x1) y1 = math.radians(y1) x2 = math.radians(x2) y2 = math.radians(y2) # Given the x and y coordinates of P1 and P2, # find the quadrant in which the angle exists quadrant = self.find_quadrant(x1, y1, x2, y2) # Given the x and y coordinates of P1 and P2 and the quadrant, # find the angle between the x or y axis and the line from P1 to P2. # Return the angle in degrees degrees = self.compute_angle(x1, y1, x2, y2, quadrant) # Using the angle and quadrant, find the direction # This function must use a dictionary direction = self.compute_direction(degrees, quadrant) # Find the distance between the points P1 and P2 # Convert the distance to miles and return it dist_miles = self.distance(x1, y1, x2, y2) * 3956 return direction, dist_miles def find_quadrant(self, x1, y1, x2, y2): """ a) Quadrant I: when x2 > x1 and y2 >= y1 b) Quadrant II: when x2 <= x1 and y2 > y1 c) Quadrant III: when x2 < x1 and y2 <= y1 d) Quadrant IV: when x2 >= x1 and y2 < y1 """ quadrant = 0 if x2 > x1 and y2 >= y1: quadrant = 1 elif x2 <= x1 and y2 > y1: quadrant = 2 elif x2 < x1 and y2 <= y1: quadrant = 3 elif x2 >= x1 and y2 < y1: quadrant = 4 return quadrant def distance(self, x1, y1, x2, y2): """ Use distance formula to find length of line from P1 to P2 """ dist = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) return dist def compute_angle(self, x1, y1, x2, y2, quadrant): """ Use the trig formula: atan = (y2-y1) / (x2-x1) Convert radians to degrees """ # Radian formula angle_A = math.atan((y2 - y1) / (x2 - x1)) # Convert to degrees based on quadrant if quadrant == 2 or quadrant == 4: angle_A_deg = math.degrees(angle_A) + 90 else: angle_A_deg = math.degrees(angle_A) return angle_A_deg def compute_direction(self, angle, quadrant): """ Create a dictionary for each quadrant that holds the angle slices for each direction. The key is a 2-tuple holding the degrees (low, high) of the angle slices, and the value is the direction """ dict_Q1 = {(00.00, 11.25): 'E', (11.25, 33.75): 'ENE', (33.75, 56.25): 'NE', (56.25, 78.75): 'NNE', (78.75, 90.00): 'N'} dict_Q2 = {(00.00, 11.25): 'N', (11.25, 33.75): 'NNW', (33.75, 56.25): 'NW', (56.25, 78.75): 'WNW', (78.75, 90.00): 'W'} dict_Q3 = {(00.00, 11.25): 'W', (11.25, 33.75): 'WSW', (33.75, 56.25): 'SW', (56.25, 78.75): 'SSW', (78.75, 90.00): 'S'} dict_Q4 = {(00.00, 11.25): 'S', (11.25, 33.75): 'SSE', (33.75, 56.25): 'SE', (56.25, 78.75): 'ESE', (78.75, 90.00): 'E'} if quadrant == 1: for k, v in dict_Q1.items(): if k[0] <= angle < k[1]: return v elif quadrant == 2: for k, v in dict_Q2.items(): if k[0] <= angle < k[1]: return v elif quadrant == 3: for k, v in dict_Q3.items(): if k[0] <= angle < k[1]: return v elif quadrant == 4: for k, v in dict_Q4.items(): if k[0] <= angle < k[1]: return v def __str__(self): """ Return road information as a string """ return self.from_vertex.get_name() + " to " + self.to_vertex.get_name() + " traveling " + self.direction + " for " + "{0:.2f}".format( self.weight) + " miles."
5fbadcc16da279332b3cf317155a683f3744e93d
acttx/Python
/Comp Fund 2/Lab4/person_main.py
3,160
4.1875
4
from comparable import Comparable from personList import PersonList from person import Person from sort_search_funcs import * def main(): """ This main function creates a PersonList object and populates it with the contents of a data file containing 30 records each containing the first name and birthdate as month day year separated by commas: Merli,9,10,1998 Next, a request is made to search for a certain Person. A Person object is created from the input. Then a linear search is performed with the Person object If the Person is located in the list, its index is returned Otherwise, -1 is returned. The number of compares for the linear search is displayed Next, a bubble sort is executed to sort the PersonList. The sorted list is displayed, along with the number of compares it took to sort it Next, a request is made to search for another Person. A Person object is created from the input. Then a binary search is performed with the Person object If the Person is located in the sorted list, its index is returned Otherwise, -1 is returned. The number of compares for the binary search is displayed """ # Create a PersonList object and add the data p_list = PersonList() p_list.populate("persons.csv") # Request a person to search print("List searched using linear search") print() name = input("Who do you want to search for?") bdate = input("What is their birthdate? (mm-dd-yyyy)") print() # Create a person object from the input month, day, year = bdate.split('-') p_obj = Person(name, int(year), int(month), int(day)) # Do a linear search index = p_list.search(linear_search, p_obj) if index == -1: print(name, "is not in the list") else: print(name, "is at position", index, "in the list") # Display the number of compares print() print("The number of compares are", Comparable.get_num_compares()) print() # Reset the compare count Comparable.clear_compares() # Sort the list using bubble sort p_list.sort(bubble_sort) print("List sorted by bubble sort") for p in p_list: print(p) # Display the number of compares print() print("The number of compares are", Comparable.get_num_compares()) print() # Reset the compare count Comparable.clear_compares() # Request a person to search print("List searched using binary search") print() name = input("Who do you want to search for?") bdate = input("What is their birthdate? (mm-dd-yyyy)") print() # Create a person object from the input month, day, year = bdate.split('-') p_obj = Person(name, int(year), int(month), int(day)) # Do a binary search index = p_list.search(binary_search, p_obj) if index == -1: print(name, "is not in the list") else: print(name, "is at position", index, "in the list") # Display the number of compares print() print("The number of compares are", Comparable.get_num_compares()) main()
6b789ec1822bfeef3b0518c2114a51dee2425424
acttx/Python
/Comp Fund 2/Lab8/charCount.py
530
3.75
4
from comparable import Comparable class CharCount(Comparable): def __init__(self, char, count): self.char = char self.count = count def get_char(self): return self.char def get_count(self): return self.count def compare(self, other_charCount): if self.char < other_charCount.char: return -1 if self.char > other_charCount.char: return 1 return 0 def __str__(self): return str(self.char) + " : " + str(self.count)
62ef143a7d1a7dd420ad2f2f4b8a4ec9dda89f4f
DanielOram/simple-python-functions
/blueberry.py
2,627
4.625
5
#Author: Daniel Oram #Code club Manurewa intermediate #This line stores all the words typed from keyboard when you press enter myString = raw_input() #Lets print out myString so that we can see proof of our awesome typing skills! #Try typing myString between the brackets of print() below print() #With our string we want to make sure that the first letter of each word is a capital letter #Try editing myString by calling .title() at the end of myString below - This Will Capitalise Every Word In Our String myCapitalString = myString print("My Capitalised String looks like \"" + myCapitalString + "\"") #Now we want to reverse myString so that it looks backwards! #Try reversing myString by putting .join(reversed(myCapitalString)) after the empty string below - it will look like this -> ''.join(reversed(myCapitalString)) myBackwardsString = '' #Lets see how we did! print(myBackwardsString) #Whoa that looks weird! #Lets reverse our string back so that it looks like normal! #Can you do that just like we did before? myForwardString = '' #remember to use myBackwardsString instead of myCapitalString ! print("My backwards string = " + "\"" + myBackwardsString + "\"") #Ok phew! we should be back to normal #Lets try reverse our string again but this time we want to reverse the word order! NOT the letter order! #To do this we need to find a way to split our string up into the individual words #Try adding .split() to the end of myForwardString kind of like we did before myListOfWords = ["We", "want", "our", "String", "to", "look", "like", "this!"] #replace the [...] with something that looks like line 27! #Now lets reverse our List so that the words are in reverse order! myBackwardsListOfWords = reversed(["Replace","this", "list", "with", "the", "correct", "list"]) #put myListOfWords here #Before we can print it out we must convert our list of words back into a string! #Our string was split into several different strings and now we need to join them back together #HINT: we want to use the .join() function that we used earlier but this time we just want to put our list of words inside the brackets and # NOT reversed(myBackwardsListOfWords) inside of the brackets! myJoinedString = ''.join(["Replace", "me", "with", "the", "right", "list!"]) # replace the [...] with the right variable! print(myJoinedString) #Hmmm our list is now in reverse.. but it's hard to read! #Go back and fix our issue by adding a space between the '' above. That will add a space character between every word in our list when it joins it together! #Nice job! You've finished blueberry.py
15cc2f889516a57be1129b8cad373084222f2c30
viniciuschiele/solvedit
/strings/is_permutation.py
719
4.125
4
""" Explanation: Permutation is all possible arrangements of a set of things, where the order is important. Question: Given two strings, write a method to decide if one is a permutation of the other. """ from unittest import TestCase def is_permutation(s1, s2): if not s1 or not s2: return False if len(s1) != len(s2): return False return sorted(s1) == sorted(s2) class Test(TestCase): def test_valid_permutation(self): self.assertTrue(is_permutation('abc', 'cab')) self.assertTrue(is_permutation('159', '915')) def test_invalid_permutation(self): self.assertFalse(is_permutation('abc', 'def')) self.assertFalse(is_permutation('123', '124'))
9332ac35cb63d27f65404bb86dfc6370c919c2be
viniciuschiele/solvedit
/strings/is_permutation_of_palindrome.py
1,117
4.125
4
""" Explanation: Permutation is all possible arrangements of a set of things, where the order is important. Palindrome is a word or phrase that is the same forwards and backwards. A string to be a permutation of palindrome, each char must have an even count and at most one char can have an odd count. Question: Given a string, write a function to check if it is a permutation of a palindrome. """ from unittest import TestCase def is_permutation_of_palindrome(s): counter = [0] * 256 count_odd = 0 for c in s: char_code = ord(c) counter[char_code] += 1 if counter[char_code] % 2 == 1: count_odd += 1 else: count_odd -= 1 return count_odd <= 1 class Test(TestCase): def test_valid_permutation_of_palindrome(self): self.assertTrue(is_permutation_of_palindrome('pali pali')) self.assertTrue(is_permutation_of_palindrome('abc111cba')) def test_non_permutation_of_palindrome(self): self.assertFalse(is_permutation_of_palindrome('pali')) self.assertFalse(is_permutation_of_palindrome('abc1112cba'))
405f28e905884cfdd2c11810b27c76f69cc636b9
nueadkie/cs362-inclass-activity-4
/wordcount.py
287
3.875
4
def calc(input_string): # Special case for empty string, or if just whitespace. if len(input_string.strip()) == 0: return 0 words = 1 # Remove any trailing and leading whitespace. for char in input_string.strip(): if char == ' ': words += 1 return words
08a4f34357da5a7063177e4996aa8cadf5c318c6
hendritedjo/python_exercise
/exercise-list.py
1,573
3.75
4
#1 hari = ['senin','selasa','rabu','kamis','jumat','sabtu','minggu'] try: inputhari = input("Masukkan hari : ") inputangka = int(input("Masukkan jumlah : ")) inputhari = inputhari.lower() if (inputhari not in hari): print("Nama hari yang anda masukkan salah") else: sisa = inputangka % 7 if (hari.index(inputhari)+sisa) > 6: sisa = sisa + hari.index(inputhari) - 7 elif (hari.index(inputhari)+sisa < 0): sisa = sisa + hari.index(inputhari) + 7 print("Hari ini hari {}. {} hari lagi adalah hari {}".format(inputhari.capitalize(),str(inputangka),hari[sisa].capitalize())) except: print("Jumlah yang anda masukkan salah") ''' #2 kalimat = input("Masukkan kalimat : ") for a in kalimat: if a in ["0","1","2","3","4","5","6","7","8","9"]: print("Tidak menerima angka") break else: kalimat = kalimat.split() if kalimat.isalpha(): for a in kalimat: print(a[::-1], end=" ") print("") else: #3 kata1 = input("Masukkan kata : ") for a in kata1: if a in ["0","1","2","3","4","5","6","7","8","9"]: print("Tidak menerima angka") break else: if kata1.isalpha(): kata2 = kata1[::-1] if kata1.lower() == kata2.lower(): print("Kata tersebut {} merupakan Palindrome".format(kata1)) else: print("Kata tersebut {} bukan merupakan Palindrome".format(kata1)) else: print("Tidak menerima di luar alphabet") '''
33ab245a6da86e5d0d8c4e51d47762afa12f85a4
hendritedjo/python_exercise
/exam-listspinner.py
434
3.78125
4
#Soal 2 list1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] def counterClockwise(num): num1 = [[a for a in range(num[0][3], num[3][3]+1, 4)], [a for a in range(num[0][2], num[3][2]+1, 4)], [a for a in range(num[0][1], num[3][1]+1, 4)], [a for a in range(num[0][0], num[3][0]+1, 4)]] return num1 print(counterClockwise(list1))
a7ff689d33dad699ac7e270958cf4d841afb5453
cathyxinxyz/Capstone_project_2
/Top_K_terms.py
3,289
3.515625
4
# function to plot the top k most frequent terms in each class import matplotlib.pyplot as plt import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer import seaborn as sns def Top_K_ngrams(k, ngram, df, text_col, class_col): vect=TfidfVectorizer(ngram_range=(ngram,ngram)) vect.fit(df[text_col]) tfidf_df=pd.DataFrame(vect.transform(df[text_col]).toarray()) tfidf_df.columns=vect.get_feature_names() top_K_ngrams_by_class=dict() for v in df[class_col].value_counts().index: freq_in_class=tfidf_df[df[class_col]==v].sum(axis=0).sort_values(ascending=False) frac_in_class=freq_in_class/freq_in_class.sum() top_K_ngrams_by_class[v]=frac_in_class[:k].index print ('the top {} frequent {}-gram terms for class {}:'.format(k,ngram, v)) sns.barplot(y=frac_in_class[:k].index, x=frac_in_class[:k]) plt.ylabel('{}-gram terms'.format(ngram)) plt.xlabel('fraction') plt.show() return top_K_ngrams_by_class # function to plot the top k most frequent nouns in each class from nltk.tag.perceptron import PerceptronTagger def Top_K_nouns(k, df, text_col, class_col, plot=False): vect=TfidfVectorizer() vect.fit(df[text_col]) tfidf_df=pd.DataFrame(vect.transform(df[text_col]).toarray()) tfidf_df.columns=vect.get_feature_names() tfidf_T=tfidf_df.transpose() tagger = PerceptronTagger() tfidf_T['pos']=tagger.tag(tfidf_T.index) tfidf_T=tfidf_T[tfidf_T['pos'].apply(lambda tup:tup[1] in ['NN','NNP','NNS','NNPS'])] tfidf_df=tfidf_T.drop(['pos'], axis=1).transpose() top_k_by_class=dict() for v in df[class_col].value_counts().index: freq_in_class=tfidf_df[df[class_col]==v].sum(axis=0).sort_values(ascending=False) frac_in_class=freq_in_class/freq_in_class.sum() top_k_by_class[v]=frac_in_class[:k].index if plot: print ('the top {} frequent nouns for class {}:'.format(k,v)) plt.figure(figsize=(5, 10)) sns.barplot(y=frac_in_class[:k].index, x=frac_in_class[:k]) plt.xlabel('fraction') plt.show() return (top_k_by_class) from nltk.tag.perceptron import PerceptronTagger def Top_K_verbs(k, df, text_col, class_col, plot=False): vect=TfidfVectorizer() vect.fit(df[text_col]) tfidf_df=pd.DataFrame(vect.transform(df[text_col]).toarray()) tfidf_df.columns=vect.get_feature_names() tfidf_T=tfidf_df.transpose() tagger = PerceptronTagger() tfidf_T['pos']=tagger.tag(tfidf_T.index) tfidf_T=tfidf_T[tfidf_T['pos'].apply(lambda tup:tup[1] in ['VB','VBD','VBG','VBN'])] tfidf_df=tfidf_T.drop(['pos'], axis=1).transpose() top_k_by_class=dict() for v in df[class_col].value_counts().index: freq_in_class=tfidf_df[df[class_col]==v].sum(axis=0).sort_values(ascending=False) frac_in_class=freq_in_class/freq_in_class.sum() top_k_by_class[v]=frac_in_class[:k].index if plot: print ('the top {} frequent nouns for class {}:'.format(k,v)) plt.figure(figsize=(5, 10)) sns.barplot(y=frac_in_class[:k].index, x=frac_in_class[:k]) plt.xlabel('fraction') plt.show() return (top_k_by_class)
4557143f73a37747a488bf808e8814b888c2e169
jerome-gingras/Advent-of-code-2015
/day9/day9.py
982
3.53125
4
from itertools import permutations import sys f = open("C:\\Dev\\Advent-of-code-2015\\day9\\input.txt", "r") line = f.readline() cities = set() distances = dict() while line != "": (source, _, destination, _, distance) = line.split() cities.add(source) cities.add(destination) if source in distances: distances[source][destination] = int(distance) else: distances[source] = dict([(destination, int(distance))]) if destination in distances: distances[destination][source] = int(distance) else: distances[destination] = dict([(source, int(distance))]) line = f.readline() shortest_path = sys.maxint longest_path = 0 for items in permutations(cities): distance = sum(map(lambda x, y: distances[x][y], items[:-1], items[1:])) shortest_path = min(shortest_path, distance) longest_path = max(longest_path, distance) print "Shortest path is " + str(shortest_path) print "Longuest path is " + str(longest_path)
8c75b7197feda25b715d4f2d0641e7e02cffa1e4
Alexionder/TheLifeOfAlex
/Exploration time/items.py
1,183
3.890625
4
class Sword(): def __init__(self, durability, strength, name): self.durability = durability self.strength = strength self.name = name def inspect(self): print "This sword has " + str(self.durability) + " durability and " + str(self.strength) + " strength." class Axe(): def __init__(self, durability, strength, name): self.durability = durability self.strength = strength self.name = name def inspect(self): print "This axe has " + str(self.durability) + " durability and " + str(self.strength) + " strength." class HPbottle(): def __init__(self, amount): self.amount = amount if amount < 15: self.name = "weak health potion" elif amount < 30: self.name = "moderate health potion" else: self.name = "strong health potion" def inspect(self): print "This potion can heal you for " + str(self.amount) + "." class Food(): def __init__(self, amount, name): self.amount = amount self.name = name def inspect(self): print "This food can satisfy you hunger for " + str(self.amount) + "."
6d52f092b0a8d34724125240a931caf789b0870a
AsleyR/Tic-Tac-Toe-Game---Python
/TTT2.py
11,984
4
4
from tkinter import * #Note: Add choice to be X or O for PvC new_gamemode = False play_as_O = False player = "" computer = "X" x = 0 #General purpose variable for operations board = {0: " ", 2: " ", 3: " ", 4: " ", 5: " ", 6: " ", 7: " ", 8: " ", 9: " "} def turn(): global computer global player global x x = x + 1 if new_gamemode == False: if (x % 2) == 0: player = "O" else: player = "X" elif new_gamemode == True and play_as_O == False: computer = "O" player = "X" elif new_gamemode == True and play_as_O == True: computer = "X" player = "O" return player #Left as a debug tool def print_board(): print(board[0] + "|" + board[2] + "|" + board[3]) print("-+-+-") print(board[4] + "|" + board[5] + "|" + board[6]) print("-+-+-") print(board[7] + "|" + board[8] + "|" + board[9]) print("\n") def free_space(position): if board[position] == " ": return True else: return False def place_mark(position, mark): if free_space(position) == True: board[position] = mark print_board() if check_win() and who_won(mark): if winner_label["text"] == "": winner_label["text"] = mark + " Wins!" print(mark + " WINS!") if check_draw() == True: if winner_label["text"] == "": winner_label["text"] = "Draw!" print("DRAW!") else: print("Space is used.") def check_draw(): for key in board.keys(): if (board[key] == " "): return False return True def check_win(): #Check horizontal if board[0] == board[2] and board[0] == board[3] and board[0] != " ": return True elif board[4] == board[5] and board[4] == board[6] and board[4] != " ": return True elif board[7] == board[8] and board[7] == board[9] and board[7] != " ": return True #Check vertical elif board[0] == board[4] and board[0] == board[7] and board[0] != " ": return True elif board[2] == board[5] and board[2] == board[8] and board[2] != " ": return True elif board[3] == board[6] and board[3] == board[9] and board[3] != " ": return True #Check diagonal elif board[0] == board[5] and board[0] == board[9] and board[0] != " ": return True elif board[3] == board[5] and board[3] == board[7] and board[3] != " ": return True else: return False def who_won(mark): #Check horizontal if board[0] == board[2] and board[0] == board[3] and board[0] == mark: return True elif board[4] == board[5] and board[4] == board[6] and board[4] == mark: return True elif board[7] == board[8] and board[7] == board[9] and board[7] == mark: return True #Check vertical elif board[0] == board[4] and board[0] == board[7] and board[0] == mark: return True elif board[2] == board[5] and board[2] == board[8] and board[2] == mark: return True elif board[3] == board[6] and board[3] == board[9] and board[3] == mark: return True #Check diagonal elif board[0] == board[5] and board[0] == board[9] and board[0] == mark: return True elif board[3] == board[5] and board[3] == board[7] and board[3] == mark: return True else: return False #I don't know why, but board is sorted like 0, 2, 3, 4.... Had to rename board[1] to board[0] # to avoid KeyErrors def computer_move(): best_score = -800 best_move = 0 for key in board.keys(): if (free_space(key) == True): board[key] = computer score = minimax(0, False) board[key] = " " if (score > best_score): best_score = score best_move = key if best_move == 0 and free_space(best_move) == True: btn1.config(text=computer, bg="grey70", state=DISABLED) elif best_move == 2 and free_space(best_move) == True: btn2.config(text=computer, bg="grey70", state=DISABLED) elif best_move == 3 and free_space(best_move) == True: btn3.config(text=computer, bg="grey70", state=DISABLED) elif best_move == 4 and free_space(best_move) == True: btn4.config(text=computer, bg="grey70", state=DISABLED) elif best_move == 5 and free_space(best_move) == True: btn5.config(text=computer, bg="grey70", state=DISABLED) elif best_move == 6 and free_space(best_move) == True: btn6.config(text=computer, bg="grey70", state=DISABLED) elif best_move == 7 and free_space(best_move) == True: btn7.config(text=computer, bg="grey70", state=DISABLED) elif best_move == 8 and free_space(best_move) == True: btn8.config(text=computer, bg="grey70", state=DISABLED) elif best_move == 9 and free_space(best_move) == True: btn9.config(text=computer, bg="grey70", state=DISABLED) place_mark(best_move, computer) return def minimax(depth, isMaximizing): if (who_won(computer)): return 1 elif (who_won(player)): return -1 elif (check_draw()): return 0 if (isMaximizing): best_score = -800 for key in board.keys(): if (free_space(key) == True): board[key] = computer score = minimax(depth + 1, False) board[key] = " " if (score > best_score): best_score = score return best_score else: best_score = 800 for key in board.keys(): if (free_space(key) == True): board[key] = player score = minimax(depth + 1, True) board[key] = " " if (score < best_score): best_score = score return best_score def comp_turn(): if new_gamemode == True: computer_move() def reset(): global x x = 0 for i in board.keys(): #i is a random variable board[i] = " " print_board() winner_label["text"] = "" btn1.config(text="", bg="lightgrey", state=NORMAL) btn2.config(text="", bg="lightgrey", state=NORMAL) btn3.config(text="", bg="lightgrey", state=NORMAL) btn4.config(text="", bg="lightgrey", state=NORMAL) btn5.config(text="", bg="lightgrey", state=NORMAL) btn6.config(text="", bg="lightgrey", state=NORMAL) btn7.config(text="", bg="lightgrey", state=NORMAL) btn8.config(text="", bg="lightgrey", state=NORMAL) btn9.config(text="", bg="lightgrey", state=NORMAL) def click1(): turn() if new_gamemode == True: place_mark(0, player) comp_turn() else: place_mark(0, player) btn1["text"] = player btn1["state"] = DISABLED btn1["bg"] = "grey70" def click2(): turn() if new_gamemode == True: place_mark(2, player) comp_turn() else: place_mark(2, player) btn2["text"] = player btn2["state"] = DISABLED btn2["bg"] = "grey70" def click3(): turn() if new_gamemode == True: place_mark(3, player) comp_turn() else: place_mark(3, player) btn3["text"] = player btn3["state"] = DISABLED btn3["bg"] = "grey70" def click4(): turn() if new_gamemode == True: place_mark(4, player) comp_turn() else: place_mark(4, player) btn4["text"] = player btn4["state"] = DISABLED btn4["bg"] = "grey70" def click5(): turn() if new_gamemode == True: place_mark(5, player) comp_turn() else: place_mark(5, player) btn5["text"] = player btn5["state"] = DISABLED btn5["bg"] = "grey70" def click6(): turn() if new_gamemode == True: place_mark(6, player) comp_turn() else: place_mark(6, player) btn6["text"] = player btn6["state"] = DISABLED btn6["bg"] = "grey70" def click7(): turn() if new_gamemode == True: place_mark(7, player) comp_turn() else: place_mark(7, player) btn7["text"] = player btn7["state"] = DISABLED btn7["bg"] = "grey70" def click8(): turn() if new_gamemode == True: place_mark(8, player) comp_turn() else: place_mark(8, player) btn8["text"] = player btn8["state"] = DISABLED btn8["bg"] = "grey70" def click9(): turn() if new_gamemode == True: place_mark(9, player) comp_turn() else: place_mark(9, player) btn9["text"] = player btn9["state"] = DISABLED btn9["bg"] = "grey70" def new_game(): reset() if play_as_O == True: pvc2() def pvp(): global new_gamemode global play_as_O new_gamemode = False play_as_O = False reset() #Player go first and plays as X def pvc1(): global new_gamemode global play_as_O new_gamemode = True play_as_O = False reset() #Player go second and plays as O def pvc2(): global new_gamemode global play_as_O reset() new_gamemode = True play_as_O = True turn() comp_turn() print_board() window = Tk() window.title("Tic Tac Toe") window.geometry("300x300") window.resizable(False, False) window.columnconfigure(0, weight=1) main_label = Label(text="Tic Tac Toe", pady= 10, font=("Helvetica", 15)) main_label.pack() frameM = Frame(window) frameM.pack() frame1 = Frame(window) frame1.pack() frame2 = Frame(window) frame2.pack() frame3 = Frame(window) frame3.pack() btn1 = Button(frame1, text="", bg="lightgrey", width= 8, pady= 15, font=("Helvetica", 10), command=click1) btn1.pack(side=LEFT) btn2 = Button(frame1, text="", bg="lightgrey", width= 8, pady= 15, font=("Helvetica", 10), command=click2) btn2.pack(side=LEFT) btn3 = Button(frame1, text="", bg="lightgrey", width= 8, pady= 15, font=("Helvetica", 10), command=click3) btn3.pack(side=LEFT) btn4 = Button(frame2, text="", bg="lightgrey", width= 8, pady= 15, font=("Helvetica", 10), command=click4) btn4.pack(side=LEFT) btn5 = Button(frame2, text="", bg="lightgrey", width= 8, pady= 15, font=("Helvetica", 10), command=click5) btn5.pack(side=LEFT) btn6 = Button(frame2, text="", bg="lightgrey", width= 8, pady= 15, font=("Helvetica", 10), command=click6) btn6.pack(side=LEFT) btn7 = Button(frame3, text="", bg="lightgrey", width= 8, pady= 15, font=("Helvetica", 10), command=click7) btn7.pack(side=LEFT) btn8 = Button(frame3, text="", bg="lightgrey", width= 8, pady= 15, font=("Helvetica", 10), command=click8) btn8.pack(side=LEFT) btn9 = Button(frame3, text="", bg="lightgrey", width= 8, pady= 15, font=("Helvetica", 10), command=click9) btn9.pack(side=LEFT) winner_label = Label(text="", fg="red", pady= 10, font=("Helvetica", 13)) winner_label.pack() menu_bar = Menu(frameM) window.config(menu = menu_bar) game_menu = Menu(menu_bar, tearoff=0) option_menu = Menu(menu_bar, tearoff=0) change_sign_menu = Menu(option_menu, tearoff=0) menu_bar.add_cascade(label="Game", menu=game_menu) menu_bar.add_cascade(label="Options", menu=option_menu) game_menu.add_command(label="New Game", command=new_game) game_menu.add_separator() game_menu.add_command(label="Exit", command=window.quit) option_menu.add_command(label="PvP", command=pvp) option_menu.add_cascade(label="PVC", menu=change_sign_menu) change_sign_menu.add_command(label="Play as X", command=pvc1) change_sign_menu.add_command(label="Play as O", command=pvc2) window.mainloop()
fa7ee8f13255f1ceda3e28c58c427c84bf81817f
LionrChen/GraphFeaturesExtraction
/graph/graph.py
7,797
3.546875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __title__ = '' __author__ = 'ChenSir' __mtime__ = '2019/7/16' # code is far away from bugs with the god animal protecting I love animals. They taste delicious. ┏┓ ┏┓ ┏┛┻━━━┛┻┓ ┃ ┃ ┃ ┳┛ ┗┳ ┃ ┃ ┻ ┃ ┗━┓ ┏━┛ ┃ ┗━━━┓ ┃神兽保佑 ┣┓ ┃ 永无BUG! ┏┛ ┗┓┓┏━━┳┓┏┛ ┃┫┫ ┃┫┫ ┗┻┛ ┗┻┛ """ from graphBase import GraphBase from node import Node from edge import Edge class Graph(GraphBase): def __init__(self, directed=False, weighted=False): super().__init__(directed, weighted) def add_node(self, value): try: new_node = Node(value) self.nodes[value] = new_node return new_node except: print("Invalid vertex id '{}', may be exits.".format(value)) def add_nodes(self, node_list): for node_name in node_list: new_node = Node(node_name) try: self.nodes[node_name] = new_node except: print("Invalid vertex id '{}', may be exits.".format(node_name)) def add_edge(self, sour, terg): try: if not self.weighted: new_edge = Edge(False, sour, terg) self.edges.append(new_edge) self.update(new_edge) except: print("The edge already exits.") def add_weight_edge(self, weight, sour, terg): try: if self.weighted: new_edge = Edge(weight, sour, terg) self.edges.append(new_edge) self.update(new_edge) except: print("The edge already exits.") def add_edges(self, edges): """ Example to [(from, to)] """ for edge in edges: try: if not self.weighted: new_edge = Edge(False, edge[0], edge[1]) self.edges.append(new_edge) self.update(new_edge) except: print("The edge already exits.") def update(self, edge): self.nodes.get(edge.head).indegree += 1 self.nodes.get(edge.tail).outdegree += 1 self.nodes.get(edge.tail).nexts.append(edge.head) self.nodes.get(edge.tail).edges.append(edge) def subgraph(self, nodes): """ Here nodes is list about node's value. """ new_graph = Graph() for node_key in nodes: node = Node(self.nodes.get(node_key).value) neighbors = list(set(self.nodes.get(node_key).nexts).intersection(set(nodes))) node.nexts = neighbors new_graph.nodes[node_key] = node return new_graph def jaccard_coefficient(self, node1, node2): """ This coefficient use to measure the ratio between the number of two node's common neighbors and them total neighbors. """ first_node = self.nodes.get(node1).nexts second_node = self.nodes.get(node2).nexts common_friends = list(set(first_node).intersection(set(second_node))) division = first_node.__len__() + second_node.__len__() if division is not 0: return format(common_friends.__len__() / division, '.6f') def total_neighbors(self, node1, node2): """ If node1 and node2 are exits, them total neighbors are the add between the node1 and node2. """ first_node = self.nodes.get(node1).nexts second_node = self.nodes.get(node2).nexts print("The number of total neighbors of Node {} and {} is {}.".format(node1, node2, first_node.__len__() + second_node.__len__())) return first_node.__len__() + second_node.__len__() def preference_attachment(self, node1, node2): """ the probability that two users yield an association in certain period of time is proportional to the product of the number of one user's neighborhoods and that of another's neighborhoods. """ first_node = self.nodes.get(node1).nexts second_node = self.nodes.get(node2).nexts print("The score of preference attachment of Node {} and {} is {}.".format(node1, node2, first_node.__len__() * second_node.__len__())) return first_node.__len__() * second_node.__len__() def friend_measure(self, node1, node2): """ the more connections their neighborhoods have with each other, the higher the chances the two users are connected in a social network. """ first_node = self.nodes.get(node1).nexts second_node = self.nodes.get(node2).nexts F_fm = 0 for node_key in first_node: x_node = self.nodes.get(node_key) for node_key_sec in second_node: # y_node = self.nodes.get(node_key_sec) if node_key is not node_key_sec and node_key_sec not in x_node.nexts: F_fm += 1 print("The score of friend measure of Node {} and {} is {}.".format(node1, node2, F_fm)) return F_fm def SCC_graph(graph): """ calculate the number of strongly connected components within neighborhood-subgraph. First generate 1-dimensional neighborhood-subgraph with source and target node. a sample of graph, use dict to store graph. G = { 'a': {'b', 'c'}, 'b': {'d', 'e', 'i'}, 'c': {'d'}, 'd': {'a', 'h'}, 'e': {'f'}, 'f': {'g'}, 'g': {'e', 'h'}, 'h': {'i'}, 'i': {'h'} } """ nodes = graph.nodes # reverse graph def reverse_graph(nodes): re_graph = dict() for key in nodes.keys(): node = nodes.get(key) node.reset_attr() re_graph[key] = node # reverse edge for key in nodes.keys(): for nei in nodes[key].nexts: re_graph[nei].nexts.append(key) return re_graph # gain a sequence sorted by time def topo_sort(nodes): res = [] S = set() # Depth-first traversal/search def dfs(nodes, u): if u in S: return S.add(u) for v in nodes[u].nexts: if v in S: continue dfs(nodes, v) res.append(u) # check each node was leave out for u in nodes.keys(): dfs(nodes, u) res.reverse() return res # gain singe strongly connected components with assigns start node def walk(nodes, s, S=None): if S is None: s = set() Q = [] P = dict() Q.append(s) P[s] = None while Q: u = Q.pop() for v in nodes[u].nexts: if v in P.keys() or v in S: continue Q.append(v) P[v] = P.get(v, u) return P # use to record the node of strongly connected components seen = set() # to store scc scc = [] GT = reverse_graph(nodes) for u in topo_sort(nodes): if u in seen: continue C = walk(GT, u, seen) seen.update(C) scc.append(sorted(list(C.keys()))) print("The number of strongly connected components of graph is {}.".format(scc.__len__())) return scc
67fe9255295af578c9721b7847299ebe185cf5b8
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Personal_programs/Input_E_rapprString.py
676
4.34375
4
# La funzione input(...) restituisce un tipo stringa, anche se viene passato un numero int o float # Puoi rappresentare una stringa concatenata in diversi modi: # 1- Concatenandola con + e convertendo i numeri con str() ----> 'numero: ' + str(3.6) # 2- Utilizzando la virgola( , ) come separatore tra stringhe e numeri o altre stringhe: 'numero' , ':' , 5 # 3- Mediante Formatted-String Literal ----> f"Il numero è { 5 }" print('numero: ' + str(3.6)) print('numero', ':', 5) print(f"Il numero è { 5 }") print(f"numero uno: { 10 }, numero2: { 22 }, loro somma: { 10 + 22 } \n") prova = input('Inserisci qualcosa: \n') print(f"Hai inserito '{ prova }', complimenti!'")
7de1ba91ebbb95ade3f54e652560b2c65369b1e3
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Corso_CISCO_netacad/Strings_in_Python/s8_center_method.py
720
4.25
4
# The one-parameter variant of the center() method makes a copy of the original string, # trying to center it inside a field of a specified width. # The centering is actually done by adding some spaces before and after the string. # Demonstrating the center() method print('[' + 'alpha'.center(10) + ']') print('[' + 'Beta'.center(2) + ']') print('[' + 'Beta'.center(4) + ']') print('[' + 'Beta'.center(6) + ']') # The two-parameter variant of center() makes use of the character from the second argument, # instead of a space. Analyze the example below: print('[' + 'gamma'.center(20, '*') + ']') s1 = "Pasquale".center(30) print(s1) print("length:", len(s1)) s2 = "Pasquale Silvestre".center(50, "-") print(s2) print(len(s2))
27598f79de97818823527e23f3969c27959f8702
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Corso_CISCO_netacad/Strings_in_Python/s15_split.py
617
4.46875
4
# The # split() # method does what it says - it splits the string and builds a list of all detected substrings. # The method assumes that the substrings are delimited by whitespaces - the spaces don't take part in the operation, # and aren't copied into the resulting list. # If the string is empty, the resulting list is empty too. # Demonstrating the split() method print("phi chi\npsi".split()) # Note: the reverse operation can be performed by the join() method. print("-------------------------") # Demonstrating the startswith() method print("omega".startswith("meg")) print("omega".startswith("om"))
0c10af8575d97394bbcb9c2363a82fe424df2bd0
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Corso_CISCO_netacad/integers_octal_exadecimal.py
1,053
4.53125
5
# If an integer number is preceded by an 0O or 0o prefix (zero-o), # it will be treated as an octal value. This means that the number must contain digits taken from the [0..7] range only. # 0o123 is an octal number with a (decimal) value equal to 83. print(0o123) # The second convention allows us to use hexadecimal numbers. # Such numbers should be preceded by the prefix 0x or 0X (zero-x). # 0x123 is a hexadecimal number with a (decimal) value equal to 291. The print() function can manage these values too. print(0x123) print(4 == 4.0) print(.4) print(4.) # On the other hand, it's not only points that make a float. You can also use the letter e. # When you want to use any numbers that are very large or very small, you can use scientific notation. print(3e8) print(3E8) # The letter E (you can also use the lower-case letter e - it comes from the word exponent) # is a concise record of the phrase times ten to the power of. print("----------------------------------------------------------") print(0.0000000000000000000001) print(1e-22)
212a0b661d06ce21a27e70d775accdbddb3a8b1e
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Corso_CISCO_netacad/number_literals.py
907
3.703125
4
# Python 3.6 has introduced underscores in numeric literals, # allowing for placing single underscores between digits and after base specifiers for improved readability. # This feature is not available in older versions of Python. """ If you'd like to quickly comment or uncomment multiple lines of code, select the line(s) you wish to modify and use the following keyboard shortcut: CTRL + / -------------------------> (Windows) or CMD + / ------------------- ---> (Mac OS). It's a very useful trick, isn't it? """ print(11_111_111 * 2) print(11111111) print(11_111_111) print("/" == "/") # Col 7 e non print("------------------------------------") leg_a = float(input("Input first leg length: ")) leg_b = float(input("Input second leg length: ")) hypo = (leg_a**2 + leg_b**2) ** .5 print("Hypotenuse length is", hypo) print("Concateno:", 33, hypo, 3.33, True)
fd80e5cecb0c723cf52c16e6b112648476b37388
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Python_Data_Science_Toolbox_Part1/Nested_Functions/NestedFunc1.py
548
4.1875
4
# Define three_shouts def three_shouts(word1, word2, word3): """Returns a tuple of strings concatenated with '!!!'.""" # Define inner def inner(word): """Returns a string concatenated with '!!!'.""" return word + '!!!' # Return a tuple of strings return (inner(word1), inner(word2), inner(word3)) # Call three_shouts() and print print(three_shouts('a', 'b', 'c')) print() tupla_prova = three_shouts('Pasquale', 'Ignazio', 'Laura') print(tupla_prova) var1, var2, var3 = tupla_prova print(var1, var2, var3)
15d42320cb2c5217991e7b6202330c9e5e5fa414
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Corso_CISCO_netacad/Strings_in_Python/s7.py
458
4.4375
4
# Demonstrating the capitalize() method print('aBcD'.capitalize()) print("----------------------") # The endswith() method checks if the given string ends with the specified argument and returns True or False, # depending on the check result. # Demonstrating the endswith() method if "epsilon".endswith("on"): print("yes") else: print("no") t = "zeta" print(t.endswith("a")) print(t.endswith("A")) print(t.endswith("et")) print(t.endswith("eta"))
ada5381cdf4e7ce76bd87b681ea3e233ab83fbc2
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Python_Data_Science_Toolbox_Part1/Part_III/reduce_and_LambdaFunc.py
439
3.9375
4
# Import reduce from functools from functools import reduce # Create a list of strings: stark stark = ['robb', 'sansa', 'arya', 'brandon', 'rickon'] # Use reduce() to apply a lambda function over stark: result result = reduce(lambda item1, item2: item1 + item2, stark) # Print the result print(result) listaNum = [3, 5, 2, 10] somma = reduce(lambda x, y: x + y, listaNum) # Printa la somma di tutti i numeri della lista print(somma)
a959f8c5d7ec65d50fea6f6ca640524a04e13501
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Regular_Expressions_in_Python/Positional_String_formatting/Positional_formatting1.py
812
4.15625
4
# positional formatting ------> .format() wikipedia_article = 'In computer science, artificial intelligence (AI), sometimes called machine intelligence, ' \ 'is intelligence demonstrated by machines, ' \ 'in contrast to the natural intelligence displayed by humans and animals.' my_list = [] # Assign the substrings to the variables first_pos = wikipedia_article[3:19].lower() second_pos = wikipedia_article[21:44].lower() # Define string with placeholders my_list.append("The tool '{}' is used in '{}'") # Define string with rearranged placeholders my_list.append("The tool '{1}' is used in '{0}'") # That's why it's called 'POSITIONAL FORMATTING' # Use format to print strings for my_string in my_list: print(my_string.format(first_pos, second_pos))
968bee9c854610fd5799d875dae04d4227c74cfe
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Functions and packages/PackagesInPython/MathPackageInPython.py
653
4.34375
4
""" As a data scientist, some notions of geometry never hurt. Let's refresh some of the basics. For a fancy clustering algorithm, you want to find the circumference, C, and area, A, of a circle. When the radius of the circle is r, you can calculate C and A as: C=2πr A=πr**2 To use the constant pi, you'll need the math package. """ # Import the math package import math # Definition of radius r = 0.43 # Calculate C C = 2*r*math.pi # Calculate A A = math.pi*r**2 # Build printout print("Circumference: " + str(C)) print("Area: " + str(A)) print() print(math.pi) print("PiGreco dal package math = " + str(math.pi))
22d7fa76f904a0ac5061338e9f90bb3b9afd5d41
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Corso_CISCO_netacad/Lists/list4.py
288
3.734375
4
# A four-column/four-row table - a two dimensional array (4x4) table = [[":(", ":)", ":(", ":)"], [":)", ":(", ":)", ":)"], [":(", ":)", ":)", ":("], [":)", ":)", ":)", ":("]] print(table) print(table[0][0]) # outputs: ':(' print(table[0][3]) # outputs: ':)'
370b98c1d042d5e7f9d98bcac7c72a2eb080385d
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Personal_programs/RandomNum.py
165
3.5625
4
import random print(random.randint(0, 100)) num_int_rand = random.randint(20, 51) print(num_int_rand) for i in range(0, 10): print(random.randint(-2100,1001))
7c92ab969dc4636d99ebe3db1de310dff9dd8727
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Working_with_relational_databases_in_Python/sqliteDB4.py
729
3.625
4
from sqlalchemy import create_engine import pandas as pd engine = create_engine('sqlite:///DB4.sqlite') # Open engine in context manager # Perform query and save results to DataFrame: df with engine.connect() as con: # come con file non hai bisogno di chiudere la connessione in questo modo. rs = con.execute('SELECT LastName, Title FROM Employee;') df = pd.DataFrame(rs.fetchmany(size=3)) # fetchmany(size=3) considere aolamente le prime 3 righe, fetchall() considera tutto. df.columns = rs.keys() # Va a settore il nome delle colonne del DF, altrimenti solo indici. # Print the length of the DataFrame df print(len(df)) # Print the head of the DataFrame df print(df.head())
100d7f48a899c20b52ee5479eccd7422a87aa667
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Python_Lists/Python_Lists11.py
707
4.125
4
# you can also remove elements from your list. You can do this with the del statement: # Pay attention here: as soon as you remove an element from a list, the indexes of the elements that come after the deleted element all change! x = ["a", "b", "c", "d"] print(x) del(x[1]) # del statement print(x) areas = ["hallway", 11.25, "kitchen", 18.0, "chill zone", 20.0, "bedroom", 10.75, "bathroom", 10.50, "poolhouse", 24.5, "garage", 15.45] print(areas) del(areas[-4:-2]) print(areas) """ The ; sign is used to place commands on the same line. The following two code chunks are equivalent: # Same line command1; command2 # Separate lines command1 command2 """
459188df05fa37b88c1e811b37fae93e096f1ce0
Pasquale-Silv/Improving_Python
/Python Programming language/SoloLearnPractice/ListsInPython/ProofList.py
305
4.03125
4
number = 3 things = ["string", 0, [1, 2, number], 4.56] print(things[1]) print(things[2]) print(things[2][2]) print("----------------------") str = "Hello world!" print(str[6]) print(str[6-1]) print(str[6-2]) print("--------------------------") nums = [1, 2, 3] print(nums + [4, 5, 6]) print(nums * 3)
1ff840fef8bc267fcf37268800d9bd29dd86f521
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Python_Data_Science_Toolbox_Part2/Generators_and_GENfunc_yield/GEN2.py
462
4.34375
4
# [ LIST COMPREHENSION ] # ( GENERATOR ) # Recall that generator expressions basically have the same syntax as list comprehensions, # except that it uses parentheses () instead of brackets [] # Create generator object: result result = (num for num in range(31)) # Print the first 5 values print(next(result)) print(next(result)) print(next(result)) print(next(result)) print(next(result)) # Print the rest of the values for value in result: print(value)
b3a3caf850d4fffd6f0864bfc293175ab28fd76c
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Python_Data_Science_Toolbox_Part1/Part_I/modulo_builtins.py
820
4.09375
4
import builtins print(builtins) print(dir(builtins)) prova = input('Cerca nel modulo builtins: \n') if prova in dir(builtins): print('La parola', prova, 'è presente nel modulo builtins.') else: print('La parola ' + prova + ' non è stata trovata.') """ Here you're going to check out Python's built-in scope, which is really just a built-in module called builtins. However, to query builtins, you'll need to import builtins 'because the name builtins is not itself built in... No, I’m serious!' (Learning Python, 5th edition, Mark Lutz). After executing import builtins in the IPython Shell, execute dir(builtins) to print a list of all the names in the module builtins. Have a look and you'll see a bunch of names that you'll recognize! Which of the following names is NOT in the module builtins? """
42582cf388cabe7d0ea2e243f171b6608d772443
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Python_Data_Science_Toolbox_Part1/Part_III/Filter_and_LambdaFunc.py
395
4.0625
4
# Create a list of strings: fellowship fellowship = ['frodo', 'samwise', 'merry', 'pippin', 'aragorn', 'boromir', 'legolas', 'gimli', 'gandalf'] # Use filter() to apply a lambda function over fellowship: result result = filter(lambda stringa: len(stringa) > 6, fellowship) # Convert result to a list: result_list print(result) result_list = list(result) # Print result_list print(result_list)
25f9ce7108bc60f7825425c67c7bb1366f184c91
SGiuri/hamming
/hamming.py
465
3.59375
4
def distance(strand_a, strand_b): # Check equal Lenght if len(strand_a) != len(strand_b): raise ValueError("Equal length not verified") # set up a counter of differences hamming_difference = 0 # checking each letter for j in range(len(strand_a)): # if there is a difference, increasing the hamming difference by 1 if strand_a[j] != strand_b[j]: hamming_difference += 1 return hamming_difference
ec1a49268a967c2d28c39a06e42f8af02f4d4c26
zomgroflmao/1st_lesson
/vat.py
162
3.578125
4
def get_vat(price, vat_rate): vat = price / 100 * vat_rate price_no_vat = price - vat print(price_no_vat) price1 = 100 vat_rate = 18 get_vat(price1, vat_rate1)
04ce4745d854c9d712ac5089ad94573fe287fae9
anjiboini/anji_python_games
/anji_tkinter_database.py
672
3.5625
4
from tkinter import * from PIL import ImageTk,Image import sqlite3 root = Tk() root.title('Wellcome to India') root.iconbitmap('D:/anji_python software/python/anji tkinter projects/resources/thanu1.ico') root.geometry("400x400") #Databases #Create a Databases or connect one conn = sqlite3.connect('address_book.db') #Create cursor c = conn.cursor() #Create table c.execute(""" CREATE TABLE addresses ( first_name text, last_name text, address text, city text, state text, zipcode integer)""") conn.commit() conn.close() root.mainloop()
21f6b720fa94adb9330322339200a7c8a7e246f6
anjiboini/anji_python_games
/anji_tkinter_databaseusing1.py
1,603
4
4
from tkinter import * from PIL import ImageTk,Image import sqlite3 root = Tk() root.title('Wellcome to India') root.iconbitmap('D:/anji_python software/python/anji tkinter projects/resources/thanu1.ico') root.geometry("400x400") #Databases # Create a Databases or connect one conn = sqlite3.connect('address_book8.db') # Create cursor c = conn.cursor() #Create table '''' c.execute(""" CREATE TABLE addresses ( first_name text, last_name text)""") ''' def submit(): # Create a Databases or connect one conn = sqlite3.connect('address_book8.db') # Create cursor c = conn.cursor() #Insert into table c.execute("INSERT INTO addresses VALUES (:f_name, :l_name )", { 'f_name': f_name.get(), 'l_name': l_name.get(),}) conn.commit() conn.close() #clear the text boxes f_name.delete(0, END) l_name.delete(0, END) #Create Query function #create text boxes f_name = Entry(root,width=30) f_name.grid(row=0,column=1,padx=20,pady=(10,0)) l_name = Entry(root,width=30) l_name.grid(row=1,column=1,padx=20) #create text boxes labels f_name_label= Label(root, text="First Name").grid(row=0,column=0,padx=20,pady=(10,0)) l_name_name_label= Label(root, text="Last Name").grid(row=1,column=0,padx=20) #Create Submit Button submit_btn = Button(root, text="Add Record to Database", command=submit) submit_btn.grid(row=3, column=0,columnspan=2,padx=10,pady=10,ipadx=100) conn.commit() conn.close() root.mainloop()
e478ccc2cff10e77e0a85ce42f68bb822ee61d5e
anjiboini/anji_python_games
/anji_tkinte_01.py
2,561
3.765625
4
from tkinter import * #.............................................. #root=Tk() #theLable=Label(root,text="Hi anji how r u") #theLable.pack() #root.mainloop() #............................................ #one=Label(root, text="One", bg="red",fg="white") #one.pack() #two=Label(root, text="Two", bg="yellow",fg="black") #two.pack(fill=X) #three=Label(root, text="Three", bg="blue",fg="white") #three.pack(side=LEFT,fill=Y) #topFrame=Frame(root) #topFrame.pack() #bottomFrame=Frame(root) #bottomFrame.pack(side=BOTTOM) #....................................... #button1 = Button(topFrame, text="Thanu sri",fg="red",bg="green",padx=50,pady=50,font=300) #button2 = Button(topFrame, text="Yesha sri",fg="blue",bg="green",padx=50,pady=50,font=300) #button3 = Button(topFrame, text="Yesha sri",fg="blue",bg="green",padx=50,pady=50,font=300) #button4 = Button(topFrame, text="Yesha sri",fg="blue",bg="green",padx=50,pady=50,font=300) #button5 = Button(bottomFrame, text="Yesha sri",fg="blue",bg="green",padx=50,pady=50,font=300) #button6 = Button(bottomFrame, text="Yesha sri",fg="blue",bg="green",padx=50,pady=50,font=300) #button1.pack(side=LEFT) #button2.pack(side=LEFT) #button3.pack(side=LEFT) #button4.pack(side=LEFT) #button5.pack(side=BOTTOM) #button6.pack(side=BOTTOM) #root.mainloop() #......................................... #lable1=Label(root, text="Name") #lable2=Label(root, text="Password") #entry1=Entry(root) #entry2=Entry(root) #lable1.grid(row=0,column=1) #lable2.grid(row=1,column=1) #entry1.grid(row=0,column=2) #entry2.grid(row=1,column=2) #c = Checkbutton(root, text="Keep me logged in") #c.grid(columnspan=2) #root.mainloop() #............................................................. #def printName(): # print("Hello thanu sri whate are you doing") #button1=Button(root, text="Click here", command=printName) #button1.pack() #root.mainloop() #................................................. class PressButtons: def __init__(self,master): frame=Frame(master) frame.pack() self.printButton=Button(frame, text="print message", command=self.printMessage) self.printButton.pack(side=LEFT) self.quitButton = Button(frame, text="Quit", command=frame.quit) self.quitButton.pack(side=LEFT) def printMessage(self): open("wow it is working") root= Tk() b = PressButtons(root) root.mainloop() #.........................................................................
4f7496a27ea1bc08d7252326cea3ee912857e39a
Angelagoodboy/Python_classifyCustomer
/Main.py
430
3.546875
4
#调用Python文件并且实现输入不同参数对应不同分类组合 import sys #实现脚本上输入参数 def main(): try: Type=sys.argv[1] FileInputpath=sys.argv[2] FileOutpupath=sys.argv[3] if Type=='-r': # 调用客户模块: except IndexError as e: print("输入的错误参数") if __name__ == '__main__': print('helloworld') main()
0e73fa953efc7182444e9bd7148d489b48f92ef6
sksuharsh1611/py18thjune2018
/code21june.py
1,418
3.515625
4
#!/usr/bin/python2 import time,webbrowser,commands menu=''' press 1: To check current date and time: press 2: To scan all your Mac Address in your current cOnnected Network: press 3: To shutdown your machine after 15 minutes: press 4: To search something on Google: press 5: To logout your current machine: press 6: To shutdown all cOnnected system in your current Network: press 7: To Update status on your Facebook: press 8: To list Ip Addresses of given Website: ''' print menu choice=raw_input("Enter your choice:") if choice == '1' : print "current date and time is : ",time.ctime() elif choice == '2' : x=commands.getoutput('cat /sys/class/net/*/address') print x elif choice == '3' : print "Your system is being shutting down after 15 minutes" commands.getoutput("sudo shutdown +1") elif choice == '4' : find=raw_input("enter your query : ") webbrowser.open_new_tab("https://www.google.com/search?q="+find) elif choice == '5' : print "logging out from your current machine: " commands.getoutput("exit") #elif choice == '6' : elif choice == '7': print "update status in facebook" username=raw_input("enter your username : ") passwd=raw_input("enter your password : ") webbrowser.open_new_tab("https://touch.facebook.com/login/") elif choice == '8' : web=raw_input("enter your website : ") ip=commands.getoutput("host "+web) print ip else : print "Invalid OPtion"
0f62b89ad95ca5e8bee9b211dc1b5bb6f940234b
melodyquintero/python-challenge
/PyPoll/main.py
2,291
3.9375
4
# Import Modules for Reading raw data import os import csv # Set path for file csvpath = os.path.join('raw_data','election_data_1.csv') # Lists to store data ID = [] County = [] Candidate = [] # Open and read the CSV, excluding header with open(csvpath, newline="") as csvfile: next(csvfile) csvreader = csv.reader(csvfile, delimiter=",") for row in csvreader: # Add ID data to the list ID.append(row[0]) # Add County data to the list County.append(row[1]) # Add Candidate data to the list Candidate.append(row[2]) # Count total number of votes Votes_count = len(ID) # Import collections to group votes by different candidates import collections counter=collections.Counter(Candidate) # With the results of collections, place candidate names and their votes to lists candidate_name =list(counter.keys()) candidate_votes = list(counter.values()) # list candidate votes percentage to store data candidate_percent = [] # calculate and formate votes percentage by candidates for i in range(len(candidate_name)): candidate_i_percent='{0:.1%}'.format(float(candidate_votes[i])/Votes_count) # add candidates percentage to the list candidate_percent.append(candidate_i_percent) # locate the index of highest votes and apply on candidate names to find the winner Winner_index = candidate_votes.index(max(candidate_votes)) Winner = candidate_name[Winner_index] # Print results on terminal print("Election Results") print("-"*30) print("Total Votes: "+ str(Votes_count)) print("-"*30) for j in range(len(candidate_name)): print(str(candidate_name[j])+": "+ str(candidate_percent[j])+ " ("+str(candidate_votes[j])+")") print("-"*30) print("Winner: "+str(Winner)) print("-"*30) # Export Text File with open("Election_Results.txt", "w+") as f: f.write("Election Results"+"\n") f.write("-"*30+"\n") f.write("Total Votes: "+ str(Votes_count)+"\n") f.write("-"*30+"\n") for j in range(len(candidate_name)): f.write(str(candidate_name[j])+": "+ str(candidate_percent[j])+ " ("+str(candidate_votes[j])+")"+"\n") f.write("-"*30+"\n") f.write("Winner: "+str(Winner)+"\n") f.write("-"*30+"\n")
cf7dbbfe0ffb7790452be0d9b0734d0f1886ce5b
Vishal19914/VishalClock
/test_clock.py
473
3.625
4
import unittest from clock import Clock_Angle class TestClock(unittest.TestCase): def test_check_angle(self): ca= Clock_Angle(3,0) angle= ca.checkValues() self.assertEqual(angle,90, "Angle is 90") def test_check_range(self): ca= Clock_Angle(23213,4324) result= ca.checkValues() self.assertEqual(result,"Incorrect hour and minutes value", "incorrect values" ) if __name__ == '__main__': unittest.main()
0d77b125701172493da106652ef0aa30551cc60c
tuxnani/open-telugu
/tamil/tscii2utf8.py
626
3.546875
4
#!/usr/bin/python # -*- coding: utf-8 -*- # (C) 2013 Muthiah Annamalai from sys import argv, exit import tamil def usage(): return u"tscii2utf8.py <filename-1> <filename-2> ... " if __name__ == u"__main__": if not argv[1:]: print( usage() ) exit(-1) for fname in argv[1:]: try: with open(fname) as fileHandle: output = tamil.tscii.convert_to_unicode( fileHandle.read() ) print( output ) except Exception as fileOrConvException: print(u"tscii2utf8 error - file %s could not be processed due to - %s"%(fname,str(fileOrConvException)))
7e8298e4733a357b535d473549a4d467b9a7f354
dilithjay/Double-Blank-NPuzzle-AStar
/Python/a_star.py
2,988
3.515625
4
from enum import Enum from queue import PriorityQueue from time import time from utils import get_blanks, get_heuristic_cost_manhattan, get_heuristic_cost_misplaced, get_2d_array_copy, swap BLANK_COUNT = 2 DIRECTION_COUNT = 4 dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)] opposite_dirs = ('down', 'up', 'right', 'left') class HeuristicType(Enum): MISPLACED = 1 MANHATTAN = 2 # A node in the search tree class State: def __init__(self, config, blanks, cost, path): self.config = config self.blanks = blanks self.cost = cost self.path = path def __lt__(self, other): return self.cost <= other.cost class AStarSearch: def __init__(self, start, goal, cost_type=HeuristicType.MISPLACED): self.goal = goal self.n = len(start) self.cost_type = cost_type state = State(start, get_blanks(start), self.get_cost(start), ()) self.open_set = PriorityQueue() self.open_set.put(state) self.closed_set = set() self.iter_count = 0 self.time = 0 def search(self) -> str: """ Perform A* search over possibilities of steps. :return: Path as a string. Format: (1st number to move, move direction (as word)), (2nd number, direction),... """ start_time = time() while not self.open_set.empty(): self.iter_count += 1 state = self.open_set.get() config = state.config if str(config) not in self.closed_set: self.closed_set.add(str(config)) else: continue path = state.path # if cost from heuristic is 0 (goal achieved) if state.cost == len(path): self.time = time() - start_time return ",".join(path) for i in range(BLANK_COUNT): blank = state.blanks[i] for j in range(DIRECTION_COUNT): r, c = blank[0] + dirs[j][0], blank[1] + dirs[j][1] if 0 <= r < self.n and 0 <= c < self.n and config[r][c] != '-': mat = get_2d_array_copy(config) swap(mat, blank, (r, c)) cost = self.get_cost(mat) path_new = path + (f"({mat[blank[0]][blank[1]]},{opposite_dirs[j]})",) self.open_set.put(State(mat, [state.blanks[i - 1]] + [[r, c]], cost + len(path_new), path_new)) return "Failed" def get_cost(self, config): """ Get the cost of the given configuration as per the chosen heuristic. :param config: Configuration matrix as a 2D list. :return: Cost of the input configuration """ if self.cost_type == HeuristicType.MISPLACED: return get_heuristic_cost_misplaced(config, self.goal) # self.cost_type == HeuristicType.MANHATTAN: return get_heuristic_cost_manhattan(config, self.goal)
0b03516098b1e064bad91970b932624408fe53fc
ryanmp/project_euler
/p056.py
875
4.0625
4
''' A googol (10^100) is a massive number: one followed by one-hundred zeros; 100^100 is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1. Considering natural numbers of the form, ab, where a, b < 100, what is the maximum digital sum? ''' def main(): n = 100 maximum_digit_sum = 0 for a in xrange(n): for b in xrange(n): new_sum = digit_sum(a**b) maximum_digit_sum = max(new_sum, maximum_digit_sum) return maximum_digit_sum # in: an integer n # out: the sum of the digits in n # since Python supports arbitrarily large Ints, we should be just fine def digit_sum(n): return sum([int(i) for i in list(str(n))]) if __name__ == '__main__': import boilerplate, time, resource t = time.time() r = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss boilerplate.all(main(), t, r)
6ab7b8b1135b74d6572efd98bb64f86f85e468ce
ryanmp/project_euler
/p076.py
1,263
4.15625
4
''' counting sums explanation via example: n == 5: 4 + 1 3 + 2 3 + 1 + 1 2 + 2 + 1 2 + 1 + 1 + 1 1 + 1 + 1 + 1 + 1 if sum == 5 -> there are 6 different combos ''' def main(): return 0 # how many different ways can a given number be written as a sum? # note: combinations, not permutations def count_sum_reps(n): ''' my gut tells me that this can be formulated as a math problem... let's first see if we can detect the pattern: 1 -> 1 2 -> 1 3 -> 1+2, 1+1+1: 2 4 -> 1+3, 2+2,2+1+1, 1+1+1+1: 4 5 -> 6 6 -> 5+1, 4+2, 4+1+1, 3+3, 3+2+1, 3+1+1+1, 2+2+2, 2+2+1+1, 2+1+1+1+1, 1+1+1+1+1+1 : 10 7 -> 6+1 5+2 5+1+1 4+3 4+2+1 4+1+1+1 3+3+1 3+2+2 3+2+1+1 3+1+1+1+1 2+2+2+1 2+2+1+1+1 2+1+1+1+1+1 (7x)+1 : 14 8 -> 7+1 6+2 6+1+1 5 = "3" 4 = "4" 3+3+2 3+3+1+1 3+2+2+1 3+2+1+1+1 3+(5x)+1 "5" 2+2+2+2 ... "4" "1" : 19 9 -> yikes, I'm seeing the emergence of a pattern, n-1 rows. growing by +1 descending.. until it reaches the corner, but i would need to do several more in order to see the pattern on the bottom rows (after the corner), assuming there is a pattern ''' return 'not finished yet' if __name__ == '__main__': import boilerplate, time boilerplate.all(time.time(),main())
905044cf0b3bbe51124477458e02b069ee72eb0f
ryanmp/project_euler
/p034.py
1,037
3.828125
4
''' 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. Find the sum of all numbers which are equal to the sum of the factorial of their digits. Note: as 1! = 1 and 2! = 2 are not sums they are not included. ''' import math f = {} for i in xrange(0,10): f[i] = math.factorial(i) def main(): # hm... still pretty slow... there's gotta be some tricks to speed this one up n = 2540160 # since 9!*7 = 2540160 all_passing_numbers = [] for i in xrange(3, n): if is_a_digit_factorial(i): all_passing_numbers.append(i) return sum(all_passing_numbers) ''' def is_a_digit_factorial(n): arr = [math.factorial(int(i)) for i in str(n)] return (n == sum(arr)) ''' def is_a_digit_factorial(n): arr = [int(i) for i in str(n)] arr.sort(reverse=True) result = 0 for i in arr: result += f[i] if result > n: return False return n == result if __name__ == '__main__': import boilerplate, time, resource t = time.time() r = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss boilerplate.all(main(), t, r)
4918127d5c7331402a9aceb8288071c0de80766b
ryanmp/project_euler
/p005.py
628
3.796875
4
''' 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? ''' def main(): divisors = [11, 13, 14, 16, 17, 18, 19, 20] smallest = 2520 while(True): passes = True for i in divisors: if smallest%i != 0: passes = False break if (passes): return smallest else: smallest += 2520 if __name__ == '__main__': import boilerplate, time, resource t = time.time() r = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss boilerplate.all(main(), t, r)
067beb1bcbc592f4a362d68cd4423eee877b094d
ryanmp/project_euler
/p017.py
1,437
3.875
4
''' If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage. ''' d = {1:3, 2:3, 3:5, 4:4, 5:4, 6:3, 7:5, 8:5, 9:4, 10:3, 11:6, 12:6, 13:8, 14:8, 15:7, 16:7, 17:9, 18:8, 19:8, 20:6, 30:6, 40:5, 50:5, 60:6, 70:7, 80:6, 90:6} def main(): n = 1000 # don't forget 'hundred' & 'and' (...that'll be in the conditional logic) total_count = 0 for i in xrange(1,n+1): total_count += get_char_cnt(i) return total_count def get_char_cnt(i): if (i < 1 or i > 1000): print "number range error: n must be in the range 1:1000" count = 0 if (i == 1000): count += 11 if (i>=100 and i<1000): dig1 = (i/100) count += d[dig1] + 7 # 7=hundred i = i%100 if i != 0: count += 3 # 3=and if (i<100 and i>=20): dig1 = (i/10)*10 count += d[dig1] i = i%10 if (i>0 and i<20): count += d[i] return count if __name__ == '__main__': import boilerplate, time, resource t = time.time() r = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss boilerplate.all(main(), t, r)
8b6fbbd63e8a5acb92eb7a2481521cb646abbad6
ryanmp/project_euler
/p024.py
990
3.796875
4
from itertools import permutations from math import factorial as f ''' Q: What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? ''' def main(): p = permutations([0,1,2,3,4,5,6,7,8,9]) # lists them in lexicographic order by default l = list(p) ans = l[1000000-1] #Why the '-1'? l[0] is the first permutation return join_ints(ans) # input: array of ints # e.g.: [1,2,3,4] # output: a single int # e.g.: 1234 def join_ints(l): l = [str(i) for i in l] # to array of chars as_str = ''.join(l) return int(as_str) if __name__ == '__main__': import boilerplate, time, resource t = time.time() r = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss boilerplate.all(main(), t, r) # ha! So originally I started with the math # approach, thinking that the factorials would # slow us down - but then I went back and tested # the naive approach and it still takes less than # 5 seconds... so that's what I have down here, # for simplicity sake
73f0378d6358f6fe1b7ae727facbd236f0134baa
ryanmp/project_euler
/p036.py
611
3.6875
4
''' The decimal number, 585 = 1001001001 (binary), is palindromic in both bases. Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2 ''' def is_palindrome(n): return str(n) == str(n)[::-1] def main(): sum = 0 for i in xrange(1,int(1e6),2): # via logic, no even solutions - 01...10 (can't start with a zero) if is_palindrome(i): if (is_palindrome(bin(i)[2:])): sum += i return sum if __name__ == '__main__': import boilerplate, time, resource t = time.time() r = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss boilerplate.all(main(), t, r)
1ddf72a48f1db42476f00c50e39af6f523899ff6
ankitjnyadav/LeetCode
/Strings/Reverse a String.py
258
3.890625
4
def reverseString(s) -> None: """ Do not return anything, modify s in-place instead. """ #Approach 1 s[:] = s[::-1] #Approach 2 i = 0 for c in s[::-1]: s[i] = c i = i + 1 reverseString(["h","e","l","l","o"])
58667121c08c196a1c8141bcdbfce21154849de2
ankitjnyadav/LeetCode
/30 Day Leet Coding Challenge/Day1 - First Bad Version/Day1.py
751
3.53125
4
''' Problem Statement - https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/534/week-1-may-1st-may-7th/3316/ ''' # The isBadVersion API is already defined for you. # @param version, an integer # @return a bool # def isBadVersion(version): class Solution: def isBadVersion(n): if n >= 4: return True else: return False def firstBadVersion(self, n): """ :type n: int :rtype: int """ if n == 1: return 1; begin = 1 end = n while begin < end: mid = begin + (end - begin) / 2 if isBadVersion(mid): end = mid else: begin = mid + 1 return int(begin)
e9916dcf5e90daa9e263831aa893b333bf0b914d
andreea-munteanu/AI-2020
/Lab2-3/Lab2.py
9,042
3.578125
4
import random import sys from queue import Queue n = 12 m = 15 # n = 4 # m = 4 print("n = ", n, "m = ", m) SIZE = (n, m) # n rows, m columns if sys.getrecursionlimit() < SIZE[0] * SIZE[1] : sys.setrecursionlimit(SIZE[0] * SIZE[1]) # if max recursion limit is lower than needed, adjust it sys.setrecursionlimit(30000) my_list = [0] * 55 + [1] * 45 # weights # initializing labyrinth with 0s and 1s at weighted random lab = list(list(random.choice(my_list) for i in range(SIZE[0])) for j in range(SIZE[1])) # lab = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] # parameters: start, destination def print_labyrinth(xs, ys, xd, yd) : print(" ", end='') for i in range(n) : if i < n - 1 : print(i, end=' ') else : print(i) print(" ", end='') for i in range(2 * n) : print("_", end='') print('') for j in range(m) : if j < 10 : print(j, " |", end='') else : print(j, "|", end='') # print("| ", end='') for i in range(n) : # start position if i == xs and j == ys : print('S', end=' ') # destination elif i == xd and j == yd : print('D', end=' ') # free cell elif lab[j][i] == 0 : print(' ', end=' ') # obstacle elif lab[j][i] == 1: print('∎', end=' ') else: # lab[i][j] == 2 print("+", end=' ') print('|', j, end='\n') """_________________________________________________________________________________________________________ 1. STATE (xc , yc , xs , ys , xd , yd) ______________ _________ ___________ current state | start |destination| # (xc, yc) - current position # (xs, ys) - start position # (xd, yd) - destination _________________________________________________________________________________________________________ 2. INITIALIZATION, INITIAL/FINAL STATE, CHECK_FINAL() 2.2. initial state: current position is start(xs, ys) _________________________________________________________________________________________________________ """ # 2.1.initialization + returning state def initialState(xc, yc, xs, ys, xd, yd) : xc = xs yc = ys return xc, yc, xs, ys, xd, yd # 2.3. bool function checking whether a state is final def finalState(xc, yc, xd, yd) : return xc == xd and yc == yd """_________________________________________________________________________________________________________ 3. TRANSITION FUNCTION 3.1. validation function (bool) 3.2. transition function returning current state _________________________________________________________________________________________________________ """ visited = [] # checks if (xc, yc) is within bounds def inside(x, y) : return 0 <= x < n and 0 <= y < m # checks if (xc, yc) has been visited before: visited = False, not visited = true def not_visited(x, y) : for i in range(0, len(visited), 2) : if visited[i] == x and visited[i + 1] == y : return False return True def is_obstacle(x, y) : if 0 <= x < n and 0 <= y < m: return lab[x][y] == 1 or lab[x][y] == 2 else: return True # validate transition def valid_transition(x, y) : return inside(x, y) and not_visited(x, y) and is_obstacle(x, y) is False def valid_transition_for_bkt(x, y): if inside(x, y): return is_obstacle(x, y) is False return False # TRANSITION FUNCTION (returns new state) def transition(x_new, y_new, xs, ys, xd, yd) : xc = x_new yc = y_new # current position (xc, yc) becomes (x_new, y_new) return xc, yc, xs, ys, xd, yd N, S, E, W = 1, 2, 4, 8 GO_DIR = {N : (0, -1), S : (0, 1), E : (1, 0), W : (-1, 0)} # dictionary with directions translated to digging moves directions = [N, E, S, W] """_________________________________________________________________________________________________________ 4. BACKTRACKING STRATEGY _________________________________________________________________________________________________________ """ BKT_stack = [] def print_BKT_path(xs, ys, xd, yd, stack) : # stack contains indices (i,j) of the path --> requires step = 2 for i in range(0, len(stack), 2) : # printing stack for check print("(", stack[i], ", ", stack[i + 1], ")", end='; ') lab[stack[i]][stack[i + 1]] = 2 # printing resulting path print("\nBKT path: ") print_labyrinth(xs, ys, xd, yd) # changing matrix to original for i in range(0, len(stack), 2) : lab[stack[i]][stack[i + 1]] = 0 def BKT(xc, yc, xs, ys, xd, yd) : # add current position to stack (for future printing) BKT_stack.append(xc) BKT_stack.append(yc) # # mark cell as visited lab[xc][yc] = 2 # path # check if current state is final if finalState(xc, yc, xd, yd) : print('Found solution: ') print_BKT_path(xs, ys, xd, yd, BKT_stack) return True # check the neighbouring cells else : for direction in directions : # N, E, W, S # if transition has been made successfully, move to new position sum_x = [GO_DIR[direction][1], xc] sum_y = [GO_DIR[direction][0], yc] # neighbour coordinates: xc_new = sum(sum_x) yc_new = sum(sum_y) # if transition can be done, perform if valid_transition_for_bkt(xc_new, yc_new) : new_x, new_y, xs, ys, xd, yd = transition(xc_new, yc_new, xs, ys, xd, yd) print("X: " , new_x , " ,Y: " , new_y) if BKT(new_x, new_y, xs, ys, xd, yd): return True # complementary operations lab[xc][yc] = 0 BKT_stack.pop() BKT_stack.pop() """_________________________________________________________________________________________________________ 5. BFS STRATEGY _________________________________________________________________________________________________________ """ class Point(object) : def __init__(self, x, y) : self.x = x self.y = y def BFS(xc, yc, xs, ys, xd, yd) : q = Queue(maxsize=10000) current_position = Point(xc, yc) BFS_visited = set() BFS_visited.add(current_position) q.put(current_position) while q : u = q.get() # calculate neighbours of u, check if they are visited for dir in directions : # directions N, S, E, W sum_x = [GO_DIR[dir][1], u.x] sum_y = [GO_DIR[dir][0], u.y] # neighbour coordinates: x_neigh = sum(sum_x) y_neigh = sum(sum_y) neighbour = Point(x_neigh, y_neigh) list_queue = list(q.queue) if neighbour not in list_queue : BFS_visited.add(neighbour) q.put(neighbour) return BFS_visited def print_BFS_path(xs, ys, xd, yd, BFS_visited) : # BFS_visited() is a set containing the visited cells (in order) initial_set = set() for i in range(len(BFS_visited)) : v = BFS_visited.pop() initial_set.add(v) lab[v.y][v.x] = 2 # path # printing resulting path print("\nBFS path: ") print_labyrinth(xs, ys, xd, yd) # changing matrix to original for i in range(len(initial_set)) : v = initial_set.pop() lab[v.y][v.x] = 0 """_________________________________________________________________________________________________________ 5. HILLCLIMBING STRATEGY _________________________________________________________________________________________________________ """ def HillClimbing(xc, yc, xs, ys, xd, yd) : print('nothing here :) ') def main() : print("\nChoose start(xs, ys) and destination (xd, yd): ", end='') # xs, ys, xd, yd = input().split() xs = input() xs = int(xs) ys = input() ys = int(ys) xd = input() xd = int(xd) yd = input() yd = int(yd) print("\nYour labyrinth is: ") print_labyrinth(xs, ys, xd, yd) # BKT if not BKT(xs, ys, xs, ys, xd, yd): print("Solution does not exist") # BFS # BFS(xs, ys, xs, ys, xd, yd) # BFS_set = BFS(xs, ys, xs, ys, xd, yd) # print_BFS_path(xs, ys, xd, yd, BFS_set) if __name__ == "__main__" : main()
8d6dd0da1e52152ebbec09722fae2d166dbcdd92
urzyasar/Python
/OOPs/Encapsulation.py
797
3.875
4
#Encapsulation class Bike: def __init__(self,n): self.name=n self.__price=50,000 #private variable def setprice(self,p): self.__price=p print(self.__price) self.__display() def __display(self): print("Bike:{} and price:{}".format(self.name,self.__price)) def getdisplay(self): self.__display() obj=Bike("yamaha") #print(obj.price) #cannot access from outside #print(obj.__price) #print(obj.name) #trying to set price obj.name="honda" print(obj.name) #obj.__price=100 obj.setprice(10000) #print(obj.__price) #Again it cannot access from outside #obj.__display() #cannot access this method from outside obj.getdisplay()
240066b054c327e6a05ab214ce54466ba9b39d6f
gonzrubio/HackerRank-
/InterviewPracticeKit/Dictionaries_and_Hashmaps/Sherlock_and_Anagrams.py
992
4.15625
4
"""Given a string s, find the number of pairs of substrings of s that are anagrams of each other. 1<=q<=10 - Number of queries to analyze. 2<=|s|<=100 - Length of string. s in ascii[a-z] """ def sherlockAndAnagrams(s): """Return the number (int) of anagramatic pairs. s (list) - input string """ n = len(s) anagrams = dict() for start in range(n): for end in range(start,n): substring = ''.join(sorted(s[start:end+1])) anagrams[substring] = anagrams.get(substring,0) + 1 count = 0 for substring in anagrams: freq = anagrams[substring] count += freq*(freq-1) // 2 return count def main(): #tests = ['abba','abcd','ifailuhkqq','kkkk'] #for test in tests: # 1<=q<=10 for _ in range(int(input())): # 1<=q<=10 print(sherlockAndAnagrams(input())) # 2<=|s|<=100 if __name__ == '__main__': main()
77dcb824eb6c6197667cb94284a26a69eb445f11
kirtivr/leetcode
/Leetcode/384.py
1,036
3.703125
4
from random import * class Solution: def __init__(self, nums): """ :type nums: List[int] """ self.N = len(nums) self.orig = list(nums) self.nums = nums def reset(self): """ Resets the array to its original configuration and return it. :rtype: List[int] """ return self.orig def shuffle(self): """ Returns a random shuffling of the array. :rtype: List[int] """ used_nums = {} for i in range(self.N): idx = randint(0,self.N-1) while used_nums.get(self.orig[idx]) != None: idx = randint(0,self.N-1) used_nums[self.orig[idx]] = True self.nums[i],self.nums[idx] = self.nums[idx],self.nums[i] return self.nums # Your Solution object will be instantiated and called as such: nums = [1,2,3,4,5] obj = Solution(nums) param_1 = obj.reset() param_2 = obj.shuffle() print(param_2)
66e4433f8027b693e555e2d80e888e69bb352834
kirtivr/leetcode
/48.py
972
3.828125
4
class Solution: def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ N = len(matrix) for i in range(N): for j in range(N//2): matrix[i][N-j-1],matrix[i][j] = matrix[i][j],matrix[i][N-j-1] #print(matrix) for i in range(N): for j in range(N-i-1): matrix[i][j], matrix[N-j-1][N-i-1]= matrix[N-j-1][N-i-1],matrix[i][j] return matrix if __name__ == '__main__': matrix = [ [ 5, 1, 9,11,3], [ 2, 4, 8,10,4], [13, 3, 6, 7,8], [15,14,12,16,14], [20,21,22,23,24] ] matrix = [ [ 5, 1, 9,11], [ 2, 4, 8,10], [13, 3, 6, 7], [15,14,12,16] ] matrix = [ [1,2,3], [4,5,6], [7,8,9] ] print(Solution().rotate(matrix))
31f66d99d35913915be26b0453125089675a58ca
kirtivr/leetcode
/Leetcode/3.py~
1,070
3.546875
4
from typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: left = 0 right = len(nums) - 1 def binary_search(start: int, end: int, target: int) -> int: if start > end: return -1 mid = start + (end - start)//2 if nums[mid] == target: print(f'mid eq = %d', mid) return mid elif nums[mid] < target: print(f'mid lt = %d end = %d', mid, end) return binary_search(mid+1, end, target) else: print(f'mid gt = %d', mid) return binary_search(start, mid-1, target) if nums[-1] == target: return len(nums) while left < len(nums) - 1: right = binary_search(left + 1, len(nums) - 1, target - nums[left]) if right != -1: return [left + 1, right + 1] left += 1 if __name__ == '__main__': N = [-4,-1,0,3,10] N = [-1] N = [5,25,75] target = 100 #N = [-7,-3,2,3,11] #N = [-5,-3,-2,-1] x = Solution() print(x.twoSum(N, target))
da16b28f0fdb072a6eacba8883f72c16506ee9b0
kirtivr/leetcode
/Leetcode/151.py
1,165
3.65625
4
class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ s = s.strip() N = len(s) ls = [] j = 0 for i in range(N): if i > 0 and s[i] == ' ' and s[i-1] == ' ': continue else: ls.append(s[i]) j += 1 s = ls N = len(s) def reverse(st,end): mid = st + (int(end - st + 0.5)//2) for i in range(mid - st): s[st+i],s[end-i-1] = s[end-i-1],s[st+i] reverse(0,N) s.append(' ') N += 1 prev = None for i in range(N): if s[i] == ' ': if prev == None: reverse(0,i) else: #print('reversing indices '+str(prev+1) +' to '+str(i)) reverse(prev+1,i) prev = i #print(s) return "".join(s[:-1]) if __name__ == '__main__': s = "the sky is blue" s = "hi!" #s = " " #s = " a b " print(Solution().reverseWords(s))
99e743c3548ab28186bb6f39b0c2f8ac666fe722
kirtivr/leetcode
/121.py
542
3.625
4
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ minNow = 1 << 30 maxProfit = 0 for i in range(len(prices)): price = prices[i] if price - minNow > maxProfit: maxProfit = price - minNow if price < minNow: minNow = price return maxProfit if __name__ == '__main__': # l = [7, 1, 5, 3, 6, 4] l = [7,6,4,3,1] print(Solution().maxProfit(l))
c630d50c2ba134e47f202ef7021270cd50198ea5
kirtivr/leetcode
/Leetcode/33.py
1,672
3.8125
4
class Solution: def findPivot(self, start, end, arr): if start > end: return 0 mid = start + (end - start)//2 #print(mid) if mid != 0 and arr[mid-1] >= arr[mid]: return mid elif arr[mid] > arr[end]: return self.findPivot(mid + 1, end, arr) else: return self.findPivot(start, mid - 1, arr) def binSearch(self, start, end, arr, target): if start > end: return None mid = start + (end - start)//2 # print(mid) if arr[mid] == target: print('!') return mid elif arr[mid] < target: return self.binSearch(mid + 1, end, arr, target) else: return self.binSearch(start, mid - 1, arr, target) def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ N = len(nums) idx = self.findPivot(0,N-1,nums) # print(idx) if N > 1: if N == 0 or idx == 0 or nums[0] > target: r = self.binSearch(idx,N-1,nums,target) return r if r != None else -1 elif nums[0] == target: return 0 else: r = self.binSearch(0,idx-1,nums,target) return r if r != None else -1 elif N == 1: return 0 if nums[0] == target else -1 return -1 if __name__ == '__main__': # nums = [4,5,6,7,0,1,2,3] # target = 2 nums = [3,1] target = 3 print(Solution().search(nums,target))
ccc20ea56a993806ec35c35eea33564c6bb83d1d
kirtivr/leetcode
/Leetcode/skip_lists_code_for_2407.py
6,090
3.625
4
from typing import List, Optional, Tuple, Dict import heapq import pdb import ast import sys from dataclasses import dataclass, field from functools import cmp_to_key import time class ListNode: def __init__(self, val, idx): self.idx = idx self.val = val self.next = None self.prev = None def __repr__(self) -> str: return 'idx = ' + str(self.idx) + ' val = ' + str(self.val) def AddAfter(node: ListNode, priority: int, idx: int): if node == None: return new_node = ListNode(priority, idx) next = node.next new_node.prev = node new_node.next = next if next: next.prev = new_node node.next = new_node def PrintList(head: Optional[ListNode]): while head is not None: print(f'idx = {head.idx} val = {head.val} next idx = {None if head.next == None else head.next.idx} prev idx = {None if head.prev == None else head.prev.idx}', end = "\n") head = head.next # Transition from greater than to less than. def FindClosestSkipListNodeBefore(sl, priority): #print('---------------------------') if sl[0].val < priority: return None def searchBinary(sl, left, right): nonlocal priority if left > right: return None mid = left + (right - left)//2 # We found the right element when: # there is only one element in sl and this is the one. # or, mid.val <= priority < (mid + 1).val node = sl[mid] #print(f'cheking idx = {node.idx} val = {node.val} looking for val = {priority} left = {left} right = {right}') #if node == None: # print(f'Line 48 Invariant violated') # for i in range(len(sl)): # print(f'i = {i} sl[i] = {sl[i]}') if (node.val > priority and mid + 1 >= right) or (node.val == priority): return mid if node.val >= priority and (mid + 1 <= right and sl[mid + 1].val <= priority): return mid elif node.val > priority: return searchBinary(sl, mid + 1, right) else: return searchBinary(sl, left, mid - 1) return searchBinary(sl, 0, len(sl) - 1) def UpdateHead(ll, node): old_head = ll old_head.prev = node node.next = old_head return node # Transition from greater than to less than. def FindClosestLinkedListNodeBeforeStartingFrom(ll, priority): prev = ll while ll.next != None: if ll.next.val <= priority: return ll prev = ll ll = ll.next return prev def UpdateSkipListAfterIdx(sl, sl_idx): # 0-----------------10------------------20 # 0-------new-------9-------------------19 # Something was added after sl_idx and before sl_idx + 1. # Update all consequent pointers to point to the previous element. print(f'old list = {sl} i = {sl_idx}') for i in range(sl_idx + 1, len(sl)): sl[i] = sl[i].prev #print(f'new list = {sl}') def MoveSkipListOneIndexForward(sl): sl.append(None) prev = sl[0] for i in range(1, len(sl)): temp = sl[i] sl[i] = prev prev = temp class Solution: def lengthOfLIS(self, nums: List[int], k: int) -> int: lis = [1 for i in range(len(nums))] sl = [] ll = None #print(nums) for i in range(0, len(nums)): #print(f'lis = {lis}') curr = ll #PrintList(ll) for j in range(0, i): index = curr.idx diff = nums[i] - nums[index] #print(f'i = {i} j = {j} nums[i] = {nums[i]} lis[j] = {curr.val} k = {k} diff = {diff}') if diff > 0 and diff <= k: lis[i] = max(lis[i], lis[index] + 1) break curr = curr.next # Insert to linked list after a binary search. if len(sl) == 0 or ll == None: # Seed the skip list with one element to begin with. node = ListNode(lis[i], i) ll = node sl.append(node) else: sl_idx = FindClosestSkipListNodeBefore(sl, lis[i]) #print(f'sl_idx = {sl_idx}') if sl_idx == None: #if ll.val < lis[i]: # print(f"Invariant violated ll.val = {ll.val} lis[{i}] = {lis[i]} skip list = {sl}") # The current element is the smallest element. MoveSkipListOneIndexForward(sl) node = ListNode(lis[i], i) sl[0] = node ll = UpdateHead(ll, node) #print(f'After adding to head new sl = {sl}') else: sl_node = sl[sl_idx] #print(f'sl_idx = {sl_idx} sl_node = ( {sl_node} ) sl ={sl}') ll_node = FindClosestLinkedListNodeBeforeStartingFrom(sl_node, lis[i]) AddAfter(ll_node, lis[i], i) #PrintList(ll) UpdateSkipListAfterIdx(sl, sl_idx) if i != 0 and i % 512 == 0: # Add a new skip list element, which will be the tail of the linked list. if len(sl) > 0: sl_node = sl[-1] curr = sl_node #print(f'going to append to skip list {sl}') while curr != None and curr.next != None: curr = curr.next sl.append(curr) #print(f'appended new skip list is {sl}') #print('\n') #print(lis) max_lis = max(x for x in lis) return max_lis if __name__ == '__main__': x = Solution() start = time.time() with open('2407_tc.text', 'r') as f: n = ast.literal_eval(f.readline()) k = ast.literal_eval(f.readline()) #print(n) #print(edges) print(x.lengthOfLIS(n, k)) end = time.time() elapsed = end - start print(f'time elapsed: {elapsed}')
c66a57a11aa2c998cb24ba707020f1a9f14eeefa
kirtivr/leetcode
/Leetcode/binary_indexed_tree_example.py
1,663
4.03125
4
# Python3 program to count inversions using # Binary Indexed Tree # Returns sum of arr[0..index]. This function # assumes that the array is preprocessed and # partial sums of array elements are stored # in BITree[]. def getSum( BITree, index): sum = 0 # Initialize result # Traverse ancestors of BITree[index] while (index > 0): # Add current element of BITree to sum sum += BITree[index] # Move index to parent node in getSum View index -= index & (-index) return sum # Updates a node in Binary Index Tree (BITree) # at given index in BITree. The given value # 'val' is added to BITree[i] and all of its # ancestors in tree. def updateBIT(BITree, n, index, val): # Traverse all ancestors and add 'val' while (index <= n): # Add 'val' to current node of BI Tree BITree[index] += val # Update index to that of parent # in update View index += index & (-index) # Returns count of inversions of size three def getInvCount(arr, n): invcount = 0 # Initialize result # Find maximum element in arrays maxElement = max(arr) # Create a BIT with size equal to # maxElement+1 (Extra one is used # so that elements can be directly # be used as index) BIT = [0] * (maxElement + 1) for i in range(n - 1, -1, -1): invcount += getSum(BIT, arr[i] - 1) updateBIT(BIT, maxElement, arr[i], 1) return invcount # Driver code if __name__ =="__main__": arr = [8, 4, 2, 1] n = 4 print("Inversion Count : ", getInvCount(arr, n))
c2e40105692a0a132ae3f2304e99d207d9cceae1
kirtivr/leetcode
/Leetcode/62.py
4,326
3.578125
4
from typing import List, Optional, Tuple, Dict import pdb from functools import cmp_to_key import time def make_comparator(less_than): def compare(x, y): if less_than(x, y): return -1 elif less_than(y, x): return 1 else: return 0 return compare class Solution: def uniquePaths(self, m: int, n: int) -> int: if m == 0 or n == 0: return 0 paths = [[0 for column in range(n)] for row in range(m)] prefill_column = n-1 for row in range(m): paths[row][prefill_column] = 1 prefill_row = m-1 for col in range(n): paths[prefill_row][col] = 1 for row in range(m-2, -1, -1): for col in range(n-2, -1, -1): paths[row][col] = paths[row + 1][col] + paths[row][col + 1] return paths[0][0] def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: m = len(obstacleGrid) n = len(obstacleGrid[0]) if len(obstacleGrid) > 0 else 0 if m == 0 or n == 0 or obstacleGrid[-1][-1] == 1 or obstacleGrid[0][0] == 1: return 0 paths = [[0 for column in range(n)] for row in range(m)] prefill_col = n-1 for row in range(m): if obstacleGrid[row][prefill_col] == 1: paths[row][prefill_col] = -1 # Left is an obstacle, may be no way to get to cell elif prefill_col >= 1 and obstacleGrid[row][prefill_col - 1] == 1 and (row == 0 or paths[row - 1][prefill_col] == -1): # First row or row above is unreachable print(f'setting 0 {row} {prefill_col}') paths[row][prefill_col] = -1 else: paths[row][prefill_col] = 1 bottom_block = None for row in range(m): if paths[row][prefill_col] == -1: bottom_block = row if bottom_block: for row in range(bottom_block, -1, -1): paths[row][prefill_col] = -1 prefill_row = m-1 #print(paths) for col in range(n): if obstacleGrid[prefill_row][col] == 1: paths[prefill_row][col] = -1 #print(f'checking {prefill_row} {col}') # Top is an obstacle - no way to get to the cell elif (prefill_row >= 1 and obstacleGrid[prefill_row - 1][col] == 1) and ( col == 0 or paths[prefill_row][col - 1] == -1): #print(f'setting 0 {prefill_row} {col}') paths[prefill_row][col] = -1 # Can't go right, so can't go anywhere. elif (col < n - 1 and obstacleGrid[prefill_row][col + 1] == 1): paths[prefill_row][col] = -1 #print(f'{prefill_row} {col}') else: paths[prefill_row][col] = 1 right_block = None for col in range(n): if paths[prefill_row][col] == -1: right_block = col if right_block: for col in range(right_block, -1, -1): paths[prefill_row][col] = -1 #print(paths) for row in range(m): for col in range(n): if obstacleGrid[row][col] == 1: paths[row][col] = -1 for path in paths: print(path) print('---------------') for row in range(m-2, -1, -1): for col in range(n-2, -1, -1): if paths[row][col] == -1: continue paths[row][col] = 0 if paths[row + 1][col] == -1 else paths[row + 1][col] paths[row][col] += 0 if paths[row][col + 1] == -1 else paths[row][col + 1] for path in paths: print(path) return paths[0][0] if paths[0][0] > 0 else 0 if __name__ == '__main__': x = Solution() start = time.time() m = 3 n = 7 m = 3 n = 3 #print(x.uniquePaths(m, n)) obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]] # obstacleGrid = [[0,0],[1,1],[0,0]] #obstacleGrid = [[0,0,0,0,0], # [0,0,0,0,1], # [0,0,0,1,0], # [0,0,1,0,0]] print(x.uniquePathsWithObstacles(obstacleGrid)) end = time.time() elapsed = end - start print(f'time elapsed: {elapsed}')
7d6ef70b32516d620199e1002228326e308d7893
kirtivr/leetcode
/Leetcode/python_linked_list_template.py
1,566
3.6875
4
from typing import List, Optional, Tuple, Dict from heapq import heappop, heappush, heapify import pdb import ast import sys from functools import cmp_to_key import time # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def __repr__(self): return str(self.val) def PrintList(head: Optional[ListNode]): while head is not None: print(head.val, end = " ") head = head.next print() def MakeNodes(input: List[int]): head = None current = None for i in range(len(input)): new_node = ListNode(input[i], None) if head == None: head = new_node current = new_node continue current.next = new_node current = new_node return head def AddAfter(node: Optional[ListNode], to_add: int): if node == None: return next = node.next new_node = ListNode(to_add, next) node.next = new_node def Length(head: Optional[ListNode]): out = 0 while head is not None: out += 1 head = head.next return out def ElementAt(head: Optional[ListNode], idx: int): out = 0 while head is not None: out += 1 if idx == out: return head head = head.next return None '''if __name__ == '__main__': x = Solution() start = time.time() nodes = MakeNodes([1, 2, 3, 4, 5]) PrintList(nodes) end = time.time() elapsed = end - start print(f'time elapsed: {elapsed}')'''
a480c4a2c398cf11d06d5d67301e2ceeff4a7a1e
kirtivr/leetcode
/538.py
754
3.671875
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None ''' 7 5 9 3 6 8 10 ''' class Solution(object): def convertBST(self, root): """ :type root: TreeNode :rtype: TreeNode """ def greaterTree(node, currentSum): if node == None: return 0 rSum = greaterTree(node.right, currentSum) lSum = greaterTree(node.left, rSum + currentSum + node.val) node.val = currentSum + node.val + rSum return node.val+lSum+rSum return root
a9e85bc4f8f394810469202a03beda752a0c8b4a
kirtivr/leetcode
/Leetcode/19.py
1,008
3.703125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ slowPtr = None fastPtr = head temp = None for i in range(n-1): fastPtr = fastPtr.next while fastPtr != None and fastPtr.next != None: fastPtr = fastPtr.next if slowPtr == None: slowPtr = head temp = slowPtr else: slowPtr = slowPtr.next if slowPtr != None: print(slowPtr.val) if slowPtr != None: if slowPtr.next != None: slowPtr.next = slowPtr.next.next elif head != None: slowPtr = head.next temp = slowPtr return temp
9fe6f08df783fa4744f9dc2efe179019007d9966
kirtivr/leetcode
/First attempts at/19.py
1,205
3.5625
4
#!/usr/bin/env python import time import pdb import sys import copy from typing import List, TypedDict # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseLinkedList(self, head: Optional[ListNode]) -> bool: if head.next == None: return head first = None second = head while second != None: temp = second.next second.next = first first = second second = temp return first def isPalindrome(self, head: Optional[ListNode]) -> bool: temp = [] ptr = head while ptr != None: temp.append(ptr.val) ptr = ptr.next head = self.reverseLinkedList(head) ptr = head i = 0 while ptr != None: if ptr.val != temp[i]: return False ptr = ptr.next i += 1 return True if __name__ == '__main__': x = Solution() print(x.minPathSum(grid)) end = time.time() elapsed = end - start print (f'time elapsed = {elapsed}')
e9b85cf35392d9b35970ccab0dab86c258aa1c37
kirtivr/leetcode
/First attempts at/146.py
5,777
3.78125
4
#!/usr/bin/env python import time import pdb import sys import copy from typing import List, TypedDict class Element(object): def __init__(self, key: int, val: int, prev, next): self.key = key self.value = val self.prev = prev self.next = next def __repr__(self): return f'{self.key}' class LRUCache: def __init__(self, capacity: int): self.cache = {} self.capacity = capacity self.head = None self.tail = None def print_cache(self): curr = self.head while curr != None: print(f'{curr}', end = " ") curr = curr.next if curr is not None: print('->', end = " ") print() def print_cache_reverse(self): print('reverse print') curr = self.tail while curr != None: print(f'{curr}', end = " ") curr = curr.prev if curr is not None: print('->', end = " ") print() def get(self, key: int) -> int: print() self.print_cache() self.print_cache_reverse() print(f'get key = {key} head = {self.head} tail = {self.tail} cache = {self.cache}') if key in self.cache: el = self.cache[key] if self.head is not None and self.head.key != key: # el will move. So set the pointers of el's previous and next elements accordingly. preceding = el.prev if el.prev: el.prev.next = el.next if el.next: el.next.prev = el.prev # Move element to front of the list old_head = self.head el.prev = None el.next = old_head old_head.prev = el self.head = el #print(f'done getting key = {key} head = {self.head} tail = {self.tail} cache = {self.cache}') # Element is now head. If el was tail, el.prev is tail now if self.tail is not None and self.tail.key == el.key and preceding is not None: self.tail = preceding self.tail.next = None return el.value return -1 def put(self, key: int, value: int) -> None: print() self.print_cache() self.print_cache_reverse() print(f'put key = {key} head = {self.head} tail = {self.tail} cache = {self.cache}') el = None new_tail = None if key not in self.cache and len(self.cache) == self.capacity and self.tail != None: #Evict LRU element. print(f'Evicting {self.tail.key}') del self.cache[self.tail.key] new_tail = self.tail.prev if key in self.cache: el = self.cache[key] el.value = value else: el = Element(key, value, None, None) if self.head is not None and self.head.key != key: print(f'updating head from {self.head} to {el}') if key in self.cache: # el will move. So set the pointers of el's previous and next elements accordingly. preceding = el.prev if el.prev: el.prev.next = el.next if el.next: el.next.prev = el.prev # Element is now head. If el was tail, el.prev is tail now if self.tail is not None and self.tail.key == el.key and preceding is not None: new_tail = preceding el.next = self.head self.head.prev = el self.head = el self.head.prev = None self.cache[key] = el if len(self.cache) == 1: self.tail = el elif len(self.cache) == 2: self.tail = el.next elif new_tail: #Remove evicted element from cache. self.tail = new_tail self.tail.next = None if __name__ == '__main__': lRUCache = LRUCache(2); #lRUCache.put(1, 1); # cache is {1=1} #lRUCache.put(2, 2); # cache is {1=1, 2=2} #print(lRUCache.get(1)); # return 1 #lRUCache.put(3, 3); # LRU key was 2, evicts key 2, cache is {1=1, 3=3} #print(lRUCache.get(2)); # returns -1 (not found) #lRUCache.put(4, 4); # LRU key was 1, evicts key 1, cache is {4=4, 3=3} #print(lRUCache.get(1)); # return -1 (not found) #print(lRUCache.get(3)); # return 3 #print(lRUCache.get(4)); # return 4 print(lRUCache.get(2)) lRUCache.put(2, 1); # cache is {1=1} #print(lRUCache.get(1)) lRUCache.put(1, 1); # cache is {1=1, 2=2} lRUCache.put(2, 3); # cache is {1=1, 2=2} lRUCache.put(4, 1); # cache is {1=1, 2=2} #print(lRUCache.get(1)) #print(lRUCache.get(2)) #print(lRUCache.get(1)); # return 1 #lRUCache.put(3, 3); # LRU key was 2, evicts key 2, cache is {1=1, 3=3} #print(lRUCache.get(2)); # returns -1 (not found) #lRUCache.put(4, 4); # LRU key was 1, evicts key 1, cache is {4=4, 3=3} #print(lRUCache.get(1)); # return -1 (not found) #print(lRUCache.get(3)); # return 3 #print(lRUCache.get(4)); # return 4 # x = Solution() # start = time.time() # print(x.minPathSum(grid)) # end = time.time() # elapsed = end - start # print (f'time elapsed = {elapsed}') # Adversarial input: # ["LRUCache","get","put","get","put","put","get","get"] # [[2],[2],[2,6],[1],[1,5],[1,2],[1],[2]]
c8c217a9b1cbcc7f7058ac1c5d31c1774edf550c
kirtivr/leetcode
/170.py
1,999
3.859375
4
class TwoSum: def __init__(self): """ Initialize your data structure here. """ self.hashmap = [] self.numbers = set() def add(self, number): """ Add the number to an internal data structure.. :type number: int :rtype: void """ index = hash(abs(number))%200000001 self.numbers.add(number) if len(self.hashmap) > index: self.hashmap[index].append(number) else: diff = index - len(self.hashmap) + 1 while diff > 0: self.hashmap.append([]) diff -= 1 self.hashmap[index].append(number) def find(self, value): """ Find if there exists any pair of numbers which sum is equal to the value. :type value: int :rtype: bool """ if value == 1467164459: print(self.hashmap) # print(value) def evaluate(curr,diff,index,diff_index): if (curr == diff): egg = 0 if len(self.hashmap[index]) >= 2: for y in self.hashmap[index]: if y == diff: egg += 1 if egg >= 2: return True elif diff_index < len(self.hashmap) and len(self.hashmap[diff_index]) >= 1: for y in self.hashmap[diff_index]: if y == diff: return True return False for i in self.numbers: index = hash(abs(i))%200000001 for curr in self.hashmap[index]: diff = value-curr diff_index = hash(abs(diff)) if evaluate(curr,diff,index,diff_index): return True return False
79cd77f09d5b0c796dd4744cd60756c735bf5105
kirtivr/leetcode
/70.py
429
3.640625
4
class Solution(object): def tryClimb(self, n, steps): if n in steps: return steps[n] return steps[n-1]+steps[n-2] def climbStairs(self, n): """ :type n: int :rtype: int """ steps = {} steps[0] = 0 steps[1] = 1 steps[2] = 2 for i in range(2,n+1): steps[i] = self.tryClimb(i,steps) return steps[n]
1a7b2f86630f2409b8100d4bc6dc040b657c3d03
kirtivr/leetcode
/56.py
1,173
3.640625
4
class Interval(object): def __init__(self, s=0, e=0): self.start = s self.end = e def __str__(self): return(str(self.start) + ' ' + str(self.end)) class Solution(object): def mergeInt(self, intv1, intv2): return Interval(intv1.start,max(intv1.end, intv2.end)) def merge(self, intervals): """ :type intervals: List[Interval] :rtype: int """ # Sort the intervals by starting time sortIntervals = sorted(intervals, key=lambda interval : interval.start) mergedInts = [] numInt = len(sortIntervals) i = 0 while i < numInt: cInt = sortIntervals[i] for j in range(i+1,numInt): nInt = sortIntervals[j] if cInt.end >= nInt.start or cInt.end >= nInt.end: cInt = self.mergeInt(cInt,nInt) i = j mergedInts.append(cInt) i = i + 1 return mergedInts il = [[1,3],[2,6],[8,10],[15,18]] intv = [ Interval(item[0],item[1]) for item in il ] Solution().merge(intv)
b854946978b0c35cb74f63eae02ea1a2aeed0967
zwilhelmsen/regex-tool
/regex-tool.py
4,451
3.75
4
####################################################### # Regular expressions tool ####################################################### """ Regular expressions tool created: zac wilhelmsen 08/31/17 Finds the regular expression used to identify patterns/strings """ def regex_tool(string): split = string.split(" ") regex = [] double_space = 0 esc_char = [r"\\", r"\'", r"\"", r"[", r"]", r"^", r"$", r".", r"|", r"?", r"*", r"+", r"(", r")", r"{", r"}"] for i in range(0, len(split), 1): # print(i,len(split)) # print("i is:", i) # print(split[i]) for k in range(0, len(split[i]), 1): # print(split[i][k]) if split[i].isdigit() and len(split[i]) > 1: regex.append(r"\d+") break elif split[i].isalpha() and len(split[i]) > 1: if r'\w' in regex[-2:] or r'\w+' in regex[-2:]: # print("should we add +?") # print(regex) if r"\w" in regex[-2:] and r"\s" in regex[-2:]: # print("adding +") # print(regex) count = -2 for element in regex[-2:]: if element == r"\w": regex[count] = r"\w+" double_space = 1 count += 1 break elif r"\w+" in regex[-2:]: # print("escape") double_space = 1 break # else: # Uncomment for testing # print("IDK why i'm here.") else: regex.append(r"\w") break # print(split[i][k]) if split[i][k].isdigit(): if prev_regex(regex) == r"\d" or prev_regex(regex) == r"\d+": # print("second digit") regex[len(regex)-1] = r"\d+" else: # print("First digit") regex.append(r"\d") elif split[i][k].isalpha(): if prev_regex(regex) == r"\p{L}" or prev_regex(regex) == r"\w": # print("second letter") regex[len(regex)-1] = r"\w" else: # print("first letter") regex.append(r"\p{L}") else: # print("its a special!") # print(split[i][k]) if not prev_regex(regex) == split[i][k]: # print("it is not already present!") # print(split[i][k]) if not split[i][k] in esc_char: # print(split[i][k]) # print("This is a regular special character. %s is not in list" % split[i][k]) regex.append(split[i][k]) else: # print("regex escape character") regex.append(r"\%s" % split[i][k]) double_space = 0 if i+1 == len(split): break count = -2 if double_space == 1: for element in regex[-2:]: # print(regex, count) if element == r"\s": # print("adding +") regex[count] = r"\s+" count += 1 double_space = 0 else: regex.append(r"\s") # print(regex) stringOfRegex = "" for each in regex: stringOfRegex += each print("Your regex is: %s" % stringOfRegex) def has_number(string): # print("Has number!") return any(str.isdigit(c) for c in string) def has_spec(string): # print("Has Special!") return any(char.isalnum() for char in string) def prev_regex(list): if len(list) >= 1: # print(list[len(list)-1]) return list[len(list)-1] # def rem_space(list): # return r"\s" in list[-2:] def main(): # print(has_spec("$abc")) # list = ['1', 2] # print(len(list)) # print("[" == r"[") while True: regex_tool(input("> Input the string you want to identify with regular expressions\n")) ans = input("Do you want to play again? y/n\n").lower() if ans == "n": break if __name__ == "__main__": main()
a0742f744b2d66be9131ab31988fba386e9178ec
likeke201/qt_code
/DemoUIonly-PythonQt/chap14matplotlib/Demo14_1Basics/Demo14_1Script.py
1,019
3.671875
4
## 程序文件: Demo14_1Script.py ## 使用matplotlib.pyplot 指令式绘图 import numpy as np import matplotlib.pyplot as plt plt.suptitle("Plot by pyplot API script") #总的标题 t = np.linspace(0, 10, 40) #[0,10]之间平均分布的40个数 y1=np.sin(t) y2=np.cos(2*t) plt.subplot(1,2,1) #1行2列,第1个子图 plt.plot(t,y1,'r-o',label="sin", linewidth=1, markersize=5) plt.plot(t,y2,'b:',label="cos",linewidth=2) plt.xlabel('time(sec)') # X轴标题 plt.ylabel('value') # Y轴标题 plt.title("plot of functions") ##子图标题 plt.xlim([0,10]) # X轴坐标范围 plt.ylim([-2,2]) # Y轴坐标范围 plt.legend() # 生成图例 plt.subplot(1,2,2) #1行2列,第2个子图 week=["Mon","Tue","Wed","Thur","Fri","Sat","Sun"] sales=np.random.randint(20,70,7) #生成7个[20,70)之间的整数 plt.bar(week,sales) #柱状图 plt.ylabel('sales') # Y轴标题 plt.title("Bar Chart") #子图标题 plt.show()
905ea1bc35f9777f9afc3d693b90aa5cde8c6c2e
patrickhaoy/RL-Tic-Tac-Toe
/src/state.py
6,654
3.921875
4
import numpy as np board_rows = 3 board_cols = 3 """ Tic Tac Toe board which updates states of either player as they take an action, judges end of game, and rewards players accordingly. """ class State: def __init__(self, p1, p2): self.board = np.zeros((board_rows, board_cols)) self.p1 = p1 self.p2 = p2 self.is_end = False # indicates if game ended self.board_hash = None self.player_symbol = 1 # p1 plays first (p1: 1, p2: -1) """ Converts current board state to String so it can be stored as the value in the dictionary """ def get_hash(self): self.board_hash = str(self.board.reshape(board_cols * board_rows)) return self.board_hash """ Returns available positions (cells with 0) as an array of pairs representing (x, y) coordinates """ def available_pos(self): pos = [] for i in range(board_rows): for j in range(board_cols): if self.board[i, j] == 0: pos.append((i, j)) return pos """ Updates state of board with player's move and switches players for the next turn """ def update_state(self, pos): self.board[pos] = self.player_symbol # switch players for next turn if self.player_symbol == 1: self.player_symbol = -1 else: self.player_symbol = 1 """ If p1 wins, 1 is returned. If p2 wins, -1 is returned. If it is a tie, 0 is returned. In either of these three cases, the game ends. If the game continues, None is returned. """ def winner(self): # checks rows for winner for i in range(board_rows): if sum(self.board[i, :]) == 3: self.is_end = True return 1 if sum(self.board[i, :]) == -3: self.is_end = True return -1 # checks columns for winner for i in range(board_rows): if sum(self.board[:, i]) == 3: self.is_end = True return 1 if sum(self.board[:, i]) == -3: self.is_end = True return -1 # checks diagonals for winner diag_sum1 = sum([self.board[i, i] for i in range(board_cols)]) diag_sum2 = sum([self.board[i, board_cols - i - 1] for i in range(board_cols)]) if abs(diag_sum1) == 3 or abs(diag_sum2) == 3: self.is_end = True if diag_sum1 == 3 or diag_sum2 == 3: return 1 else: return -1 # checks for tie if len(self.available_pos()) == 0: self.is_end = True return 0 # else, game has not ended yet self.is_end = False return None """ The winner gets a reward of 1, and the loser gets a reward of 0. As ties are also "undesirable", we set its reward from 0.5 to 0.1 (this is up for experimentation). """ def give_reward(self): winner = self.winner() if winner == 1: self.p1.feed_reward(1) self.p2.feed_reward(0) elif winner == -1: self.p1.feed_reward(0) self.p2.feed_reward(1) else: self.p1.feed_reward(0.1) self.p2.feed_reward(0.1) """ Training the bots against each other and saving the policies for the player going first as "policy_p1" and the player going second as "policy_p2". """ def play(self, rounds=100): for i in range(rounds): if i % 1000 == 0: print("Round {}".format(i)) while not self.is_end: # Simulating p1's turn pos = self.available_pos() p1_action = self.p1.choose_action(pos, self.board, self.player_symbol) self.update_state(p1_action) board_hash = self.get_hash() self.p1.add_state(board_hash) if self.winner() is not None: self.total_reset() break else: pos = self.available_pos() p2_action = self.p2.choose_action(pos, self.board, self.player_symbol) self.update_state(p2_action) board_hash = self.get_hash() self.p2.add_state(board_hash) if self.winner() is not None: self.total_reset() break self.p1.save_policy() self.p2.save_policy() """ Simulating play against a human. """ def play2(self): while not self.is_end: # Simulating p1's turn pos = self.available_pos() p1_action = self.p1.choose_action(pos, self.board, self.player_symbol) self.update_state(p1_action) self.show_board() winner = self.winner() if winner is not None: if winner == 1: print(self.p1.name, "wins!") else: print("tie!") self.state_reset() break else: # Simulating p2's turn pos = self.available_pos() p2_action = self.p2.choose_action(pos) self.update_state(p2_action) self.show_board() winner = self.winner() if winner is not None: if winner == -1: print(self.p2.name, "wins!") else: print("tie!") self.state_reset() break """ Resets state of board and is_end for next round """ def state_reset(self): self.board = np.zeros((board_rows, board_cols)) self.board_hash = None self.is_end = False self.player_symbol = 1 """ Reset players and board for next round """ def total_reset(self): self.give_reward() self.p1.reset() self.p2.reset() self.state_reset() """ Prints out board for human user """ def show_board(self): for i in range(0, board_rows): print("-------------") out = "|" for j in range(0, board_cols): if self.board[i, j] == 1: token = 'x' elif self.board[i, j] == -1: token = 'o' else: token = ' ' out += token + ' | ' print(out) print('-------------')
0c1b5328bcf938b70a3a96ef1b4ac433ea771e4c
jiangeyre/Graphs
/Day_2_Lecture/graph_with_search.py
2,516
3.921875
4
class Queue: def __init__(self): self.queue = [] def enqueue(self, value): self.queue.append(value) def dequeue(self): if self.size() > 0: return self.queue.pop(0) else: return None def size(self): return len(self.queue) ​ class Graph: ​ def __init__(self): self.vertices = {} ​ def add_vertex(self, vertex_id): self.vertices[vertex_id] = set() # set of edges ​ def add_edge(self, v1, v2): """Add edge from v1 to v2.""" ​ # If they're both in the graph if v1 in self.vertices and v2 in self.vertices: self.vertices[v1].add(v2) ​ else: raise IndexError("Vertex does not exist in graph") ​ def get_neighbors(self, vertex_id): return self.vertices[vertex_id] ​ def bft(self, starting_vertex_id): """Breadth-first Traversal.""" ​ q = Queue() q.enqueue(starting_vertex_id) ​ # Keep track of visited nodes visited = set() ​ # Repeat until queue is empty while q.size() > 0: # Dequeue first vert v = q.dequeue() ​ # If it's not visited: if v not in visited: print(v) ​ # Mark visited visited.add(v) ​ for next_vert in self.get_neighbors(v): q.enqueue(next_vert) ​ def dft_recursive(self, start_vert, visited=None): print(start_vert) ​ if visited is None: visited = set() ​ visited.add(start_vert) ​ for child_vert in self.vertices[start_vert]: if child_vert not in visited: self.dft_recursive(child_vert, visited) ​ def dfs_recursive(self, start_vert, target_value, visited=None, path=None): print(start_vert) ​ if visited is None: visited = set() ​ if path is None: path = [] ​ visited.add(start_vert) ​ # Make a copy of the list, adding the new vert on path = path + [start_vert] ​ # Base case if start_vert == target_value: return path ​ for child_vert in self.vertices[start_vert]: if child_vert not in visited: new_path = self.dfs_recursive(child_vert, target_value, visited, path) if new_path: return new_path ​ return None ​ g = Graph() g.add_vertex(99) g.add_vertex(3) g.add_vertex(3490) g.add_vertex(34902) g.add_edge(99, 3490) # Connect node 99 to node 3490 g.add_edge(99, 3) # Connect node 99 to node 3 g.add_edge(3, 99) # Connect node 3 to node 99 g.add_edge(3490, 34902) ​ ​ #print(g.get_neighbors(99)) #print(g.get_neighbors(3)) ​ g.bft(99) g.bft(3490) ​ g.dft_recursive(99) print(g.dfs_recursive(99, 34902))
d38f462e41e1f2fd0e9f07623bca3fc6a5619272
mikaelgba/PythonDSA
/cap5/Metodos.py
1,411
4.25
4
class Circulo(): # pi é um varialvel global da classe pi = 3.14 # com raio = 'x valor' toda vez que criar um objeto Circulo ele automaticamnete já concidera que o raio será 'x valor' #mas se colocar um outro valor ele vai sobreescrever o 'x valor' def __init__( self, raio = 3 ): self.raio = raio def area( self ): return ((self.raio * self.raio) * Circulo.pi) def getRaio( self ): return self.raio def setRaio( self, novo_circulo ): self.raio = novo_circulo circulo = Circulo(4) print(circulo.getRaio(),"\n") print(circulo.area(),"\n") circulo.setRaio(7) print(circulo.area(),"\n") #Classe quadrado class Quadrado(): def __init__( self, altura, largura ): self.altura = altura self.largura = largura def area( self ): return ( self.altura * self.largura ) def getAltura( self ): return self.altura def setAltura( self, nova_altura ): self.altura = nova_altura def getLargura( self ): return self.largura def setLargura( self, nova_largura ): self.largura = nova_largura quad = Quadrado(2,2) print("Altura:",quad.getAltura(),"Largura:", quad.getLargura(),"\n") print(quad.area(),"\n") quad.setAltura(4) print(quad.getAltura(),"\n") quad.setLargura(4) print(quad.getLargura(),"\n") print(quad.area(),"\n")
c735af789942fa33262fc7f6b6e6970351d3cb1d
mikaelgba/PythonDSA
/cap4/Funcao_Filter.py
687
3.828125
4
#Criando uma função para verificar se um numero é impar def ver_impar(numero): if ((numero % 2) != 0): return True else: return False print(ver_impar(10), "\n") #Criando uma lista adicionando nela valores randomicos import random # a se torna em uma lista com 10 varoles random a = random.sample(range(100),10) print(a) print("\n") # In[ ]: print(filter(ver_impar,a)) print("\n") # In[ ]: #imprimindo o retorno da função com os valores apenas imapres print(list(filter(ver_impar,a))) print("\n") # In[ ]: #Ultilixando o filter com lambda print(list(filter(lambda x: (x % 2) == 0, a))) print("\n") print(list(filter(lambda x: x >= 50, a)))
26690c4000dbfd7bc49817c00aee7d1a406f4475
mikaelgba/PythonDSA
/cap2/Dicionarios.py
1,339
3.875
4
dicio1 = {"Mu":1,"Aiolia":5,"Aiolos":9,"Aldebaran":2,"Shaka":6,"Shura":10,"Saga":3,"Dorko":7,"Kamus":11,"Mascará da Morte":4,"Miro":8,"Afodite":12} print(dicio1) print(dicio1["Mu"]) #Limpar os elementos do Dicionario dicio1.clear() print(dicio1) dicio2 ={"Seiya":13,"Shiryu":15,"Ikki":15,"Yoga":14,"Shun":13} dicio2["Seiya"] = 14 print(dicio2) #Retorna se há uma chave no dicionario print("Seiya" in dicio2) #Retorna se há uma elemento no dicionario print(13 in dicio2.values()) #Retorna o tamanho print(len(dicio2)) #Retorna as chaves dos elementos print(dicio2.keys()) #Retorna os elementos do dicionario print(dicio2.values()) #Retorna os elementos do dicionario print(dicio2.items()) #Mescla 2 dicionarios dicio3 = {"Saori":14, "Karno":23} dicio2.update(dicio3) print(dicio3) dicio4 = {1:"eu", 2:"você",3:"e o zubumafu"} print(dicio4[1].upper()) dicio4 = {1:"eu", 2:"você",3:"e o zubumafu"} print(dicio4[1].lower()) #Adicionando um elemento dicio4[4] = " para sempre" print(dicio4) #Removendo um elemento del dicio4[4] print(dicio4) #Dicioario com subListas dicio5 = {"a":[23,58,19],"b":[35,75,95],"c":[41,53,24]} dicio5["a"][0] -= 2 print(dicio5) #Dicioario com mais de uma chave para cada elemento dicio6 = {"id1":{"user1":"a"},"id2":{"user2":"b"}} dicio6["id1"]["user1"] = "A" dicio6["id2"]["user2"] = "B" print(dicio6)
ea8211501e5fcb7ae3a319cf7c9f2e6878ad759b
mikaelgba/PythonDSA
/cap2/Variaveis.py
362
3.734375
4
a = 1.7 b = 2 print(a , b) print(pow(a,b)) print() a = 1.7777 b = 2 print(round(a,b)) print() b = 2 print(float(b)) print() a = 1.7 print(int(a)) print() var_test = 1 print(var_test) print(type(var_test)) print() pessoa1, pessoa2, pessoa3 = "eu", "você", "E o Zubumafu" print(pessoa1) print(pessoa2) print(pessoa3) print() print(pessoa1 == pessoa2)
ea62f060d4d0d4e1b9250e8edd041cc939b109da
mikaelgba/PythonDSA
/cap4/Datetime.py
1,007
3.90625
4
#Importando o pacote DataTime, aplicações de data e hora import datetime # datetime.datetime.now() retorna a data e o horario atual hora_agora = datetime.datetime.now() print(hora_agora) print("\n") # datetime.time() cria um horario hora_agora2 = datetime.time(5,7,8,1562) print("Hora(s): ", hora_agora2.hour) print("Minuto(s): ", hora_agora2.minute) print("Segundo(s): ", hora_agora2.second) print("Mini segundo(s): ", hora_agora2.microsecond) print("\n") print(datetime.time.min) print("\n") # datetime.date.today() retorna a data atual hoje = datetime.date.today() print(hoje) print("Hora(s): ", hoje.ctime()) print("Minuto(s): ", hoje.year) print("Segundo(s): ", hoje.month) print("Mini segundo(s): ", hoje.day) print("\n") #Criando uma data com o datetime.date() data1 = datetime.date(2019,12,31) print("Dia: ", data1) print("\n") #Alterando a data com replace(year='x'), replace(month='x'), replace(day='x') data2 = data1.replace(year=2020) print(data2) print(data2 - data1) # In[ ]:
e1a234adfa92c9621b97e9ea3b9b07b112ff8a23
itsanti/gbu-ch-py-algo
/hw6/hw6_task3.py
1,979
3.609375
4
"""HW6 - Task 3 Подсчитать, сколько было выделено памяти под переменные в ранее разработанных программах в рамках первых трех уроков. Проанализировать результат и определить программы с наиболее эффективным использованием памяти. """ import sys from math import sqrt from memory_profiler import profile print(sys.version, sys.platform) def meminfo(obj): print(f'ref count: {sys.getrefcount(obj)}') print(f'sizeof: {sys.getsizeof(obj)}') @profile() def sieve(n): def _sieve(n): sieve = [i for i in range(n)] sieve[1] = 0 for i in range(2, n): j = i * 2 while j < n: sieve[j] = 0 j += i return [i for i in sieve if i != 0] i = 100 result = _sieve(i) while len(result) < n: i += 50 result = _sieve(i) meminfo(result) return result[n - 1] @profile() def prime(n): def is_prime(n): i = 2 while i <= sqrt(n): if n % i == 0: return False i += 1 return True result = [] first = 2 size = 50 while len(result) < n: for k in range(first, size): if is_prime(k): result.append(k) first = size size *= 2 meminfo(result) return result[n - 1] n = 500 print(f"sieve: {sieve(n)}") print(f"prime: {prime(n)}") """ 3.7.0 (default, Jun 28 2018, 08:04:48) [MSC v.1912 64 bit (AMD64)] win32 Количество ссылок на объект result: sieve: 6 prime: 6 Размер объекта result в байтах: sieve: 4272 prime: 7056 Выделено памяти на выполнение скрипта: sieve: 37.6 MiB prime: 37.9 MiB Вариант sieve - оптимальный по памяти. """
c58df5c0848e33e443e455f26433efd010276218
itsanti/gbu-ch-py-algo
/hw8/hw8_task1.py
589
3.6875
4
"""HW8 - Task 1 На улице встретились N друзей. Каждый пожал руку всем остальным друзьям (по одному разу). Сколько рукопожатий было? Примечание. Решите задачу при помощи построения графа. """ n = int(input('Сколько встретилось друзей: ')) graph = [[int(i > j) for i in range(n)] for j in range(n)] count = 0 for r in range(len(graph)): count += sum(graph[r]) print(f'Количество рукопожатий {count}')
dc4153dddd83d25e90daaa526124291729b85405
itsanti/gbu-ch-py-algo
/hw3/hw3_task5.py
1,288
3.9375
4
"""HW3 - Task 5 В массиве найти максимальный отрицательный элемент. Вывести на экран его значение и позицию в массиве. Примечание к задаче: пожалуйста не путайте «минимальный» и «максимальный отрицательный». Это два абсолютно разных значения. """ import random in_arr = [random.randint(-3, 3) for _ in range(5)] print(in_arr) max_negative = (-1, 0) for i, el in enumerate(in_arr): if 0 < -el and -el > max_negative[1]: max_negative = (i, el) if max_negative[0] > -1: print(f'максимальный отрицательный элемент: {max_negative[1]}\nнаходится на позиции: {max_negative[0]}') else: print('все элементы в массиве положительные') '''OUTPUT [2, -2, 1, -1, 2] максимальный отрицательный элемент: -1 находится на позиции: 3 [3, 1, -3, -2, -1] максимальный отрицательный элемент: -1 находится на позиции: 4 [3, 3, 2, 2, 3] все элементы в массиве положительные '''
f6c3bc55ec38fefd1cf9b8dd646f6bf5135716d4
itsanti/gbu-ch-py-algo
/hw2/hw2_task5.py
489
3.6875
4
"""HW2 - Task 5 Вывести на экран коды и символы таблицы ASCII, начиная с символа под номером 32 и заканчивая 127-м включительно. Вывод выполнить в табличной форме: по десять пар «код-символ» в каждой строке. """ i = 1 for code in range(32, 128): end = '\n' if i % 10 == 0 else '\t' print(f'{code:3}-{chr(code)}', end=end) i += 1
51ac5cfbf207126f3cf7ea7066c7c942d91dc074
mahanta-tapas/WebScrapers
/verbose.py
467
3.765625
4
import sys question = "Are you Sure ??" default = "no" valid = {"yes": True , "y": True, "ye" : True} invalid = {"no" :False,"n":False} prompt = " [y/N] " while True: choice = raw_input(question + prompt ) if choice in valid: break elif choice in invalid: sys.stdout.write("exiting from program \n") exit() else: sys.stdout.write("Please respond with 'yes' or 'no' " + "(or 'y' or 'n').\n") print "Going Ahead\n"