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
228c27b3406c45f10f3df2588de29e1d4ad5bfcb
AjayHao/helloPy
/demos/basic/list.py
684
4.21875
4
#!/usr/bin/python3 # 元祖 list1 = ['Google', 'Runoob', 1997, 2000] list2 = [1, 2, 3, 4, 5, 6, 7, 8] # 随机读取 print ("list1[0]: ", list1[0]) print ("list1[-2]: ", list1[-2]) print ("list2[1:3]: ", list2[1:3]) print ("list2[2:]: ", list2[2:]) # 更新 list1[2] = '123' print ("[update] list1: ", list1) # 删除 del list1[2] print ("[del] list1: ", list1) # 操作符 print ("[len()] list1: ", len(list1)) print ("list1 + list2: ", list1 + list2) print ("list1 * 2: ", list1 * 2) print ("2000 in list1: ", 2000 in list1) for x in list1: print(x, end=" ") print() print(1 not in list2) # 列表数组转换 tuple = tuple(list2) print(tuple)
a97267baf084e7e54bc75706b82fe02fcbe7f519
AjayHao/helloPy
/demos/designpatterns/creational/singleton_pattern.py
301
3.59375
4
class Singleton: def __init__(self): pass def __new__(cls): if not hasattr(Singleton, "__instance"): Singleton.__instance = super(Singleton, cls).__new__(cls) return Singleton.__instance obj1 = Singleton() obj2 = Singleton() print(obj1, obj2)
3551929bd1814c20eca69cbb80290d2ff8de8372
chaksamu/python
/venv/binarysearch.py
442
3.609375
4
pos=-1 def search(list,s): l=0 u=len(list)-1 print(l,u) while l<=u: mid=(l+u) // 2 print(mid) if list[mid]==s: globals()['pos']=mid return True else: if list[mid] < s: l=mid+1 else: u=mid-1 return False list=[1,2,3,4,5,6,7,8,9,10,11] s=11 if search(list,s): print("Found",pos) else: print("NotFound")
7a5473750801417f14ab6605e911b5d5765d04b7
chaksamu/python
/venv/multithreads.py
486
3.90625
4
from time import sleep from threading import * class Hello(Thread): def run(self): #run is default method for i in range(5): print("Hello") sleep(1) t1=Hello() #t1.run() t1.start() sleep(0.5) class Hi(Thread): def run(self): for i in range(5): print("Hi") sleep(1) t2=Hi() #t2.run() t2.start() t1.join() #Join will tell to main thread wait till completion of t1 and t2 thread. t2.join() print("By1")
477250d187e782933186cb9bf8b3b4e6a9ece45c
chaksamu/python
/venv/calendar.py
595
3.90625
4
import calendar for month in calendar.month_name: print(month) for month in calendar.day_name: print(month) for month in calendar.day_name: print(month) c=calendar.TextCalendar(calendar.SUNDAY) str=c.formatmonth(2025,12) print(str) c = calendar.TextCalendar(calendar.TUESDAY) str = c.formatmonth(2025, 2) print(str) c = calendar.HTMLCalendar(calendar.TUESDAY) str = c.formatmonth(2025, 2) print(str) c = calendar.TextCalendar(calendar.TUESDAY) for i in c.itermonthdays(2025,4): print(i) for month in range (1,13): mycal=calendar.monthcalendar(2025,month) print(mycal)
b8ad231bf1e687ee05105ea6440ed20c9f263f6f
chaksamu/python
/venv/classinsideclass.py
711
3.8125
4
class Student: def __init__(self,name,rollno): self.N = name self.R = rollno self.L = self.Laptop() def show(self): print(self.N,self.R) self.L.show() class Laptop: def __init__(self): self.brand = 'hp' self.cpu = 'i8' self.ram = 20 #print(self.brand) #print(self.cpu) def show(self): print(self.brand, self.cpu, self.ram) s1=Student('chakri',1) s2=Student('chandu',2) print(s1.N,s1.R) print(s2.N,s2.R) s1.show() s2.show() #one way s1.L.brand s2.L.cpu #other way l1=s1.L l2=s2.L print(l1.cpu) print(l2.ram) print(id(l1)) print(id(l2)) lap1 = Student.Laptop()
35d4105326e91ac51680a7a0d7e50d17a87c79d9
chaksamu/python
/venv/loops.py
594
3.921875
4
#While def main(): x=0 while (x<=5): print(x) x=x+1 #print(x) main() #For def main(): x=0 for x in range(2,7): print("The ",x) main() def main(): Months={"Jan", "Feb", "Mar"} for i in Months: print(i) main() #break def main(): y={1,2,3,4,5,6,7,8,9,10} for x in y: if(x==5): #break continue print(x) else: print(x) main() def main(): Months={"Jan", "Feb", "Mar", "Apr", "May"} for i, m in enumerate(Months): print(i,m) # print(z) main()
227ace258237b03dd4bb000ad3b4abec216c656b
chaksamu/python
/venv/bubblesort.py
305
3.828125
4
def sort(nums): print(nums) for i in range(len(nums)-1,0,-1): for j in range(i): if nums[j]>nums[j+1]: t=nums[j] nums[j]=nums[j+1] nums[j+1]=t print(nums) #print(nums) nums=[6,5,4,3,2,1] sort(nums) #print(nums)
a547e08af1445d7aa9f2ff0d95fc66d9f2a8c9db
chaksamu/python
/venv/steps/liststeps3.py
271
3.609375
4
name=str(input("Enter the Filename: ")) f=open(name,'r') #ff=f.read() #print(ff) #gg=(ff.split()) #print(gg) for line in f: if not line.startswith('From'): continue tt=line.split() print(tt[1]) yy=tt[1] zz=yy.split('@') print(zz) #4:13:00
e99b2ad952745f289c6e8e19ac756e975092606c
Akshay1997a/Python-Datastructure
/LinkedList.py
1,841
4
4
from os import system def cls(): system('clear') class Node: def __init__(self, val): self.data = val self.next = None class LinkedList: def __init__(self): self.head = None def addNode(self, list): for i in list: if self.head == None: self.head = Node(i) else: temp = self.head while(temp.next): temp = temp.next temp.next = Node(i) def deleteNode(self, node, val): if node == None: print('Value not found') return False if self.head.data == val: self.head = self.head.next else: if node.data == val: return node.next else: temp = self.deleteNode(node.next, val) if temp != False: node.next = temp return False return False def printNode(self, node): if node != None: print(str(node.data), end=' ') self.printNode(node.next) cls() ll = LinkedList() while(True): print() print('...................Linked List........................') print('1 - Add list') print('2 - Delete Node') print('3 - Print List') print('4 - Clear console') print('5 - exit') x = int(input('Enter your feedback :: ')) if (x == 1): ll.addNode([int(x) for x in input('Enter List :: ').split(' ')]) print('current list :: ', end='') ll.printNode(ll.head) elif (x == 2): ll.deleteNode(ll.head, int(input('Enter value: : '))) print('current list :: ', end='') ll.printNode(ll.head) elif (x == 3): ll.printNode(ll.head) elif (x == 4): cls() else: break
faf4ef2dab7840dfe0c778377e4998fa951ab988
quynhhgoogoo/Artificial-Intelligence
/lectures/n-grams/ngrams.py
1,105
3.625
4
from collections import Counter import math import nltk import os import sys nltk.download('punkt') def main(): '''Calculate top term frequencies for a corpus of documents''' if len(sys.argv) != 3: sys.exit("Usage: python ngrams.py n corpus") print("Loading data...") # Loading input n = int(sys.argv[1]) corpus = load_data(sys.argv[2]) # Compute n-grams ngrams = Counter(nltk.ngrams(corpus, n)) # Print most common n-grams for ngram, freq in ngrams.most_common(10): print(f"{freq}: {ngram}") def load_data(directory): contents = [] # Read all files and extract words for filename in os.listdir(directory): with open(os.path.join(directory, filename)) as f: # Convert all the words to lower case # For all the words which are characters contents.extend([ word.lower() for word in nltk.word_tokenize(f.read()) if any (c.isalpha() for c in word) ]) return contents if __name__ == "__main__": main()
1d2d81b28514c9d02774bab739dff207a7e619f0
nixeagle/euler
/2/flare183.py
265
3.53125
4
def fib(): x,y = 0,1 while True: yield x x,y = y, x+y def even(seq): for number in seq: if not number % 2: yield number def problem(seq): for number in seq: if number > 4000000: break yield number print sum(even(problem(fib())))
4646413619e71320a217116999fa2ba6fc4e7992
ZanderBE/Fill-in-the-Blank-Quiz
/Final-Version-Fill-In-The-Blank-Quiz.py
7,241
3.71875
4
guessCounter = 5 guessIndex = 0 outOfLives = 0 blankList = ["BLANK1", "BLANK2", "BLANK3", "BLANK4"] promptList = ['What do you think fills "BLANK1"? ', 'What do you think fills "BLANK2"? ', 'What do you think fills "BLANK3"? ', 'What do you think fills "BLANK4"? '] easyMode =''' [EASY MODE]The current problem reads: Twenty BLANK1 from now you will be more BLANK2 by the things that you BLANK3 do than by the ones you BLANK4 do. ''' easyList = ["years", "dissapointed", "didn't", "did"] mediumMode =''' [MED. MODE]The current problem reads: I'm a BLANK1 today because I had a BLANK2 who BLANK3 in me and I didn't have the BLANK4 to let him down. ''' mediumList = ["success", "friend", "believed", "heart"] hardMode = ''' [HARD MODE]The current problem reads: It is BLANK1 to escape the BLANK2 that people commonly use false standards of measurement - that they seek power, success and BLANK3 for themselves and admire them in others, and that they underestimate what is of true BLANK4 in life. ''' hardList = ["impossible", "impression", "wealth", "value"] def show_intro(): """This function will show the user tips on how to get started with the quiz and select difficulty""" print(""" Welcome to my Quiz! Please select your difficulty from below: Easy Peezy Lemon Squeezy - Type: Easy You Can Probably Handle This... Maybe - Type: Medium Almost Impossible - Type: Hard **You will get 5 guesses per blank regardless of difficulty """) def difficulty_selector(): """ This function will prompt the user to select a difficulty out of the available choices. Input: The user selects between "easy", "medium" or "hard." Behavior: Once user has selected the difficulty it will assign the difficulty and answers based on that choice. Return: This function will return the difficulty and answer variables for question_prompter(). """ answer_choices = ["easy","medium", "hard"] new_answer = raw_input("Please feel free to type your answer here: ").lower() while new_answer not in answer_choices: print("That's not a valid answer! Please select from Easy, Medium or Hard.") new_answer = raw_input("Please feel free to type your answer here: ").lower() if new_answer == "easy": difficulty = easyMode answers = easyList elif new_answer == "medium": difficulty = mediumMode answers = mediumList elif new_answer == "hard": difficulty = hardMode answers = hardList return question_prompter(difficulty, answers, guessIndex) def question_prompter(difficulty, answers, guessIndex): """ This function will prompt the user to guess for the current BLANK. Input: The user will input their guess for the corresponding BLANK. Behavior: This will ask the user for a guess based on the guessIndex to correspond with correct prompt Return: This function will return the new_answer through the answer_checker to check users response. """ global guessCounter print(difficulty) while guessCounter > outOfLives: new_answer = raw_input(promptList[guessIndex]).lower() return answer_checker(new_answer, answers, difficulty) def answer_checker(new_answer, answers, difficulty): """ This function will check the users response against the correct answers. Input: This will receive the users newest response as well as the current answer list and difficulty. Behavior: Loop through each correct answer and check if the newest response matches the current answer. If there is a match, move the guessIndex to the next prompt check game_status in case game is over reset the guess counter If there is no match, remove a guess check game_status in case game is over alert user of incorrect response and remaining guesses, if any. Return: This function will return the question_prompter with either the same guessIndex (response was wrong) or new guessIndex (response was correct). """ global guessIndex global guessCounter for answer in answers: if new_answer in answers: difficulty = answer_filler(answers, difficulty) print("That's correct!!\n") guessIndex += 1 if guessIndex == len(answers): return end_game(1, difficulty) guessCounter = 5 return question_prompter(difficulty, answers, guessIndex) else: guessCounter -= 1 if guessCounter == outOfLives: end_game(0, difficulty) else: print("Uh oh, that's incorrect! You currently have {} guesses left!\n").format(guessCounter) return question_prompter(difficulty, answers, guessIndex) def answer_filler(answers, difficulty): """ This function will add the correct answer to the problem if the user guesses correctly. Input: This will receive the correct answer and current difficulty problem. Behavior: Take difficulty and break it into a list of strings Loop through each word in difficulty If the word matches the current BLANK, replace it with current word from correct answer list and add to new_difficulty remaining words can be added to new_difficulty with no change combine new list into one string Return: This function will return the updated difficulty the fills correctly answered blanks """ global guessIndex new_difficulty = [] difficulty = difficulty.split() for word in difficulty: if word == blankList[guessIndex]: word = answers[guessIndex] new_difficulty.append(word) else: new_difficulty.append(word) new_difficulty = " ".join(new_difficulty) return new_difficulty def end_game(game_status, difficulty): """ This function will check if the game win or lose conditions have been met and end game accordingly. Input: This will receive the current game_status and current difficulty. Behavior: If answer_checker() sees that guessCounter equals outOfLives it will send a game status of 0 is sent to this function. A game_status of 0 will end the game and print the corresponding message. If answer_checker sees that guessIndex equals the length of the answer list a game status of 1 is sent to this function. a game_status of 1 will end the game and print the finished problem with corresponding message Return: This function will end the game. """ if game_status == 0: print(""" **Game Over!** Uh oh! Looks like the last guess was incorrect and you're out of guesses now. Better luck next time!""") else: print(''' Completed Quiz: {} You won!!! Nice Job completing that quiz!!!''').format(difficulty[38:]) def play_game(): """This game will begin the game by showing the intro function and running the difficulty selector function.""" show_intro() difficulty_selector() play_game()
0d113719859b6ff06717d69e0bd4aee5150985ee
wrf22805656/Web-Crawler
/Scraping data - example one
555
3.640625
4
#! /user/bin/env python import re import urllib2 def download(url): print ('downloading:' "\n", url) try: html = urllib2.urlopen(url).read() except urllib2.URLError as e: print 'Downloading error:', e.reason html = None return html url = 'http://example.webscraping.com/view/United-Kingdom-239' html = download(url) # results = re.findall('<td class="w2p_fw">(.*?)</td>',html) # print results result2 = re.findall('<td class="w2p_fw">(.*?)</td>',html)[1] print result2
aeed9a1fecdf64c15fed3310d68fc54cfb839475
trallorc/Steev
/Moshe Sharat/hexmap/Render.py
7,712
3.640625
4
from abc import ABCMeta, abstractmethod import pygame import math from Map import Grid SQRT3 = math.sqrt(3) class Render(pygame.Surface): __metaclass__ = ABCMeta def __init__(self, map, radius=16, *args, **keywords): self.map = map self.radius = radius # Colors for the map self.GRID_COLOR = pygame.Color(50, 50, 50) super(Render, self).__init__((self.width, self.height), *args, **keywords) self.cell = [(.5 * self.radius, 0), (1.5 * self.radius, 0), (2 * self.radius, SQRT3 / 2 * self.radius), (1.5 * self.radius, SQRT3 * self.radius), (.5 * self.radius, SQRT3 * self.radius), (0, SQRT3 / 2 * self.radius) ] @property def width(self): return math.ceil(self.map.cols / 2.0) * 2 * self.radius + \ math.floor(self.map.cols / 2.0) * self.radius + 1 @property def height(self): return (self.map.rows + .5) * self.radius * SQRT3 + 1 def get_surface(self, ( row, col )): """ Returns a subsurface corresponding to the surface, hopefully with trim_cell wrapped around the blit method. """ width = 2 * self.radius height = self.radius * SQRT3 top = (row - math.ceil(col / 2.0)) * height + (height / 2 if col % 2 == 1 else 0) left = 1.5 * self.radius * col return self.subsurface(pygame.Rect(left, top, width, height)) # Draw methods @abstractmethod def draw(self): """ An abstract base method for various render objects to call to paint themselves. If called via super, it fills the screen with the colorkey, if the colorkey is not set, it sets the colorkey to magenta (#FF00FF) and fills this surface. """ color = self.get_colorkey() if not color: magenta = pygame.Color(255, 0, 255) self.set_colorkey(magenta) color = magenta self.fill(color) # Identify cell def get_cell(self, ( x, y )): """ Identify the cell clicked in terms of row and column """ # Identify the square grid the click is in. row = math.floor(y / (SQRT3 * self.radius)) col = math.floor(x / (1.5 * self.radius)) # Determine if cell outside cell centered in this grid. x = x - col * 1.5 * self.radius y = y - row * SQRT3 * self.radius # Transform row to match our hex coordinates, approximately row = row + math.floor((col + 1) / 2.0) # Correct row and col for boundaries of a hex grid if col % 2 == 0: if y < SQRT3 * self.radius / 2 and x < .5 * self.radius and \ y < SQRT3 * self.radius / 2 - x: row, col = row - 1, col - 1 elif y > SQRT3 * self.radius / 2 and x < .5 * self.radius and \ y > SQRT3 * self.radius / 2 + x: row, col = row, col - 1 else: if x < .5 * self.radius and abs(y - SQRT3 * self.radius / 2) < SQRT3 * self.radius / 2 - x: row, col = row - 1, col - 1 elif y < SQRT3 * self.radius / 2: row, col = row - 1, col return (row, col) if self.map.valid_cell((row, col)) else None def fit_window(self, window): top = max(window.get_height() - self.height, 0) left = max(window.get_width() - map.width, 0) return (top, left) class RenderUnits(Render): """ A premade render object that will automatically draw the Units from the map """ def __init__(self, map, *args, **keywords): super(RenderUnits, self).__init__(map, *args, **keywords) if not hasattr(self.map, 'units'): self.map.units = Grid() def draw(self): """ Calls unit.paint for all units on self.map """ super(RenderUnits, self).draw() units = self.map.units for position, unit in units.items(): surface = self.get_surface(position) unit.paint(surface) class RenderGrid(Render): def draw(self): """ Draws a hex grid, based on the map object, onto this Surface """ super(RenderGrid, self).draw() # A point list describing a single cell, based on the radius of each hex for col in range(self.map.cols): # Alternate the offset of the cells based on column offset = self.radius * SQRT3 / 2 if col % 2 else 0 for row in range(self.map.rows): # Calculate the offset of the cell top = offset + SQRT3 * row * self.radius left = 1.5 * col * self.radius # Create a point list containing the offset cell points = [(x + left, y + top) for (x, y) in self.cell] # Draw the polygon onto the surface pygame.draw.polygon(self, self.GRID_COLOR, points, 1) class RenderFog(Render): OBSCURED = pygame.Color(00, 00, 00, 255) SEEN = pygame.Color(00, 00, 00, 100) VISIBLE = pygame.Color(00, 00, 00, 0) def __init__(self, map, *args, **keywords): super(RenderFog, self).__init__(map, *args, flags=pygame.SRCALPHA, **keywords) if not hasattr(self.map, 'fog'): self.map.fog = Grid(default=self.OBSCURED) def draw(self): # Some constants for the math height = self.radius * SQRT3 width = 1.5 * self.radius offset = height / 2 for cell in self.map.cells(): row, col = cell surface = self.get_cell(cell) # Calculate the position of the cell top = row * height - offset * col left = width * col # Determine the points that corresponds with points = [(x + left, y + top) for (x, y) in self.cell] # Draw the polygon onto the surface pygame.draw.polygon(self, self.map.fog[cell], points, 0) def trim_cell(surface): pass if __name__ == '__main__': from Map import Map, MapUnit import sys class Unit(MapUnit): color = pygame.Color(200, 200, 200) def paint(self, surface): radius = surface.get_width() / 2 pygame.draw.circle(surface, self.color, (radius, int(SQRT3 / 2 * radius)), int(radius - radius * .3)) m = Map((5, 5)) grid = RenderGrid(m, radius=32) units = RenderUnits(m, radius=32) fog = RenderFog(m, radius=32) m.units[(0, 0)] = Unit(m) m.units[(3, 2)] = Unit(m) m.units[(5, 3)] = Unit(m) m.units[(5, 4)] = Unit(m) for cell in m.spread((3, 2), radius=2): m.fog[cell] = fog.SEEN for cell in m.spread((3, 2)): m.fog[cell] = fog.VISIBLE print(m.ascii()) try: pygame.init() fpsClock = pygame.time.Clock() window = pygame.display.set_mode((640, 480), 1) from pygame.locals import QUIT, MOUSEBUTTONDOWN # Leave it running until exit while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == MOUSEBUTTONDOWN: print(units.get_cell(event.pos)) window.fill(pygame.Color('white')) grid.draw() units.draw() fog.draw() window.blit(grid, (0, 0)) window.blit(units, (0, 0)) window.blit(fog, (0, 0)) pygame.display.update() fpsClock.tick(10) finally: pygame.quit()
7c3a1cf25c041f0212a7764e4aad57abecf7f9bf
kanglicheng/GoogleCodeJam
/2019/Qualification/B/b.py
263
3.59375
4
def solve(): N = int(input()) S = input() ans = "" for c in S: ans += "E" if c == "S" else "S" return ans if __name__ == "__main__": T = int(input()) for t in range(1, T + 1): print("Case #{}: {}".format(t, solve()))
7dbb6ceb733fa90b5f1cc5ab5521cffaf24d7c0f
ryanmcfarland/file-tk-downloader
/classes/reqdl.py
937
3.5625
4
import requests import os import sys import urllib3 class RequestFile: def __init__(self, dir="", filename="", url=""): self.dir = dir self.filename = filename self.url = url ## --> check if the directory exists def check_dir_exists(self): if not os.path.exists(self.filepath): os.makedirs(self.filepath) ## --> create full filename def generate_filename(self): return self.dir + "/" + self.filename ## --> return the full filepath of the file def return_filepath(self): self.filepath = self.generate_filename() return self.filepath def download_file(self): r = requests.get(self.url, stream = True) with open(self.filepath, "wb") as fileDownload: for chunk in r.iter_content(chunk_size=1024): if chunk: fileDownload.write(chunk) return "Success"
a66405eeea9904f8c4967a7789bc6a4841713f24
anumulaphani/nodejs-application
/sales enhancement.py
255
3.796875
4
sales = float(input("Enter sales: $")) while sales <= 0: print("Invalid option") sales = float(input("Enter sales: $")) if sales < 1000: bonus = sales * 0.1 print(bonus) else: bonus = sales * 0.15 print(bonus) print("good bye")
fcf2d76ad0f3015988ae7b445870405ac0e2e668
anumulaphani/nodejs-application
/practicals 2/practicals_3/value_error.py
436
4.0625
4
def get_num(lower, upper): while (True): try: user_input = int(input("Enter a number ({}-{}):".format(lower, upper))) if user_input < lower: print("Number too low.") elif user_input > upper: print("please enter a valid number") else: return user_input except ValueError: print("Please enter a valid number")
977529bdb4da2c8b6a0a7d5749b57dca59ece90c
Wormandrade/Trabajo01
/eje02.py
358
4.03125
4
#Calcular el perímetro y área de un círculo dado su radio. print("========================") print("\tEJERCICIO 02") print("========================") print("Cálculo de périmetro y área de un círculo\n") radio = float(input("Ingrese el radio: \n")) pi=3.1416 print("El perímetro es: ",round(radio*pi,2)) print("El área es: ",round(radio*radio*pi,2))
2c388737f42543942819ef22f8faac2098bff0c3
SeanLau/leetcode
/problem_167.py
1,444
3.640625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- class Solution(object): def twoSum(self, numbers, target): """ 时间复杂度,O(N*logN) :type numbers: List[int] :type target: int :rtype: List[int] """ def binary_search(mlist, start, end, target): while end >= start: mid = (start + end) // 2 if mlist[mid] == target: return mid elif mlist[mid] > target: end = mid - 1 elif mlist[mid] < target: start = mid + 1 for i in range(len(numbers) - 1): new_target = target - numbers[i] res = binary_search(numbers, i + 1, len(numbers) - 1, new_target) if res: return i + 1, res + 1 def twoSum2(self, numbers, target): """" 时间复杂度O(n) """ if numbers: start = 0 end = len(numbers) - 1 while True: if start == end: return temp = numbers[start] + numbers[end] if temp == target: return start + 1, end + 1 elif temp > target: end -= 1 else: start += 1 pass if __name__ == '__main__': l = [2,7,11,15] s = Solution() print(s.twoSum2(l, 9))
0b303dde589390cf6795a2fc79ca473349c5e190
SeanLau/leetcode
/problem_104.py
1,203
4.125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # 此题可以先序遍历二叉树,找到最长的即可 # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ depth = 0 if not root: return depth result = [] def preOrder(root, depth): # return root depth += 1 if root.left: preOrder(root.left, depth) if root.right: preOrder(root.right, depth) # yield depth if not (root.left and root.right): print("## depth in ===>", depth) result.append(depth) preOrder(root, depth) return max(result) if __name__ == '__main__': root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(2) root.left.left = TreeNode(3) root.left.right = TreeNode(4) root.right.right = TreeNode(3) root.right.left = TreeNode(4) so = Solution() print(so.maxDepth(root))
454512c0eacf9f9471ce330911247e85b5723d71
SeanLau/leetcode
/problem_190.py
733
3.578125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- class Solution(object): """ 这里需要注意的是,切片使用的灵活性. """ def reverseBits(self, n): """ :param n: :return: """ foo = bin(n) foo_str = str(foo)[2:] foo_str = foo_str.rjust(32, "0") foo_str = list(foo_str) foo_str.reverse() return int(eval("0b" + "".join(foo_str))) def reverseBits2(self, n): s = bin(n)[-1:1:-1] s += (32 - len(s)) * "0" return int(s, 2) def reverseBits3(self, n): tmp = "{0:032b}".format(n) return int(tmp[::-1], 2) if __name__ == '__main__': s = Solution() print(s.reverseBits3(43261596))
6cfb4c27f0a897695d4b0bf229f64f5d0d5bb378
SeanLau/leetcode
/problem_160.py
3,348
3.75
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ 采用边遍历边判断的方法,实现了功能,但是提交超时 :type head1, head1: ListNode :rtype: ListNode """ if headA is None or headB is None: return cur1 = headA while cur1: cur2 = headB while cur2: if cur1 == cur2: return cur1 else: cur2 = cur2.next cur1 = cur1.next return def getIntersectionNode2(self, headA, headB): """ 采用先遍历后判断的逻辑,此种方法把链表的存储优势浪费了,使用庞大的列表,对空间的需求和遍历也是绝大的开支,仍超时 :param headA: :param headB: :return: """ listA= [] if headA is None or headB is None: return cur1 = headA while cur1: listA.append(cur1) cur1 = cur1.next cur2 = headB while cur2: if cur2 in listA: return cur2 else: cur2 = cur2.next def getIntersectionNode3(self, headA, headB): """ 两个链表,如果能同步遍历,则是寻找共同节点的最好办法.先找到共同长度 :param headA: :param headB: :return: """ cur1, cur2 = headA, headB len1, len2 = 0, 0 while cur1 or cur2: if cur1: len1 += 1 cur1 = cur1.next if cur2: len2 += 1 cur2 = cur2.next delta = abs(len1 - len2) cur1, cur2 = headA, headB if len1 > len2: while delta > 0: cur1 = cur1.next delta -= 1 elif len2 > len1: while delta > 0: cur2 = cur2.next delta -= 1 while cur1 and cur2: if cur1 == cur2: return cur1 cur1 = cur1.next cur2 = cur2.next def getIntersectionNode4(self, headA, headB): """ 车轮战的方式匹配,这种匹配判断逻辑统一,没有程序跳转的过程,用时在提交代码中最短,代码也相对简洁 cur1 = headA + headB cur2 = headB + headA 这样两者的长度就想相同了,next的步调也是一直的.妙! :param headA: :param headB: :return: """ cur1, cur2 = headA, headB while cur1 and cur2 and cur1 != cur2: cur1 = cur1.next cur2 = cur2.next if cur1 is None: cur1 = headB if cur2 is None: cur2 = headA if cur1 == cur2: return cur1 if __name__ == '__main__': a = ListNode(1) b = ListNode(3) c = ListNode(4) d = ListNode(5) e = ListNode(6) f = ListNode(7) a.next = b b.next = c c.next = d d.next = e e.next = f A = ListNode(100) B = ListNode(200) A.next = B B.next = c s = Solution() print(s.getIntersectionNode3(a, A).val)
ee7fb11021cb2d237d0dcc5409c8a91461956339
vojtsek/tts-utils
/model/model.py
3,216
3.59375
4
''' A linear regression learning algorithm example using TensorFlow library. Author: Aymeric Damien Project: https://github.com/aymericdamien/TensorFlow-Examples/ ''' import tensorflow as tf import argparse from dataset import Dataset, Utterance import tensorflow.contrib.layers as tf_layers ap = argparse.ArgumentParser() ap.add_argument("-l", type=int) ap.add_argument("-s", type=int) ap.add_argument("-e", type=int) ap.add_argument("--include_gold", action="store_true") args = ap.parse_args() no_classes = 4 d = Dataset(length=args.s, dataset_path="dataset.dump") d.load_data(size=no_classes, include_gold=args.include_gold) # Parameters learning_rate = 0.01 training_epochs = args.e display_step = 2 input_size = d.data_X.shape[1] batch_size = 8 print(d.data_X.shape) # batch x frames x order x engines X = tf.placeholder("float", [None, input_size]) Y = tf.placeholder(tf.int64, [None]) # Set model weights l1_size = args.l # W1 = tf.Variable(initial_value=tf.random_uniform([input_size, l1_size], 0, 1), name="weights1", trainable=True) # b1 = tf.Variable(initial_value=tf.random_uniform([l1_size], 0, 1), name="bias1", trainable=True) # W2 = tf.Variable(initial_value=tf.random_uniform([100, no_classes], 0, 1), name="weights2", trainable=True) # b2 = tf.Variable(initial_value=tf.random_uniform([no_classes], 0, 1), name="bias2", trainable=True) l1 = tf.sigmoid(tf_layers.linear(X, l1_size)) logits = tf_layers.linear(l1, no_classes) # softmax = tf.nn.softmax(logits) pred = tf.argmax(logits, axis=1) # Mean squared error cost = tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits(labels=tf.one_hot(Y, no_classes), logits=logits)) # Gradient descent optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost) # Initializing the variables init = tf.global_variables_initializer() # Launch the graph with tf.Session() as sess: sess.run(init) # Fit all training data # train_X, train_Y = d.get_data() for epoch in range(training_epochs): for x, y in d.next_batch(): sess.run([optimizer, cost], feed_dict={X: x, Y: y}) if d.batch_end(): break # Display logs per epoch step if (epoch+1) % display_step == 0: predictions, c = sess.run([pred, cost], feed_dict={X: x, Y:y}) print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), "pred=", predictions) valid_X, valid_Y = d.get_valid() train_X, train_Y = d.get_train() predictions, c = sess.run([pred, cost], feed_dict={X: valid_X, Y: valid_Y}) print("Cost: {}, predictions: {}".format(c, predictions)) diff = abs((valid_Y - predictions) != 0) print("Valid: ", 1 - ((sum(diff)) / len(diff))) predictions, c = sess.run([pred, cost], feed_dict={X: train_X, Y: train_Y}) print("Cost: {}, predictions: {}".format(c, predictions)) diff = abs((train_Y - predictions) != 0) print("Train: ", 1 - ((sum(diff)) / len(diff))) print("Optimization Finished!") # # # Graphic display # plt.plot(train_X, train_Y, 'ro', label='Original data') # plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line') # plt.legend() # plt.show()
de483b8ac3b15b2472aac0ba7baf79f59c4bfb48
Aromi-s/Assignment-function
/evnorodd.py
129
4.1875
4
num=int(input("Enter a number")) mode=num%2 if mode>0: print("This is an odd number") else: print("This is an even number")
467a4efb5a3fde195fbf79387f3d3871f757a979
Vishruth-S/Hack-CP-DSA
/Hackerrank/drawingbook/solution.py
2,478
3.828125
4
#!/bin/python3 import os import sys # # Complete the pageCount function below. # def pageCount(n, p): # # Write your code here. # pages = [] count = 0 #For turing from page 1. loop_run_one = 0 #For turning from page n. loop_run_two = 0 #For storing count from page 1 and page n and then finding the min value from this array. count_turns = [] #Appending the page numbers. for i in range(0, n + 1): pages.append(i) #checking if total number of pages is odd. if len(pages) % 2 != 0: #checking if page to turn is odd. if p % 2 != 0: p = p - 1 #Checking and counting the page turns from page 1. for j in range(0, len(pages), 2): loop_run_one = loop_run_one + 1 #if pages array equals the page number then turns should be turns - 1. Suppose if we go to page 2 from page 1. Then the loop count will be 2 but we had only one turn so -1. if j == p: loop_run_one = loop_run_one - 1 count_turns.append(loop_run_one) break #Reversing the pages to start counting from page n. pages.reverse() for k in range(0, len(pages), 2): loop_run_two = loop_run_two + 1 #if pages array equals the page number then turns should be turns - 1. Suppose if we go to page 2 from page 1. Then the loop count will be 2 but we had only one turn so -1. if pages[k] == p: loop_run_two = loop_run_two - 1 count_turns.append(loop_run_two) break else: #Checking when page n is even. if p % 2 != 0: p = p - 1 for j in range(0, len(pages), 2): loop_run_one = loop_run_one + 1 if j == p: loop_run_one = loop_run_one - 1 count_turns.append(loop_run_one) break pages.reverse() p = p + 1 for k in range(0, len(pages), 2): loop_run_two = loop_run_two + 1 if pages[k] == p: loop_run_two = loop_run_two - 1 count_turns.append(loop_run_two) break if len(count_turns) > 1: #Checking for min turns required from the count_turns from back and front. turns = min(count_turns) else: turns = 0 return turns print(pageCount(6,2))
22bd9bc0d83a2d0390ad93812f48c6d8924ddee7
sberen/uninterrupted
/summarizer.py
2,179
3.53125
4
import requests def summary_from_url(url, sentences): f = open("key.txt", "r") querystring = { "key":f.read(), "sentences":sentences, "url":url } return summary(querystring) def summary_from_text(txt, sentences): f = open("key.txt", "r") querystring = { "key":f.read(), "sentences":sentences, "txt":txt } return summary(querystring) def summary(querystring): url = "https://api.meaningcloud.com/summarization-1.0" response = requests.request("Post", url, headers=None, params=querystring) data = response.json() print(data) return(data["summary"]) #Uncomment for sample usage # txt = """ # Joe Biden believes to his core that there’s no greater economic engine in the world than the hard work and ingenuity of the American people. Nobody has more respect for the working women and men who get up every day to build and sustain this country, or more confidence that they can meet the challenges we face. # Make no mistake: America has been knocked down. The unemployment rate is higher than it was in the Great Recession. Millions have lost jobs, hours, pay, health care, or the small business they started, through no fault of their own. # The pandemic has also laid bare some unacceptable truths. Even before COVID-19, the Trump Administration was pursuing economic policies that rewarded wealth over work and corporations over working families. Too many families were struggling to make ends meet and too many parents were worried about the economic future for their children. And, Black and Latino Americans, Native Americans, immigrants, and women have never been welcomed as full participants in the economy. # Biden believes this is no time to just build back to the way things were before, with the old economy’s structural weaknesses and inequalities still in place. This is the moment to imagine and build a new American economy for our families and the next generation. # An economy where every American enjoys a fair return for their work and an equal chance to get ahead. An economy more vibrant and more powerful precisely because everybody will be cut in on the deal. # """ # print(summary_from_text(txt, 5))
c99bae5ac1bfa06c3796c5bb54a1d37d501a5a6a
srhternl/gaih-students-repo-example
/Homeworks/HW3.py
731
3.609375
4
def prime_first(number): # asal sayı hesaplayan 1. fonksiyonum. if number !=1 and number !=0: for i in range(2, number): if number % i == 0: break else: print("Prime numbers between 0-500:", number) def prime_second(number): # asal sayı hesaplayan 2. fonksiyonum. if number !=1 and number !=0: for i in range(2, number): if number % i == 0: break else: print("Prime numbers between 500-1000:", number) for i in list(range(1000)): # 0-500 ve 500-1000 arası asal sayıları hesaplayıp, ekrana yazdıran döngüm. if i < 500: prime_first(i) else: prime_second(i)
fb7f473982a26309c9ec086f0595c25ee1df5b2f
thoftheocean/project
/python/0homework/supplement/ascii.py
226
3.984375
4
# !/usr/bin/env python # coding:utf-8 # author hx #描述:将ascii码转化为对应的字符。如65 #ascii码转字母 chr() for i in range(26): print chr(i+65), #字母转ascii码 ord() print '\n', ord('a')
4ddcc55205d7213c9e5cc51275bc953053038784
thoftheocean/project
/python/0homework/search_num.py
649
3.875
4
# !/usr/bin/env python # coding:utf-8 # author:hx ''' 实现一个函数handler_num,输入为一个任意字符串,请将字符串中的数 字取出,将偶数放入一个列表,再将奇数放入一个列表,并将两个列表返回 ''' str = raw_input('输入一串字符:') def search_num(str): even = list() odd = list() result1 = dict() for i in str: if i.isdigit(): if int(i) % 2 == 0: even.append(i) else: odd.append(i) else: continue result1['even'] = even result1['odd'] = odd return result1 print search_num(str)
501275ca7933a25249bda2278eca0be3fefb59ea
WiktorSa/Operating-Systems
/OS4/algorithms/equal_algorithm.py
1,895
3.609375
4
import math from algorithms.algorithm import Algorithm class EqualAlgorithm(Algorithm): def perform_simulation(self, processes: list): original_no_of_frames = self.divide_frames_at_start(processes) for i in range(len(processes)): processes[i].lru.set_original_number_of_frames(original_no_of_frames[i]) no_page_errors = 0 # Perform simulation until all processes are finished no_finished_processes = 0 while no_finished_processes < len(processes): # Doing one iteration of lru algorithm for every process for i in range(len(processes)): if processes[i].state == 'Active': no_page_errors += processes[i].use_lru() # The process has finished if processes[i].state == 'Finished': no_finished_processes += 1 print("Equal algorithm - number of page errors: ", no_page_errors) print("Number of page errors for every process: ") for i in range(len(processes)): print("Process number: {no} - {no_page_errors}".format(no=i+1, no_page_errors=processes[i].no_page_errors)) self.no_page_errors_process[i] += processes[i].no_page_errors self.overall_no_page_errors += no_page_errors # This algorithm will divide frames for every process equally def divide_frames_at_start(self, processes: list): # Distributing frames for every process average_no_frames_per_process = math.floor(self.no_frames / len(processes)) no_frames_per_process = [average_no_frames_per_process] * len(processes) # Assigning leftover frames left_frames = self.no_frames - average_no_frames_per_process * len(processes) for i in range(left_frames): no_frames_per_process[i] += 1 return no_frames_per_process
ceaf75e59c51a4374dc12cc8adee3c3f663449a7
skiranu/Python_
/Interface_Abstract_Concrete_class.py
548
3.96875
4
from abc import * #interface class Vehicle(ABC): @abstractmethod def noOfWheels(self): pass def noOfDoors(self): pass def noOfExhaust(self): pass #abstract class class Bus(Vehicle): def noOfWheels(self): return 7 def noOfDoors(self): return 2 #concrete class class Completebus(Bus): def noOfExhaust(self): return 2 #object creation and calling a=Completebus() print(a.noOfWheels()) print(a.noOfDoors()) print(a.noOfExhaust())
2f66a3dbe7423cbee94f32ee46a12af9262ca8d9
skiranu/Python_
/unzipping_disp.py
288
3.796875
4
from zipfile import * f=ZipFile('zippedfiles.zip','r',ZIP_STORED) content=f.namelist() for eachfile in content: k=open(eachfile,'r') print(k.read()) print('the contents of {} are displayed above'.format(eachfile)) print('unzipping and displaying of files are accomplished!!')
7907ca619c61fadfc515d1081b96da4c274954cb
skiranu/Python_
/Alpha_Ascii_Sequence_2.py
330
3.953125
4
a=input("enter the string:") #Input declaration. s=k=d=s1=' ' #Variable for loop for x in a: # loop to check the type of input(either alphabet or digit) if x.isalpha(): s=x else: s1=x k=k+s+chr(ord(s)+int(s1)) d=d+k print(d)
688be646bf564663c8cf00b9dac769a45d2e30fb
skiranu/Python_
/Dict_Char_Count.py
190
3.765625
4
a=input("Enter the string:") b={} for x in a: b[x]=b.get(x,0)+1 print(b) #dictionary form for k,v in sorted(b.items()): print("The number of occurances of : ",k,"is:",v)
bcab985c6af25defb7fa3bb752d2c8989f89466b
ardnahcivar/Python
/Learning python/LarryArray.py
544
3.546875
4
if __name__ == "__main__": t = int(input()) for i in range(t): inversion_count = 0 n = int(input()) a = [int(i) for i in input().split()] #print(a) b = sorted(a) # print('sorted list is:', b) for i, j in enumerate(a): b = a[i+1:] for k in b: if k < j: inversion_count = inversion_count+1 #print(inversion_count) if(inversion_count%2 ==0): print('YES') else: print('NO')
8e304fd05a53a20ad9bc8576c4eb8b9dc85f73c2
fly8764/LeetCode
/Tree/437 pathSum.py
2,411
3.890625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 题目说明,路径不一定包含根节点和叶子节点,所有,要遍历所有的可能 # 每个节点都可能 在或者不在路径中 # 单递归:从根节点遍历到每个节点时,从该节点往根节点遍历,必须包含该节点连续 # 路径中,其和满足要求的有多少条 # 双递归,包含该节点和不包含该节点,不包含该节点 又分为 左子树 右子树两种 # 其中用到的递归非常好,从符合要求的节点 返回的过程中,把所有的可能结果累加 class Solution(object): def pathSum(self, root, target): # 双递归 if not root: return 0 def dfs(root,target): if not root: return 0 cnt = 0 if root.val == target: cnt += 1 #这种递归循环非常好,从符合要求的节点往上返回,如果只有一种路径,则出栈到最后,结果为1 #在出栈的过程中,增量来自于 另外一个节点(eg右节点)的可能路径,最后得到所有的路径数 cnt += dfs(root.left,target - root.val) cnt += dfs(root.right,target - root.val) return cnt # 这种return 就分为必须包含 根节点 和不包含根节点 两类 return dfs(root,target)+ self.pathSum(root.left,target)+ self.pathSum(root.right,target) # def pathSum(self, root, target): # #单递归 # """ # :type root: TreeNode # :type sum: int # :rtype: int # """ # self.cnt = 0 #这里为什么非得要加个self # path = [] #这里的path就不要加 # def dfs(root): # if not root: # return 0 # path.append(root.val) # tmp = 0 # #这里要算到根节点,因为 可能出现中间几项和为0 # for i in range(len(path)-1,-1,-1): # tmp += path[i] # if tmp == target: # self.cnt += 1 # dfs(root.left) # dfs(root.right) # # 别忘了把加入的这个节点 pop() # path.pop() # dfs(root) # # return self.cnt
67c0a68629883bbbc5b2ebe32f5ffb832e458008
fly8764/LeetCode
/DP/121 maxProfit.py
2,308
4.09375
4
''' 思路: 方法一: 方法二:动态的选取 当前的最大收益 和当前的最小价格(为后面的服务) 当前最大收益 等于 max(当前收益,当前价格与之前最小价格差) 这个当前最大收益和当前最小价格 分别使用一个变量保存当前情况即可, 不需要保存之前的情况,保存了也用不到 ''' #second class Solution: def maxProfit(self, prices): size = len(prices) if size < 2:return 0 profit = 0 # min_price = float('-inf') #用负数来表示 # for i in range(size): # profit = max(profit,prices[i] + min_price) # min_price = max(min_price,-prices[i]) #绝对值最小 # return profit min_price = float('inf') # 用整数来表示 for i in range(size): profit = max(profit,prices[i] - min_price) min_price = min(min_price,prices[i]) return profit # def maxProfit(self, prices): # size = len(prices) # if size < 2:return 0 # dp = [0]*size # #dp[i]:代表到prices[i]为止的最大收益 # for i in range(1,size): # #这种方式里面的max() 和min()在数据量大时,容易超时 # #最小价格使用一个变量保存,实时更新即可,使用一个数组保存,查询时耗时 # dp[i] = max(max(dp[i-1]),prices[i]- min(prices[:i])) # return dp[-1] if __name__ == '__main__': so = Solution() print(so.maxProfit([7,1,5,3,6,4])) print(so.maxProfit([7,6,4,3,1])) # class Solution: # def maxProfit(self, prices): # length = len(prices) # # dp_0 = 0 # dp_1 = -999999 # # for i in range(length): # dp_0 = max(dp_0,dp_1 + prices[i]) # dp_1 = max(dp_1,-prices[i]) # return dp_0 # # # def maxProfit1(self, prices): # length = len(prices) # # min_p = 99999 # profit = 0 # # for i in range(length): # if prices[i]< min_p: # min_p = prices[i] # elif prices[i]-min_p > profit: # profit = prices[i] - min_p # return profit # # # if __name__ == '__main__': # so = Solution() # res = so.maxProfit([7,1,5,3,6,4]) # print(res) #
5f94c757a6e5feee5379278fa951e69e1fbc48a4
fly8764/LeetCode
/Tree/404 sumOfLeftLeaves.py
1,160
3.859375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def __init__(self): self.ret = 0 def dfs(self,root): if not root: return if root.left and not root.left.left and not root.left.right: self.ret += root.left.val self.dfs(root.left) self.dfs(root.right) def sumOfLeftLeaves(self, root): self.dfs(root) return self.ret # def sumOfLeftLeaves(self, root): # if not root: # return 0 # # ret = 0 # parent= [[root.left,root.right]] # while parent: # cur = [] # for node in parent: # left,right = node[0],node[1] # if left and (not left.left and not left.right): # ret += left.val # # if left: # cur.append([left.left,left.right]) # if right: # cur.append([right.left, right.right]) # parent = cur[:] # return ret
628bc364f43090ac70474469d2e708ffa27b02d8
fly8764/LeetCode
/Tree/104 maxDepth.py
683
3.90625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution1(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 return 1+max(self.maxDepth(root.left),self.maxDepth(root.right)) ''' 2020/12/8 1:19 深度优先搜索 递归 ''' class Solution: def maxDepth(self, root): if not root: return 0 depth_l = self.maxDepth(root.left) depth_r = self.maxDepth(root.right) return max(depth_l,depth_r) + 1
9ba3bdd359faaa10341fdd3d8eb98f5b09022945
fly8764/LeetCode
/Linked/61 rotateRight.py
2,050
3.75
4
# Definition for singly-linked list. ''' 注意点: 1. 空节点 2.k值的大小,k一般在长度范围内cnt, 如果大于长度范围cnt,要把k对cnt取余,使其在cnt范围内 取余要注意cnt = 1的特殊情况,取余无效,其实这时候就不用再算了, 长度为1的链表,怎么旋转都不会变化 3.cnt = 1,这个一上来要想到,不然后面就可能忘了 方法一:找到链表的长度,把后面k个节点一整串的拼接到开头 方法二:双指针法,也是先找到链表长度,再把后面k个节点使用双指针法 一个一个地 调换到前面 ''' class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def rotateRight1(self, head, k): #双指针法 pass def rotateRight(self, head, k): if k == 0 or not head: return head dummy = ListNode(0) cnt = 0 dummy.next = head pre = dummy while pre.next: pre = pre.next cnt += 1 if cnt == 1: return head #标记尾巴节点 end = pre #k作为除数,要注意k=0的情况, # if k > cnt: # temp = k//cnt # k = k - cnt*temp # if k == 0: # return head # k = 1时,无效 k %= cnt if k == 0: return head #找到倒数第k+1个节点,next置为空None,执行cnt - k次操作 node = dummy for _ in range(cnt -k): node= node.next new_start = node.next node.next = None end.next = dummy.next dummy.next = new_start return dummy.next if __name__ == '__main__': so = Solution() a = ListNode(1) start = a # for i in range(2,6): # a.next = ListNode(i) # a = a.next # while start: # print(start.val) # start = start.next res = so.rotateRight(start,k = 12) while res: print(res.val) res = res.next
62538b8fd6f4befdbe1fbd8635f6ed884eb50716
fly8764/LeetCode
/Tree/257 binaryTreePaths.py
1,189
3.578125
4
class Solution(object): def binaryTreePaths(self, root): if not root: return [] if not root.left and not root.right: return [str(root.val)] left, right = [], [] if root.left: left = [str(root.val) + '->' + x for x in self.binaryTreePaths(root.left)] if root.right: right = [str(root.val) + '->' + x for x in self.binaryTreePaths(root.right)] return left + right # def binaryTreePaths(self, root): # """ # :type root: TreeNode # :rtype: List[str] # """ # if not root.left and not root.right: # return [str(root.val)] # left,right = [],[] # # if not root.left: # for x in self.binaryTreePaths(root.left): # left += [str(root.val)+ '->'+ str(x)] # for x in self.binaryTreePaths(root.right): # right += [str(root.val) + '->'+str(x)] # # # left = [str(root.val) + '->'+str(x) for x in self.binaryTreePaths(root.left)] # # right = [str(root.val) + '->'+str(x) for x in self.binaryTreePaths(root.right)] # return left + right
5def0d595f79218e4cb62f249a1fa1a56dc4668d
fly8764/LeetCode
/Bit Manipulation/342 isPowerOfFour.py
877
3.640625
4
class Solution: def isPowerOfFour(self, n): #1.4的幂 最高位的1 都在奇数位上,所以判断最高位的1是否在奇数位, #2.或者奇数位只有一个1 #1.0x5 0101 &(0100)(4)== 0100(num) 判断奇数位上的1 #2.16进制 a:1010 都在偶数位上,(0100)(4)&(1010)(a)== 0 表示在奇数位上 #0xaaaaaaaa&n == 0 # return n > 0 and not n&(n-1) and n&(0x55555555) == n return n > 0 and not n&(n-1) and n&(0xaaaaaaaa) == 0 def isPowerOfFour0(self, n): #4的幂 是1 左移 2n位的结果, if n & (n-1): return False temp = 1 while temp < n: temp <<= 2 if temp == n: return True else: return False if __name__ == "__main__": so = Solution() res = so.isPowerOfFour(16) print(res)
19af6699431a5b3892d415b2941aa893a8c1bdea
fly8764/LeetCode
/Linked/92 reverseBetween.py
7,775
4.15625
4
# Definition for singly-linked list. ''' 方法一:递归法 问题:反转前N个节点 第N+1个节点,successor节点 递归解决,当N=1时,记录successor节点,successor = head.next 和全部反转不同,最后一个节点的next要指向 successor;head.next = successor 问题:反转第m到第n个节点 递归 一直到m= 1,则此时相当于反转前N个节点, 然后把之前的节点拼接起来 这里的递归返回的节点不像 全部反转或反转前N个节点, 这里返回的是正常的节点,相当于才重新拼接一下 方法二:双指针法 in-place 找到第m-1个节点pre,和第m个节点cur 从左往后遍历的过程中,更新 cur.next,pre.next,使得这两个节点反转, 并更新这两个节点,cur.next = temp.next在刚开始更新,pre.next = temp在最后更新 方法三:三指针法 类似于下面的双指针法,只不过这里把tail单独拎出来,并更新, 下面的双指针法,tail每次需要时生成, ''' class ListNode: def __init__(self, x): self.val = x self.next = None class Solution1: def __init__(self): self.successor = None def reverseBetween1(self, head, m, n): # 这种方法没有在开头插入一个哑节点,所以当遇到m = 1时, # 没有前面的头指针,即哑节点来拼接后面的反转链表 if m >= n or not head: return head start = head idx = 1 while idx < m-1: #先不直接到达第m个节点,因为后面要通过next把后面的拼接起来 head = head.next idx += 1 #找到第n+1个节点,最后把其节点反转好的链表后面 new = head new_idx = idx while new_idx <n+1: new = new.next new_idx += 1 #为了保存head,后面要通过head.next把反转后的链表接上去 node = head.next idx += 1 pre_node =None p = ListNode(0) while idx < n+1: idx += 1 p = ListNode(node.val) p.next = pre_node pre_node = p node = node.next head.next = p while head.next: head = head.next head.next = new return start def reverseBetween2(self, head, m, n): if m >= n or not head: return head start = ListNode(0) start.next = head p = start idx = 0 while idx < m-1: #先不直接到达第m个节点,因为后面要通过next把后面的拼接起来 p = p.next idx += 1 #找到第n+1个节点,最后把其接在反转好的链表后面 new = p new_idx = idx while new_idx <n+1: new = new.next new_idx += 1 #为了保存head,后面要通过head.next把反转后的链表接后面 #node 第m个节点 node = p.next idx += 1 pre_node =None point = ListNode(0) while idx < n+1: point = ListNode(node.val) point.next = pre_node pre_node = point node = node.next idx += 1 p.next = point while p.next: p = p.next p.next = new return start.next def reverseBetween3(self, head, m, n): #三指针法 哑光节点为m= 1考虑的 in-place 在原链表上改变 #类似于下面的双指针法,只不过这里把tail单独拎出来,并更新, #下面的双指针法,tail每次需要时生成, dummy = ListNode(0) dummy.next = head pre = dummy #找到要反转的起始点的上一个节点,即第m-1个节点 for _ in range(m-1): pre = pre.next #使用三指针pre,start,tail #cnt个节点,往前调换cnt-1次即可 start = pre.next tail = start.next #tail紧接在start后面 for _ in range(n-m): start.next = tail.next tail.next = pre.next pre.next = tail tail = start.next return dummy.next def reverseBetween4(self, head, m, n): #双指针法、哑节点 非常好 in-place 相比于三指针法 更简洁一些 dummy = ListNode(0) dummy.next = head pre = dummy #pre始终是第m-1个节点 for _ in range(m-1): pre = pre.next cur = pre.next #这里的循环,cur不改变 for _ in range(n-m): temp = cur.next cur.next = temp.next # 下面只能用 pre.next,不能用cur,cur只在刚开始可以,后面就不行了,pre.next最准。 temp.next = pre.next pre.next = temp return dummy.next def reverseList(self, node): if not node: return node if not node.next: return node last = self.reverseList(node.next) node.next.next = node node.next = None return last def reverseN(self,head,n): if not head: return head if n == 1: self.successor = head.next return head last = self.reverseN(head.next,n-1) head.next.next = head head.next = self.successor return last def reverseBetween(self, head, m, n): # 递归法 if m == 1: return self.reverseN(head,n) head.next = self.reverseBetween(head.next,m-1,n-1) return head ''' 2020/12/13 16:40 第二次做,一上来就去找交界处左右两边的点,一共四个点,然后把m-n的节点反转,最后再重新连接到原链表上。 起始只要找到第m-1个节点即可,然后 in-place的方式直接在原链表上进行修改,比较间接。 注意:反转链表时注意细节, cur = pre.next for _ in (n-m): tmp = cur.next cur.next = tmp.next # 下面只能用 pre.next,不能用cur,cur只在刚开始可以,后面就不行了,pre.next最准。 tmp.next = pre.next pre.next = tmp ''' class Solution: # 常规做法 def reverseBetween1(self, head, m, n): if not head or not head.next: return head dummy = ListNode(-1) dummy.next = head left,right = head,head first = dummy tail = head.next l,r = 1,1 while r < n: r += 1 right = right.next tail = tail.next while l < m: l += 1 left = left.next first = first.next s,e = m,n pre = None mnode = None mflag = True while s <= e: s += 1 node = ListNode(left.val) if mflag: mnode = node mflag = False node.next = pre pre = node left = left.next first.next = pre mnode.next = tail return dummy.next # 简便一些 def reverseBetween(self, head, m, n): if not head or not head.next: return head dummy = ListNode(-1) dummy.next = head pre = dummy for _ in range(m-1): pre = pre.next cur = pre.next for _ in (n-m): tmp = cur.next cur.next = tmp.next tmp.next = pre.next pre.next = tmp return dummy.next if __name__ == '__main__': so = Solution() a = ListNode(3) a.next = ListNode(5) m= 1 n = 2 res = so.reverseBetween(a,m,n) while res: print(res.val) res = res.next
4d6575ccd0f71b77f94f037547af970f1d1a4ce4
fly8764/LeetCode
/sort/386 lexicalOrder.py
895
3.515625
4
class Solution: # def __init__(self): # self.res = [] # # def find(self,m,n): # if m > n: # return # self.res.append(m) # # t = m*10 # for i in range(10): # self.find(t+i,n) # # def lexicalOrder(self, n): # res = [] # for i in range(1,10): # self.find(i,n) # return self.res def __init__(self): self.res = [] self.n = 0 def dfs(self,temp): for i in range(10): ans = temp*10 + i if ans <= self.n: if ans > 0: self.res.append(ans) self.dfs(ans) else:return def lexicalOrder(self, n): self.n = n self.dfs(0) return self.res if __name__ == '__main__': so = Solution() res = so.lexicalOrder(13) print(res)
443f43d8573c1f93becc0c91150fcc81f5a82634
fly8764/LeetCode
/sort/insert_sort.py
9,983
3.5625
4
class Solution1: def __init__(self): self.size = 0 def insetSort(self,nums): #T(n) = n**2 #从前往后遍历 size = len(nums) if size < 2: return nums for i in range(1,size): j = i-1 temp = nums[i] #扫描,从后往前扫描 while j > -1 and nums[j] > temp: nums[j+1] = nums[j] #较大值往后挪 j -= 1 nums[j+1] = temp return nums def shellSort(self,nums): #T(n) = n*logn # 实际遍历时,不是 在一定间隔下,把一个子序列简单插入排序后,再对下一个子序列排序 # 而是 把所有的从前(nums[d])到后逐元素的进行,排序时找到前面间隔d的元素比较 # 一种子序列拍完了 size = len(nums) if size < 2: return nums d = size//2 while d > 0: for i in range(d,size): temp = nums[i] j = i - d while j > -1 and nums[j] > temp: #这里注意 nums[j] > temp而不是 nums[j]> nums[j+d](下面第一行会更行nums[j+d]) nums[j+d] = nums[j] j -= d nums[j+d] = temp d //= 2 return nums def bubbleSort(self,nums): #T(n) = n**2 size = len(nums) if size < 2:return nums for i in range(1,size): for j in range(i-1,-1,-1): if nums[j] > nums[j+1]: temp = nums[j+1] nums[j+1] = nums[j] nums[j] = temp return nums # def quickSort(self,nums): #递归 #方法一:开辟新的数组 # size = len(nums) # if size < 2:return nums # temp = nums[0] # left_sub = [] # right_sub = [] # # for i in range(1,size): # if nums[i] < temp: # left_sub.append(nums[i]) # else: # right_sub.append(nums[i]) # left = self.quickSort(left_sub) # right = self.quickSort(right_sub) # return left+[temp] + right # def quickSort(self,nums,s,t): #这里理解错了, #实际上,每次swap 都是在调整 pivot的位置,当左右指针相等时,pivot的位置也调整好了, #不用在最后再次调整 开头与i的位置元素,即 nums[left] = temp # left = s # right = t # if s < t: # temp = nums[s] # while left < right: #从两边往中间扫描,直到left == right # while right > left and nums[right] > temp: # right -= 1 # if left < right: #看是上面哪个条件跳出来的 # 先不管 nums[left]的大小如何,先交换到右边的nums[right]再说,到那边再比较 # tmp = nums[left] # nums[left] = nums[right] # nums[right] = tmp # left += 1 # while left < right and nums[left] < temp: # left += 1 # if left < right:#先不管 nums[right]的大小如何,先交换到左边的nums[left]再说,到那边再比较 # tmp = nums[right] # nums[right] = nums[left] # nums[left] = tmp # right -= 1 # nums[left] = temp #这一步不需要 # self.quickSort(nums,s,left-1) # self.quickSort(nums,left+1,t) def swap(self,nums,i,j): temp = nums[i] nums[i] = nums[j] nums[j] = temp def partition(self,nums,s,t): #从左往右逐个扫描,而不是像上面那个解法,左右两边同时向中间扫描,直到相等 #这种方法 每次需要调整位置时,都要交换一次位置,操作数比较多 pivot = s index = pivot + 1 temp = nums[pivot] for i in range(pivot+1,t+1): if nums[i] < temp: self.swap(nums,i,index) index += 1 self.swap(nums,pivot,index-1) return index - 1 def quickSort(self,nums,s,t): if s == t:return nums elif s < t: # 不要把partition写在里面,不然变量的作用范围容易受到影响; # 最好写在外面 pivot = self.partition(nums, s, t) self.quickSort(nums, s, pivot - 1) self.quickSort(nums, pivot + 1, t) def selectSort(self,nums): #类似于冒泡排序,只不过,是在找到未排列 列表中的最小元素与 表头元素交换 size = len(nums) def mergeSort(self,nums): #递归,从上到下 递归,从下到上返回; #递归题目:先假设 递归函数存在,拿过来直接用;然后,考虑如何处理边界情况 size = len(nums) if size < 2:return nums mid = size//2 left = nums[:mid] right = nums[mid:] return self.merge(self.mergeSort(left),self.mergeSort(right)) def merge(self,left,right): res = [] while left and right: if left[0] < right[0]: res.append(left.pop(0)) else: res.append(right.pop(0)) while left: res.append(left.pop(0)) while right: res.append(right.pop(0)) return res def buildMaxheap(self,nums): #这里从size//2开始往前遍历有两个好处 #1.类似于从完全二叉树的倒数第二层开始调整堆,2*i+1 2*i+2分别对应 节点i的左右子节点 #2.从后往前,从下往上,一层一层地“筛选”,保证最大的元素在堆顶。类似于冒泡 self.size = len(nums) for i in range(self.size//2,-1,-1): self.heapify(nums,i) def heapify(self,nums,i): left = 2*i + 1 right = 2*i + 2 largest = i if left < self.size and nums[left] > nums[largest]: largest = left if right < self.size and nums[right] > nums[largest]: largest = right if largest != i: #继续递归,使得上面调整后,下面的堆 仍然符合最大/小 堆的要求 self.swap(nums, i, largest) self.heapify(nums, largest) def heapSort(self,nums): #最大堆排序 self.bubbleSort(nums) for i in range(self.size-1,0,-1): #把堆顶元素放到后面,最小元素放在堆顶,后面再重新调整堆;同时为处理的列表长度减1 self.swap(nums,0,i) self.size -= 1 #从堆顶开始重新调整堆,原先的堆整体往上升了一层 self.heapify(nums,0) return nums def buildMinheap(self,nums): self.size = len(nums) for i in range(self.size//2,-1,-1): self.heapifyMin(nums,i) def heapifyMin(self,nums,i): left = 2*i + 1 right = 2*i + 2 least = i if left < self.size and nums[left] < nums[least]: least = left if right < self.size and nums[right] < nums[least]:least = right if least != i: self.swap(nums,i,least) self.heapifyMin(nums,least) def heapSortMin(self,nums): #T(n) = (n/2)logn + nlogn #要保证 不改变 完全二叉树的 结构,因为在调整堆时,有 left = 2*i + 1 等的存在,要用到堆的结构 #因此,最小堆排序只能 额外申请一个数组,每次保存 堆顶的最小值, #之后把右小角的值 交换到 堆顶,删除末尾元素,修改堆的长度,再次调整堆 res = [] self.buildMinheap(nums) for i in range(self.size): res.append(nums[0]) #把最大元素放到堆顶,之后删掉最后一个元素,修改堆的长度 self.swap(nums,0,self.size-1) nums.pop() self.size -= 1 self.heapifyMin(nums,0) return res def radixSort(self,nums): maxx = max(nums) bit = 0 while maxx: bit += 1 maxx //= 10 mod = 10 dev = 1 for i in range(bit): temp = {} for j in range(len(nums)): bucket = nums[j]%mod//dev if bucket not in temp: temp[bucket] = [] temp[bucket].append(nums[j]) cur = [] for idx in range(10): if idx in temp: cur.extend(temp[idx]) nums = cur[:] mod *= 10 dev *= 10 return nums class Solution: def quickSort(self,nums,s,t): if s >=t: return # 这里需要额外的变量保存边界索引, l,r = s,t temp = nums[l] while l < r: while r > l and nums[r] > temp: r -= 1 if r > l: nums[l] = nums[r] l += 1 while l < r and nums[l] < temp: l += 1 if l < r: nums[r] = nums[l] r -= 1 nums[l] = temp self.quickSort(nums,s,l-1) self.quickSort(nums,l+1,t) def heapSort(self,nums): pass if __name__ == '__main__': so = Solution() nums = [4,1,5,3,8,10,28,2] print(nums,'raw') print(sorted(nums),'gt') # res = so.insetSort(nums[:]) # print(res) # res2 = so.shellSort(nums[:]) # print(res2) # res3 = so.bubbleSort(nums[:]) # print(res3,'bubbleSort') so.quickSort(nums,0,len(nums)-1) print(nums) # res = so.mergeSort(nums) # print(res) res = so.heapSort(nums[:]) print(res) # res = so.heapSortMin(nums[:]) # print(res) # res = so.radixSort(nums[:]) # print(res)
c2d2c20ed5eab1db361735ead1d82573231ccdf5
fly8764/LeetCode
/Tree/429 levelOrderN.py
1,255
3.625
4
""" # Definition for a Node. class Node: def __init__(self, val, children): self.val = val self.children = children """ class Solution1: def levelOrder(self, root): if not root: return [] res = [] parent = [root] while parent: child = [] cur = [] for _ in range(len(parent)): node = parent.pop(0) cur.append(node.val) if node.children: child.extend(node.children) res.append(cur) parent = child[:] return res ''' 2020/12/7 22:40 node.children是个列表,需要注意 ''' class Solution: def levelOrder(self, root): if not root: return [] res = [] parent = [root] while parent: children = [] tmp_res = [] # 有两种遍历方式 for node in parent: # for _ in range(len(parent)): # node = parent.pop(0) tmp_res.append(node.val) if node.children: children.extend(node.children[:]) res.append(tmp_res) parent = children[:] return res
911f7a55fcbe555fab00846892307a841e906bc5
fly8764/LeetCode
/Linked/328 oddEvenList.py
1,088
3.78125
4
# Definition for singly-linked list. ''' 大致思路: 把奇偶位置的节点分开,各自串接自己一类的节点,最后在拼接起来 使用双指针,一个是奇数节点,一个是偶数节点 在开头别忘了使用一个临时节点,保存第一个偶数节点,后面把其拼接在奇数尾节点的后面 ''' class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def oddEvenList(self, head): if not head or not head.next: return head odd = head even = head.next temp = head.next #while循环里面的三个条件,有顺序要求 #首先判断even,其来自于head.next,有可能为空 #even不为空,则可以判断 even.next #odd = head,在开头已经判断了,不为空,可以直接判断odd.next while even and even.next and odd.next: odd.next = even.next odd = odd.next even.next = odd.next even = even.next odd.next = temp return head
22a46ad25d160525a0137a0ef1833d2845b89aff
AmrEsam0/HackerRank
/python3/2d_Array_DS.py
709
3.609375
4
#!/bin/python3 def list_sum(l): total = 0 for i in range(len(l)): total = total + l[i] return total def hourglassSum(arr): max = -1000 s= [] sub_array = [] for m in range(4): for col in range(4): for row in range(3): sub_array.append(arr[row + m][col: col + 3]) s = sub_array hour_sum = list_sum(s[0]) + s[1][1] + list_sum(s[2]) if (max < hour_sum): max = hour_sum sub_array = [] return max if __name__ == '__main__': arr = [list(map(int, input().split())) for y in range(6)] print(hourglassSum(arr))
e3fc26f817596ff52cf7a97933ea0c192c5cef42
dsintsov/python
/labs/lab1/lab1-1_7.py
989
4.125
4
# № 7: В переменную Y ввести номер года. Определить, является ли год високосным. """ wiki: год, номер которого кратен 400, — високосный; остальные годы, номер которых кратен 100, — невисокосные (например, годы 1700, 1800, 1900, 2100, 2200, 2300); остальные годы, номер которых кратен 4, — високосные """ # Checking the user input while True: Y = input("Enter a year: ") try: if int(Y) > 0: break # input is INT and greater than 0 else: raise TypeError() # just call an exception except: print("ERR: \"{0}\" - it\'s NOT a valid year number, try again!".format(str(Y))) Y = int(Y) print(str(Y), end='') if Y % 400 == 0 or Y % 4 == 0 and Y % 100 != 0: print(" - is a leap year") else: print(" - isn't a leap year") exit(0)
0d6c52bea723ecd9bd447f2b0962b4fb2f8876c5
Kenjal1992/Kenjal_Python
/Assignment_6.py
365
3.9375
4
def CheckNumber(no): if no>0: print("{} is Positive Number".format(no)) elif no<0: print("{} is Negative Number".format(no)) else: print("{} is Zero".format(no)) def main(): print("Enter the number:") n=int(input()) CheckNumber(n) if __name__=="__main__": main()
61108fc4bf8d95401c043bf945d49567192ed9f3
Kenjal1992/Kenjal_Python
/Assignment_7.py
216
3.765625
4
def Printstar(no): for i in range (0,no): print("*") def main(): print("Enter the number:") n=int(input()) Printstar(n) if __name__=="__main__": main()
c608249eb220babe22952f716e4c378ec3501ea4
jjalomo93/Python-Analysis
/PyRamen/main.py
5,151
3.921875
4
#!/usr/bin/env python # coding: utf-8 # In[1]: # import libraries from pathlib import Path import csv # In[2]: # Read in `menu_data.csv` and set its contents to a separate list object. # (This way, you can cross-reference your menu data with your sales data as you read in your sales data in the coming steps.) # set the file path for menu_csv menu_path = Path("Resources/menu_data.csv") # In[3]: # Initialize an empty `menu` list object to hold the contents of `menu_data.csv`. menu = [] # In[4]: # Use a `with` statement and open the `menu_data.csv` by using its file path. with open(menu_path, "r") as csvfile: # Use the `reader` function from the `csv` library to begin reading `menu_data.csv`. menu_reader = csv.reader(csvfile, delimiter=",") # Use the `next` function to skip the header (first row of the CSV). menu_header = next(menu_reader) # Loop over the rest of the rows and append every row to the `menu` list object (the outcome will be a list of lists). for row in menu_reader: # add items to the menu list menu.append(row) # In[5]: # Set up the same process to read in `sales_data.csv`. However, instead append every row of the sales data to a new `sales` list object # set the file path for sales_data sales_path = Path("Resources/sales_data.csv") # In[6]: # Initialize an empty 'sales' list object to hold the contents of 'sales_data.csv' sales = [] # In[7]: # Use a `with` statement and open the `sales_data.csv` by using its file path. with open(sales_path, "r") as csvfile: # Use the `reader` function from the `csv` library to begin reading `menu_data.csv`. sales_reader = csv.reader(csvfile, delimiter=",") # Use the `next` function to skip the header (first row of the CSV). sales_header = next(sales_reader) # Loop over the rest of the rows and append every row to the `menu` list object (the outcome will be a list of lists). for row in sales_reader: # add items to the menu list sales.append(row) # In[8]: # Initialize an empty `report` dictionary to hold the future aggregated per-product results. # The `report` dictionary will eventually contain the following metrics: # * `01-count`: the total quantity for each ramen type # * `02-revenue`: the total revenue for each ramen type # * `03-cogs`: the total cost of goods sold for each ramen type # * `04-profit`: the total profit for each ramen type report = {} # In[9]: # Then, loop through every row in the `sales` list object. for sales_data in sales: # For each row of the `sales` data, set the following columns of the sales data to their own variables: # * Quantity # * Menu_Item quantity = int(sales_data[3]) menu_item = sales_data[4] # define variable for the record record = {"01-count": 0, "02-revenue": 0, "03-cogs": 0, "04-profit": 0,} # Perform a quick check if the `sales_item` is already included in the `report`. if menu_item not in report: # If not, initialize the key-value pairs for the particular `sales_item` in the report. # Then, set the `sales_item` as a new key to the `report` dictionary and the values as a nested dictionary containing the record report[menu_item] = record # set the elif to add the "quantity" data to the count if menu_item in report: report[menu_item]["01-count"] += quantity # In[11]: # Create a nested loop by looping through every record in 'menu' for sales_data in sales: # set the values to compare against menu data quantity = int(sales_data[3]) menu_item = sales_data[4] for menu_data in menu: # For each row of the `menu` data, set the following columns of the menu data to their own variables: item = menu_data[0] price = float(menu_data[3]) # float because there are decimals in price data cost = int(menu_data[4]) # If the `sales_item` in sales is equal to the `item` in `menu` # capture the `quantity` from the sales data and the `price` and `cost` from the menu data to calculate the `profit` for each item. if menu_item == item: report[item]["02-revenue"] += (quantity * price) report[item]["03-cogs"] += (quantity * cost) # else: # print(f"{menu_item} does not equal {item}! NO MATCH!) # In[14]: # define and add the profit to the report (revenue - cogs) # use nested for loop to calculate at the individual level for menu_item, value_dict in report.items(): for key in value_dict: # define the revenue, cogs, and profit variables revenue = report[menu_item]["02-revenue"] cogs = report[menu_item]["03-cogs"] profit = (revenue - cogs) # set the profit based on the "04-profit" key value if key == "04-profit": report[menu_item][key] = profit # In[17]: # print(report) to check values # In[20]: # set the output path for the text file output_path = "pyramen_results.txt" # In[21]: # write the text file with open(output_path, "w") as file: for key in report: file.write(f"{key} {report[key]}\n")
663b7ccb52e70b73824fe5f431fdc48c4e1e649a
MKerbleski/Data-Structures
/linked_list/linked_list.py
2,989
3.75
4
""" Class that represents a single linked list node that holds a single value and a reference to the next node in the list """ class Node: def __init__(self, value=None, next_node=None): self.value = value self.next_node = next_node def get_value(self): return self.value def get_next(self): return self.next_node def set_next(self, new_next): self.next_node = new_next class LinkedList: def __init__(self): self.head = None self.tail = None def add_to_tail(self, value): new_node = Node(value) if self.head == None: self.head = new_node self.tail = new_node else: self.tail.set_next(new_node) # takes the current node 1 and points to new node self.tail = new_node # assigns the new node self.tail.set_next(None) pass def remove_head(self): # print("------------remove--------") if self.head == None: return None else: old = self.head.value nextt = self.head.get_next() if nextt == None: self.head = None self.tail = None return old else: self.head = nextt if old == None: return None else: return old pass def contains(self, value): # print("----------contains--------") if self.head == None: return False else: if self.head.value == value: return True else: x = self.head.get_next() while x != None: if x.value == value: return True else: x = x.get_next() return False pass def get_max(self): print("----------get_max--------") if self.head == None: return None else: global maxx maxx = 0 x = self.head while x!= None: if x.value > maxx: maxx = x.value else: x = x.get_next() return maxx pass # notes # def add_to_tail(self, value): # print(self.tail, '-- self.tail A') # print(self.head, '-- self.head A') # new_node = Node(value) # print(new_node.get_value(), '-- new_node value') # if self.head == None: # print('no head', new_node) # self.head = new_node # print(self.head, '-- self.head B') # print(self.head.value, '-- self.head C') # self.tail = new_node # print(self.tail.value, '-- self.tail.value B') # print(self.head.get_next(), '41') # else: # self.tail.set_next(new_node) # # takes the current node 1 and points to new node # self.tail = new_node # # assigns the new node # self.tail.set_next(None) # print(self.tail.value, '-- self.tail B') # print(self.tail.get_next(), '-- self.tail next B') # print(self.head.get_next().value, '46') # print(self.head.value, self.head.get_next(), self.head.get_next().get_next().value) # pass
b263615206c83b6d159fa7e138052a007b3940b9
billdonghp/Python
/variable.py
514
3.8125
4
''' 变量的作用域 ''' salary = 7000 def raiseSalary(salary): #salary形参 salary += salary * 0.08 raiseSalary(salary) print("raiseSalary加薪后:%d"%(salary)) def raiseSalaryII(salary): #通过返回值影响 salary += salary * 0.08 return salary salary = raiseSalaryII(salary) print("raiseSalaryII加薪后:%d"%(salary)) def raiseSalaryIII(): global salary #使用全局变量 salary += salary * 0.1 raiseSalaryIII() print("raiseSalaryIII加薪后:%d"%(salary))
24ef3ae3700fb03f7376673ee39067c362eee76a
billdonghp/Python
/stringDemo.py
877
4.25
4
''' 字符串操作符 + * 字符串的长度 len 比较字符串大小 字符串截取 [:] [0:] 判断有无子串 in not in 查找子串出现的位置 find() index() 不存在的话报错 encode,decode replace(old,new,count)、count(sub,start,end) isdigit()、startswith split、join '-'.join('我爱你中国') 隔位截取str1[::2] = str1[0:-1:2] start 和end不写时为全部;step=2 如果 step为负数时,倒序截取; ''' str1 = 'hello' a = 'a' b = 'b' def stringEncode(str): myBytes = str.encode(encoding='utf-8') return myBytes if __name__ == "__main__": print(len(str1)) print(a < b) print('中国' < '美国') #utf-8中 美比中大 print(str1[2:]) print(str1.upper()) sEncode = stringEncode('我爱你中国') print(sEncode.decode(encoding='utf-8')) print(str1.find('7')) print(str1[::-1]) pass
a38739c2fa2c242811821ac1232993c8abf52047
billdonghp/Python
/Person.py
787
3.890625
4
''' 封装人员信息 Person类 ''' class Person: #属性 name = "林阿华" age = 20 rmb = 50.0 #构造方法 外界创建类的实例时调用 #构选方法是初始化实例属性的最佳时机 def __init__(self,name,age,rmb): print("老子被创建了") self.name = name self.age = age self.rmb = rmb # def __str__(self): return "{name:%s,age:%d,rmb:%s}"%(self.name,self.age,format(self.rmb,".2f")) #方法或函数 #self 类的实例 #自我介绍方法 def tell(self): print("我是%s,我%d岁了,我有%s元"%(self.name,self.age,format(self.rmb,".2f"))) if __name__ =='__main__': p = Person("易中天",50,100000.0) p.tell() print(p)
79cae2d6bab2e3f3ae2bdd46882a0546c6f44b5e
izmailovpavel/gplib
/gplib/covfun/cov_base.py
2,322
3.5
4
import numpy as np from abc import ABCMeta, abstractmethod from .utility import pairwise_distance, stationary_cov class CovarianceFamily: """This is an abstract class, representing the concept of a family of covariance functions""" __metaclass__ = ABCMeta @abstractmethod def covariance_function(self, x, y, w=None): """ A covariance function :param x: vector :param y: vector :param w: hyper-parameters vector of the covariance functions' family :return: the covariance between the two vectors """ pass @staticmethod @abstractmethod def get_bounds(): """ :return: The bouns on the hyper-parameters """ pass @abstractmethod def set_params(self, params): """ A setter function for the hyper-parameters :param params: a vector of hyper-parameters :return: CovarianceFamily object """ pass @abstractmethod def get_params(self): """ A getter function for the hyper-parameters :param params: a vector of hyper-parameters :return: CovarianceFamily object """ pass @abstractmethod def get_derivative_function_list(self, params): """ :return: a list of functions, which produce the derivatives of the covariance matrix with respect to hyper-parameters except for the noise variance, when given to the covariance_matrix() function """ pass @abstractmethod def covariance_derivative(self, x, y): """derivative wrt x""" def get_noise_derivative(self, points_num): """ :return: the derivative of the covariance matrix w.r.t. to the noise variance. """ return 2 * self.get_params()[-1] * np.eye(points_num) def __call__(self, x, y, w=None): return self.covariance_function(x, y, w) class StationaryCovarianceFamily(CovarianceFamily): """This is an abstract class, representing the concept of a family of stationary covariance functions""" __metaclass__ = ABCMeta def covariance_function(self, x, y, w=None): return self.st_covariance_function(pairwise_distance(x, y), w) @abstractmethod def st_covariance_function(self, d, w=None): pass
fbf161851509a46fda44a240008bbe87d399d90b
pythonmentor/charles-p3
/maze.py
1,854
3.734375
4
#!/usr/bin/python3 # coding: utf-8 import pygame from pygame.locals import * from graphic_level import GraphicLevel from level import Level from inputs import inputs def screen_loop(picture): """ Welcome screen """ # Opening the Pygame window (660x600 corresponds # to a maze of 15x15 squares of 40x40 pixels + tools banner) fenetre = pygame.display.set_mode((660, 600)) # !!! quand je veux mettre cette ligne dans main(), ca ne marche pas ?!? screen = pygame.image.load("images/" + picture).convert_alpha() pygame.display.set_caption("OC python project n°3") stay = True while stay: pygame.time.Clock().tick(100) fenetre.blit(screen, (0, 0)) pygame.display.flip() if inputs() == "end": stay = False def game_loop(level_num): """ The game ! """ level_num.display() pygame.display.flip() stay = True while stay: move = inputs() if move in list((K_LEFT, K_UP, K_RIGHT, K_DOWN)): pos_current = level_num.mac_gyver.move(move) level_num.tools.pick_up(pos_current) stay = level_num.mac_gyver.fight(pos_current) level_num.display() pygame.display.flip() if stay == "win": screen_loop("free.png") stay = False elif stay == "defeat": screen_loop("defeat.png") stay = False elif move == "end": stay = False def main(): """ Main frame """ pygame.init() screen_loop("welcome_game.png") # Can choose a level and the console mode (Level) or graphic mode # (GraphicLevel) here game_level = GraphicLevel("level_1") # Setting up tools game_level.tools.put(game_level) game_loop(game_level) if __name__ == "__main__": main()
504efd209634a4f0c4b34995a7cdef6bc5dcdfe7
namle-gamer/DP_CS_Code
/Tools Files/toolsNL.py
2,832
3.96875
4
''' isEven takes a single integer paramenter a >= 0 returning True if a is even then return true otherwise turn false ''' def isEven(a): if a % 2 == 0: return True return False ''' missing_char will take a letter away from a word in a given position ''' def missing_char(str, n): newStr = "" #create an empty string newStr = str[0:n] + str[n + 1: len(str)] #create limit of print return newStr ''' sumDigits takes a single positive integer paramenter and returns the sum of the digits Parameters: i >= 0 return: returns sum of the digits precondition: i is a valid integer greater than 0 ''' def sumDigits(a): total = 0 #Casting is the change of type of variable a = str(a) #Looping through string #Count, check, change for i in range(0, len(a),1): print(a[i]) total = total + int(a[i]) return total #Trace Table: #a = "1234" # i | i < len(a)| # 0 | 0 < 4| T RUN LOOP | total = 0 + a[0] = 1 # 1 | 1 < 4| T RUN LOOP | total = 1 + a[1] = 3 # 2 | 2 < 4| T RUN LOOP | total = 3 + a[2] = 6 # 3 | 3 < 4| T RUN LOOP | total = 6 + a[3] = 10 # 4 | 4 < 4| F EXIT LOOP ''' Different approach of sumDigits ''' def sumDigitsA(a): total = 0 while (a > 0): total = total + a % 10 #access the ones digit a = a // 10 #cut down the ones digit from the number return total #Trace # a = 57 # a | a > 0 | # 57| 57 > 0 | TRUE RUN LOOP total = total + 57%10 = 7 # 5 | 5 > 0 | TRUE RUN LOOP total = total + 5%10 = 12 # 0 | 0 > 0 | FALSE EXIT LOOP ''' scaleElementsA takes an integer value a and a list reference b. This function should scale each elemnt of b''' def scaleElementA(int, b): for i in range(0,len(int)): int[i] = int[i]*b #Change value inside the array ''' scaleElementsB will create another list with the equal length of the previous array. For example if the list is [1,2,3,4] and the scale factor a = 2 then the returned array should be [2,4,6,8]''' def scaleElementB(int,b): array = [] for i in range(0,len(int)): int[i] = int[i]*b #Calculate new value array.append(int[i]) #Insert value into new array return array '''addStringsSmallLarge will take two strings as arguements. The function should return a new string consisting of the two strings combined with the largest string first. If the strings are of equal length it will return the first argument followed by the second argument''' def addStringsSmallLarge(string1,string2): string = ""#Empty string to combine 2 arguements later string1 = str(string1) string2 = str(string2) a = len(string1) b = len(string2) if a > b or a == b: string = string1 + " " + string2 elif a < b: string = string2 + " " + string1 return string
962f447a73ebaa7f9c501e2acaca7dc2a71d6a58
t0rx/friendly-schedule
/friendlyschedule/scheduleparser.py
8,088
3.59375
4
"""Class to parse a textual schedule into a usuable structure.""" from datetime import date, datetime, time, timedelta import re from typing import List from .schedule import Schedule from .scheduletypes import ScheduleEntry, ScheduleEvent class Invalid(Exception): """Raised when there is a parsing error.""" class ScheduleParser: """ Class providing facilities to parse schedule text. The class may be run in one of two modes: - Stateful (the default) allows schedules to specify on-off ranges or even specifically named states (e.g. 'cold', 'warm', 'hot') - Stateless means that the schedule consists purely of events and doesn't allow state transitions. In stateless mode, the schedule returned consists entirely of 'on' events. """ _day_map = {'Mon': 0, 'Tue': 1, 'Wed': 2, 'Thu': 3, 'Fri': 4, 'Sat': 5, 'Sun': 6} _weekday_pattern = re.compile(r'^(?P<start>\w+)\s*\-\s*(?P<finish>\w+)$') _time_pattern = re.compile(r'^\d?\d:\d\d$') _time_seconds_pattern = re.compile(r'^\d?\d:\d\d:\d\d$') _time_delta_pattern = re.compile( r'^((?P<hours>\d+)h)?((?P<mins>\d+)m)?((?P<secs>\d+)s)?$') def __init__(self, *, on_state: str = 'on', off_state: str = 'off', stateless: bool = False) \ -> None: """ Initialise the parser. Keyword arguments: on_state -- the string to use to represent on (default 'on') off_state -- the string to use to represent off (default 'off') stateless -- if False then do not allow event states """ self.on_state = on_state self.off_state = off_state self.stateless = stateless def parse_weekdays(self, text: str) -> List[int]: """ Parse a string of the form 'Mon-Wed,Fri' into a list of integers. Note that the integers correspond to the Python day numbers of those days, not ISO standard day numbers. """ parts = [p.strip() for p in text.split(',')] result = [] # type: List[int] for part in parts: match = self._weekday_pattern.match(part) if match: # Range start, finish = self.weekday(match.group( 'start')), self.weekday(match.group('finish')) result += [start] while start != finish: start = (start + 1) % 7 result += [start] else: # Singleton result += [self.weekday(part)] return result def weekday(self, text: str) -> int: """Convert a single day string into a Python day number.""" result = self._day_map.get(text) if result is None: raise Invalid('Bad weekday format: "{}"'.format(text)) return result def parse_time(self, text: str) -> time: """Parse a string of the form H:M or H:M:S into a time object.""" text = text.strip() if self._time_pattern.match(text): return datetime.strptime(text, '%H:%M').time() elif self._time_seconds_pattern.match(text): return datetime.strptime(text, '%H:%M:%S').time() else: raise Invalid('Bad time format: "{}"'.format(text)) def parse_time_delta(self, text: str) -> timedelta: """ Parse a string of the form XhYmZx into a timedelta object. All of the components of the string are optional, so you can do things like '2h1s' or '1m'. """ text = text.strip() match = self._time_delta_pattern.match(text) if match: hours = int(match.group('hours') or 0) mins = int(match.group('mins') or 0) secs = int(match.group('secs') or 0) return timedelta(hours=hours, minutes=mins, seconds=secs) else: raise Invalid('Bad time delta format: "{}"'.format(text)) def parse_time_schedule_part(self, text: str) -> List[ScheduleEvent]: """ Parse a time range string into a list of events. The string may be one of: - Simple time: 11:15[:30] (in stateless mode only this is supported) - On/off time range: 11:15-12:30 - On/off time range: 11:15+1h15m - Time and state: 11:15=idle """ if self.stateless: return [(self.parse_time(text), self.on_state)] if '-' in text: return self.parse_time_range(text) elif '+' in text: return self.parse_end_offset(text) elif '=' in text: return self.parse_explicit_state_change(text) # Assume single time only return [(self.parse_time(text), self.on_state)] def parse_time_range(self, text: str) -> List[ScheduleEvent]: """Parse a string of the form 11:00-12:30 into an on/off pair.""" bits = text.split('-') if len(bits) != 2: msg = 'Bad time range format: "{}"'.format(text) raise Invalid(msg) start, finish = bits start_time = self.parse_time(start) finish_time = self.parse_time(finish) if finish_time < start_time: msg = 'Finish time cannot be before start: "{}"'.format(text) raise Invalid(msg) return [(start_time, self.on_state), (finish_time, self.off_state)] def parse_end_offset(self, text: str) -> List[ScheduleEvent]: """Parse a string of the form 11:00+2h30m into an on/off pair.""" bits = text.split('+') if len(bits) != 2: msg = 'Bad time range format: "{}"'.format(text) raise Invalid(msg) start, delta = bits start_time = self.parse_time(start) time_delta = self.parse_time_delta(delta) # We can only apply a time delta to a datetime, not a time base_date = date(2000, 1, 1) start_datetime = datetime.combine(base_date, start_time) end_datetime = start_datetime + time_delta if end_datetime.date() != base_date: msg = ('Cannot currently have time range going past end ' + 'of day: "{}"').format(text) raise Invalid(msg) return [(start_time, self.on_state), (end_datetime.time(), self.off_state)] def parse_explicit_state_change(self, text: str) -> ScheduleEvent: """Parse a state change of the form 11:00=state.""" bits = text.split('=') if len(bits) != 2: msg = 'Bad state change format: "{}"'.format(text) raise Invalid(msg) time_str, state = bits return [(self.parse_time(time_str), state.strip())] def parse_time_schedule(self, text: str) -> List[ScheduleEvent]: """ Parse a string into a list of time events. Example: '10:00-11:15, 12:30-14:45' """ result = [] # type: List[ScheduleEvent] for part in text.split(','): result += self.parse_time_schedule_part(part) return result def parse_schedule_entry(self, text: str) -> ScheduleEntry: """ Parse a string into a ScheduleEntry structure. Example: 'Mon-Fri: 10:00-11:15, 12:30-14:45' """ bits = text.split(':') if len(bits) < 2: raise Invalid('Bad schedule format: "{}"'.format(text)) days = bits[0] times = ':'.join(bits[1:]) return (self.parse_weekdays(days), self.parse_time_schedule(times)) def parse_schedule_line(self, text: str) -> List[ScheduleEntry]: """ Parse a string separated with ';' into a list of ScheduleEntries. Example: 'Mon-Fri: 10:00-11:15; Sat: 09:00-12:15' """ return [self.parse_schedule_entry(p) for p in text.split(';')] def parse_schedule(self, text: str) -> Schedule: """ Parse a string separated with ';' into a Schedule object. Example: 'Mon-Fri: 10:00-11:15; Sat: 09:00-12:15' """ return Schedule(self.parse_schedule_line(text), text)
33f20b00560ce5050b419684c709bec347aba42e
tymefighter/AI
/gridMDP/gridMDP2.py
6,054
3.71875
4
import numpy as np import math """ 0: (r-1, c): up 1: (r+1, c): down 2: (r, c-1): left 3: (r, c+1): right """ def print_mat(a): for row in a: s = '' for x in row: s += ' ' + str(x) print(s) def print_grid(grid): for row in grid: s = '' for x in row: s += x print(s) def reward(grid, r, c, a): m = len(grid) n = len(grid[0]) if grid[r][c] == '#': return 0 if a == 0: # up if r-1 < 0 or grid[r-1][c] == '#': return -100 if grid[r-1][c] == 'g': return 100 elif a == 1: # down if r + 1 >= m or grid[r+1][c] == '#': return -100 if grid[r+1][c] == 'g': return 100 elif a == 2: # left if c - 1 < 0 or grid[r][c-1] == '#': return -100 if grid[r][c-1] == 'g': return 100 elif a == 3: # right if c + 1 >= n or grid[r][c+1] == '#': return -100 if grid[r][c+1] == 'g': return 100 return 0 def prob(p, grid, a, r, c, r_d, c_d): m = len(grid) n = len(grid[0]) if ((r_d == r and c_d == c) or (r_d == r-1 and c_d == c) or (r_d == r+1 and c_d == c) or (r_d == r and c_d == c-1) or (r_d == r and c_d == c+1)) == False: return 0 count = 0 up = False down = False left = False right = False if r-1 < 0 or grid[r-1][c] == '#': count += 1 up = True if r+1 >= m or grid[r+1][c] == '#': count += 1 down = True if c-1 < 0 or grid[r][c-1] == '#': count += 1 left = True if c+1 >= n or grid[r][c+1] == '#': count += 1 right += True if r_d == r and c_d == c: if grid[r][c] == 'g' or count == 4 or grid[r][c] == '#': return 1 else: return 0 if grid[r][c] == 'g' or count == 4 or grid[r][c] == '#': return 0 #print(str(count) + " " + str(up) + " " +str(down)+" "+str(left) +" "+str(right)) if a == 0: if up: if r_d == r-1: return 0 elif grid[r_d][c_d] == '#': return 0 else: return 1.0 / (4.0 - count) else: if r_d == r-1: if count == 3: return 1.0 else: return p elif grid[r_d][c_d] == '#': return 0 else: if count == 3: return 0 else: return (1.0 - p) / (3.0 - count) elif a == 1: if down: if r_d == r+1: return 0 elif grid[r_d][c_d] == '#': return 0 else: return 1.0 / (4.0 - count) else: if r_d == r+1: if count == 3: return 1.0 else: return p elif grid[r_d][c_d] == '#': return 0 else: if count == 3: return 0 else: return (1.0 - p) / (3.0 - count) elif a == 2: if left: if c_d == c-1: return 0 elif grid[r_d][c_d] == '#': return 0 else: return 1.0 / (4.0 - count) else: if c_d == c-1: if count == 3: return 1.0 else: return p elif grid[r_d][c_d] == '#': return 0 else: if count == 3: return 0 else: return (1.0 - p) / (3.0 - count) else: if right: if c_d == c+1: return 0 elif grid[r_d][c_d] == '#': return 0 else: return 1.0 / (4.0 - count) else: if c_d == c+1: if count == 3: return 1.0 else: return p elif grid[r_d][c_d] == '#': return 0 else: if count == 3: return 0 else: return (1.0 - p) / (3.0 - count) def BellmanOp(Q, p, grid, gamma = 0.9): TQ = np.zeros(Q.shape) m = len(grid) n = len(grid[0]) for r in range(m): for c in range(n): for a in range(4): TQ[r][c][a] = reward(grid, r, c, a) for r_d in range(m): for c_d in range(n): TQ[r][c][a] += gamma * prob(p, grid, a, r, c, r_d, c_d) * np.max(Q[r_d][c_d]) return TQ def valueIter(p, grid, iters, gamma = 0.9): m = len(grid) n = len(grid[0]) Q = np.zeros((m, n, 4)) V = np.zeros((m, n)) pred = np.zeros((m, n)) for i in range(iters): Q = BellmanOp(Q, p, grid, gamma) for r in range(m): for c in range(n): V[r][c] = - math.inf for a in range(4): val = reward(grid, r, c, a) for r_d in range(m): for c_d in range(n): val += gamma * prob(p, grid, a, r, c, r_d, c_d) * np.max(Q[r_d][c_d]) if val > V[r][c]: pred[r][c] = a V[r][c] = val return V, pred def main(): p = 0.8 with open('grid', 'r') as fl: grid = [] for line in fl.readlines(): arr = [] for x in line: if x != '\n': arr.append(x) grid.append(arr) print_grid(grid) V, pred = valueIter(p, grid, 20) print_mat(V) print_mat(pred) #print(prob(p, grid, 3, 4, 2, 4, 3)) if __name__ == '__main__': main()
144aadab9b2167c896838ae99747d606b91834a3
skad00sh/algorithms-specialization
/Divide and Conquer, Sorting and Searching, and Randomized Algorithms/0.4 week1 - bubble-sort.py
691
4.21875
4
def bubble_sort(lst): """ ------ Pseudocode Steps ----- begin BubbleSort(list) for all elements of list if list[i] > list[i+1] swap(list[i], list[i+1]) end if end for return list end BubbleSort ------ Doctests ----- >>> unsorted_list = [8,4,3,7,87,5,64,6,73] >>> sorted_list = insertion_sort(unsorted_list) >>> sorted_list [3, 4, 5, 6, 7, 8, 64, 73, 87] """ for h in range(len(lst)): for i in range(len(lst)-h-1): if lst[i] > lst[i+1]: lst[i], lst[i+1] = lst[i+1], lst[i] return lst
fbcb252e38b6a91f947100d88f8828802bec1856
carmsanchezs/datacademy
/python_basic/diccionarios.py
532
3.78125
4
def main(): poblacion_paises = { 'Argentina': 44938712, 'Brasil': 210147125, 'Colombia': 50372424 } print(poblacion_paises['Argentina']) # imprime 44938712 #print(poblacion_paises['Mexico']) # KeyError for pais in poblacion_paises.keys(): print(pais) for valor in poblacion_paises.values(): print(valor) for key, value in poblacion_paises.items(): print('{} tiene {} habitantes'.format(key, value)) if __name__ == '__main__': main()
b39e3d3e69f8a8452d6d5d4c8031a84d3b3b7c70
carmsanchezs/datacademy
/python_basic/recorrer.py
150
3.765625
4
def main(): frase = input('Escribe una frase: ') for letra in frase: print(letra.upper()) if __name__ == '__main__': main()
ada8e3b64923945dd7c82f9767b587ed40e377fb
abhyuday10/NEA-Intelligent-Car
/car.py
9,189
3.65625
4
"""Car module to manage all data for one car. Each car represents a solution in the environment. Performance of car in environment determines the strength of that solution.""" import pygame import math import environment as env import constants class Car(pygame.sprite.Sprite): """Defining the car class which inherits properties from the Pygame sprite class""" DELTA_ANGLE = 5.5 # Specifies the maximum rotation vector on each frame SPEED = 5 # Specifies the maximum movement possible on each frame def __init__(self, solution, x, y): # Initialise the sprite masterclass pygame.sprite.Sprite.__init__(self) # Initialise images required for rendering self.boom = pygame.image.load("images/explosion.png") self.boom = pygame.transform.scale(self.boom, (50, 50)) if solution.fittest: # Load image of different colour car if this member is the fittest from previous generation self.image = pygame.image.load("images/car_fit.png") else: # Otherwise load default car self.image = pygame.image.load("images/car.png") # Scale the image for the environment self.image = pygame.transform.scale(self.image, (30, 60)) self.orig_image = self.image # Create mask from image. Mask contains each pixel overlapping the image in the environment. # Required for pixel perfect collision detection at the cost of evaluation time. self.mask = pygame.mask.from_surface(self.image) # Create rectangle to store car coordinates self.pos = [x, y] self.rect = self.image.get_rect() self.rect.center = (x, y) # Store current angle car is facing. self.angle = 0 # Boolean to store whether the car has collided in the environment. self.crashed = False # Store location of obstacles and screen boundary to check for collisions self.obstacles = None self.borders = None # Store the solution representing this car self.solution = solution # Imputs and outputs for the neural network making decisions for this car. self.inputs = None self.output = None def rotate_right(self): """Rotate car by maximum angle specified""" self.angle = (self.angle - self.DELTA_ANGLE) % -360 def rotate_left(self): """Rotate car by maximum angle specified""" self.angle = (self.angle + self.DELTA_ANGLE) % -360 def move_forward(self): """Trigonometric function to determine new position based on the angle car is facing.""" dx = math.cos(math.radians(self.angle + 90)) dy = math.sin(math.radians(self.angle + 90)) # Update position of car self.pos = self.pos[0] + (dx * self.SPEED), self.pos[1] - (dy * self.SPEED) self.rect.center = self.pos def update(self): """Overriding the default Pygame update method Update mask and collision state""" self.mask = pygame.mask.from_surface(self.image) self.crashed = self.check_if_crashed() # Helper methods to get and set neural network values def set_inputs(self, inputs): self.solution.brain.set_inputs(inputs) def feed_forward(self): self.solution.brain.feed_forward() def get_outputs(self): return self.solution.brain.get_decision() def calculate_fitness(self, time): """Simple algorithm to determine fitness from time spent in environment Can be adjusted to make fitness increase exponentially with time""" fitness = math.pow(time, 1) self.solution.fitness = fitness def draw(self): """Method to draw car data on this frame to the Pygame screen. Rotate image to the angle the car is currently facing.""" self.image = pygame.transform.rotate(self.orig_image, self.angle) self.rect = self.image.get_rect(center=self.rect.center) # Rendering the image to the current coordinates of the car. env.Environment.screen.blit(self.image, self.rect) def check_if_crashed(self): """Algorithm to check if car has crashed by checking overlaps""" sample_points = [] outline_points = self.mask.outline() # Samples points by checking every tenth point in the car outline to reduce time required for i in range(len(outline_points)): if i % 10 == 0: sample_points.append(outline_points[i]) # Points need to be offsetted as mask does not store absolute position for point in sample_points: offsetted_mask_point = [0, 0] offsetted_mask_point[0] = point[0] + self.rect[0] offsetted_mask_point[1] = point[1] + self.rect[1] # Checks for overlaps between sampled points to check if crashed into object if self.check_if_point_in_any_obstacle(offsetted_mask_point) or self.check_if_point_in_any_border( offsetted_mask_point): adjusted_rect = [offsetted_mask_point[0] - 25, offsetted_mask_point[1] - 25] env.Environment.screen.blit(self.boom, adjusted_rect) # Display collision graphic if crashed return True return False def get_arm_distance(self, arm, x, y, angle, offset): """Function to return sensor distance to objects""" i = 0 # Used to count the distance. # Look at each point and see if we've hit something. for point in arm: i += 1 # Move the point to the right spot. rotated_p = self.get_rotated_point( x, y, point[0], point[1], angle + offset ) # Check if we've hit something. Return the current i (distance) if we did. if rotated_p[0] <= 0 or rotated_p[1] <= 0 \ or rotated_p[0] >= env.Environment.width or rotated_p[1] >= env.Environment.height: return i # Sensor is off the screen. elif self.check_if_point_in_any_obstacle(rotated_p): return i elif constants.DRAW_SENSORS: # Only render sensor arms is specified pygame.draw.circle(env.Environment.screen, constants.BLACK, rotated_p, 2) # Return the distance for the arm. return i def check_if_point_in_any_border(self, point): """Method to check for border intersection with a point""" for border in self.borders: if self.check_inside_rect(point[0], point[1], border): return True return False def check_if_point_in_any_obstacle(self, point): """Method to check for obstacle intersection with a point""" for obstacle in self.obstacles: if self.check_inside_circle(point[0], point[1], obstacle.pos[0], obstacle.pos[1], obstacle.radius): return True return False # Static helper methods to check for point intersections with circles and rectangles @staticmethod def check_inside_rect(x, y, rect): return (rect[0] + rect[2]) > x > rect[0] and (rect[1] + rect[3]) > y > rect[1] @staticmethod def check_inside_circle(x, y, a, b, r): return (x - a) * (x - a) + (y - b) * (y - b) < r * r def get_sensor_data(self): """Method to get sensors readings for the car""" return self.get_sensor_readings(self.rect.center[0], self.rect.center[1], math.radians(abs(self.angle) - 90)) def get_sensor_readings(self, x, y, angle): """Return the values of each sensor in a list""" readings = [] # List to store each sensor value # Make our arms arm_left = self.make_sensor_arm(x, y) arm_middle = arm_left arm_right = arm_left # Rotate them and get readings. readings.append(self.get_arm_distance(arm_left, x, y, angle, 0.75)) readings.append(self.get_arm_distance(arm_left, x, y, angle, 1.55)) readings.append(self.get_arm_distance(arm_middle, x, y, angle, 0)) readings.append(self.get_arm_distance(arm_left, x, y, angle, -1.55)) readings.append(self.get_arm_distance(arm_right, x, y, angle, -0.75)) return readings @staticmethod def make_sensor_arm(x, y): """Method to create array of points representing one arm of sensor.""" spread = 16 # Default spread between sensor points. distance = 10 # Gap before first sensor point. arm_points = [] # Make an arm. for i in range(1, 15): arm_points.append((distance + x + (spread * i), y)) return arm_points @staticmethod def get_rotated_point(x_1, y_1, x_2, y_2, radians): """Algorithm to rotate a point by an angle around another point. Rotate x_2, y_2 around x_1, y_1 by angle.""" x_change = (x_2 - x_1) * math.cos(radians) + \ (y_2 - y_1) * math.sin(radians) y_change = (y_1 - y_2) * math.cos(radians) - \ (x_1 - x_2) * math.sin(radians) new_x = x_change + x_1 new_y = y_change + y_1 return int(new_x), int(new_y)
73b64affd060589fbe25c5a49efcf9e41ad81993
DorianKucharski/big-data-vehicle-traffic
/Data/data_preparing.py
2,800
3.53125
4
""" Przygotowanie danych pobranych z Kaggle """ import random import pandas def generate_year(df_tmp: pandas.DataFrame, year: int) -> pandas.DataFrame: """ Generuje dane na zadany rok, posługując się przekazanymi danymi w obiekcie DataFrame. Generowanie obdywa się poprzez kopiowanie wpisów z równoległych dat i nakładanie na nich niewielkiego szumu, bazując na odchyleniu standardowym. Parameters ---------- df_tmp: pandas.DataFrame Dane z wybranego roku year: int Rok który ma być wygenerowany Returns ---------- pandas.DataFrame Wygenerowane dane """ new_df = df_tmp.copy() new_df = new_df[new_df["Year"] == 2020] new_df["Year"].replace([2020], year, inplace=True) sd = int(new_df["Volume"].std()) new_df["Volume"] = new_df["Volume"].apply(lambda x: x + int((random.randint(0, sd) * random.randint(0, 100)) / 100)) return new_df if __name__ == '__main__': # Wczytywanie danych z pliku csv do obiektu DataFrame df = pandas.read_csv("Radar_Traffic_Counts.csv") # Filtrowanie danych na podstawie lokalizacji w kolumnie location_name df = df[df['location_name'] == " CAPITAL OF TEXAS HWY / WALSH TARLTON LN"] # Usuwanie zbednych kolumn df.drop('location_name', axis=1, inplace=True) df.drop('location_latitude', axis=1, inplace=True) df.drop('location_longitude', axis=1, inplace=True) df.drop('Day of Week', axis=1, inplace=True) df.drop('Time Bin', axis=1, inplace=True) # Filtrowanie danych starszych niz te z 2018. Starsze dane byly niekompletne. df = df[df["Year"] >= 2018] # Usuwanie duplikatow bazujac na kolumnach okreslajacych czas df = df.drop_duplicates(subset=['Year', 'Month', 'Day', 'Hour', 'Minute', 'Direction'], keep='first') # Zmiana wartosci w kolumnie direction df["Direction"].replace({"NB": "IN", "SB": "OUT"}, inplace=True) # Zmiana lat na bardziej terazniejsze df["Year"].replace([2019], 2021, inplace=True) df["Year"].replace([2018], 2020, inplace=True) # Generowanie i laczenie danych years = [df] for i in range(8): years.append(generate_year(df, 2020 - (i + 1))) df = pandas.concat(years) # Utworzenie kolumny datatime na podstawie innych kolumn okreslajacych czas df['Datetime'] = pandas.to_datetime(df[['Year', 'Month', 'Day', 'Hour', 'Minute']]) # Usuwanie niepotrzebnych kolumn df = df[['Datetime', 'Direction', 'Volume']] # Sortowanie df = df.sort_values(by=['Datetime']) # Konwersja danych w kolumnie Datetime na timestamp df['Datetime'] = df['Datetime'].astype('int64') // 10 ** 9 # Zapis danych do pliku df.to_csv("prepared_data.csv", index=False)
9fd432ad1b1ee73e07698c9ab1c83312bebfb922
thinkphp/collatz
/collatz.py
205
3.859375
4
def Collatz(n): while True: yield n if n == 1: break if n & 1: n = 3 * n + 1 else: n = n // 2 for j in Collatz(1780): print(j, end = ' ')
379a186bc1a21dc591556d80a5298ceca9b77a80
mfigand/start_with_python
/07 - Error handling/logic.py
130
3.90625
4
x = 206 y = 42 if x < y: print(str(y) + ' is greater than ' + str(x)) else: print(str(x) + ' is greater than ' + str(y))
650c122e59fe918a01e76c0a01f794432e621279
shubh4197/Python
/PycharmProjects/day4/program1.py
934
3.671875
4
def outer(a): print("This is outer") def inner(*args, **kwargs): # inner function should be generic print("This is inner") for i in args: if type(i) != str: print("Invalid") break else: for i in kwargs.values(): if type(i) != str: print("Invalid") break else: a(*args, **kwargs) print("Inner finished") return inner @outer def hello(name): print("Hello" + name) @outer def sayhi(name1, name2): print("Hello1 " + name1 + " " + name2) # hello = outer(hello) This can be replaced by @wrapperfunctionname above the real function # sayhi = outer(sayhi) This can be replaced by @wrapperfunctionname above the real function hello("Sachin") sayhi(name1="Sachin", name2="Rahul") hello(1)
6179fa6cf1814016ab7b13e6cbb4dcf0d7e2833a
shubh4197/Python
/PycharmProjects/day4/program4.py
500
3.671875
4
class InvalidCredential(Exception): def __init__(self, msg="Not found"): Exception.__init__(self, msg) try: dict = {"Sachin": "ICC", "Saurav": "BCCI"} username = input("Enter username:") password = input("Enter password:") if username not in dict: raise InvalidCredential else: if dict[username] == password: print("success") else: raise InvalidCredential except InvalidCredential as e: print(e)
52603c0b3bda574f3d6225bee89492e87df8b79e
EvanShui/interview_prep
/sort/selection_sort.py
483
3.6875
4
def selection_sort(A): for i in range(len(A)): min_idx = i for j in range(i+1, len(A)): if A[min_idx] > A[j]: min_idx = j print("swapping [idx: {}, val: {}] with [idx: {}, val: {}]".format(i, A[i], min_idx, A[min_idx])) A[i], A[min_idx] = A[min_idx], A[i] def main(): A = [2, 42, 1, 94, 4, 3, 321] selection_sort(A) assert(A == [1, 2, 3, 4, 42, 94, 321]) if __name__ == '__main__': main()
3bd6fa3a0e8d61e0fd0c10304a79d883c6471aae
deepakmatam/content_summary
/hack_gui.py
2,534
3.625
4
import Tkinter from tkFileDialog import askopenfilename m = Tkinter.Tk() m.title('News categorizer ') m.minsize(width=566, height=450) def choosefile(): filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file label = Tkinter.Label( m, text = filename ) label.pack() def categorize(): input_list = [] with open('c:/python27/words.txt','r') as f: for line in f: for word in line.split(): chars_to_remove=['.',',','?','!','@','#','$','%','^','&','*',')','(','-','_','+','=','{','}','[','}','|','<','>',':',';','"'] r=word.translate(None, ''.join(chars_to_remove)) input_list.append(r) #print(word) #print input_list stop_words_list = [] with open('stop_words.txt','r') as f: for line in f: for word in line.split(): stop_words_list.append(word) c_list = [] c_list = list(set(input_list) - set(stop_words_list)) c_list = list(set(c_list)) sports_list,entertainment_list,politics_list,business_list = [],[],[],[] with open('sports.txt','r') as f: for line in f: for word in line.split(','): sports_list.append(word) with open('politics.txt','r') as f: for line in f: for word in line.split(','): politics_list.append(word) with open('entertainment.txt','r') as f: for line in f: for word in line.split(','): entertainment_list.append(word) with open('business_2.txt','r') as f: for line in f: for word in line.split(','): business_list.append(word) #print politics_list sports_count,ent_count,politics_count,business_count,other_count = 0,0,0,0,0 for item in c_list: if item in sports_list: sports_count +=1 if item in entertainment_list: ent_count +=1 if item in politics_list: politics_count +=1 if item in business_list: business_count +=1 #else: # other_count +=1 dict = {'sports':sports_count,'Entertainment':ent_count,'politics':politics_count,'Business':business_count,'other':other_count} print dict result = max(dict,key = dict.get) fresult = 'This news is about ',result if result == 'other': print "This content does not belong to any news" else: label = Tkinter.Label( m, text = fresult ) label.pack() B_choose = Tkinter.Button(m, text ="choose a file", command = choosefile) B_choose.place(x=250,y=130) categorize = Tkinter.Button(m, text ="categorize", command = categorize) categorize.place(x=255,y=170) m.mainloop()
b970b5e47e71e96495d5a7fef82af57309da2599
jffist/pyfoo
/pyfoo/mathfun.py
352
3.546875
4
import numpy as np def scale(x): """ Centers the vector by subtracting it's mean and scales by the standart error :param x: numeric vector :type x: numpy.array or list of numbers :returns: scaled vector of the same length with zero mean and deviation equal to 1 :rtype: numpy.array """ return (x - np.mean(x)) / np.std(x)
a2848e9c028940ce1147501710bef4dbcc147f59
darshind/python_intermediate_project
/q03_create_3d_array/build.py
230
3.90625
4
# Default Imports import numpy as np # Enter solution here def create_3d_array(): N = 28 random_array = np.arange(N-1) reshaped_array = random_array.reshape((3,3,3)) return reshaped_array print create_3d_array()
bf2cd8065542e92a19b392ab44b5bd8038077b07
helani04/EulerProjects
/16/1_Multiples of 3 or 5 below 1000 .py
87
3.640625
4
a=1 s=0 while (a<1000): if(a%3==0 ) or (a%5==0): s = s+a a=a+1 print (s)
d193d76fbd81a2e83bdbc76d62fc5f44726c4b55
helani04/EulerProjects
/16/19-Counting Sundays.py
482
3.734375
4
import time start = time.time() year=1901 day=6 firsts=1 count=0 while year<=2000: if year%400==0 or (year%4==0 and year%100!=0): feb=29 else: feb=28 months=0 NoOfDaysInMonths=[31,feb,31,30,31,30,31,31,30,31,30,31] while months<12: if day==firsts: count+=1 if day-firsts>7: firsts+=NoOfDaysInMonths[months] months+=1 day+=7 year+=1 print(count) end = time.time() print(end - start)
5d9044a28fd1cbeeb0178f4be8abba86875ff2eb
marekhaba/addwidgets
/addwidgets/scrollable_frame.py
2,629
3.671875
4
import tkinter as tk from tkinter import ttk class ScrollableFrame(ttk.Frame): """ for adding widgets into the frame use .scrollable_frame, do NOT add widgets directly. use width and height to enforce size. for modifing the forced size use change_size. """ #borroved from "https://blog.tecladocode.com/tkinter-scrollable-frames/" and modified a little bit. def __init__(self, container, *args, y_scroll=True, x_scroll=True, **kwargs): super().__init__(container, *args, **kwargs) forced_width = kwargs.pop("width", None) forced_height = kwargs.pop("height", None) canvas = tk.Canvas(self, width=forced_width, height=forced_height) self.canvas = canvas if y_scroll: scrollbar_y = ttk.Scrollbar(self, orient="vertical", command=canvas.yview) if x_scroll: scrollbar_x = ttk.Scrollbar(self, orient="horizontal", command=canvas.xview) self.scrollable_frame = ttk.Frame(canvas) self.scrollable_frame.bind( "<Configure>", lambda e: canvas.configure( scrollregion=canvas.bbox("all") ) ) canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw") if x_scroll and y_scroll: canvas.configure(yscrollcommand=scrollbar_y.set, xscrollcommand=scrollbar_x.set) elif x_scroll: canvas.configure(xscrollcommand=scrollbar_x.set) elif y_scroll: canvas.configure(yscrollcommand=scrollbar_y.set) if x_scroll: scrollbar_x.pack(side="bottom", fill="x") canvas.pack(side="left", fill="both", expand=True) if y_scroll: scrollbar_y.pack(side="right", fill="y") def change_size(self, width=None, height=None): """ Changes the enforced size of the ScrollableFrame """ if width is not None: #self.forced_width = width super().configure(width=width) self.canvas.configure(width=width) if height is not None: #self.forced_height = height super().configure(height=height) self.canvas.configure(height=height) if __name__ == "__main__": root = tk.Tk() #ScrollableFrame frame = ScrollableFrame(root, width=150, height=400, x_scroll=False) frame.change_size(height=200) for i in range(50): ttk.Label(frame.scrollable_frame, text="Sample scrolling label").pack() frame.pack() root.mainloop()
f7b532d7e46b5ffc609da81fcc795d85bbaadf19
danielabar/python-practice
/solutions/pick_word.py
414
3.578125
4
#!/usr/bin/envn python """Pick a random word from text file. Usage: python pick_word """ import random def pick_word(): with open('sowpods.txt', 'r') as sowpods: lines = sowpods.readlines() num_lines = len(lines) some_line_num = random.randint(0, num_lines - 1) print('Your random word is {}'.format(lines[some_line_num])) if __name__ == '__main__': pick_word()
9be81cae09ef9b0c9401efc4f9edbbe43758bd24
mac912/python
/dictonary4.py
242
3.875
4
d={'d1':{'name':'zoro','age':21,'country':'japan'},'d2':{'name':'jerry','age':21,'country':'uk'},'d3':{}} print(d) print(d['d1']) print(d['d1']['name']) print(d['d2']['country']) d['d3']['name']='henry' d['d3']['age']=21 print(d)
60cff1227d0866a558d88df56dad871a8d189d9e
mac912/python
/calender.py
1,021
4.3125
4
# program to print calender of the month given by month number # Assumptions: Leap year not considered when inputed is for February(2). Month doesn't start with specific day mon = int(input("Enter the month number :")) def calender(): if mon <=7: if mon%2==0 and mon!=2: for j in range(1,31): print(j, end=' ') if j%7==0: print() elif mon==2: for j in range(1,29): print(j, end=' ') if j%7==0: print() elif mon<=7 and mon%2!=0: for j in range(1,32): print(j, end=' ') if j%7==0: print() elif mon>7 and mon%2==0: for j in range(1,32): print(j, end=' ') if j%7==0: print() elif mon>7 and mon%2!=0: for j in range(1,31): print(j, end=' ') if j%7==0: print() calender()
e7921ad0ba8990d2dafb5c39d2804463820cb46d
mac912/python
/dictonary.py
310
3.859375
4
dict1 = {1:'start', 'name':'saini', 'age':10} print(dict1) print(dict1['name']) #or print(dict1.get('age')) print(dict1.get(1)) print("After making some changes") print() dict1[1] = 'end' dict1['name']= 'manish' dict1['age'] = 20 print(dict1[1]) print(dict1['name']) print(dict1['age'])
24e2224dd8d882665643ddaf11800f602e81027e
scarint/usingpython
/exercises/14 python-inventory-program.py
2,075
4.03125
4
# http://usingpython.com/python-lists/ # Write a program to store items in an inventory for an RPG computer game. # Your character can add items (like swords, shields, and various potions) # to their inventory, as well as 'use' an item, that will remove it from the # inventory list. # You could even have other variables like 'health' and 'strength', that are # affected by 'finding' or 'using' items in the inventory. health = 100 armor = 100 weight = 0 maxWeight = 100 def ReportStats(itemList, maxWeight): health = 100 armor = 100 weight = 0 print("Equipment: ") for item in itemList: health = health + item[3] armor = armor + item[4] weight = weight + item[5] print(item[0]) if weight > maxWeight: print("\n!!!WARNING: Encumbered!!!\n") print("Total health:\t" + str(health) + "\n" "Total armor:\t " + str(armor) + "\n" "Total weight:\t" + str(weight) + "\n") # Item framework: # item-type = ['name', #atk, #speed, #health, #armor, #weight] # speed 1-10; 1 is fastest weapon1 = ['sword', 50, 5, 0, 0, 20] weapon2 = ['stick', 10, 1, 0, 0, 5] weapon3 = ['axe', 70, 7, 0, 0, 50] armor1 = ['helmet', 0, 0, 0, 5, 3] armor2 = ['pauldron', 0, 0, 0, 10, 7] armor3 = ['breastplate', 0, 0, 0, 30, 15] armor4 = ['greaves', 0, 0, 0, 10, 8] armor5 = ['shield', 0, 0, 0, 20, 10] potion1 = ['smallHealth', 0, 0, 10, 0, 2] potion2 = ['medHealth', 0, 0, 20, 0, 5] potion3 = ['largeHealth', 0, 0, 50, 0, 10] potion4 = ['smallArmor', 0, 0, 0, 10, 5] potion5 = ['medArmor', 0, 0, 0, 20, 10] potion6 = ['largeArmor', 0, 0, 0, 50, 15] items_available = [weapon1, weapon2, weapon3, armor1, armor2, armor3, armor4, potion1, potion2, potion3, potion4, potion5, potion6] itemList1 = [weapon1, armor1, armor2, potion3, potion4] itemList2 = [weapon2, armor2, armor3, armor4, armor5] itemList3 = [weapon3, armor1, armor2, armor3, armor4, armor5, armor5] ReportStats(itemList1, maxWeight) ReportStats(itemList2, maxWeight) ReportStats(itemList3, maxWeight)
c4fd4291d7c6ff4ebe40d28579192478fb776e80
bisharma/Binay_Seng560
/converter.py
622
4.03125
4
import math # This will import math module # Now we will create basic conversion functions. def decimal_to_binary(decimal_num): result = bin(decimal_num) return result def binary_to_decimal(binary_num): result = int(binary_num) return result def decimal_to_octal(decimal_num): result = oct(decimal_num) return result def octal_to_decimal(octal_num): result = int(octal_num) return result def decimal_to_hexa(decimal_num): result = hex(decimal_num) return result def hexa_to_decimal(hexa_num): result = int(hexa_num) return result
b7fa421982e1756aca5ca2afc4c743d1bd7b7d0d
YuyangMiao/IBI1_2019-20
/Practical5/collatz.py
491
3.875
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 11 09:54:34 2020 @author: joe_m """ #import an integer n n=7 #Judge if n=1 #If yes: print n and stop #If no: # print n # Repeat: # If n is even: n=n/2, print n # If n is odd: n=3n+1, print n # If n==1, stop if n==1: print (n) else: print (n) while n!=1: if n%2==0: n=n/2 print (n) else: n=3*n+1 print (n) if n==1: break
60363908ab9baed3f64f207efce46e44165d896f
Hyeeein/ClassLion_Python_2
/Week_2_Q9.py
532
3.546875
4
# Q9. 첫 번째 줄에 사람 수 N을 입력받고, 두 번째 줄에 N개의 정수를 공백으로 구분되어 입력받음 # 마피아 1명을 찾기 위해 투표를 하게 되는데 참가하는 사람의 수는 N명, 두 번째 줄은 차례로 마피아 의심자 번호를 적음 # 표 많이 받은 사람 퇴장 / 표 많이 받은 사람 2명 이상이면 skipped / 무효표 > 많이 받은 사람인 경우, 표를 가장 많이 받은 사람 퇴장 N = int(input()) data = list(map(int, input().split()))
8edf41423eeb9a977ad8f378c0b325d415470459
ryanbergner/nba-playoff-predictions
/Nba-Merge-df.py
1,216
3.578125
4
import pandas as pd import numpy as np # data from https://www.basketball-reference.com/leagues/NBA_2020.html # First, we will rename the columns in the opponent dataframe so we can tell the difference between the columns in the team dataframe and the opponent dataframe dfteam = pd.read_csv("NbaTeamData.csv") dfopponent_unlabled = pd.read_csv("NbaOpponentData.csv") # Create a dictionary to convert team column names to opponent stats column names for clarity (did not include team column because that would make no sense) # We will also use team name dict_to_opp = {'Rk' : 'opp_Rk', 'G' : 'opp_G', 'MP' : 'opp_MP', 'FG' : 'opp_FG', 'FGA' : 'opp_FGA', 'FG % ' : 'opp_FG %', '3P' : 'opp_3P', '3PA' : 'opp_3P', '3P % ' : 'opp_3P %', '2P' : 'opp_2P', '2PA' : 'opp_2PA', '2P%' : 'opp_2P%', 'FT' : 'opp_FT', 'FTA' : 'opp_FTA', 'FT%' : 'opp_FT%', 'ORB' : 'opp_ORB', 'DRB' : 'opp_DRB' , 'TRB' : 'opp_TRB', 'AST' : 'opp_AST', 'STL' : 'opp_STL', 'BLK' : 'opp_BLK', 'TOV' : 'opp_TOV', 'PF' : 'opp_PF', 'PTS' : 'opp_PTS'} dfopponent = dfopponent_unlabled.rename( columns = dict_to_opp , inplace = False) df_nba = dfteam.merge(dfopponent, how = "right", on = ["Team"]) print(df_nba)
3c70d4ae169d4f9a4523648aae1ac89137ca0c74
rakuishi/deep-learning-from-scratch
/ch04/error_functions.py
627
3.59375
4
# coding: utf-8 import numpy as np # 2 乗和誤差 def mean_squared_error(y, t): return 0.5 * np.sum((y-t)**2) # 交差エントロピー誤差 def cross_entropy_error(y, t): delta = 1e-7 return -np.sum(t * np.log(y + delta)) # 2 を正解とする t = [0, 0, 1, 0, 0, 0, 0, 0, 0, 0] y1 = [0.1, 0.05, 0.6, 0.0, 0.05, 0.1, 0.0, 0.1, 0.0, 0.0] y2 = [0.1, 0.05, 0.1, 0.0, 0.05, 0.1, 0.0, 0.6, 0.0, 0.0] print(mean_squared_error(np.array(y1), np.array(t))) print(mean_squared_error(np.array(y2), np.array(t))) print(cross_entropy_error(np.array(y1), np.array(t))) print(cross_entropy_error(np.array(y2), np.array(t)))
76199c07a591052fa6309227c134850017f0fc5a
aomi/battlesnake-python
/app/astar.py
3,227
3.6875
4
#Determines distance via manhattan style def manhattanWeight(current, goal): return abs(current.x - goal.x) + abs(current.y - goal.y) def astar(start, goal): print("start: ", start.x, start.y) print("goal: ", start.x, start.y) start.netWeight = 0 lastTurnWeight = 0 openList = [start] closedList = [] start.parent = 0 while(len(openList)>0): centreNode = findSmallestWeightedNode(openList, lastTurnWeight) openList.remove(centreNode) successors = [] if (centreNode.up != 0) and (centreNode.up.content != "wall") and not (centreNode.up in closedList): successors.append(centreNode.up) if (centreNode.down != 0) and (centreNode.down.content != "wall")and not (centreNode.down in closedList): successors.append(centreNode.down) if (centreNode.left != 0) and (centreNode.left.content != "wall")and not (centreNode.left in closedList): successors.append(centreNode.left) if (centreNode.right != 0) and (centreNode.right.content != "wall")and not (centreNode.right in closedList): successors.append(centreNode.right) for successor in successors: successor.parent = centreNode successor.distance = manhattanWeight(successor, goal) successor.netWeight = successor.weight + successor.distance if (checkNodeEquality(successor, goal)): return goal if (not(successor in openList and successor.netWeight < openList[openList.index(successor)].netWeight)): if (not(successor in closedList and successor.netWeight < closedList[closedList.index(successor)].netWeight)): openList.insert(0,successor) closedList.insert(0,centreNode) lastTurnWeight = centreNode.netWeight def checkNodeEquality(nodeA, nodeB): return nodeA.x == nodeB.x and nodeA.y == nodeB.y def findSmallestWeightedNode(openNodeList, previousWeighting): if (len(openNodeList)<=4): return compareMinimums(openNodeList) else: smallestWeightedNode = compareMinimums(openNodeList[:4]) if (smallestWeightedNode.netWeight <= previousWeighting): return smallestWeightedNode else: return compareMinimums(openNodeList) def compareMinimums(openNodeList): minimumWeight = 10000000 for openNode in openNodeList: if openNode.netWeight < minimumWeight: minimumWeight = openNode.netWeight minimumWeightNode = openNode return minimumWeightNode def calculatePathWeight(start, goal): totalWeight = 0 currentNode = astar(start, goal) while (currentNode.parent != 0): totalWeight += currentNode.netWeight lastNode = currentNode currentNode = currentNode.parent totalWeight += currentNode.netWeight print("currentNode: ", currentNode.x, currentNode.y) print("lastNode: ", lastNode.x, lastNode.y) if (currentNode.y - lastNode.y == 1): direction = "up" elif (currentNode.y - lastNode.y == -1): direction = "down" elif (currentNode.x - lastNode.x == 1): direction = "left" elif (currentNode.x - lastNode.x == -1): direction = "right" else: direction = "fail" return [totalWeight, direction]
375c3c159d03fef9573d88b80e29b7bd532544a4
c3forlive/uip-prog3
/Tareas/Tarea2.py
543
3.796875
4
#Tarea2 #License by : Karl A. Hines #Velocidad #Crear un programa en Python que resuelva el siguiente problema #de física: #Una ambulancia se mueve con una velocidad de 120 km/h y #necesita recorrer un tramo recto de 60km. #Calcular el tiempo necesario, en segundos, #para que la ambulancia llegue a su destino. #La fórmula a utilizar es: velocidad = distancia / tiempo. velocidad = 120 distancia = 60 tiempo = velocidad / distancia print ('El tiempo a recorrer es '+str(tiempo)) print ('El tiempo en segundos es '+str((tiempo)*3600))
47e4b1b02962b4264cc9836d2733dd0c5ea674f6
nixil/python_study
/insertion_sort.py
340
3.984375
4
def insertionSort(ar): for j in range(1, len(ar)): key = ar[j] i = j - 1 while i >= 0 and ar[i] > key: ar[i + 1] = ar[i] i -= 1 print " ".join([str(x) for x in ar]) ar[i + 1] = key print " ".join([str(x) for x in ar]) return ar insertionSort([2, 4, 6, 8, 3])
6ba56f86733692c643f7c7e7e1808773a56d23f3
nancypareta/Dice-Roll-Game
/dice roll game .py
477
3.53125
4
import tkinter import random root=tkinter.Tk() root.geometry('600x600') root.title('Roll Dice') l1=tkinter.Label(root,text='',font=('Helvetica',260)) def rolldice(): dice=['\u2680','\u2681','\u2682','\u2683','\u2684','\u2685'] l1.configure(text=f'{random.choice(dice)}{random.choice(dice)}') l1.pack() b1=tkinter.Button(root,text="let's Roll dice...........",foreground='red',command=rolldice) b1.place(x=330,y=0) b1.pack() root.mainloop()
d332a00c6b70b60c577c65af2257d7bd6437c280
ruben-fuertes/rosalind
/mmch.py
595
3.703125
4
from sys import argv from math import factorial file = open(argv[1]) seq = '' for line in file: line = line.rstrip().upper() if not line.startswith('>'): seq+=line # seq = 'CAGCGUGAUCACCAGCGUGAUCAC' def maxmatches(sec): '''This function takes a RNA sequence and calculates the number of different max matches that can be made''' A = sec.count('A') U = sec.count('U') G = sec.count('G') C = sec.count('C') print(A,U,G,C) return factorial(max(A,U))//factorial(max(A,U)-min(A,U)) * factorial(max(G,C))//factorial(max(G,C)-min(G,C)) print (maxmatches(seq))
ef81ba52131119c1e7052aa18f9cecda63883f1c
zhangdzh/GWC_Projects
/RandomMenu.py
1,317
4.09375
4
from random import * entrees=["burger", "chicken", "steak", "pasta"] sides=["macaroni and cheese", "salad", "fries", "biscuit", "coleslaw", "fruit"] desserts=["sundae", "cheesecake", "strawberry shortcake", "pie"] drinks=["soda", "smoothie", "milkshake", "water"] print("Here's your random menu:") EntreeIndex=randint(0, len(entrees)-1) SidesIndex=randint(0, len(sides)-1) SidesIndex2=randint(0, len(sides)-1) DessertIndex=randint(0, len(desserts)-1) DrinkIndex=randint(0, len(drinks)-1) print("Your entree is", entrees[EntreeIndex]) print("Your sides are", sides[SidesIndex], "and", sides[SidesIndex2]) print("Your dessert is", desserts[DessertIndex]) print("Your drink is", drinks[DrinkIndex]) dessertprice=randint(3,7) entreeprice=randint(7,12) sidesprice=randint(3,6) sidesprice2=randint(2,5) drinkprice=randint(1,3) '''if EntreeIndex==0 or 3: entreeprice=9 else: entreeprice=12 if SidesIndex==0 or 2 or 3: sidesprice=3 else: sidesprice=5 if SidesIndex2==0 or 2 or 3: sidesprice2=3 else: sidesprice2=5 if DessertIndex==0 or 1: dessertprice=7 else: dessertprice=5 if DrinkIndex==0 or 3: drinkprice=1 else: drinkprice=3''' print("Your total cost is", entreeprice+sidesprice+dessertprice+sidesprice2+drinkprice, "dollars")
8e5865daf077399e2e57f53532c0600611a6f717
dr2moscow/GeekBrains_Education
/I четверть/Основы языка Python (Вебинар)/Lesson-1/hw_1_6.py
2,173
3.75
4
''' # 6 Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить номер дня, на который результат спортсмена составит не менее b километров. Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня. Например: a = 2, b = 3. Результат: 1-й день: 2 2-й день: 2,2 3-й день: 2,42 4-й день: 2,66 5-й день: 2,93 6-й день: 3,22 Ответ: на 6-й день спортсмен достиг результата — не менее 3 км. ''' growth = 1.1 try: a = float(input("Введите пожалуйста результат спортсмена в первый день: ")) except ValueError: print('Число введено неверно. Будет заменено на 1.') a = 1 try: b = float(input("Введите пожалуйста желаемый результат спортсмена при текущем уровне улучшения: ")) except ValueError: print('Число введено неверно. Будет заменено на 2.') b = 2 if b <= a: print(f'Число введено неверно. Будет заменено на {a + 1}.') b = a + 1 # Итерационный метод a_to_b = a count = 1 while a_to_b < b: a_to_b = a_to_b * growth count += 1 print(f"Спортсмен достигнет результата через : {count} дня(-ей,-ь). (рассчитано в цикле)") # Логичный метод import math period = int(-(-math.log(b/a, growth) // 1)) + 1 print(f"Спортсмен достигнет результата через : {period} дня(-ей,-ь). (рассчитано по формуле)")
01ed5a8e3395ce7ca90b82ee6d4a8c9f1d1ab67a
dr2moscow/GeekBrains_Education
/I четверть/Основы Python (Видеокурс)/Python_1_7/Task_1_7_1.py
749
3.625
4
# Задание # 1 # # Даны два списка фруктов. Получить список фруктов, присутствующих в обоих исходных списках. # Примечание: Списки фруктов создайте вручную в начале файла. list_1 = ['Апельсин', 'Ананас', 'Манго', 'Маракуйя', 'Фейхуа', 'Банан', 'Помело', 'Апельсин'] list_2 = ['Апельсин', 'Яблоко', 'Груша', 'Грейпфрут', 'Гранат', 'Хурма', 'Манго', 'Апельсин'] list_common = [el for el in list_1 if list_2.count(el) > 0] print(list_common) list_common = [el for el in list_1 if el in list_2] print(list_common)
839276f68d78539ebce39b5cbd8de329282fd68e
dr2moscow/GeekBrains_Education
/I четверть/Основы языка Python (Вебинар)/Lesson-2/homework_2.py
4,143
4.0625
4
# print("***********************************************************************") # print(" Задание № 1") # print("***********************************************************************") # ''' # # 1 # Даны два произвольные списка. Удалите из первого списка элементы присутствующие во втором списке. # ''' # # my_list_1 = [2, 5, 8, 2, 12, 12, 4, 4, 4] # my_list_2 = [2, 7, 12, 3] # # for number in my_list_1[:]: # print(number) # if number in my_list_2: # my_list_1.remove(number) # print('removing') # print(my_list_1) # # my_list_1 = [2, 5, 8, 2, 12, 12, 4, 4, 4] # my_list_2 = [2, 7, 12, 3] # for list_val in my_list_2: # while list_val in my_list_1: # my_list_1.remove(list_val) # # print(my_list_1) # print("***********************************************************************") # print(" Задание № 2") # print("***********************************************************************") # ''' # # 2 # Дана дата в формате dd.mm.yyyy, например: 02.11.2013. Ваша задача — вывести дату в текстовом виде, # например: второе ноября 2013 года. Склонением пренебречь (2000 года, 2010 года) # ''' # date_dict = {'01':'первое','02':'второе','03':'третье','04':'четвертое','05':'пятое', # '06':'шестое','07':'седьмое','08':'восьмое','09':'девятое','10':'десятое', # '11':'одиннадцатое','12':'двенадцатое','13':'тринадцатое','14':'четырнадцатое','15':'пятнадцатое', # '12':'шестнадцатое','17':'семнадцатое','18':'восемнадцатое','19':'девятнадцатое','20':'двадцатое', # '21':'двадцать первое','22':'двадцать второе','23':'двадцать третье','24':'двадцать четвертое','25':'двадцать пятое', # '26':'двадцать шестое','27':'двадцать седьмое','28':'двадцать восьмое','29':'двадцать девятое','30':'тридцатое', # '31':'тридцать первое'} # # month_dict = {'01':'января','02':'февраля','03':'марта','04':'апреля','05':'мая', # '06':'июня','07':'июля','08':'августа','09':'сентября','10':'октября', # '11':'ноября','12':'декабря'} # # changed_date = '17.04.1979' # # dd = changed_date[:2] # mm = changed_date[3:5] # yyyy = changed_date[-4:] # print(dd, mm, yyyy) # # changed_date_in_word = '{} {} {} года'.format(date_dict[dd], month_dict[mm], yyyy) # print(f'Дата прописью: {changed_date_in_word}') # # print("***********************************************************************") # print(" Задание № 3") # print("***********************************************************************") # ''' # # 3 # Дан список заполненный произвольными целыми числами. # Получите новый список, элементами которого будут только уникальные элементы исходного. # ''' # # my_list_1 = [2, 2, 5, 12, 8, 2, 12] # my_set_1 = set([]) # my_set_1_dublicates = set([]) # # for list_val in my_list_1: # if list_val in my_set_1: # my_set_1_dublicates.add(list_val) # else: # my_set_1.add(list_val) # # my_list_2 = list(my_set_1 - my_set_1_dublicates) # # print(f'Новый список, который содержит только уникальные элементы: {my_list_2}') print(type(10)) = <class 'int'> type(10) == int - РАБОТАЕТ print(type(None)) - <class 'NoneType'> type(None) == NoneType - НЕ РАБОТАЕТ. Можно как-то обойти?
44db1bec51190545210fd7565518ad602e33b937
dr2moscow/GeekBrains_Education
/I четверть/Основы языка Python (Вебинар)/lesson-5/hw_5_5.py
2,192
3.78125
4
# Задание # 5 # # Создать (программно) текстовый файл, записать в него программно набор чисел, # разделенных пробелами. Программа должна подсчитывать сумму чисел в файле и выводить ее на экран. from random import randint def cat_numbers(file_object): # Генератор, который считыват "слова" разделенные пробелами и, преобразовав их в числа, передает во внешний код. str_var = '' eof = False while not eof: symbol = file_object.read(1) if symbol == '': symbol = ' ' eof = True if str_var == '': break if symbol != ' ': str_var = str_var + symbol else: try: current_number = float(str_var) except ValueError: current_number = 0 str_var = '' yield current_number if __name__ == '__main__': # file_name = 'lesson_5_task_5_temporary_file.txt' file_name = input(f'Введите имя файла, в котором будут записаны числа: ') quantity = randint(10, 100) numbers_sum = 0 numbers_count = 0 # Программное создание и запись файла с числами with open(file_name, 'w', encoding='utf-8') as file_obj: for el in range(quantity): print(f'{randint(1000, 350000)/100}', file=file_obj, end=' ') # Чтение файла и суммирование всех чисел из него происходит с помощью генератора with open(file_name, 'r', encoding='utf-8') as file_obj: for curr_number in cat_numbers(file_obj): numbers_sum += curr_number numbers_count += 1 print(f'{numbers_count}) {curr_number}. А сумма стала равной: {numbers_sum}') print() print(f'Сумма всех ({numbers_count} штук(-и, -а)) равна {numbers_sum}')
773d9211d4e6037aff180f87f135d11e0f660d7e
dr2moscow/GeekBrains_Education
/I четверть/Основы языка Python (Вебинар)/lesson-3/hw_3_3.py
696
4.15625
4
''' Задание # 3 Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов. ''' def f_max_2_from_3(var_1, var_2, var_3): return var_1 + var_2 + var_3 - min(var_1, var_2, var_3) my_vars = [] for count in range(3): try: var = float(input(f'Введите число # {count+1}: ')) except ValueError: print('Должно быть число! По умолчанию подставлена 1') var = 1 my_vars.append(var) print(f'{f_max_2_from_3(my_vars[0], my_vars[1], my_vars[2])}')