blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
06f5a29c7f7dc8f1b2458f1689cf7df529e62b5e
asperaa/programming_problems
/tree/zigzag_traversal_of_tree.py
1,293
3.9375
4
"""Zigzag traversal of tree""" from collections import deque class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def zigzag(root): if not root: return root result = [] level = [] queue = deque() queue.append(root) zigzag = False while queue: count = len(queue) for _ in range(count): if zigzag: node = queue.pop() level.append(node.val) if node.right: queue.appendleft(node.right) if node.left: queue.appendleft(node.left) else: node = queue.popleft() level.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) result.append(level) zigzag = not zigzag level = [] return result if __name__ == "__main__": root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) root.right.left = TreeNode(6) root.right.right = TreeNode(7) print(zigzag(root))
fa3403ed0039f21928a102e1c84c42827ea6d55d
komtaki/atCoder
/contest_abc/153/d.py
231
3.609375
4
def solve(H): ans_attack = 0 hp = H enemy = 1 while hp > 1: hp = hp // 2 ans_attack = ans_attack + enemy enemy = enemy * 2 return ans_attack + enemy H = int(input()) print(solve(H))
2475e8224b37268619a53919f76c4e51391a7505
ay701/Coding_Challenges
/number/fibonacci.py
713
3.875
4
# Use recursion def fib(n): if n in [0, 1]: return n return fib(n-1)+fib(n-2) # print fib(5) # Use iterative def fib_iterative(n): n1 = 0 n2 = 1 cnt = 0 if n < 0: raise Exception('Error number') while cnt < n: print(n1) nth = n1 + n2 n1 = n2 n2 = nth cnt += 1 fib_iterative(6) # use generator def fib2(): a, b = 0, 1 while True: yield a a, b = b, a+b for ind, res in enumerate(fib2()): if ind == 6: print ind, res break # Large data # use generator def fib3(n): a, b = 0, 1 for i in range(n): yield a a, b = b, a+b for x in fib3(6): print(x)
4ad92217ace34156b69228a48ba0cb2fe844cb2a
the-hobbes/hadoop_mapreduce
/part_2/reducer_hits_per_file.py
1,014
3.8125
4
#!/usr/bin/env python ''' Answer the following with this reducer: 1) Write a mapreduce to display thenumber of hits for each different file on the website Expected input is: filename timestamp Output should look like: filename total(number_of_hits) ''' import sys def reducer(): ''' Sum the total instances of each filename. ''' hit_total = 0 old_file = None for line in sys.stdin: data = line.strip().split('\t') if len(data) != 2: continue this_file, this_hit = data if old_file and old_file != this_file: print '{0}\t{1}'.format(old_file, hit_total) hit_total = 0 old_file = this_file hit_total += 1 if old_file != None: print old_file, '\t', hit_total def main(): reducer() if __name__ == '__main__': ''' remember, this allows you to use the same file both as a library (by importing it) or as the starting point for an application by calling it. http://stackoverflow.com/questions/8228257/what-does-if-name-main-mean-in-python ''' main()
5b6eac3e41a094a3005143b9f23c1128a55c15ff
skariyadan/StaCIA
/queryparser.py
7,862
3.5
4
import re import nltk ''' parseQuestions(): parses query.txt file and creates 2 data structures, a questions dictionary keyed by linenumber and contains a list with the question and response; parse variable names from query.txt into a list ''' def parseQuestions(): questions = {} variables = [] i = 0 f = open("query.txt","r") for line in f.readlines(): i += 1 if "A1" in line: cols = line.split("|") q = cols[1] a = cols[2] questions[i] = [q, a[:-1]] else: if line != "\n": var = re.search(".*(?=:)", line).group(0) variables.append(var[1:-1]) f.close() return questions, variables ''' parseQuery(): parses the input question and returns a dictionary containing a signal (normal, unknown, question, end, error etc), and returns a dictionary of signals and (if normal) the question number and variables associated with it ''' def parseQuery(input, questions, classifier): label = classifier.classify(getFeatures(input.lower())) probs = classifier.prob_classify(getFeatures(input.lower())) probLabel = probs.prob(label) if probLabel < .1: return {"signal":"Unknown"} else: parsed = {"signal": "Normal", "question":label} variable = {} inputSplit = input.split(" ") detQuestion = questions[label][0].split(" ") idq = 0 iis = 0 var = "" varname = "" stop = "" while iis < len(inputSplit) and idq < len(detQuestion): if "[" in detQuestion[idq] and "]" in detQuestion[idq]: varname = detQuestion[idq][1:-1] if "]" in varname: varname = varname[:-1] idq += 1 if idq >= len(detQuestion): var = " ".join(inputSplit[iis:])[:-1] else: stop = detQuestion[idq].lower() while iis < len(inputSplit) and stop not in inputSplit[iis].lower(): var += inputSplit[iis] + " " iis += 1 if var == "WISH": var = "Women Involved in Software and Hardware" elif var == "Linux User Group": var = "Linux Users Group" variable[varname] = var.strip() var = "" varname = "" else: iis += 1 idq += 1 parsed["variables"] = variable return parsed ''' createModel(): creates and trains a model to classify the question ''' def createModel(questions): labeled = [] for k, v in questions.items(): labeled.append((v[0].lower(), k)) labeled = [(getFeatures(q), num) for (q, num) in labeled] classifier = nltk.NaiveBayesClassifier.train(labeled) return classifier ''' getFeatures(): extracts features from the question ''' def getFeatures(question): features = {"who":"who" in question, "what":"what" in question, "where":"where" in question, "when":"when" in question, "why":"why" in question, "how":"how" in question, "are":"are" in question, "club":"club" in question, "tutor":"tutor" in question, "center":"center" in question, "offer":"offer" in question, "many":"many" in question, "number":"number" in question, "advise":"advise" in question, "advisor":"advisor" in question, "email":"email" in question, "type":"type" in question, "kind":"kind" in question, "president":"president" in question and "vice" not in question, "vice president":"vice president" in question, "secretary":"secretary" in question, "treasurer":"treasurer" in question, "homepage":"homepage" in question, "page":"page" in question, "box":"box" in question, "box number":"box number" in question, "social":"social" in question, "social media":"social media" in question, "facebook":"facebook" in question, "instagram":"instagram" in question, "upcoming":"upcoming" in question, "next":"next" in question, "follower":"follower" in question, "following":"following" in question, "account":"account" in question, "latest":"latest" in question, "post":"post" in question, "is":"is" in question, "on":"on" in question, "does":"does" in question, "room":"room" in question, "office":"office" in question, "officer":"officer" in question, "meeting":"meeting" in question, "event":"event" in question, "meet":"meet" in question, "project":"project" in question, "sponsor":"sponsor" in question, "technical track":"technical track" in question, "department":"department" in question, "past":"past" in question, "contact":"contact" in question, "name":"name" in question, "reach":"reach" in question, "phone":"phone" in question, "resource":"resource" in question, "together":"together" in question, "have":"have" in question, "WISH":"WISH" in question, "fee":"fee" in question, "due":"due" in question, "available":"available" in question, "begin":"begin" in question, "start":"start" in question, "end":"end" in question, "finish":"finish" in question, "head":"head" in question, "get":"get" in question, "week":"week" in question, "csse":"csse" in question, "stat":"stat" in question, "computer":"computer" in question, "science":"science" in question, "program":"program" in question, "speak":"speak" in question, "be":"be" in question, "sign":"sign" in question, "requirement":"requirement" in question, "private":"private" in question, " r ": " r " in question, "information":"information" in question, "assistance":"assistance" in question, "help":"help" in question, "schedule" : "schedule" in question, "locate" : "locate" in question, "data":"data" in question, "service":"service" in question, "peer":"peer" in question, "assistant":"assistant" in question, "become":"become" in question, "people":"people" in question, "working":"working" in question, "with":"with" in question, "sign-up":"sign-up" in question, "free":"free" in question, "subscription":"subscription" in question, "need":"need" in question, "require":"require" in question, "option":"option" in question, "can" :"can" in question, "do" : "do" in question, "the": "the" in question, "a": "a" in question } return features
f5027edebed58f6bb21c6812becd45789f90b2e3
weverson23/ifpi-ads-algoritmos2020
/Atividade_Semana_08_e_09/uri_1178.py
365
3.640625
4
def metade(x): # função que divide os valores e adiciona em cada # posição do vetor e depois imprime o resultado vet = [] for i in range(100): vet.append(x) x = x / 2 for i in range(100): print('N[{}] = {:.4f}'.format(i,vet[i])) def main(): # entrada do valor x = float(input()) metade(x) main()
03f42d8fce0813e508db18eb3c95c48b30965686
badrjarjarah/SchoolHomwork
/Python/hw5a.py
4,242
4.03125
4
# Joseph Leiferman # Student ID: 00990636 # Discussion Section: A06 import time # Two words are neighbors if they differ in exactly on letter. # This function returns True if a given pair of words are neighbors def areNeighbors(w1, w2): count = 0 for i in range(len(w1)): if w1[i] != w2[i]: count = count + 1 return count == 1 # The function reads from the file "words.dat" and inserts the words that are read # into a list. The words are also inserted into a dictionary as keys, with each key # initialized to have [] as its value. def readWords(wordList, D): fin = open("words.dat", "r") # Loop to read words from the and to insert them in a list # and in a dictionary for word in fin: newWord = word.strip("\n") wordList.append(newWord) D[newWord] = [] fin.close() # Builds the network of words using a dictionary. Two words are connected by an edge in this # network if they are neighbors of each other, i.e., if they differ from each # other in exactly one letter. def buildDictionary(wordList, D): #create wordMatrix and suffixes wordMatrix = [[] for x in range(26)] suffixes = [[] for x in wordList] # add data to wordList for x in wordList: char = ord(x[0])-97 wordMatrix[char].append(x) # add data to suffixes for x in range(len(wordList)): suffixes[x].append(wordList[x][1:]) suffixes[x].append(wordList[x][0]) # sortes suffixes by first index suffixes.sort() # builds type one of neighbors for index in range(len(wordMatrix)): for x in range(len(wordMatrix[index])): for y in range(x+1,len(wordMatrix[index])): if areNeighbors(wordMatrix[index][x],wordMatrix[index][y]): D[wordMatrix[index][x]].append(wordMatrix[index][y]) D[wordMatrix[index][y]].append(wordMatrix[index][x]) # builds type two of neighbors for x in range(len(suffixes)): for y in range(x+1, len(suffixes)): if suffixes[x][0] == suffixes[y][0]: D[suffixes[x][1]+suffixes[x][0]].append(suffixes[y][1]+suffixes[y][0]) D[suffixes[y][1]+suffixes[y][0]].append(suffixes[x][1]+suffixes[x][0]) # Explores the network of words D starting at the source word. If the exploration ends # without reaching the target word, then there is no path between the source and the target. # In this case the function returns False. Otherwise, there is a path and the function # returns True. def searchWordNetwork(source, target, D): # Initialization: processed and reached are two dictionaries that will help in the # exploration. # reached: contains all words that have been reached but not processed. # processed: contains all words that have been reached and processed, i.e., their neighbors have also been explored. # The values of keys are not useful at this stage of the program and so we use 0 as dummy values. processed = {source:0} reached = {} for e in D[source]: reached[e] = 0 # Repeat until reached set becomes empty or target is reached while reached: # Check if target is in reached; this would imply there is path from source to target if target in reached: return True # Pick an item in reached and process it item = reached.popitem() # returns an arbitrary key-value pair as a tuple newWord = item[0] # Find all neighbors of this item and add new neighbors to reached processed[newWord] = 0 for neighbor in D[newWord]: if neighbor not in reached and neighbor not in processed: reached[neighbor] = 0 return False # Main program wordList = [] D = {} readWords(wordList, D) buildDictionary(wordList, D) source = input("Please type the source word: ") target = input("Please type the target word: ") if searchWordNetwork(source, target, D): print ("There is path from source to target") else: print ("There is no path from source to target")
b731350924bf3fff5df624cc0a4008015e5fd817
Abigye/Games
/RockPaperScissors/RockPaperScissors.py
2,200
3.984375
4
import random def game(): total_count = 0 user_count = 0 computer_count = 0 while total_count <=10: List = ["Rock","Paper","Scissors"] computer = random.choice(List) print ("Rock , Paper, Scissors ?") player = input () print(f'You played {player}, the computer played {computer}') if player == computer: print("It's a tie!") computer_count = computer_count + 1 user_count = user_count + 1 elif player == "Rock": if computer == "Paper" : print ("Ouch! " + computer + " covers " + player) computer_count = computer_count + 1 else: print ("Good one there " + player + " smashes " + computer) user_count = user_count + 1 elif player == "Scissors": if computer == "Rock": print("Ouch! " + computer + " smashes " + player) computer_count = computer_count + 1 else: print("Smart ugh " + player + " cuts " + computer) user_count = user_count + 1 elif player == "Paper": if computer == "Scissors": print ("Ouch! " + computer + " cuts " + player) computer_count = computer_count + 1 else: print ("Nice move " + player + " covers " + computer) user_count = user_count + 1 else : print("Invalid play") print(f'Computer: {computer_count} - You: {user_count}') print() total_count = total_count + 1 if total_count == 10: if user_count > computer_count : print("You win") elif user_count < computer_count: print ("Be smart next time!") else: print("Wow, u are as smart as the computer!!") print ("\nWould you like to play again, type y for yes or n for no?") again = str(input("> ")) again = again.lower() if again == "y": game() else: quit() game()
2b40546c8492e48396467400b349479c29df4f11
rsata/kais-gradebook
/Final.py
2,395
3.796875
4
#Reginal Database Management System #6/1/2016 #Kai Sata #Program that takes data and can edit it then report it each time it is called #KS import all external programs that will be called later on in the user choice import Add_class import Class_report import Delete_class import Add_student import Delete_student import Student_report import Student_report_class import os #KS define user choice def user_choice(): os.system('clear') #KS set classes and students to empty lists to be appended later on classes = [] students = [] #KS create spacing for title screen using title.center to center it title = "Class Roster Database" print(title.center(80, ' ')) print() #KS print all options available for user choice print("1. Add a Class") print("2. Add a Student") print("3. Delete a Class Record") print("4. Delete a Student Record") print("5. Class Report") print("6. Student Report") print("7. Student Report by Class") print("8. Exit") print() #KS user can input their choice choice = str(input("Please choose: ")) print() #KS if the user inputs any choice that is not 8 the program will run one of the options while choice != 8: if choice == "1": classes = Add_class.run(classes) if choice == "2": students = Add_student.run(students) if choice == "3": classes = Delete_class.run(classes) if choice == "4": students = Delete_student.run(students) if choice == "5": Class_report.run(classes) if choice == "6": Student_report.run(students) if choice == "7": Student_report_class.run(classes, students) if choice == "8": break #KS if no number between 1 and 7 (8 will exit the program) re-print the title screen title = "Class Roster Database" print(title.center(80, ' ')) print() print("1. Add a Class") print("2. Add a Student") print("3. Delete a Class Record") print("4. Delete a Student Record") print("5. Class Report") print("6. Student Report") print("7. Student Report by Class") print("8. Exit") print() choice = str(input("Please choose: ")) print() #KS cs call to user_choice user_choice()
1d9195cd72352ee5ab2a2ca48f9c92185995f0f7
MarcosNocetti/PY
/joguinho do mal.py
607
3.5625
4
#--coding:utf8;-- #qpy:3 #qpy:console import subprocess import sys e = input("Arquivo ou programa? \n").lower() if e == "programa": while a == True : print( "TAKSBAR" ) a = input( "Entre com o nome do programa \n" ) if a == "exit": a = False else: subprocess.run( a ) continue elif e == "arquivos": while s == True: s = input("nome do arquivo\n") if s == "exit": s = False else: s.open() s.read() s.close() continue else: print("tchau") sys.exit()
4bab62a009ce751855f45a2cdcf8e9673ebaceb6
borislavstoychev/Soft_Uni
/soft_uni_basic/While Loop/exercise/04. Walking.py
609
4
4
steps_needed = 10000 steps_counter = 0 steps_home = 0 while steps_counter < steps_needed: command = input() if command == 'Going home': steps_home = int(input()) steps_counter += steps_home if steps_counter < steps_needed: print(f'{steps_needed - steps_counter} more steps to reach goal.') break steps = int(command) steps_counter += steps if steps_counter >= steps_needed: break if steps_counter >= steps_needed: print('Goal reached! Good job!') print(f'{steps_counter - steps_needed} steps over the goal!')
00810e6d82eadcefd857be63319e07356c69cf77
stewartad/goodcop-dadcop
/player.py
3,247
3.515625
4
import pygame, constants class Player(pygame.sprite.Sprite): # constrctor class that takes x, y coordinates as parameters def __init__(self, x, y): # call parent constructor pygame.sprite.Sprite.__init__(self) # set sprite image and rectangle self.image = pygame.image.load("goodcop.png") self.rect = self.image.get_rect() # set position self.rect.x = x self.rect.y = y # set width and height self.width = self.rect.width self.height = self.rect.height # set velocity and acceleration self.dx = 0 self.dy = 0 self.ay = constants.GRAV # set variable to retrieve platforms from main self.walls = None def moveLeft(self): # Move in negative x direction self.dx = -constants.X_VEL def moveRight(self): # Move in positive x direction self.dx = constants.X_VEL def jump(self): # Move down 2 pixels and check for collision, then move back up 2 pixels self.rect.y += 2 block_hit_list = pygame.sprite.spritecollide(self, self.walls, False) self.rect.y -=2 # jump if sprite is on the ground, or collided with a platform if self.checkGround() or len(block_hit_list)>0: self.dy = -constants.Y_VEL self.rect.y -= 4 def stop(self): # set x velocity to zero to stop movement self.dx = 0 def checkGround(self): onGround = False # if bottom of rectangle is greater than or equal to the screen height, # then the sprite is on the ground if self.rect.bottom >= constants.SCR_HEIGHT: onGround = True return onGround def addGrav(self): # If platform moves, this ensures player moves with it if self.dy == 0: self.dy = 1 else: self.dy -= constants.GRAV if self.checkGround(): # If on the ground, negate gravity self.dy = 0 self.rect.y = constants.SCR_HEIGHT - self.height def update(self): # Account for gravity self.addGrav() # move in x direction self.rect.x += self.dx # check if x movement resulted in collision block_hit_list = pygame.sprite.spritecollide(self, self.walls, False) for block in block_hit_list: if self.dx > 0: self.rect.right = block.rect.left if self.dx < 0: self.rect.left = block.rect.right # check if x movement goes off screen if self.rect.right >= constants.SCR_WIDTH: self.rect.right = constants.SCR_WIDTH elif self.rect.x <= 0: self.rect.x = 0 # move in y direction self.rect.y += self.dy # check if y movement resulted in collision block_hit_list = pygame.sprite.spritecollide(self, self.walls, False) for block in block_hit_list: if self.dy > 0: self.rect.bottom = block.rect.top if self.dy < 0: self.rect.top = block.rect.bottom self.dy=0
b2a3bdfcf6de7c67077936020bda8f20df741a04
arsoljon/My-scary-python
/firststars.py
446
3.546875
4
# This does a star with Juan & I. import turtle turtle.write("hello world", "center") #turtle.shapetransform(25, 10, 15, 1) turtle.color("red", "green") turtle.colormode("blue") turtle.speed(20) for i in range(5): turtle.forward(200) turtle.right(144) turtle.clear() for i in range(5): turtle.fd(50) turtle.rt(144) for i in range(5): turtle.fd(10) turtle.rt(144) turtle.done()
545abee6b90ff06959c2700961e5c88986dd3281
denetti/PythonHSE
/W1/1-8 sumofnum.py
106
3.5625
4
num = int(input()) sumc = 0 while (num != 0): sumc = sumc + num % 10 num = num // 10 print(sumc)
3d431df9ba38d3c51cfff4aea06386c49d420fbf
andrewupk/HackerRank
/Python/Collections/WordOrder.py
358
3.734375
4
from collections import OrderedDict if __name__ == '__main__': N = int(input()) words = OrderedDict() for i in range(N): word = input() if word in words: words[word] += 1 else: words[word] = 1 print(len(words)) for word, count in words.items(): print('{0}'.format(count), end=' ')
af3b31bdea030e65d585160dbaf57ace35b70b55
brewswain/PCC
/Part II - Projects/Project 1 - Alien Invasion/Chapter 14 - Scoring/Notes/2 Leveling Up/1_modifying_the_speed_settings.py
3,013
4.25
4
""" We'll first reorganize the Settings class to group the game settings into static and changing ones. We'll also make sure that settings that change over the course of a game reset when we start a new game. Here's the __init__() method for settings.py: """ # settings.py def __init__(self): """Initialize the game's static settings.""" --snip-- # Alien settings self.alien_speed_factor = 1 # self.fleet_drop_speed = 10 # How quickly the game speeds up self.speedup_scale == 1.1 self.initialize_dynamic_settings() # fleet_direction of 1 represents rights; -1 represents left. self.fleet_direction = 1 """ We continue to initialize the settings that stay constant in the __init__() method. At line 43 we add a speedup_scale setting to control how quickly the game speeds up: A value of 2 will double the game speed every time the player reaches a new level; a value of 1 will keep the speed constant. A speed value like 1.1 should increase the speed enough to make the game challenging but not impossible. Finally, we call initialize_dynamic_settings() to initialize the values for attributes that need to change throughout the course of a game(line 45). Here's the code for initialize_dynamic_settings(): """ # settings.py def initialize_dynamic_settings(self): """Initialize settings that change throughout the game.""" self.ship_speed_factor = 1.5 self.bullet_speed_factor = 3 self.alien_speed_factor = 1 # fleet_direction of 1 represents rights; -1 represents left. self.fleet_direction = 1 """ This method sets the initial values for the ship, bullet, and alien speeds. We'll increase these speeds as the player progresses in the game and reset them each time the player starts a new game. We include fleet_direction in this method so the aliens always move right at the beginning of a new game. To increase the speeds of the ship, bullets, and aliens each time the player reaches a new level, use increase_speed(): """ # settings.py def increase_speed(self): """Increase speed settings.""" self.ship_speed_factor *= self.speedup_scale self.bullet_speed_factor *= self.speedup_scale self.alien_speed_factor *= self.speedup_scale """ To increase the speed of these game elements, we multiply each speed setting by the value of speedup_scale. We increase the game's tempo by calling increase_speed() in check_bullet_alien_collisions() when the last alien in a fleet has been shot down but before creating a new fleet: """ # game_functions.py def check_bullet_alien_collisions(ai_settings, screen, ship, aliens, bullets): --snip-- if len(aliens) == 0: # Destroy existing bullets, speed up game, and create new fleet. bullets.empty() ai_settings.increase_speed() create_fleet(ai_settings, screen, ship, aliens) """ Changing the values of the speed settings ship_speed_factor, alien-speed_factor, and bullet_speed_factor is enough to speed up the entire game! """
8f885550b4262c31355a4cbba8e3d51c30c3c56f
Quidge/cs50
/pset6/similarities/score
960
3.609375
4
#!/usr/bin/env python3 import sys from argparse import ArgumentParser from helpers import distances def main(): # Parse command-line arguments parser = ArgumentParser() parser.add_argument("FILE1", help="file to compare") parser.add_argument("FILE2", help="file to compare") args = vars(parser.parse_args()) # Read files try: with open(args["FILE1"], "r") as file: file1 = file.read() except IOError: sys.exit(f"Could not read {args['FILE1']}") try: with open(args["FILE2"], "r") as file: file2 = file.read() except IOError: sys.exit(f"Could not read {args['FILE2']}") # Compare files d = distances(file1, file2) #print(d) '''for y in d: for x in y: print(f" {x[0]}, {str(x[1])[0].upper()} |", end="") print() ''' print(d[len(file1)][len(file2)][0]) #print(d) if __name__ == "__main__": main()
311fba0777ef7a120c51436743d9ceb3e0fd3470
ArseniyCool/Python-YandexLyceum2019-2021
/Основы программирования Python/4. While-loop/Скидки!.py
550
4.125
4
# Программ считает сумму товаров и делает скидку 5 % на товар,если его стоимость превышает 1000 price = float(input('Введите цену на товар:')) cost = 0 while price >= 0: if price > 1000: cost = cost + (price - 0.05 * price) else: cost = cost + price price = float(input('Введите цену на товар:')) # Сигнал остановки - нуль или отрицательное число print(cost)
f349f90fbf58d53717ad36548a9837e498c8d707
lukegao/leetcode-practices
/linkedlist.py
3,786
4.03125
4
class Node(object): """docstring for Node""" def __init__(self, val): self.val = val self.next = None def __repr__(self): if self.next is not None: return f"{id(self)}: value={self.val}, next={id(self.next)}" else: return f"{id(self)}: value={self.val}, next=NULL" class MyLinkedList: def __init__(self): """ Initialize your data structure here. """ self.head = None def get(self, index: int) -> int: """ Get the value of the index-th node in the linked list. If the index is invalid, return -1. """ cur = self.head counter = 0 while cur is not None: if index == counter: return cur.val cur = cur.next counter += 1 return -1 def addAtHead(self, val: int) -> None: """ Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. """ node = Node(val) if self.head is not None: node.next = self.head self.head = node def addAtTail(self, val: int) -> None: """ Append a node of value val to the last element of the linked list. """ prev = None current = self.head node = Node(val) if current is None: return self.addAtHead(val) while current is not None: if current.next is None: current.next = node return current = current.next def addAtIndex(self, index: int, val: int) -> None: """ Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. """ node = Node(val) if index == 0: return self.addAtHead(val) current = self.head prev = current counter = 0 while current is not None: if counter == index: node.next = current prev.next = node return counter += 1 prev = current current = current.next if index == counter: prev.next = node def deleteAtIndex(self, index: int) -> None: """ Delete the index-th node in the linked list, if the index is valid. """ if index < 0: return if index == 0 and self.head is not None: self.head = self.head.next return counter = 0 current = self.head prev = current while current is not None: if counter == index: prev.next = current.next return counter += 1 prev = current current = current.next return def __repr__(self): current = self.head string = 'head' while current is not None: string += f"--> {current.val}" current = current.next string += '--> NULL' return string if __name__ == '__main__': llist = MyLinkedList() llist.addAtIndex(0, 10) llist.addAtIndex(0, 20) llist.addAtIndex(1, 30) print(llist) print(llist.get(0)) # llist.addAtHead(7) # llist.addAtHead(2) # llist.addAtHead(1) # llist.addAtIndex(3, 0) # llist.deleteAtIndex(2) # llist.addAtHead(6) # llist.addAtTail(4) # print(llist) # print(llist.get(4)) # llist.addAtHead(4) # llist.addAtIndex(5, 0) # llist.addAtHead(6) # print(llist)
bc366a88886f35a0139811d7ebf3f77dbc32fcce
PowerSnail/tool_scripts
/py/rm_duplicate_env_val.py
941
3.5625
4
#!/usr/bin/env python3 """Remove duplicated value in environment variable This script preserves the ordering of the environment variable. Only Compatible with python3.7 or later, as this script uses the order-preserving feature added in python3.7. Input is taken from standard input as a single line of ":"-delimited string. Output is printed to standard output, as a single line of ":"-delimited string. Usage: python3 rm_duplicate_env_val.py python3 rm_duplicate_env_val.py -h|--help python3 rm_duplicate_env_val.py -v|--version Other options will be ignored. """ import sys __version__ = "0.1.0" if len(sys.argv) > 1: option = sys.argv[1] if option in ("-h", "--help"): print(__doc__) sys.exit(0) elif option in ("-v", "--version"): print(__version__) sys.exit(0) values = input().split(":") values_uniq = { v : None for v in values } print(":".join(values_uniq.keys()))
1c783c650ed4c775c29743bb83c8170495f84b43
richard-paredes/CS-Fundamentals
/IntroToProgramming/Week14/assignment10.py
2,891
3.859375
4
# -*- coding: utf-8 -*- """ Richard Paredes PSID: 1492535 COSC 1306 Assignment #10 """ def generateTriangle1(triangle): a,b,c = triangle ''' [ 1 -2 2 2 -1 2 2 -2 3 ] ''' _a = a - 2*b + 2*c _b = 2*a - b + 2*c _c = 2*a - 2*b + 3*c return tuple(sorted([_a,_b,_c])) def generateTriangle2(triangle): a,b,c = triangle ''' [ 1 2 2 2 1 2 2 2 3 ] ''' _a = a + 2*b + 2*c _b = 2*a + b + 2*c _c = 2*a + 2*b + 3*c return tuple(sorted([_a,_b,_c])) def generateTriangle3(triangle): a,b,c = triangle ''' [ -1 2 2 -2 1 2 -2 2 3 ] ''' _a= -a + 2*b + 2*c _b= -2*a + b + 2*c _c= -2*a + 2*b + 3*c return tuple(sorted([_a,_b,_c])) def getTriangles(allPerimeters, baseTriangle, limit, isScaled=False): perimeter = sum(baseTriangle) if (perimeter > limit): return if (perimeter not in allPerimeters): allPerimeters[perimeter] = [] if (baseTriangle not in allPerimeters[perimeter]): allPerimeters[perimeter].append(baseTriangle) multiple = 1 nextTriangle = baseTriangle while (not isScaled and sum(nextTriangle) < limit): getTriangles(allPerimeters, nextTriangle, limit, True) tri_1 = generateTriangle1(nextTriangle) getTriangles(allPerimeters, tri_1, limit) tri_2 = generateTriangle2(nextTriangle) getTriangles(allPerimeters, tri_2, limit) tri_3 = generateTriangle3(nextTriangle) getTriangles(allPerimeters, tri_3, limit) multiple += 1 nextTriangle = tuple([multiple* side for side in baseTriangle]) def determineMostTriangles(allPerimeters): # start with smallest pythagorean triple correspondingPerimeter = 12 maxNumTriangles = len(allPerimeters[correspondingPerimeter]) for perimeter in sorted(allPerimeters.keys()): numTriangles = len(allPerimeters[perimeter]) if (numTriangles > maxNumTriangles): correspondingPerimeter = perimeter maxNumTriangles = numTriangles return (correspondingPerimeter, maxNumTriangles) def printTriangles(allPerimeters, perimeter, numTriangles): print('The perimeter of {} gives a maximum number of {} triangles.'.format(perimeter, numTriangles)) for triangle in allPerimeters[perimeter]: print(triangle) print() def main(): allPerimeters = {} # start with smallest pythagorean triple baseTriangle = (3, 4, 5) getTriangles(allPerimeters, baseTriangle, 2019) perimeter, numTriangles = determineMostTriangles(allPerimeters) printTriangles(allPerimeters, perimeter, numTriangles) main()
32011f88f37646db35052bc761164eebec10c7c0
JazzFiend/AdventOfCode
/2016/Day08_TwoFactorAuthentication/Screen.py
1,044
3.5
4
import sys class Screen(): # Constructor def __init__(self, height, width): self.display = [['.' for x in range(width)] for y in range(height)] self.HEIGHT = height self.WIDTH = width # Public Methods def displayScreen(self): for line in self.display: for pixel in line: sys.stdout.write(pixel) sys.stdout.write('\n') sys.stdout.write('\n') sys.stdout.flush() def turnOnRange(self, width, height): for i in range(0, height): for j in range(0, width): self.display[i][j] = '#' def getHeight(self): return self.HEIGHT def getWidth(self): return self.WIDTH def getPixelState(self, x, y): return self.display[y][x] def setPixel(self, x, y, state): if(state == '.' or state == '#'): self.display[y][x] = state else: raise ValueError('Wrong pixel state: %s' % state) def getLitPixelCount(self): count = 0 for line in self.display: for pixel in line: if(pixel == '#'): count += 1 return count
112901592133b84d0e8219e331c3ca65407e21c9
SigmaQuan/NTM-Keras
/datasets/repeat_copy.py
3,561
3.6875
4
# -*- coding: utf-8 -*- import numpy as np from utils import initialize_random_seed # Initialize the random seed initialize_random_seed() def generate_one_sample(dimension, sequence_length, repeat_times): """Generate one sample of repeat copy algorithm. # Arguments dimension: the dimension of each input output tokens. sequence_length: the length of input sequence, i.e. the number of input tokens. repeat_times: repeat times of output. # Returns input_sequence: the input sequence of a sample. output_sequence: the output sequence of a sample. """ # produce random sequence sequence = np.random.binomial( 1, 0.5, (sequence_length, dimension - 1)).astype(np.uint8) # allocate space for input sequence and output sequence input_sequence = np.zeros( (sequence_length + 1 + sequence_length * repeat_times, # + 1 dimension), dtype=np.bool) output_sequence = np.zeros( (sequence_length + 1 + sequence_length * repeat_times, # + 1 dimension), dtype=np.bool) # set value of input sequence input_sequence[:sequence_length, :-1] = sequence # input_sequence[sequence_length, -1] = repeat_times input_sequence[sequence_length, -1] = 1 # set value of output sequence ## sequence_length + 1 output_sequence[sequence_length+1:, :-1] = \ np.tile(sequence, (repeat_times, 1)) # "1": A special flag which indicate the begin of the output # output_sequence[sequence_length, -1] = 1 # return the sample return input_sequence, output_sequence def generate_data_set( dimension, max_length_of_original_sequence, max_repeat_times, data_set_size): """Generate samples for learning repeat copy algorithm. # Arguments dimension: the dimension of each input output tokens. max_length_of_original_sequence: the max length of original sequence. max_repeat_times: the maximum repeat times. data_set_size: the size of total samples. # Returns input_sequences: the input sequences of total samples. output_sequences: the output sequences of total samples. repeat_times: the repeat times of each output sequence of total samples. """ # produce random sequence lengths from uniform distribution # [1, max_length] sequence_lengths = np.random.randint( 1, max_length_of_original_sequence + 1, data_set_size) # produce random repeat times from uniform distribution # [1, max_repeat_times] repeat_times = np.random.randint(1, max_repeat_times + 1, data_set_size) input_sequences = np.zeros( (data_set_size, max_length_of_original_sequence * (max_repeat_times + 1) + 1, # + 1 dimension), dtype=np.bool) output_sequences = np.zeros( (data_set_size, max_length_of_original_sequence * (max_repeat_times + 1) + 1, # + 1 dimension), dtype=np.bool) # set the value for input sequences and output sequences for i in range(data_set_size): input_sequence, output_sequence = generate_one_sample( dimension, sequence_lengths[i], repeat_times[i]) input_sequences[i, :sequence_lengths[i]*(repeat_times[i]+1)+1] = \ input_sequence output_sequences[i, :sequence_lengths[i]*(repeat_times[i]+1)+1] = \ output_sequence # return total samples return input_sequences, output_sequences, repeat_times
7cba4ff49fe5909489c0ef2eac3cd4fa0897af13
mecozma/100DaysOfCode-challenge
/day3/q13.py
588
4.0625
4
""" Write a program that accepts a sentence and calculate the number of letters and digits. Suppose the following input is supplied to the program: hello world! 123 Then, the output should be: LETTERS 10 DIGITS 3 """ def count_alfa_and_digits(): letters, digits = 0, 0 input_values = [i for i in input("Please type alphanumeric values: ")] for character in input_values: if character.isdigit(): digits += 1 elif character.isalpha(): letters += 1 return f"LETTERS: {letters}\nNUMBERS: {digits}" print(count_alfa_and_digits())
30242c4cab7c38094cfd8c349eb0ad1cd3f610e3
wburford1/CSCI375_QA_System
/QuestionProcessor.py
2,174
3.625
4
# HomeworkFive import nltk from nltk.corpus import stopwords import string # a class for processing questions class QuestionProcessor: # constructs a QuestionProcessor object for 'question' # q is a question def __init__(self): self.question = None self.key_words = [] self.stop_words = [] # tokenizes question, removes stopwords and makes anything in quotations its own token, also removes punctuation. def process(self): toks = nltk.word_tokenize(self.question) i = 0 while i < len(toks): quotes = ['``', "''", '"'] # if there is a quoted entity in the question, it is added in its entirety to the list of key words if toks[i] in quotes: i += 2 tok = toks[i-1] while not toks[i] in quotes: tok = ' '.join([tok, toks[i]]) i += 1 i += 1 self.key_words.append(tok.lower()) # if a token is not a stopword, it is added to the list of key words else: if toks[i] not in set(stopwords.words('english')): self.key_words.append(toks[i].lower()) else: self.stop_words.append(toks[i].lower()) i += 1 # removes punctuation self.key_words = [word for word in self.key_words if word not in list(string.punctuation)] # print(self.question) # print(self.key_words) def get_keywords(self): return self.key_words def get_question(self): return self.question def get_stopwords(self): return self.stop_words def set_question(self, q): self.clear() self.question = q self.process() def clear(self): self.question = None self.key_words = [] def find_keywords(self, q): self.set_question(q) return self.key_words # testing if __name__ == '__main__': process_question = QuestionProcessor('What is the length, of "tail of two cities"') process_question.set_question('What team did Wayne Gretzky play for?')
0af7f021fef95aa00530ca1f28947e0eb252a4e6
HarikrishnaRayam/Data-Structure-and-algorithm-python
/Binary Tree/Lectures/Print Node at depth k.py
769
3.65625
4
# -*- coding: utf-8 -*- """ Created on Sun Apr 26 00:24:22 2020 @author: cheerag.verma """ class BinaryTree: def __init__(self,data): self.data = data self.left = None self.right = None def takeInput(): root = int(input()) if root ==-1: return btn = BinaryTree(root) leftTree = takeInput() rightTree = takeInput() btn.left = leftTree btn.right = rightTree return btn def NodeAtKDepth(root,k,count=0): if root == None: return if count == k: print(root.data) return NodeAtKDepth(root.left,k,count+1) NodeAtKDepth(root.right,k,count+1) root = takeInput() result = NodeAtKDepth(root,2) print(result)
8e44b9168fdff7b9e57cfa2a3ea6b497f5d9e085
Lucces/leetcode
/merge_88.py
966
3.875
4
#!/usr/bin/env python # coding=utf-8 class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead. """ if m == 0: nums1[0:n] = nums2[0:n] return elif n == 0: return size = len(nums1) nums1[size - m:] = nums1[0:m] i = size - m j = 0 k = 0 while i < size and j < n: if nums1[i] <= nums2[j]: nums1[k] = nums1[i] k += 1 i += 1 else: nums1[k] = nums2[j] k += 1 j += 1 print i, j, k print nums1, nums2 if i == size: nums1[k : m + n] = nums2[j:n] elif j == n: nums1[k : m + n] = nums1[i:size]
3c72755faaa5c4e0e3ee20d262064bfc9c4091dc
cyrnicolase/leetcode
/169/169.py
652
3.6875
4
#!/usr/bin/python class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ count_values = {} for num in nums: if count_values.has_key(num): count_values[num] += 1 else: count_values[num] = 1 max_count = 0 result = None for num, count in count_values.items(): if max_count < count: max_count = count result = num return result nums = [3,2,3] nums = [2,2,1,1,1,2,2] so = Solution() print so.majorityElement(nums)
e2bc5da0d4ce924d8bb9873a41a663d9b02d9618
umunusb1/PythonMaterial
/python2/02_Basics/01_Arithmetic_Operations/j_complex_numbers.py
964
4.375
4
#!/usr/bin/python """ Purpose: Demonstration of complex numbers Complex Number = Real Number +/- Imaginary Number In python, 'j' is used to represent the imaginary number. """ num1 = 2 + 3j print "num1=", num1 print "type(num1)=", type(num1) print num2 = 0.0 - 2j print "num2 = ", num2 print "type(num2) = ", type(num2) print print "num1 = ", num1 print "num1.conjugate() = ", num1.conjugate() print "num1.real = ", num1.real print "num1.imag = ", num1.imag print print "num1 * num2.real = ", num1 * num2.real print "(num1*num2).real = ", (num1 * num2).real # Observe the signs of imaginary numbers print '========================================' print 'arithmetic operations on complex numbers' print '========================================' print "num1 + num2 = ", num1 + num2 print "num1 - num2 = ", num1 - num2 print "num1 * num2 = ", num1 * num2 print "num1 / num2 = ", num1 / num2 print print "num1 / 2 = ", num1 / 2
422c80d04488829e8065d15186e2bde30d970888
kishorepro/learningGithub
/src/ifels.py
255
4.09375
4
grade= input("Enter your grade: ") if grade >= 90: print ("A") elif grade >= 80: print ("B") elif grade >= 75: print ("BC") elif grade >= 85: print ("CB") elif grade >= 70: print ("C") elif grade >= 60: print ("D") else: print ("F")
73e1fdc1c4fa312f56c490bec97b739c2be5f039
Divyaansh313/100DaysofCode
/RockPaperScissors.py
2,917
4.1875
4
""" Implements the game of Rock-Paper-Scissors! History: This classic game dates back to the Han Dinesty, over 2200 years ago. The First International Rock-Paper-Scissors Programming Competition was held in 1999 and was won by a team called "Iocaine Powder" The Game: Each player choses a move (simultaneously) from the choices: rock, paper or scissors. If they chose the same move the game is a tie. Otherwise: rock beats scissors scissors beats paper paper beats rock. In this program a human plays against an AI. The AI choses randomly (we promise). The game is repeated N_GAMES times and the human gets a total score. Each win is worth +1 points, each loss is worth -1 """ import random N_GAMES = 3 def main(): print_welcome() score = 0 for i in range(N_GAMES): ai_move = get_ai_move() human_move = get_human_move() winner = choose_winner(ai_move, human_move) announce_winner(ai_move, winner) score = calculate_score(score, winner) print("Your score", score) def calculate_score(score, winner): if winner == 'human': score += 1 if winner == 'ai': score -= 1 if winner == 'tie': score +=0 return score print("You shouldn't reach here") def announce_winner(ai_move, winner): print("AI plays", ai_move) print("The winner is", winner) print('') def get_ai_move(): """ for now the AI plays randomly. But the optimal strategy is: If you lose, switch to the thing that beats the thing your opponent just played. If you win, switch to the thing that would beat the thing that you just played. """ int = random.randint(1,3) if int == 1: return 'rock' if int == 2: return 'paper' return 'scissors' def get_human_move(): while True: move = input("What do you play? ") if move_is_valid(move): return move print("Invalid move, try again: ") def choose_winner(ai_move, human_move): if ai_move == human_move: return 'tie' if ai_move == 'rock': if human_move == 'paper': return 'human' return 'ai' if ai_move == 'paper': if human_move == 'scissors': return 'human' return 'ai' if ai_move == 'scissors': if human_move == 'rock': return 'human' return 'ai' print("You shouldn't reach here") def move_is_valid(move): if move == 'rock': return True if move == 'scissors': return True if move == 'paper': return True return False def print_welcome(): print('Welcome to Rock Paper Scissors') print('You will play '+str(N_GAMES)+' games against the AI') print('rock beats scissors') print('scissors beats paper') print('paper beats rock') print('----------------------------------------------') print('') if __name__ == '__main__': main()
e795a762a18354f494c96e285a617074634d20c8
Tuchev/Python-Basics---september---2020
/07.Exams/Programming Basics Online Exam - 15 and 16 June 2019/01. Movie Profit.py
344
3.875
4
film_name = input() num_of_days = int(input()) num_of_tickets = int(input()) price_for_ticket = float(input()) percent_for_cinema = int(input()) sum_of_all = num_of_days * num_of_tickets * price_for_ticket profit = sum_of_all - (sum_of_all * percent_for_cinema / 100) print(f"The profit from the movie {film_name} is {profit:.2f} lv.")
716327832e739d163bc309902115b88760f29bfb
ctbeiser/Evolution_full
/11/evolution/traitcard.py
1,484
3.84375
4
from .trait import Trait # Because range is inclusive only on the bottom FOOD_VALUE_RANGE = range(-8, 8+1) class TraitCard: def __init__(self, food_value, trait): """ Represents a Card with a Trait and a quantity of Food :param food_value: An Integer between -8 and 8 :param trait: A Trait """ if food_value in FOOD_VALUE_RANGE: self.food_value = food_value else: raise ValueError("Food value for a trait card must be in the acceptable range") self.trait = trait def make_tree(self, tree, parent): """ Modify the ttk tree provided to add a representation of this data structure :param tree: a ttk Treeview widget object :param parent: the ttk reference to a row in the ttk Treeview under which this content should be added. """ tree.insert(parent, 'end', text=(str(self.food_value) + ", " + self.trait.serialize())) def serialize(self): """ Returns a serialized version of the Card :return: serialized version of the Card """ return [self.food_value, self.trait.serialize()] @classmethod def deserialize(cls, data): """ Given a serialized Card, :param data: A list of [foodValue, name] where the former is between -8 and 8, and the latter is a serialized trait :return: a new TraitCard """ food_value, name = data return cls(food_value, Trait(name))
354e21f2823534da9f431acde5687411e95b60cd
AidanCurley/Codio
/polymorphism_2_overriding_dunders.py
781
3.71875
4
class Characters: def __init__(self, phrases): self._phrases = phrases def total_chars(self): total = 0 for phrase in self._phrases: total += len(phrase) return total def __gt__(self, other): return self.total_chars() > other.total_chars() def __lt__(self, other): return self.total_chars() < other.total_chars() def __eq__(self, other): return self.total_chars() == other.total_chars() sample_phrases1 = ['cat in the hat', 'green eggs and ham', 'the lorax'] sample_phrases2 = ['the taming of the shrew', 'hamlet', 'othello'] c1 = Characters(sample_phrases1) c2 = Characters(sample_phrases2) print(c1 > c2) # prints 'True' print(c1 < c2) # prints 'False' print(c1 == c1) # prints 'True'
95ee624b4650c322f47f1e76c89e97edac43ee1f
joshsanyal/pythonroom
/things.py
285
4.09375
4
# author: joshsanyal thingstodo = ["watch a Rockets game", "visit the southern hemisphere", "go camping"] for thing in thingstodo: answer = input ( "Would you want to " + thing + "?" ) if answer == "yes": print "Then do " + thing if answer == "no": print "Then don't " + thing
796ae277c7b42cb3e892032de37c229b82f0aed5
cedadev/cmip6-data-transfer-mgmt
/scripts/query_sdt.py
988
3.53125
4
import sqlite3 from sqlite3 import Error class ConnectDB(object): def __init__(self, database_file=False, verbose=False): self.database_file = database_file self.verbose = verbose self.conn = self.connect_to_database() def connect_to_database(self): if self.verbose: print("Connecting to database: {}".format(self.database_file)) try: conn = sqlite3.connect(self.database_file) return conn except Error as e: if verbose: print(e) return None def run_database_query(self, query_str): if self.verbose: print("Querying database: {}".format(query_str)) query = self.conn.cursor() query.execute(query_str) return query.fetchall() def query_database(self, query): if self.conn: return self.run_database_query(query) else: return "Unable to connect to database"
66d407d714258a6aceea8e800a10ba5994af040a
ecastillob/project-euler
/101 - 150/112.py
1,846
4.40625
4
#!/usr/bin/env python # coding: utf-8 """ Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468. Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420. We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, 155349. Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538. Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%. Find the least number for which the proportion of bouncy numbers is exactly 99%. """ # In[1]: def arriba(N): valor = -1 actual = -1 for n_str in str(N): actual = int(n_str) if actual < valor: return False valor = actual return True # In[2]: def abajo(N): valor = 10 actual = 10 for n_str in str(N): actual = int(n_str) if actual > valor: return False valor = actual return True # In[3]: def es_bouncy(N): return not (arriba(N) or abajo(N)) # In[4]: arriba(134468), abajo(66420), es_bouncy(155349) # In[5]: def contar_bouncies(RATIO_LIMITE): contador = 0 ratio = 0 i = 100 while (ratio != RATIO_LIMITE): if es_bouncy(i): contador += 1 ratio = contador / i i += 1 return [contador, i - 1, ratio] # In[6]: contar_bouncies(0.5) # [269, 538, 0.5] # In[7]: contar_bouncies(0.9) # [19602, 21780, 0.9] # In[8]: contar_bouncies(0.99) # [1571130, 1587000, 0.99]
ad4f61bbec452521c9bd6673717c712c5f1ef6fe
liaison/LeetCode
/python/199_Binary_Tree_with_Right_Side_View.py
634
3.5625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def rightSideView(self, root: TreeNode) -> List[int]: results = [] def DFS(node, depth): if node: if depth == len(results): results.append(node.val) # preorder with the priority on the right child DFS(node.right, depth+1) DFS(node.left, depth+1) DFS(root , 0) return results
87b73f58573920489cb7c29fa4f8a27ec1253597
ganeshtunuguntla/Diabetes-Prediction
/project/graph.py
523
3.5
4
import matplotlib.pyplot as plt import numpy as np import pandas as pd # Data df=pd.DataFrame({'x': range(1,11), 'y1': np.random.randn(10), 'y2': np.random.randn(10)+range(1,11), 'y3': np.random.randn(10)+range(11,21) }) # multiple line plot plt.plot( 'x', 'y1', df, marker='o', markerfacecolor='blue', markersize=12, color='red', linewidth=4) plt.plot( 'x', 'y2', df, marker='', color='olive', linewidth=2) plt.plot( 'x', 'y3', df, marker='', color='olive', linewidth=2, linestyle='dashed', label="toto") plt.legend()
a4df84bf65629a146d05f723a441f3b18d62db79
marco-lavagnino/advent-of-code-2020
/day3/run.py
764
3.5625
4
# https://adventofcode.com/2020/day/3 #%% with open("sample.txt") as f: lines = f.read().split("\n") #%% with open("input.txt") as f: lines = f.read().split("\n") # %% row = 0 column = 0 trees = 0 while row < len(lines): if lines[row][column] == "#": trees += 1 column = (column + 3) % len(lines[row]) row += 1 trees # %% def get_trees(right, down): row = 0 column = 0 trees = 0 while row < len(lines): if lines[row][column] == "#": trees += 1 column = (column + right) % len(lines[row]) row += down return trees slopes = ( (1, 1), (3, 1), (5, 1), (7, 1), (1, 2), ) mul = 1 for right, down in slopes: mul *= get_trees(right, down) mul # %%
563e54e7ac52bdae8c659c5658aa5a311246aa97
cmjao/Python-practicespace
/ch7_list_001.py
212
4
4
birth_year = 1992 years_list = [years for years in range(birth_year, birth_year + 5)] print("Print years list :", years_list) print("Print third item :", years_list[2]) print("Print last item :", years_list[-1])
c739025009ab6a31182180aedb360a5164704005
shulme33/Programming
/Python/cci_1-2.py
4,635
3.78125
4
# Samuel Hulme # Cracking the Coding Interview # Question 1.2 # # Given two strings, wite a method to decide if one is a permutation of the other. # # Thoughts: # 1.) The simple answer is to sort the strings and then check them one letter at a time. This could be done in # O(nlogn) for the sort and O(n) for the comparison. Therefore, the overall runtime is O(nlogn) # # 2.) The quicker implementation is to use a dictionary/hashtable. Below is an example of this implementation. # It involves a hash table that is made up of 128 indexes where the index holds a "count" value. Each index represents # and ASCII character and each "count" represents the total number of times that that character has been seen in # String 1. We go through String 1 and add all the characters to the string. As we do this, we increase the # num_characters field by 1 for each new character we see. Then we go through String 2 and delete 1 from the count # value for each character that we see. When we hit 0, we remove one from the num_character variable. If we never # see a new character in String 2 and the num_characters value is 0 at the end, then the strings are permutations # of one another. This algorithm involves traversing each string once. Therefore the runtime is O(2n) = O(n) # class StringChar: def __init__(self, char, count): self.char = char self.count = count def upCount(): self.count = self.count + 1 def downCount(): self.count = self.count - 1 class HashTable: def __init__(self): self.table = [None] * 128 #Assume ASCII self.num_characters = 0 def determine_index(self, new_char): #Assume ASCII index = ord(new_char) def insert_char(self, char): index = ord(char) #If already in table, add +1. If not, add the new character. if self.table[index] == None: #This is a fresh index self.num_characters += 1 self.table[index] = StringChar(char, 1) else: #A character already exists here self.table[index].count += 1 def insert_string(self, str): for char in str: self.insert_char(char) def compare_char_for_permutation(self, char): #If at a new index, count gets below 0, or num_characters gets below 0, then this is not a permutation index = ord(char) if self.table[index] == None: # New index. This char was not in the original string return False else: # A character already exists here self.table[index].count -= 1 if self.table[index].count == 0: self.num_characters -= 1 self.table[index] = None if self.num_characters < 0: return False return True def second_string_is_permutation(self, str): for char in str: if self.compare_char_for_permutation(char) == False: return False return True def is_permutation_dict(str1, str2): if len(str1) != len(str2): return False hash = HashTable() #Init list with length twice that of the length of the strings hash.insert_string(str1) return hash.second_string_is_permutation(str2) def is_permutation_sorted(str1, str2): sort_str1 = sorted(str1) # O(nlogn) sort_str2 = sorted(str2) # O(nlogn) if sort_str1 == sort_str2: return True return False def check_permutations(use_dict): str1 = input("Enter the first string: ") str2 = input("Enter the second string: ") is_perm = False if not use_dict: is_perm = is_permutation_sorted(str1, str2) else: is_perm = is_permutation_dict(str1, str2) print("\nThese two strings ARE permutations" if is_perm else "\nThese are NOT permutations") #compare_str1 = "kljioilk5498u0jvc#@$%^Erlkj32ijodf$%^SDEFSeijhjel3" #compare_str2 = "jdf$%^SDEFoil2ijo5jel3kvc#@eijhk498u0Silj$%^Erlkj3" print("\n\nThis program will take two strings and determine if they are permutations of one another. ") print("There are two different algorithms used to do this. Choose an algorithm from the following by entering 1 or 2.") print(" 1.) Sorting Strings First - O(nlogn)") print(" 2.) Using A Dictionary/Hash Table - O(n)") bad_answer = True while bad_answer: answer = input("Select an algorithm by typing 1 or 2: ") if answer == "1": bad_answer = False check_permutations(False) #Sorting elif answer == "2": bad_answer = False check_permutations(True) #Dictionary
5a71efd94cdeda2ade61ec8e122438f31aa20dbc
BREG001/osp_repo_sub
/py_lab2/my_pkg/bin_conv.py
770
3.8125
4
#!/usr/bin/python3 def bin_conv(): bin = int(input("input binary number:")) bin_ = bin temp = 0 oct = 0 i = 0 asdf = 0 while (bin_ >= 1): for j in range(0, 3): temp += (bin_ % 10) * pow(2, j) bin_ = int(bin_ / 10) oct += (temp * pow(10, i)) i += 1 temp = 0 print("=> OCT> %d" % oct) bin_ = bin dec = 0 i = 0 while (bin_ >= 1): dec += (bin_ % 10) * pow(2, i) bin_ = int(bin_ / 10) i += 1 print("=> DEC> %d" % dec) bin_ = bin hex = "" i = 0 while (bin_ >= 1): for j in range(0, 4): temp += (bin_ % 10) * pow(2, j) bin_ = int(bin_ / 10) if (temp < 10): hex = chr(temp + ord("0")) + hex else: hex = chr(temp - 10 + ord("A")) + hex temp = 0 i += 1 print("=> HEX>",hex) if __name__=='__main__': bin_conv()
92b077752573078adc4e32eec6f82be54cf824c4
jeetsaha5338/College_Study
/TRAINNING/ML/Globesyn/work/REGRETION/ML_sanu/temp.py
228
3.875
4
import matplotlib.pyplot as plt #%matplotlib inline x=range(0,100,1) y=[x+1 for x in range(0,100,1)]#this is known as list argument plt.plot(x,y) z=[x+200 for x in range(0,100,1)] plt.plot(x,z) plt.show() LOL KID
57e64b636d5012b2d816f88d7d89388894ad428e
yingang/python-challenge
/11.py
453
3.59375
4
from PIL import Image im = Image.open("cave.jpg") (width, height) = im.size # put even/odd in same image (left/right) output = Image.new(im.mode, (width, height//2)) # even for y in range(0, height, 2): for x in range(0, width, 2): output.putpixel((x//2, y//2), im.getpixel((x, y))) # odd for y in range(1, height, 2): for x in range(1, width, 2): output.putpixel((x//2 + width//2, y//2), im.getpixel((x, y))) output.show()
1833c736b7daab7377235e39fbd809a7e104abd4
nrouleau/rosalind
/2TranscribingDnaIntoRna.py
206
3.609375
4
dna_string = raw_input() rna_string = [] for nucleotide in dna_string: if (nucleotide == 'T'): rna_string.append('U') else: rna_string.append(nucleotide) print ''.join(rna_string)
7eeaedec78c8ea24b4db2df5eecefbff7a7120a5
random-forest-ai/python_course
/Chapter_2/Boolean/Boolean.py
699
4.21875
4
if __name__ == '__main__': # == / != / < / <= / > / >= operator (Change the operator as you wish!) # print(7 == 7) # print(7 == 8) # print(7 == 7.0) # print("ABC" == "ABC") # print("ABC" == "ABCD") # print("ABC" == "abc") # print((5, 3, 2) == (5, 3, 2)) # print((5, 3, 2) == (5, 3, 2.1)) # = vs == x = 2 print(x == 2) # Logic Relation # not print(not 7 >= 7) # and print(7 >= 7 and "Apple" > "Banana") # short circuit print(False and 3 / 0) # OK print(True and 3 / 0) # Error # or print(7 >= 7 or "Apple" > "Banana") # short circuit print(True or 3 / 0) # OK print(False or 3 / 0) # Error
521ab13981c1f2d4c66c2df7cd6f2eeb92a1882d
gangooteli/ClassificationHousingDataset
/demo.py
2,341
3.65625
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf dataframe = pd.read_csv('data.csv') dataframe = dataframe.drop(['index','price','sq_price'], axis=1) dataframe = dataframe[0:10] dataframe dataframe.loc[:, ('y1')] = [1,1,1,0,0,1,0,1,1,1] dataframe.loc[:,('y2')] = dataframe['y1'] == 0 dataframe.loc[:,('y2')] = dataframe['y2'].astype(int) dataframe inputX = dataframe.loc[:,['area','bathrooms']].as_matrix() inputY = dataframe.loc[:,['y1','y2']].as_matrix() inputX inputY #parameters learning_rate = 0.000001 training_epochs = 2000 display_step = 50 n_samples = inputY.size #write out computation graph #for feature input tensors, none means any number of examples #placeholders are gateways of data into our computation graph x = tf.placeholder(tf.float32, [None, 2]) #create weights # 2x2 float matrix that we'll keep updating through the #training process #variable in tf hold and update parameters #in memory buffers containing tensors W = tf.Variable(tf.zeros([2,2])) #add biases(example is b/bias in y = mx + b) b = tf.Variable(tf.zeros([2])) #multiply our weights by our inputs, first calculation #weight are how we govern how data flow in our computation graph y_values = tf.add(tf.matmul(x,W),b) #apply softmax to value we just created #softmax is activation function y = tf.nn.softmax(y_values) y_ = tf.placeholder(tf.float32, [None,2]) #perform training #create our cost function, mean squared error #reduce_sum computes the sum of elements across dimensions of a tensor cost = tf.reduce_sum(tf.pow(y_ - y, 2))/(2*n_samples) #Gradient descent optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) #initialize variables and tensorflow session init = tf.initialize_all_variables() sess = tf.Session() sess.run(init) #now for the actual running for i in range(training_epochs): sess.run(optimizer, feed_dict={x:inputX, y_:inputY}) if(i)%display_step == 0: cc = sess.run(cost, feed_dict = {x: inputX, y_ :inputY}) print "Training step:", '%04d'% (i), "cost=","{:.9f}".format(cc) print "Optimization Fininshed!" training_cost = sess.run(cost, feed_dict = {x: inputX, y_: inputY}) print "Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b),'\n' sess.run(y, feed_dict = {x:inputX}) sess.run(tf.nn.softmax([1.,2.]))
97fbbd18e3965cd3dbb0a5a5eb52d27e2f290840
why2lyj/Bloxorz
/solver.py
2,055
3.53125
4
# coding=utf-8 from state import State from utility import Direction class Solver: # Simple Depth First Search to calculate time @staticmethod def dfs(state: State): while state.states: player, bridge = state.states.pop() state.load_state(player, bridge) for direction in ['up', 'down', 'left', 'right']: if state.move(direction, False): if state.found: return if state.get_direction(state.player) == Direction.none: state.move('swap', False) # Simple Breadth First Search to calculate time @staticmethod def bfs(state: State): while state.states: player, bridge = state.states.pop(0) state.load_state(player, bridge) for direction in ['up', 'down', 'left', 'right']: if state.move(direction, False): if state.found: return if state.get_direction(state.player) == Direction.none: state.move('swap', False) # Depth First Search with path to visualize @staticmethod def dfs_path(state: State): move_stack = [] while state.states: player, bridge = state.states.pop() move = move_stack.pop() if len(move_stack) > 0 else [] state.load_state(player, bridge) for direction in ['up', 'down', 'left', 'right']: if state.move(direction, False): if state.found: return move + [direction] move_stack.append(move + [direction]) if state.get_direction(state.player) == Direction.none: if state.move('swap', False): move_stack.append(move + ['swap']) # Breadth First Search with path to visualize @staticmethod def bfs_path(state: State): move_queue = [] while state.states: player, bridge = state.states.pop(0) move = move_queue.pop(0) if len(move_queue) > 0 else [] state.load_state(player, bridge) for direction in ['up', 'down', 'left', 'right']: if state.move(direction, False): if state.found: return move + [direction] move_queue.append(move + [direction]) if state.get_direction(state.player) == Direction.none: if state.move('swap', False): move_queue.append(move + ['swap'])
0b43cce63b5e8a71eac3cdf37a1aff2ddcb81088
areebahmad01/TSF
/Task 1(% vs score).py
1,484
3.828125
4
#!/usr/bin/env python # coding: utf-8 # Prediciton using supervised learning by AREEB AHMAD # In[4]: import pandas as pd import numpy as np import matplotlib.pyplot as plt #importing all the libraries # In[5]: link = "http://bit.ly/w-data" dataset = pd.read_csv(link) #storing data from link in dataset # In[6]: dataset.head() #printing first five rows of data # In[7]: #now we will plot a graph from the given data using matplotlib # In[27]: dataset.plot(kind='scatter', x='Hours', y='Scores', color = 'g') # In[43]: x=dataset.iloc[:,0:1] y=dataset.iloc[:,1:2] #dividing values in labels and targets as X and Y respectively # In[48]: from sklearn.linear_model import LinearRegression #importing linear regression model # In[49]: lin_reg=LinearRegression() #assigning object lin_reg for LinearRegression class # In[50]: lin_reg.fit(x,y) #fitting model for x and y # In[53]: yp=lin_reg.predict(x) #predicting values for input x # In[57]: from sklearn.metrics import r2_score r2_score(y,yp) #checking accuracy of model # In[58]: #95 % accurcy # In[59]: x=dataset.iloc[:,0:1] y=dataset.iloc[:,1:2] dataset.plot(kind='scatter', x='Hours', y='Scores', color='b') plt.plot(x,lin_reg.coef_[0]*x+lin_reg.intercept_,color='r') plt.grid() plt.show #plotting the regression line for predictions # In[67]: Hours=9.25 prediction=lin_reg.predict([[Hours]]) print(f"number of hours={Hours}") print(f"Predicted Score={prediction}") # In[ ]:
2294a19efd69e7dffd40b3622665e8060fc719b5
brucekk4/pyefun
/pyefun/encoding/compress/zip.py
2,489
3.703125
4
import os import sys import zipfile # # def rename(pwd: str, filename=''): # """压缩包内部文件有中文名, 解压后出现乱码,进行恢复""" # # path = f'{pwd}/{filename}' # if os.path.isdir(path): # for i in os.scandir(path): # rename(path, i.name) # newname = filename.encode('cp437').decode('gbk') # os.rename(path, f'{pwd}/{newname}') """ zip文件解压缩 https://docs.python.org/zh-cn/3.9/library/zipfile.html?highlight=zipfile# """ import zipfile from pyefun import * import pyefun.commonlyUtil as commonlyUtil @异常处理返回类型逻辑型 def zip解压(压缩包的路径: str, 解压路径: str): file = zipfile.ZipFile(压缩包的路径) if 文件是否存在(解压路径) == False: commonlyUtil.目录_创建(解压路径) file.extractall(解压路径) file.close() @异常处理返回类型逻辑型 def zip压缩(保存压缩包的路径: str, 欲压缩文件或者文件夹: str,mode="w"): pass 保存压缩包的路径 = 路径优化(保存压缩包的路径) 欲压缩文件或者文件夹 = 路径优化(欲压缩文件或者文件夹) 路径字符长度 = 取文本长度(欲压缩文件或者文件夹) if 文件_是否为文件(欲压缩文件或者文件夹): with zipfile.ZipFile(保存压缩包的路径, mode=mode) as target: target.write(欲压缩文件或者文件夹, 文件_取文件名(欲压缩文件或者文件夹)) return True if 文件_是否为目录(欲压缩文件或者文件夹): with zipfile.ZipFile(保存压缩包的路径, mode=mode) as target: 压缩文件列表 = [] for 路径信息 in os.walk(欲压缩文件或者文件夹): for 文件名 in 路径信息[2]: 目录 = 路径信息[0] 文件路径 = 路径_合并(目录, 文件名) 相对路径 = 取文本右边(文件路径, 取文本长度(文件路径) - 路径字符长度) if(文件路径 == 保存压缩包的路径): continue # 防止死循环一直压缩 压缩文件列表.append([文件路径,相对路径]) # 开始压缩 for item in 压缩文件列表: 文件路径 = item[0] 相对路径 = item[1] target.write(文件路径, 相对路径) return True
42a863830825b7fb5f483af75e1185ec5335d483
ZYZhang2016/think--Python
/chapter04/Exercise4.3.5.py
585
3.9375
4
#coding: utf-8 from swampy.TurtleWorld import * import math world = TurtleWorld() def polyline(t,n,length,angle):#t:turtle;n:n边正多边型 print t for i in range(n): fd(t,length) lt(t,angle) def polygon(t,n,length): angle = 360.0/n polyline(t,n,length,angle) def arc(t,r,angle):#t:turtle;r:r半径;angle:圆弧的角度 circumference = 2*math.pi*r arc_length = circumference*angle/360 n = int(arc_length/3)+1 step_length = arc_length/n step_angle = float(angle)/n polyline(t, n, step_length, step_angle) bob=Turtle() bob.delay=0.01 arc(bob,100,90 ) wait_for_user()
82fc9f064a6c678d581bde28d542b40d82f9383d
pjjefferies/python_practice
/binary_matrix_ops_elder_add.py
874
3.515625
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 19 23:14:52 2019 @author: PaulJ """ import unittest def elder_age(m, n, l, t): pass class TestMethods(unittest.TestCase): tests = {(8, 5, 1, 100): 5, (8, 8, 0, 100007): 224, (25, 31, 0, 100007): 11925, (5, 45, 3, 1000007): 4323, (28827050410, 35165045587, 7109602, 13719506): 5456283} def test_basic(self): for params in self.tests: answer = self.tests[params] result = elder_age(*params) if result != answer: print('\nwrong: params:', params, ', answer:', answer, ', result:', result) else: print('\ncorrect!') pass self.assertEqual(result, answer) if __name__ == '__main__': unittest.main() """ Result: """
8e76d3338294614422df04814ba4eb04ff7789f5
amalphonse/Python_WorkBook
/37.py
626
4.15625
4
# -*- coding: utf-8 -*- """ Created on Fri Feb 17 16:39:38 2017 @author: ANju """ #Create a function that takes a text file as input and returns the number of words #contained in the text file. Please take into consideration that some words can #be separated by a comma with no space. For example "Hi,it's me." would need #to be counted as three words. For your convenience, you can use the text #file in the attachment. import re def count_words(filepath): with open(filepath,'r') as f: strng = f.read() strng = re.split(",| ",strng) return len(strng) print(count_words('words2.txt'))
6b94f445f427dcd3005a3ec2a3c912e297a70ac1
ibrahimuslu/udacity-p1
/problem_1.py
7,185
3.671875
4
class DoubleNode: def __init__(self, key,value): self.value = value self.key = key self.next = None self.previous = None class DoublyLinkedList: def __init__(self): self.head = None self.tail = None def append(self, value): if self.head is None: self.head = DoubleNode(value) self.tail = self.head return self.tail.next = DoubleNode(value) self.tail.next.previous = self.tail self.tail = self.tail.next return def remove(self,node): if(node.next != None): node.next.previous = node.previous else: self.tail = node.previous if(node.previous!=None): node.previous.next = node.next else: self.head = node.next def pushTop(self,node): node.previous = None node.next = self.head if(self.head != None): self.head.previous = node self.head = node if( self.tail == None): self.tail = self.head class LinkedListNode: def __init__(self, key, value): self.key = key self.value = value self.next = None class HashMap: def __init__(self, initial_size = 15): self.bucket_array = [None for _ in range(initial_size)] self.p = 31 self.num_entries = 0 self.load_factor = 0.7 def put(self, key, value): bucket_index = self.get_bucket_index(key) new_node = LinkedListNode(key, value) head = self.bucket_array[bucket_index] # check if key is already present in the map, and update it's value while head is not None: if head.key == key: head.value = value return head = head.next # key not found in the chain --> create a new entry and place it at the head of the chain head = self.bucket_array[bucket_index] new_node.next = head self.bucket_array[bucket_index] = new_node self.num_entries += 1 # check for load factor current_load_factor = self.num_entries / len(self.bucket_array) if current_load_factor > self.load_factor: self.num_entries = 0 self._rehash() def get(self, key): bucket_index = self.get_hash_code(key) head = self.bucket_array[bucket_index] while head is not None: if head.key == key: return head.value head = head.next return None def get_bucket_index(self, key): bucket_index = self.get_hash_code(key) return bucket_index def get_hash_code(self, key): key = str(key) num_buckets = len(self.bucket_array) current_coefficient = 1 hash_code = 0 for character in key: hash_code += ord(character) * current_coefficient hash_code = hash_code % num_buckets # compress hash_code current_coefficient *= self.p current_coefficient = current_coefficient % num_buckets # compress coefficient return hash_code % num_buckets # one last compression before returning def size(self): return self.num_entries def _rehash(self): old_num_buckets = len(self.bucket_array) old_bucket_array = self.bucket_array num_buckets = 2 * old_num_buckets self.bucket_array = [None for _ in range(num_buckets)] for head in old_bucket_array: while head is not None: key = head.key value = head.value self.put(key, value) # we can use our put() method to rehash head = head.next def delete(self, key): bucket_index = self.get_bucket_index(key) head = self.bucket_array[bucket_index] previous = None while head is not None: if head.key == key: if previous is None: self.bucket_array[bucket_index] = head.next else: previous.next = head.next self.num_entries -= 1 return else: previous = head head = head.next class LRU_Cache(object): def __init__(self, capacity): # Initialize class variables self.cache_memory = HashMap(capacity) self.leastRecent = DoublyLinkedList() self.num_entries = 0 self.capacity = capacity def get(self, key): returnNode = self.cache_memory.get(key) if(returnNode != None): self.leastRecent.remove(returnNode) self.leastRecent.pushTop(returnNode) return returnNode.value return -1 def set(self,key,value): newNode = self.cache_memory.get(key) if(newNode == None): newNode = DoubleNode(key,value) # print("capacity ",self.capacity) if(self.num_entries < self.capacity): self.leastRecent.pushTop(newNode) # print(self.leastRecent.tail.key) else: # print('delete') # print(self.leastRecent.tail.key) self.cache_memory.delete(self.leastRecent.tail.key) self.num_entries-=1 self.leastRecent.remove(self.leastRecent.tail) self.leastRecent.pushTop(newNode) self.cache_memory.put(key,newNode) self.num_entries+=1 # print("num_entries",self.num_entries); ## First test case our_cache = LRU_Cache(5) # print("num_entries",our_cache.num_entries); our_cache.set(1, 1) our_cache.set(2, 2) our_cache.set(3, 3) our_cache.set(4, 4) print(our_cache.get(1)) # returns 1 print(our_cache.get(2) ) # returns 2 print(our_cache.get(9) ) # returns -1 because 9 is not present in the cache our_cache.set(5, 5) our_cache.set(6, 6) print(our_cache.get(3)) # returns -1 because the cache reached it's capacity and 3 was the least recently used entry ## Second test case second_cache = LRU_Cache(1000) # print("num_entries",our_cache.num_entries); for i in range(1000): second_cache.set(i, i) print(second_cache.get(1)) # returns 1 print(second_cache.get(202) ) # returns 2 print(second_cache.get(1002) ) # returns -1 because 9 is not present in the cache second_cache.set(123, 523) second_cache.set(1001, 123) print(second_cache.get(2)) # returns -1 because the cache reached it's capacity and 2 was the least recently used entry ## Third test case third_cache = LRU_Cache(10000) # print("num_entries",our_cache.num_entries); for i in range(10000): third_cache.set(i, i) print(third_cache.get(1)) # returns 1 print(third_cache.get(2022) ) # returns 2 print(third_cache.get(10002) ) # returns -1 because 9 is not present in the cache third_cache.set(123, 5233) third_cache.set(10001, 1231) print(our_cache.get(3)) # returns -1 because the cache reached it's capacity and 2 was the least recently used entry
d2428c07892bdac82d32af9b898579f8cee60c4b
xizhang77/LeetCode
/UnionFind/128-longest-consecutive-sequence.py
1,645
3.796875
4
# -*- coding: utf-8 -*- ''' Given an unsorted array of integers, find the length of the longest consecutive elements sequence. Your algorithm should run in O(n) complexity. Example: Input: [100, 4, 200, 1, 3, 2] Output: 4 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. ''' class Solution(object): def longestConsecutive(self, nums): """ :type nums: List[int] :rtype: int """ hashMap = {} ans = 0 for num in nums: if num in hashMap: continue start = end = num if num - 1 in hashMap: start = hashMap[ num-1 ][0] if num + 1 in hashMap: end = hashMap[ num+1 ][1] hashMap[ start ] = hashMap[ end ] = hashMap[ num ] = [ start, end ] ans = max(ans, end - start + 1) return ans # Both of the solutions are inspired by Union Find class Solution(object): def longestConsecutive(self, nums): """ :type nums: List[int] :rtype: int """ hashmap = {} for num in nums: hashmap[ num ] = num ans = 0 for num in nums: temp = num while temp - 1 in hashmap and hashmap[ temp ] != hashmap[ temp - 1]: temp -= 1 for val in range( temp, num + 1): hashmap[ val ] = hashmap[ temp ] ans = max( ans, num - hashmap[ temp ] + 1 ) return ans
09d36035423e0d7ef57b798e8bb86548dbd873b2
AvishaSharma23/Hacktoberfest21
/Palindrome_Number.py
447
3.90625
4
class Solution: def isPalindrome(self, x) -> bool: reversed = 0 original = x if(x<0): return False while (x>0): reversed = reversed*10 + x % 10 x = x // 10 if(reversed == original): return True else: return False def main(): x = int(input()) print(Solution().isPalindrome(x)) if __name__ == "__main__": main()
696d042bc97125a643ab2c2e3553da01f5c4afe9
msahu2595/PYTHON_3
/193_16_class_variable.py
917
3.90625
4
# # class variable # # circle # # area # # circum # class Circle: # pi = 3.14 # def __init__(self, radius): # self.radius = radius # def calc_circumfrence(self): # return 2*Circle.pi*self.radius # c1 = Circle(4) # c2 = Circle(5) # print(c1.calc_circumfrence()) class Laptop: discount_percent = 10 def __init__(self, brand_name, model_name, price): # instance variable self.com_brand_name = brand_name self.com_model_name = model_name self.com_price = price self.com_laptop_name = brand_name + " " + model_name def apply_discount(self): return self.com_price-((self.com_price/100)*Laptop.discount_percent) l1 = Laptop('asus', 'lf5005', 33000) l2 = Laptop("hp", 'hs990', 35000) l3 = Laptop('lenovo', 'la632526', 28000) print(l1.apply_discount()) print(l2.apply_discount()) print(l3.apply_discount())
5ce9b893c674db26feb6e71c124f2a029d67aabf
tnotstar/tnotbox
/Python/Learn/LPTHW/ex11_dr03.py
198
3.859375
4
name = input("What's your name? ") salary = input("What's your current salary? ") company = input("Where do you work? ") print(f"Hello, I'm {name}, currently I work at {company} earning {salary}.")
c419e1a011594dd46eab4ba82d826a869241f985
hosmanadam/coding-challenges
/@HackerRank/Problem Solving/20_circular-array-rotation/main.py
224
3.546875
4
"""https://www.hackerrank.com/challenges/circular-array-rotation/problem""" def circularArrayRotation(a, k, queries): a_rotated = [a[i - (k % len(a))] for i in range(len(a))] return [a_rotated[i] for i in queries]
b5deecc7d00f598cb5d15d951fcb9aef488ca90b
arnoringi/forritun
/Assignment 3 (While loops)/3_2) First n even numbers.py
177
4.09375
4
num = int(input("Input an int: ")) # Do not change this line count = 0 even = 0 # Fill in the missing code below while count < num: even += 2 count += 1 print(even)
300cf7eb84977f3133e687ce4876e59b6511a515
FantasyEngineer/pythonProject
/输入与输出.py
1,062
3.890625
4
import math s = 'Hello, Runoob' print(str(s)) print(s.__repr__()) # rjust是右对齐 # for x in range(1, 11): # print(repr(x).rjust(2), repr(x * x).rjust(3), end=' ') # print(repr(x * x * x).rjust(4))® # for x in range(1, 111): # print('{0:2d} {1:3d} {2:4d}'.format(x, x * x, x * x * x)) print('{}网址: "{}!"'.format('菜鸟教程', 'www.runoob.com')) print('{0} 和 {1}'.format('Google', 'Runoob')) print('{1} 和 {0}'.format('Google', 'Runoob')) print('{name}网址: {site}'.format(name='菜鸟教程', site='www.runoob.com')) print('站点列表 {0}, {1}, 和 {other}。'.format('Google', 'Runoob', other='Taobao')) print('常量 PI 的值近似为: {}。'.format(math.pi)) print(max([1, 2, 3, 4])) print('常量 PI 的值近似为: {!r}。'.format(math.pi)) print('常量 PI 的值近似为 {0:.3f}。'.format(math.pi)) table = {'Google': 1, 'Runoob': 2, 'Taobao': 3} for name, number in table.items(): print('{0:10} ==> {1:10d}'.format(name, number)) str = input("请输入:"); print("你输入的内容是: ", str)
c01c69f9d7c65db5d5e00125f944f2119c8efaf7
Tiezzi96/SlidingPuzzle
/main.py
24,024
3.890625
4
from __future__ import print_function from __future__ import generators import sys import time import os import psutil from copy import deepcopy import random import bisect import pickle infinity = 1.0e400 def update(x, **entries): """Update a dict; or an object with slots; according to entries. >>> update({'a': 1}, a=10, b=20) {'a': 10, 'b': 20} >>> update(Struct(a=1), a=10, b=20) Struct(a=10, b=20) """ if isinstance(x, dict): x.update(entries) else: x.__dict__.update(entries) return x class Problem: """The abstract class for a formal problem. You should subclass this and implement the method successor, and possibly __init__, goal_test, and path_cost. Then you will create instances of your subclass and solve them with the various search functions.""" def __init__(self, initial, goal=None): """The constructor specifies the initial state, and possibly a goal state, if there is a unique goal. Your subclass's constructor can add other arguments.""" self.initial = initial self.goal = goal def successor(self, state): """Given a state, return a sequence of (action, state) pairs reachable from this state. If there are many successors, consider an iterator that yields the successors one at a time, rather than building them all at once. Iterators will work fine within the framework.""" pass # abstract def goal_test(self, state): """Return True if the state is a goal. The default method compares the state to self.goal, as specified in the constructor. Implement this method if checking against a single self.goal is not enough.""" return state == self.goal def path_cost(self, c, state1, action, state2): """Return the cost of a solution path that arrives at state2 from state1 via action, assuming cost c to get up to state1. If the problem is such that the path doesn't matter, this function will only look at state2. If the path does matter, it will consider c and maybe state1 and action. The default method costs 1 for every step in the path.""" return c + 1 class Node: """A node in a search tree. Contains a pointer to the parent (the node that this is a successor of) and to the actual state for this node. Note that if a state is arrived at by two paths, then there are two nodes with the same state. Also includes the action that got us to this state, and the total path_cost (also known as g) to reach the node. Other functions may add an f and h value; see best_first_graph_search and astar_search for an explanation of how the f and h values are handled. You will not need to subclass this class.""" def __init__(self, state, parent=None, action=None, path_cost=0): "Create a search tree Node, derived from a parent by an action." update(self, state=state, parent=parent, action=action, path_cost=path_cost, depth=0) if parent: self.depth = parent.depth + 1 self.cammino=0 self.camminoimp=0 def __repr__(self): """(pf) Modified to display depth, f and h""" if hasattr(self,'f'): return "<Node: f=%d, depth=%d, h=%d\n%s>" % (self.f, self.depth, self.h, self.state) else: return "<Node: depth=%d\n%s>" % (self.depth,self.state) def path(self): "Create a list of nodes from the root to this node." x, result = self, [self] while x.parent: result.append(x.parent) x = x.parent self.cammino+=1 self.camminoimp+=x.state.hu return result def expand(self, problem): "Return a list of nodes reachable from this node. [Fig. 3.8]" return [Node(next_state, self, action, problem.path_cost(self.path_cost, self.state, action, next_state)) for (action, next_state) in problem.successor(self.state)] class PuzzleState: """ The board is NxN so use N=4 for the 15-puzzle, N=5 for the 24-puzzle, etc The state of the puzzle is simply a permutation of 0..N-1 The position of the blank (element zero) is stored in r,c """ def __init__(self,board,N,r,c): self.board=board self.r=r self.c=c self.N = N self.hu = 0 def __getitem__(self,(r,c)): return self.board[r*self.N+c] def __setitem__(self,(r,c),val): self.board[r*self.N+c]=val def move(self,direction): ch=deepcopy(self) c,r = ch.c,ch.r if direction == 'left' and self.c != 0: ch[(r,c)], ch[(r,c-1)] = self[(r,c-1)],self[(r,c)] ch.c = c-1 elif direction == 'right' and c != self.N-1: ch[(r,c)],ch[(r,c+1)] = self[(r,c+1)],self[(r,c)] ch.c = c+1 elif direction == 'up' and self.r != 0: ch[(r,c)],ch[(r-1,c)] = self[(r-1,c)],self[(r,c)] ch.r = r-1 elif direction == 'down' and r != self.N-1: ch[(r,c)],ch[(r+1,c)] = self[(r+1,c)],self[(r,c)] ch.r = r+1 else: return None return ch def misplaced(self): """Misplaced tiles heuristic""" blank = self.r*self.N+self.c return sum([idx!=val for idx,val in enumerate(self.board) if idx!=blank]) def lcheuristic(self): m = self.manhattan() m += self.LCH() m += (self.LCV()) return m def potlch(self): a = range(16) listup = [] listdown = [] for j in range(self.N): for i in range(self.N): l = [] l1 = [] d = i u = i while u != 3: u += 1 if a[j * self.N + u] is not 0: l.append(a[j * self.N + u]) while d != 0: d -= 1 if a[j * self.N + d] is not 0: l1.append(a[j * self.N + d]) listup.append(l) listdown.append(l1) return (listup, listdown) def potlcv(self): a = range(16) listup = [] listdown = [] for i in range(self.N): for j in range(self.N): l = [] l1 = [] d = j u = j while u != 3: u += 1 if a[u * self.N + i] is not 0: l.append(a[u * self.N + i]) while d != 0: d -= 1 if a[d * self.N + i] is not 0: l1.append(a[d * self.N + i]) listup.append(l) listdown.append(l1) return (listup, listdown) def LCH(self): linearconflict = 0 listup, listdown = self.potlch() for j in range(self.N): for i in range(self.N): if self[(j,i)] != 0: k=i u=i casella=self[[j,i]] while k != 3: k += 1 for l in range(len(listdown[self[(j,i)]])): if self[(j,k)]==listdown[self[(j,i)]][l] and j is (self[(j,i)]//4): linearconflict+=1 while u != 0: u -= 1 for l in range(len(listup[self[(j,i)]])): if self[(j, u)] == listup[self[(j,i)]][l] and j is (self[(j,i)]//4): linearconflict += 1 return linearconflict def LCV(self): linearconflict = 0 listup, listdown = self.potlcv() for j in range(self.N): for i in range(self.N): if self[(i,j)] != 0: k=i u=i a=range(16) col=-1 row=-1 for n in range(self.N): for m in range(self.N): if a[m*self.N+n] is self[(i,j)]: col=n row=m while k != 3: k += 1 for l in range(len(listdown[col*self.N +row])): if self[(k,j)]==listdown[col*self.N +row][l] and j is (self[(i,j)] % 4): linearconflict+=1 while u != 0: u -= 1 for l in range(len(listup[col*self.N +row])): if self[(u, j)] == listup[col*self.N +row][l] and j is (self[(i,j)] % 4): linearconflict += 1 return linearconflict def manhattan(self): """Manhattan distance heuristic""" m=0 blank = self.r*self.N+self.c for index,value in enumerate(self.board): if index != blank and index != value: r = index // self.N c = index % self.N rr = value // self.N cc = value % self.N # print('misplaced',value,rr,r,cc,c) m += abs(r-rr) + abs(c-cc) assert(m>=0) return m def __str__(self): # forza un dato ad essere una stringa """Serialize the state in a human-readable form""" s = '' for r in xrange(self.N): for c in xrange(self.N): if self[(r,c)]>0: s += '%3d' % self[(r,c)] else: s += ' ' s += '\n' return s def __repr__(self): return self.__str__() class Puzzle(Problem): """Base class - For 8-puzzle use Puzzle(3) -- a 3x3 grid""" def __init__(self, N, seed,scrambles=10): self.N = N self.actions = ['left','right','up','down'] self.make_initial_state(seed,scrambles) self.dict1 = {} self.dict2 = {} self.dict3 = {} self.dict4 = {} self.dict5 = {} self.dict6 = {} def make_initial_state(self,seed,scrambles): """ To ensure a solution exists, start from the goal and scramble it applying a random sequence of actions. An alternative is to use the permutation parity property of the puzzle but using the scrambling we can roughly control the depth of the solution and thus limit CPU time for demonstration """ seen = {} ns=0 x = range(self.N*self.N) for r in range(self.N): for c in range(self.N): if x[r*self.N+c]==0: row,col=r,c self.initial = PuzzleState(x,self.N,row,col) R = random.Random() R.seed(seed) while ns<scrambles: index = R.randint(0,len(self.actions)-1) a = self.actions[index] nexts = self.initial.move(a) if nexts is not None: serial = nexts.__str__() if serial not in seen: seen[serial] = True self.initial = nexts ns += 1 print('Problem:', self.__doc__, 'Initial state:') print(self.initial) print('==============') def successor(self, state): """Legal moves (blank moves left, right, up, down). Implemented as a generator""" for action in self.actions: nexts = state.move(action) if nexts is not None: yield (action,nexts) def goal_test(self, state): """For simplicity blank on top left""" return state.board==range(self.N*self.N) def h(self,node): """No heuristic. A* becomes uniform cost in this case""" return 0 def graph_search(problem, fringe): """Search through the successors of a problem to find a goal. The argument fringe should be an empty queue. If two paths reach a state, only use the best one. [Fig. 3.18]""" counter = 0 closed = {} fringe.append(Node(problem.initial)) max_depth=0 while fringe: node = fringe.pop() # Print some information about search progress if node.depth>max_depth: max_depth=node.depth if max_depth<50 or max_depth % 1000 == 0: pid = os.getpid() py = psutil.Process(pid) memoryUse = py.memory_info()[0]/1024/1024 print('Reached depth',max_depth, 'Open len', len(fringe), 'Node expanse', counter, 'Memory used (MBytes)', memoryUse) if problem.goal_test(node.state): return node, counter serial = node.state.__str__() if serial not in closed: counter += 1 closed[serial] = True fringe.extend(node.expand(problem)) return None def best_first_graph_search(problem, f): """Search the nodes with the lowest f scores first. You specify the function f(node) that you want to minimize; for example, if f is a heuristic estimate to the goal, then we have greedy best first search; if f is node.depth then we have depth-first search. There is a subtlety: the line "f = memoize(f, 'f')" means that the f values will be cached on the nodes as they are computed. So after doing a best first search you can examine the f values of the path returned.""" f = memoize(f, 'f') return graph_search(problem, PriorityQueue(min, f)) def astar_search(problem, h=None): """A* search is best-first graph search with f(n) = g(n)+h(n). You need to specify the h function when you call astar_search. Uses the pathmax trick: f(n) = max(f(n), g(n)+h(n)).""" h = h or problem.h h = memoize(h, 'h') def f(n): return max(getattr(n, 'f', -infinity), n.path_cost + h(n)) return best_first_graph_search(problem, f) def memoize(fn, slot=None): """Memoize fn: make it remember the computed value for any argument list. If slot is specified, store result in that slot of first argument. If slot is false, store results in a dictionary.""" if slot: def memoized_fn(obj, *args): if hasattr(obj, slot): return getattr(obj, slot) else: val = fn(obj, *args) setattr(obj, slot, val) return val else: def memoized_fn(*args): if not memoized_fn.cache.has_key(args): memoized_fn.cache[args] = fn(*args) return memoized_fn.cache[args] memoized_fn.cache = {} return memoized_fn class Queue: """Queue is an abstract class/interface. There are three types: Stack(): A Last In First Out Queue. FIFOQueue(): A First In First Out Queue. PriorityQueue(lt): Queue where items are sorted by lt, (default <). Each type supports the following methods and functions: q.append(item) -- add an item to the queue q.extend(items) -- equivalent to: for item in items: q.append(item) q.pop() -- return the top item from the queue len(q) -- number of items in q (also q.__len()) Note that isinstance(Stack(), Queue) is false, because we implement stacks as lists. If Python ever gets interfaces, Queue will be an interface.""" def __init__(self): abstract def extend(self, items): for item in items: self.append(item) class PriorityQueue(Queue): """A queue in which the minimum (or maximum) element (as determined by f and order) is returned first. If order is min, the item with minimum f(x) is returned first; if order is max, then it is the item with maximum f(x).""" def __init__(self, order=min, f=lambda x: x): update(self, A=[], order=order, f=f) def append(self, item): bisect.insort(self.A, (self.f(item), item)) def __len__(self): return len(self.A) def pop(self): if self.order == min: return self.A.pop(0)[1] elif self.order is max: return self.A.pop(len(self.A)-1)[1] else: return self.A.pop()[1] def fmin(self): return self.A[0][0] class PuzzleManhattan(Puzzle): """Manhattan heuristic""" def h(self, node): return node.state.manhattan() class PuzzleLinearConflict(Puzzle): def h(self, node): return node.state.lcheuristic() class PuzzleDPreflected(Puzzle): def disjointpattern(self): dict1=pickle.load(open('DP1-2-3-new.p', 'rb')) print('scaricato file DP1-2-3-new.p: ', len(dict1)) dict2 = pickle.load(open('DP4-5-8-9-12-13-new.p', 'rb')) print('scaricato file DP4-5-8-12-13-new.p: ', len(dict2)) dict3 = pickle.load(open('DP6-7-10-11-14-15-new.p', 'rb')) print('scaricato file DP6-7-10-11-14-15-new.p: ', len(dict3)) dict4 = pickle.load(open('DP4-8-12-new.p', 'rb')) print('scaricato file DP4-8-12-new.p: ', len(dict4)) dict5 = pickle.load(open('DP1-2-3-5-6-7-new.p', 'rb')) print('scaricato file DP1-2-3-5-6-7-new.p: ', len(dict5)) dict6 = pickle.load(open('DP9-10-11-13-14-15-new.p', 'rb')) print('scaricato file DP9-10-11-13-14-15-new.p: ', len(dict6)) self.dict1 = dict1 self.dict2 = dict2 self.dict3 = dict3 self.dict4 = dict4 self.dict5 = dict5 self.dict6 = dict6 def h(self, node): board = node.state.board board1 = [] board2 = [] board3 = [] board4 = [] board5 = [] board6 = [] list1 = [] list2 = [] list3 = [] list4 = [] list5 = [] list6 = [] for p in range(len(board)): if board[p] is 1 or board[p] is 2 or board[p] is 3: list = [] list.append(board[p]) list.append(p) list1.append(list) if board[p] is 4 or board[p] is 5 or board[p] is 8 or board[p] is 9 or board[p] is 12 or board[p] is 13: list = [] list.append(board[p]) list.append(p) list2.append(list) if board[p] is 6 or board[p] is 7 or board[p] is 10 or board[p] is 11 or board[p] is 14 or board[p] is 15: list = [] list.append(board[p]) list.append(p) list3.append(list) if board[p] is 4 or board[p] is 8 or board[p] is 12: list = [] list.append(board[p]) list.append(p) list4.append(list) if board[p] is 1 or board[p] is 2 or board[p] is 3 or board[p] is 5 or board[p] is 6 or board[p] is 7: list = [] list.append(board[p]) list.append(p) list5.append(list) if board[p] is 9 or board[p] is 10 or board[p] is 11 or board[p] is 13 or board[p] is 14 or board[p] is 15: list = [] list.append(board[p]) list.append(p) list6.append(list) list1.sort() list2.sort() list3.sort() list4.sort() list5.sort() list6.sort() for p in range(len(list1)): e = list1[p][1] e1 = list4[p][1] row = e // 4 + 1 row1 = e1 // 4 + 1 board1.append(row) board4.append(row1) col = e % 4 + 1 col1 = e1 % 4 + 1 board1.append(col) board4.append(col1) for p in range(len(list2)): e = list2[p][1] e1= list3[p][1] e2 = list5[p][1] e3 = list6[p][1] row = e // 4 + 1 row1 = e1 // 4 + 1 row2 = e2 // 4 + 1 row3 = e3 // 4 + 1 board2.append(row) board3.append(row1) board5.append(row2) board6.append(row3) col = e % 4 + 1 col1 = e1 % 4 + 1 col2 = e2 % 4 + 1 col3 = e3 % 4 + 1 board2.append(col) board3.append(col1) board5.append(col2) board6.append(col3) board1 = map(str,board1) board1 = ''.join(board1) board1 = int(board1) board2 = map(str, board2) board2 = ''.join(board2) board2 = int(board2) board3 = map(str, board3) board3 = ''.join(board3) board3 = int(board3) board4 = map(str, board4) board4 = ''.join(board4) board4 = int(board4) board5 = map(str, board5) board5 = ''.join(board5) board5 = int(board5) board6 = map(str, board6) board6 = ''.join(board6) board6 = int(board6) h1 = self.dict1[board1] h2 = self.dict2[board2] h3 = self.dict3[board3] h4 = self.dict4[board4] h5 = self.dict5[board5] h6 = self.dict6[board6] hfirst = h1+h2+h3 hsecond = h4+h5+h6 h = max(hfirst, hsecond) return h class PuzzleDP(Puzzle): def disjointpattern(self): dict1 = pickle.load(open('DP1-2-3-new.p', 'rb')) print('scaricato file DP1-2-3-new.p: ', len(dict1)) dict2 = pickle.load(open('DP4-5-8-9-12-13-new.p', 'rb')) print('scaricato file DP4-5-8-9-12-13-new.p: ', len(dict2)) dict3 = pickle.load(open('DP6-7-10-11-14-15-new.p', 'rb')) print('scaricato file DP6-7-10-11-14-15-new.p: ', len(dict3)) self.dict1 = dict1 self.dict2 = dict2 self.dict3 = dict3 def h(self, node): board = node.state.board board1 = [] board2 = [] board3 = [] list1=[] list2= [] list3 = [] for p in range(len(board)): if board[p] is 1 or board[p] is 2 or board[p] is 3: list = [] list.append(board[p]) list.append(p) list1.append(list) if board[p] is 4 or board[p] is 5 or board[p] is 8 or board[p] is 9 or board[p] is 12 or board[p] is 13: list = [] list.append(board[p]) list.append(p) list2.append(list) if board[p] is 6 or board[p] is 7 or board[p] is 10 or board[p] is 11 or board[p] is 14 or board[p] is 15: list = [] list.append(board[p]) list.append(p) list3.append(list) list1.sort() list2.sort() list3.sort() for p in range(len(list1)): e = list1[p][1] row = e // 4 + 1 board1.append(row) col = e % 4 + 1 board1.append(col) for p in range(len(list2)): e = list2[p][1] e1= list3[p][1] row = e // 4 + 1 row1 = e1 // 4 + 1 board2.append(row) board3.append(row1) col = e % 4 + 1 col1 = e1 % 4 + 1 board2.append(col) board3.append(col1) board1 = map(str,board1) board1 = ''.join(board1) board1 = int(board1) board2 = map(str, board2) board2 = ''.join(board2) board2 = int(board2) board3 = map(str, board3) board3 = ''.join(board3) board3 = int(board3) h1 = self.dict1[board1] h2 = self.dict2[board2] h3 = self.dict3[board3] h = h1+h2+h3 return h
90c4df64b45d0a11a27e493dbf166c8e3c96b887
JorgeChaparroS/PythonBasics
/3. Estructuras de Control/fizzbuzz2.py
196
3.921875
4
numero = int(input("Ingrese un número: ")) salida = "" if numero % 3 == 0: salida += "Fizz" if numero % 5 == 0: salida += "Buzz" if salida == "": salida = str(numero) print(salida)
71f77ff4bf6361d92260720a4e60967f82783592
ZU3AIR/DCU
/Year2/ca268Labs/Sorting/merge/QueueBasedMergesort.py
427
4.0625
4
from Queue import Queue def split(q): """ A split function which will split a queue into two. The function returns a tuple containing the two queues. """ que1 = len(q) que2 = len(q) que3 = len(q) Q = Queue() Q2 = Queue() for i in range(len(q)): if i % 2: Q.enqueue(q.dequeue()) else: Q2.enqueue(q.dequeue()) return Q, Q2
6e8084c443a861fde75949190aa8ba2f9893f714
WesWang93/Python
/Projects/Card_Game/test_card.py
2,364
4.125
4
''' Test for Card class in card.py ''' import pytest from card import Card def test_inputs(): ''' Test different formats of suit and rank of same card to see if they are still equal ''' spade_ace_a = Card("Spade", "A") spade_ace_b = Card("SPADE", "a") assert spade_ace_a == spade_ace_b club_three_a = Card("Club", 3) club_three_b = Card("club", "3") club_three_c = Card("Club", "three") assert club_three_a == club_three_b == club_three_c def test_print(): ''' Test different formats of suit and rank of same card to check if print() will still output the same result ''' output = "Ten of Spades" spade_ten_1 = Card("Spade", "ten") spade_ten_2 = Card("spAde", "10") spade_ten_3 = Card("SPADE", 10) assert str(spade_ten_1) == output assert str(spade_ten_2) == output assert str(spade_ten_3) == output def test_attr(): ''' Test rank and suit attributes rank will return the value of the card (Ace being 14) suit will return a number based on hierarchy Club - 1, Diamond - 2, Heart - 3, Spade - 4 ''' heart_queen = Card("Heart", "Q") assert heart_queen.rank == 12 assert heart_queen.suit == 3 diam_six = Card("Diamond", 6) assert diam_six.rank == 6 assert diam_six.suit == 2 def test_comparison(): ''' Test comparison of two card objects based on suit and rank ''' spade_king = Card("Spade", "K") club_king = Card("Club", "K") assert (spade_king == club_king) is False assert (spade_king != club_king) is True assert (spade_king > club_king) is True assert (spade_king >= club_king) is True assert (spade_king < club_king) is False assert (spade_king <= club_king) is False def test_sort(): ''' Test if the card objects are sortable based on suit and rank ''' club_five = Card("Club", 5) spade_seven = Card("Spade", 7) heart_jack = Card("Heart", "J") club_queen = Card("Club", "Q") diamond_ace = Card("Diamond", "A") spade_ace = Card("Spade", "A") deck = sorted([heart_jack, spade_ace, club_five, diamond_ace, club_queen, spade_seven]) assert deck[0] == club_five assert deck[1] == spade_seven assert deck[2] == heart_jack assert deck[3] == club_queen assert deck[4] == diamond_ace assert deck[5] == spade_ace
913c438bd6441bda67259a24e00ef6dc25001382
coprobo/DaftCode_Python
/zajęcia nr 4/zadanie domowe nr 4/Zad2.py
2,053
4.0625
4
# Chcemy napisać sprawdzarkę do testu znajomości stolic europejskich. # Format listy stolic taki jak w pliku stolice.csv # Format pytań taki jak w pliku pytania.csv # Format odpowiedzi taki jak w pliku odpowiedzi.csv # Napisz funkcję check_homework, która przyjmuje trzy argumenty: # - capitals_csv to ścieżka do pliku, który zawiera listę stolic europejskich # - questions_csv to ścieżka pliku csv, który zawiera pytania # - answers_csv to ścieżka pliku, który zawiera odpowiedzi # Funkcja zwraca liczbę poprawnych odpowiedzi import csv def check_homework(capitals_csv, questions_csv, answers_csv): with open(capitals_csv, 'r') as stolice, open(questions_csv, 'r') as pytania, open(answers_csv, 'r') as odpowiedzi: reader_answers = csv.reader(odpowiedzi, delimiter=';') reader_questions = csv.reader(pytania, delimiter=';') reader_capitals = csv.reader(stolice, delimiter=';') next(reader_capitals) next(reader_questions) next(reader_answers) questions = [] answers = [] capitals =[] for row in reader_answers: #print(row) answers.append(*row) for row2 in reader_questions: questions.append(row2) for row3 in reader_capitals: capitals.append(row3) # print(answers) # print(questions) # print(capitals) temp = 0 kraje_stolice ={} for i in capitals: kraje_stolice[capitals[temp][0]] = capitals[temp][1] temp = temp + 1 i = 0 poprawne_odp = 0 for odp in answers: if odp =='A': j = 1 elif odp =='B': j = 2 elif odp =='C': j = 3 elif odp =='D': j = 4 kraj = questions[i][0] stolica = questions[i][j] i = i + 1 if kraje_stolice[kraj] == stolica: poprawne_odp = poprawne_odp + 1 return poprawne_odp check_homework('stolice.csv', 'pytania.csv', 'odpowiedzi.csv') assert check_homework('stolice.csv', 'pytania.csv', 'odpowiedzi.csv') == 7
d09bb3ab9831a60344e749753ba6b0b5d66e11ec
sodri126/hackerrank
/print_bilangan_triangle.py
273
3.6875
4
import sys if __name__ == "__main__": n = int(input()) + 1 for i in range(0, n): cal = n - i for j in range(0, cal): print(end=' ') for k in range(0, i): print(k+1, end=' ') print() # create triangle numer
c68b06a717574572326373c4fd06c9f2c9a9e986
SpikyClip/rosalind-solutions
/bioinformatics_textbook_track/BA1M_implement_NumberToPattern.py
673
4.09375
4
def number_to_pattern(index,pattern_len): '''Converts an index number for k-mer of giving length to its corresponding pattern''' pattern = '' letter_value = {0: 'A', 1: 'C', 2: 'G', 3: 'T'} # Starts reconstructing the symbols from the last letter of the k-mer for i in range(pattern_len): quotient = index // 4 # value for remainder corresponds to the letter_value of the last symbol remainder = index % 4 symbol = letter_value[remainder] pattern = symbol + pattern # quotient becomes the next index for the following iteration index = quotient return pattern print(number_to_pattern(5246, 9))
b9f66d1b92597f6bc8cb4da517317b2337c9f129
dukeofdisaster/CodeWars
/sumTwoSmallest.py
856
4.15625
4
# The challenge is to define a function that takes the sum of the two # smallest numbers in an array of integers and returns said sum. # We are not allowed to modify the original array def sumTwoSmallest(numbers): copiedArray = numbers lowest = min(copiedArray) copiedArray.remove(lowest) nextLowest = min(copiedArray) return lowest+nextLowest # Again, we commit the sin of reinventing the wheel. A novice # does something like the above, but clever ol' python has some # built in functions that would have helped us, coupled with slicing def sumTwoSmallest(numbers): # the sorted function takes in the array and the slicing at the end tells us we want # the portion of the array up to but not including index 2, so 0,1 which in a sorted # array will always be the two lowest numbers return sum(sorted(numbers)[:2])
a22284040293fd7415822ba0b62e0d500b5dd9d1
thraddash/python_tut
/14_ojbect_oriented_programming/method_overiding.py
673
4.21875
4
#!/usr/bin/env python # Method overriding class Math: def __init__(self, x, y): self.x = x self.y = y def sum(self): return self.x + self.y class MathExtend1(Math): # Child class def __init__(self, x, y): super().__init__(x,y) def subtract(self): return self.x - self.y def sum(self): # Override parent sum method return self.x +self.y + 100 def show_all(self): print("Sum: " + str(self.sum())) #call the sum method in child class if exist, if not, parents class print("Subtract: " + str(self.subtract())) math_ext_obj = MathExtend1(10, 2) math_ext_obj.show_all()
f7fe60a3eca66a7a905c36916e6d0ac441d02e6b
huazhige/EART119_Lab
/mid-term/martinezverenise/martinezverenise_22776_1312454_PartB-1.py
2,658
3.921875
4
# -*- coding: utf-8 -*- """ - we will be finding the roots for each of the three given functions - f1 = x**5 +(2/5)*x**2 - 2 - f2 = exp((-1/10)*x) +x - f3 = 10*sin((1/4)*x)+ .1*(x+12) - all within the interval [-10,10] """ import matplotlib.pyplot as plt import numpy as np def f1(x): return x**5 +(2/5)*x**2 - 2 def dfdt1(x): return 5*x**4 +(1/5)*x def f2(x): return np.exp((-1/10)*x) +x def dfdt2(x): return (-1/10)*np.exp((-1/10)*x) +1 def f3(x): return 10*np.sin((1/4)*x)+ .1*(x+12) def dfdt3(x): return (10/4)*np.cos((1/4)*x) + .1 """ Here we are using the secant method to find the roots of each individual function """ def secant1(f1, x0, x1, tol=1e-5, N = 20): x0 = float(x0) x1 = float(x1) i = 0 while abs(f1(x1)) > tol and i < N: dfdt = (f1(x1) - f1(x0))/(x1-x0) #bassically newton x_next = x1 - f1(x1)/dfdt x0 = x1 x1 = x_next i += 1 #check i solution converges if abs(f1(x1)) > tol: return np.nan else: return x1 def secant2(f2, x0, x1, tol=1e-5, N = 20): x0 = float(x0) x1 = float(x1) i = 0 while abs(f2(x1)) > tol and i < N: dfdt = (f2(x1) - f2(x0))/(x1-x0) #bassically newton x_next = x1 - f2(x1)/dfdt x0 = x1 x1 = x_next i += 1 #check i solution converges if abs(f2(x1)) > tol: return np.nan else: return x1 def secant3(f3, x0, x1, tol=1e-5, N = 20): x0 = float(x0) x1 = float(x1) i = 0 while abs(f3(x1)) > tol and i < N: dfdt = (f3(x1) - f3(x0))/(x1-x0) #bassically newton x_next = x1 - f3(x1)/dfdt x0 = x1 x1 = x_next i += 1 #check i solution converges if abs(f3(x1)) > tol: return np.nan else: return x1 ################################## Parameters################################## x0 = -9 xmax, xmin= -10, 10 ############################################################################### x_roots_f1 = secant1(f1, x0, x0+10) x_roots_f2 = secant2(f2, x0, x0+10) x_roots_f3 = secant3(f3, x0, x0+10) x = np.linspace(xmax, xmin, 1000) ############################### Plots ################################### plt.figure(1) plt.plot(x, f1(x), 'k-') plt.plot(x_roots_f1, f1(x_roots_f1), 'b*', ms=12) plt.figure(2) plt.plot(x, f2(x), 'k-') plt.plot(x_roots_f2, f2(x_roots_f2), 'b*', ms=12) plt.figure(3) plt.plot(x, f3(x), 'k-') plt.plot(x_roots_f3, f3(x_roots_f3),'b*', ms =12)
43352811b2b3969bb991fae10ef8615d4d450f84
yaksas443/SimplyPython
/rectangle.py
514
4.15625
4
# Source: Understanding Computer Applications with BlueJ - X # Find the area, perimeter and diagonal of a rectangle import math l = int(raw_input("Enter the length of rectangle (cm): ")) b = int(raw_input("\nEnter the breadth of rectangle (cm): ")) area = l * b perimiter = 2 * (l + b) diagonal = math.sqrt(l*l + b*b) print "\nArea of the rectanle is : " + str(area) + " cm^2" print "\nPerimeter of the rectanle is : " + str(perimiter) + " cm" print "\nDiagonal of the rectanle is : " + str(diagonal) + " cm"
ad4de85771be40247c74448caf2d561ca2b06cf8
ZanetaWidurska/ZanetaWidurska
/test_point.py
4,866
3.6875
4
# -*- coding: utf-8 -*- from point import Point, normalize_angle def test_should_check_constructor_without_z(): # given point_a = Point('A', 1, 1) # when # then assert point_a.name == 'A' assert point_a.x == 1 assert point_a.y == 1 assert point_a.z == 0 def test_should_check_constructor_with_z(): # given point_a = Point('A', 1, 1, 1) # when # then assert point_a.name == 'A' assert point_a.x == 1 assert point_a.y == 1 assert point_a.z == 1 def test_should_check_x_y_z_is_number(): # given point_a = Point('A', '1', '1', '1') # when # then assert point_a.name == 'A' assert point_a.x == 1 assert point_a.y == 1 assert point_a.z == 1 def test_should_check_print_method(): # given point_a = Point('A', 1, 1, 1) # when # then assert point_a.__str__() == 'Point(nr="A", x=1.0, y=1.0, z=1.0)' def test_should_check_get_length(): # given begin_point = Point('P1245', 0, 0) end_point = Point('P12', 3, 4) end_point_3d = Point('P12', 3, 4, 1) # when # then assert begin_point.get_length(begin_point) == 0 assert begin_point.get_length(end_point) == 5 assert end_point.get_length(begin_point) == 5 assert begin_point.get_length(begin_point, _3d=True) == 0 assert begin_point.get_length(end_point_3d, _3d=True) == (9 + 16 + 1) ** 0.5 assert end_point_3d.get_length(begin_point, _3d=True) == (9 + 16 + 1) ** 0.5 def test_should_check_get_azimuth(): # given begin_point = Point('P1245', 0, 0) end_point_0 = Point('P0', 1, 0) end_point_50 = Point('P50', 1, 1) end_point_100 = Point('P100', 0, 1) end_point_150 = Point('P150', -1, 1) end_point_200 = Point('P200', -1, 0) end_point_250 = Point('P250', -1, -1) end_point_300 = Point('P300', 0, -1) end_point_350 = Point('P350', 1, -1) # when # then assert begin_point.get_azimuth(end_point_0) == 0 assert begin_point.get_azimuth(end_point_50) == 50 assert begin_point.get_azimuth(end_point_100) == 100 assert begin_point.get_azimuth(end_point_150) == 150 assert begin_point.get_azimuth(end_point_200) == 200 assert begin_point.get_azimuth(end_point_250) == 250 assert begin_point.get_azimuth(end_point_300) == 300 assert begin_point.get_azimuth(end_point_350) == 350 def test_should_check_get_angle(): # given central_point = Point('P1245', 0, 0) end_point_0 = Point('P0', 1, 0) end_point_50 = Point('P50', 1, 1) end_point_100 = Point('P100', 0, 1) end_point_150 = Point('P150', -1, 1) end_point_200 = Point('P200', -1, 0) end_point_250 = Point('P250', -1, -1) end_point_300 = Point('P300', 0, -1) end_point_350 = Point('P350', 1, -1) # when # then assert central_point.get_angle(end_point_0, end_point_0) == 0 assert central_point.get_angle(end_point_0, end_point_50) == 50 assert central_point.get_angle(end_point_0, end_point_100) == 100 assert central_point.get_angle(end_point_0, end_point_150) == 150 assert central_point.get_angle(end_point_0, end_point_200) == 200 assert central_point.get_angle(end_point_0, end_point_250) == 250 assert central_point.get_angle(end_point_0, end_point_300) == 300 assert central_point.get_angle(end_point_0, end_point_350) == 350 assert central_point.get_angle(end_point_50, end_point_50) == 0 assert central_point.get_angle(end_point_50, end_point_100) == 50 assert central_point.get_angle(end_point_50, end_point_150) == 100 assert central_point.get_angle(end_point_50, end_point_200) == 150 assert central_point.get_angle(end_point_50, end_point_250) == 200 assert central_point.get_angle(end_point_50, end_point_300) == 250 assert central_point.get_angle(end_point_50, end_point_350) == 300 assert central_point.get_angle(end_point_50, end_point_0) == 350 assert central_point.get_angle(end_point_100, end_point_100) == 0 assert central_point.get_angle(end_point_100, end_point_150) == 50 assert central_point.get_angle(end_point_100, end_point_200) == 100 assert central_point.get_angle(end_point_100, end_point_250) == 150 assert central_point.get_angle(end_point_100, end_point_300) == 200 assert central_point.get_angle(end_point_100, end_point_350) == 250 assert central_point.get_angle(end_point_100, end_point_0) == 300 assert central_point.get_angle(end_point_100, end_point_50) == 350 def test_check_normalize_angle(): assert normalize_angle(0) == 0 assert normalize_angle(100) == 100 assert normalize_angle(-100) == 300 assert normalize_angle(-400) == 0 assert normalize_angle(-800) == 0 assert normalize_angle(-4000) == 0 assert normalize_angle(400) == 0 assert normalize_angle(800) == 0 assert normalize_angle(4000) == 0
8bcdb21d520dc720e80f83546f311d1a77979e51
Angelday8/hatnotation
/Password_Generator_python-hatnotation_v3.py
1,373
3.578125
4
import string import secrets import sys import math #Author: © Steven J Hatzakis, 2020 alphabet = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "!", '"', "#", "$", "%", "&", "'", "(", ")", "*", '+', ",", "-", ".", "{", ":", ";", "<", "=", ">", "?", "@", "[", "}", "]", "^", "_", "`"] joinedalphabet="".join(alphabet) print('This is the alphabet we will be using:',joinedalphabet, 'which has', len(alphabet), 'characters (total 64), and where the length of passwords generated randomly from this alphabet will determine their strength in terms of bits of security (entropy).') print(len(string.ascii_letters + string.digits+ string.punctuation)) # total printable is 95 with whitespace: #'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ ' char=int(input('Please enter a number (i.e. enter ''22'' for a 22-character password with 128 bits of security):')) password = ''.join(secrets.choice(alphabet) for i in range(char)) library=64 #used to calculate entropy numberchars=len(password) entropy=library**numberchars logentropy=math.log2(entropy) print(password) print("your above",len(password), "character-long password has entropy of security in this many bits", int(logentropy))
ac9c4d4e6aff256dc81758536c68b96a8ab72b4a
vladsadretdinov/skillsmart-education
/algorithms/5-extended.py
2,216
3.8125
4
import unittest class Queue: def __init__(self): # инициализация хранилища данных self.queue = [] def enqueue(self, item): # вставка в хвост self.queue.append(item) def dequeue(self): # выдача из головы if self.size() == 0: return None return self.queue.pop(0) def size(self): # размер очереди return len(self.queue) def __getitem__(self, i): if i < 0 or i >= self.size(): raise IndexError('Index is out of bounds') return self.queue[i] class TestUM(unittest.TestCase): def setUp(self): self.queue = Queue() def test_len(self): self.assertEqual(0, self.queue.size()) self.queue.enqueue(1) self.queue.enqueue(2) self.queue.enqueue(3) self.assertEqual(3, self.queue.size()) self.queue.dequeue() self.queue.dequeue() self.assertEqual(1, self.queue.size()) def test_enqueue(self): self.assertEqual(0, self.queue.size()) self.queue.enqueue(1) self.assertEqual(1, self.queue[0]) self.assertEqual(1, self.queue.size()) self.queue.enqueue(2) self.assertEqual(2, self.queue[1]) self.assertEqual(2, self.queue.size()) self.queue.enqueue('vlad') self.assertEqual('vlad', self.queue[2]) self.assertEqual(3, self.queue.size()) def test_dequeue(self): self.assertEqual(0, self.queue.size()) self.queue.enqueue(1) self.queue.enqueue(2) self.queue.enqueue('vlad') self.assertEqual(1, self.queue.dequeue()) self.assertEqual(2, self.queue.size()) self.assertEqual(2, self.queue.dequeue()) self.assertEqual(1, self.queue.size()) self.assertEqual('vlad', self.queue.dequeue()) self.assertEqual(0, self.queue.size()) self.assertEqual(None, self.queue.dequeue()) self.assertEqual(0, self.queue.size()) self.assertEqual(None, self.queue.dequeue()) self.assertEqual(0, self.queue.size()) if __name__ == '__main__': unittest.main()
f56a398a019f0d3094e401f52ac062c3f1898a4e
bijiuni/preprocess_brain
/Basic_suggested_answer.py
1,523
4.09375
4
import numpy as np #Task 1 #We define an array1 array1 = np.array ( [[1., 1., 1.], [1., 1., 1.]], dtype=int) #Use ones function to define array_ones so that it is equal to array1 array_ones = np.ones ( (2,3) ) #Make this true print (np.array_equal(array_ones, array1) ) #Task 2 #We define an array2 array2 = np.array ( [0, 2, 4, 6, 8] ) #Use arange function to define array_arange so that it is equal to array2 array_arange = np.arange (0, 9, 2) #Make this true print (np.array_equal(array_arange, array2) ) #Task 3 #We define an array3 array3 = np.array ( [0, 0.25, 0.5, 0.75, 1] ) #Use linspace function to define array_linspace so that it is equal to array3 array_linspace = np.linspace (0, 1, 5) #Make this true print (np.array_equal(array_linspace, array3) ) #Task 4 #Before uncommenting and running these, think about what the results will be print ("--------------simple operations----------------------") print (array2 * 5) print (array2 / 2) print (array2 ** 2) print (array2 <= 5) print ("----------------upcasting----------------------------") array4 = array2 + array3 print (array4) print (array4.dtype) #Task 5 #Which of the following demand will not generate errors? #Uncomment that one print ("------------------multiplication---------------------") array1 = np.array ( [[1., 1., 1.], [1., 1., 1.]], dtype=int) array5 = np.array( [[1, 2], [3, 4], [5, 6]] ) #print (array1 * array5) print (np.dot (array1, array5) )
3e3d0d3da4855fb08f4ba0dff4935bb8e9141b44
Antohnio123/Python
/Practice/n.vasyaeva/HWLec3.py
1,667
4.03125
4
# Числа # 1 print("Enter the number of seconds:") x = int(input()) hours = x // 3600 minutes = x % 3600 // 60 print("It is", hours, "hours,", minutes, "minutes.") # 2 print("Enter the number of degrees:") y = int(input()) n = y // 30 #кол-во часов m = y % 30 // float('0.5') #кол-во мин print("It is", n, "hours,", m, "minutes.") # Строки # 1 s = "Home work" print("Третий символ строки -", s[2]) s1 = len(s) # длина строки print("Предпоследний символ строки -", s[s1 - 2]) print("Первые пять символов строки -", s[0:5]) print("Строка без последних двух символов -", s[0:s1 - 3]) print("Символы с четными индексами - ", s[0:s1:2]) print("Символы с нечетными индексами -", s[1:s1:2]) k = s1 - 1 #индекс последнего символа s2 = "" while k >= 0: s2 = s2 +s[k] #строка в обратном порядке k = k - 1 print("Все символы в обратном порядке - ", s2) print("Все символы строки через один в обратном порядке, начиная с последнего -", s2[0:s1:2]) print("Длина данной строки -", s1, "символов.") # 2 s3 = "Mather hello hello hello" z = s3.count("h") - 2 #кол-во "h" - 2 t = 0 s4 = "" while "h" not in s3[t]: t = t + 1 else: s4 = s3[t + 1:len(s3)] print(s3[0:t + 1], s4.replace("h", "H", z)) # 3 k = "hello friend" n = k.find(" ") print(k[n + 1:len(k)], k[0:n])
1abdf2eb9732c77595174bed0dae4ee0d3efbfc0
zlezero/Methodes_Numeriques
/average_1_to_N.py
194
4.21875
4
nbr = input("Enter a number > 1 : ") def average_1_to_N(n): sum = 0 for i in range(1, n + 1): sum += i return sum / n print("The average is : ", average_1_to_N(nbr))
4560a6ebbc818a071df9b12f764a1d376ff1fcdf
Enedavid/helloworld
/ps0.py
217
4.09375
4
# -*- coding: utf-8 -*- import math x = input("Enter numner x: ") y = input("Enter number y: ") x_power_y = int(x) ** int(y) print("x**y = " + str(x_power_y)) print("log(x) " + str(math.log(int(x),2)))
3595475991a3e65dcb2de467194e90ff3bf631f0
vikioza/portfolio_mazes
/maze_viz.py
2,911
3.71875
4
import pygame from tile import * from math import ceil WIDTH = 720 BORDER_MARGIN = 20 MAZE_MARGIN = 5 WIN = pygame.display.set_mode((WIDTH, WIDTH)) pygame.display.set_caption("Pathfinding Algorithm Visualization") RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 255, 0) YELLOW = (255, 255, 0) WHITE = (255, 255, 255) BLACK = (0, 0, 0) PURPLE = (128, 0, 128) ORANGE = (255, 165, 0) GREY = (128, 128, 128) TURQUOISE = (64, 224, 208) class MazeViz: row_size: int col_size: int tile_size: int def __init__(self, row_size, col_size): WIN.fill(GREY) width = WIDTH - BORDER_MARGIN self.row_size = row_size self.col_size = col_size tile_width = width / self.row_size tile_height = width / self.col_size self.tile_size = ceil(min(tile_width, tile_height)) def draw_maze(self, tiles): self._draw_tiles(tiles) pygame.display.update() def _draw_tiles(self, tiles): for i, tile in enumerate(tiles): x, y = self.get_coords(i) self.draw_tile(tile, x, y) def draw_tile(self, tile: Tile, x: int, y: int): if tile.entrance_tile(): self._draw_entrance(tile, x, y) return if tile.exit_tile(): self._draw_exit(tile, x, y) return if tile.visited(): self.draw_visited(tile, x, y) return self._draw_hallway(tile, x, y) def _draw_entrance(self, tile: Tile, x: int, y: int): pygame.draw.rect(WIN, ORANGE, (x + 1, y + 1, self.tile_size - 1, self.tile_size - 1)) self._draw_walls(WIN, tile, x, y) def _draw_exit(self, tile: Tile, x: int, y: int): pygame.draw.rect(WIN, GREEN, (x + 1, y + 1, self.tile_size - 1, self.tile_size - 1)) self._draw_walls(WIN, tile, x, y) def _draw_hallway(self, tile: Tile, x: int, y: int): pygame.draw.rect(WIN, WHITE, (x, y, self.tile_size, self.tile_size)) self._draw_walls(WIN, tile, x, y) def draw_visited(self, tile: Tile, x: int, y: int): pygame.draw.rect(WIN, TURQUOISE, (x, y, self.tile_size, self.tile_size)) self._draw_walls(WIN, tile, x, y) def draw_best(self, tile: Tile, x: int, y: int): pygame.draw.rect(WIN, PURPLE, (x, y, self.tile_size, self.tile_size)) self._draw_walls(WIN, tile, x, y) def draw_current(self, tile: Tile, x: int, y: int): pygame.draw.rect(WIN, YELLOW, (x, y, self.tile_size, self.tile_size)) self._draw_walls(WIN, tile, x, y) def _draw_walls(self, win, tile, x, y): if tile.has_top(): pygame.draw.line(win, BLACK, (x, y), (x + self.tile_size, y)) if tile.has_right(): pygame.draw.line(win, BLACK, (x + self.tile_size, y), (x + self.tile_size, y + self.tile_size)) if tile.has_bottom(): pygame.draw.line(win, BLACK, (x, y + self.tile_size), (x + self.tile_size, y + self.tile_size)) if tile.has_left(): pygame.draw.line(win, BLACK, (x, y), (x, y + self.tile_size)) def get_coords(self, index): x = get_column(index, self.row_size) * self.tile_size + MAZE_MARGIN y = get_row(index, self.row_size) * self.tile_size + MAZE_MARGIN return x, y
3adaf85184174615ac3cd25b5810115b569dccde
ksparkje/leetcode-practice
/python/too_easy/q78.py
679
3.703125
4
# 78. Subsets # Medium # # Given a set of distinct integers, nums, return all possible subsets (the power set). # # Note: The solution set must not contain duplicate subsets. # # Example: # # Input: nums = [1,2,3] # Output: # [ # [3], # [1], # [2], # [1,2,3], # [1,3], # [2,3], # [1,2], # [] # ] class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: def backtrack(start_idx, temp): so_far.append(temp) for idx in range(start_idx, length): backtrack(idx+1, temp + [nums[idx]]) so_far = [] length = len(nums) backtrack(0, []) return so_far
980e0b7114fbc4ba30ce07ad4fd3ab05b2624a32
kevinwsouza/phytonEX
/mediana.py
700
3.5
4
import sys def main (): numberLines = sys.stdin.readline() numbers = [] typeList = '' numberLines = int(numberLines) if(numberLines % 2 == 0): typeList = 'pair' else: typeList = 'odd' while(numberLines > 0): newNumber = sys.stdin.readline() numbers.append(newNumber) numberLines = numberLines - 1 ordenedArray = sorted(numbers) if(typeList == 'odd'): numberMedian = (len(ordenedArray) // 2) print(ordenedArray[numberMedian]) else: indexMedian = (len(ordenedArray) // 2) + 1 indexMediaTwo = (len(ordenedArray) // 2) numberMedian = ((int(ordenedArray[indexMedian] + int(ordenedArray[indexMediaTwo])) / 2) print(numberMedian) main()
e83abc88d93732ecea940247046ee47f003db0ae
pablodarius/mod02_pyhton_course
/Curso Udemy/SQLite Leccion 01/Leccion3.pyw
616
3.734375
4
import sqlite3 # conexion y se creara si no existe la BBDD conexion = sqlite3.connect("usuarios.db") cursor = conexion.cursor() """ cursor.execute("SELECT * FROM personas WHERE id=1") per = cursor.fetchone() print(per) """ cursor.execute("SELECT * FROM personas WHERE edad=34") per = cursor.fetchone() print(per) per = cursor.fetchone() print(per) cursor.execute("SELECT * FROM personas WHERE edad=34") perso = cursor.fetchall() print(perso) cursor.execute("UPDATE personas SET nombre='Pablo Pantoja' WHERE nombre='Pablo'") cursor.execute("DELETE FROM personas WHERE nombre='Pablo Pantoja'") conexion.commit() conexion.close()
01650206a8387a9cc686b84e15e24ad6ca03fbc8
JakobKallestad/Python-Kattis
/src/LineSegmentDistance.py
2,447
3.65625
4
from math import sqrt def direction(x1, y1, x2, y2, x3, y3): val = (y3 - y1) * (x2 - x1) >= (y2 - y1) * (x3 - x1) if val == 0: return 0 #colinear elif val < 0: return 1 #anticlockwise else: return 2 #clockwise def perpendicular_intersection_distance(x1, y1, x2, y2, x3, y3): try: k = ((y2 - y1) * (x3 - x1) - (x2 - x1) * (y3 - y1)) / ((y2 - y1)**2 + (x2 - x1)**2) except: k = 0 x4 = x3 - k * (y2 - y1) y4 = y3 + k * (x2 - x1) if is_point_on_line(x1, y1, x2, y2, x4, y4): return sqrt((x3-x4)**2+(y3-y4)**2) else: return float('inf') def is_point_on_line(x1, y1, x2, y2, x3, y3): dist_A = sqrt((x1-x3)**2+(y1-y3)**2) dist_B = sqrt((x2-x3)**2+(y2-y3)**2) dist_C = sqrt((x1-x2)**2+(y1-y2)**2) return round(dist_A + dist_B, 7) == round(dist_C, 7) def is_intersecting(x1, y1, x2, y2, x3, y3, x4, y4): dir1 = direction(x1, y1, x2, y2, x3, y3) dir2 = direction(x1, y1, x2, y2, x4, y4) dir3 = direction(x3, y3, x4, y4, x1, y1) dir4 = direction(x3, y3, x4, y4, x2, y2) if dir1 != dir2 and dir3 != dir4: return True if dir1 == 0 and is_point_on_line(x1, y1, x2, y2, x3, y3): # when p2 of line2 are on the line1 return True if dir2 == 0 and is_point_on_line(x1, y1, x2, y2, x4, y4): # when p1 of line2 are on the line1 return True if dir3 == 0 and is_point_on_line(x3, y3, x4, y4, x1, y1): # when p2 of line1 are on the line2 return True if dir4 == 0 and is_point_on_line(x3, y3, x4, y4, x2, y2): # when p1 of line1 are on the line2 return True return False n_test_cases = int(input()) for _ in range(n_test_cases): x1, y1, x2, y2, x3, y3, x4, y4 = map(int, input().split()) if is_intersecting(x1, y1, x2, y2, x3, y3, x4, y4): print("0.00") continue line_one = [(x1, y1), (x2, y2)] line_two = [(x3, y3), (x4, y4)] distances = [] # Distance between points for p1 in line_one: for p2 in line_two: dist = sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2) distances.append(dist) # Perpendicular distances: for p in line_one: distances.append(perpendicular_intersection_distance(*line_two[0], *line_two[1], *p)) for p in line_two: distances.append(perpendicular_intersection_distance(*line_one[0], *line_one[1], *p)) print("{:.2f}".format(min(distances)))
d786e2158f126fc7c27f3518b3f3930ef4e5dd34
Putnic/python_learning
/generators/generator_ex.py
1,793
4.4375
4
from sys import getsizeof from typing import List # Generator Expressions gen_exp = (x * x for x in [1, 2, 3, 4, 5]) print('Generator Expressions', gen_exp) print('gen_exp:', getsizeof(gen_exp)) # gen_exp = (x * x for x in [1, 2, 3, 4, 5]) # [1, 4, 9, 16, 25] # print(list(gen_exp)) # **************************************************** # Generator # Generator-Function : A generator-function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function. # A generator function that yields 1 for first time, # 2 second time and 3 third time # A generator function def simpleGeneratorFun(): yield 1 yield 2 yield 3 for value in simpleGeneratorFun(): print(value) def square_numbers(nums: List[int | float]): for i in nums: yield (i * i) # Generator-Object : Generator functions return a generator object. Generator objects are used either by calling the next method on the generator object or using the generator object in a “for in” loop (as shown in the above program). # x is a generator object x = simpleGeneratorFun() # Iterating over the generator object using next print(next(x)) print(x.__next__()) print(x.__next__()) ################################################# gen = square_numbers([1, 2, 3, 4, 5]) print('generator: ', gen) print('gen:', getsizeof(gen)) # calculate at each iteration for num in gen: print(num) # ************************************************** # several yields def testgen(index: int): weekdays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'] yield weekdays[index] yield weekdays[index + 1] return 'End' day = testgen(0) # print(next(day))
46974ba349374634780d329800b4b001ac1738b5
stensaethf/Palindrome-DP
/longestpalindrome.py
2,927
3.921875
4
''' longestpalindrome.py Frederik Roenn Stensaeth 09.27.15 A Python program to find the longest palindrome subsequence of a string. Algorithm is implemented using dynamic programming. ''' import sys import time def longestPalindrome(string): """ longestPalindrome() finds the longest palindrome subsequence of a given string using a table format. @params: string @return: string -> palindrome """ n = len(string) # Create table where we will keep the palindromes table = [['' for i in range(n)] for j in range(n)] # All strings of length 1 are palindromes for i in range(n): table[i][i] = string[i] # Sub_len is the length of the substring # We loop over all the possible sustring lengths. # Length 1 is not considered, as those were covered above. for sub_len in range(2, n + 1): # Need to find all the possible substrings of that length. # We do this by looping over all the possible starting indexes. for i in range(n - sub_len + 1): # Find the index at which the substring ends. j = i + sub_len - 1 # Is the first and last letter the same? Length == 2? if string[i] == string[j] and sub_len == 2: # Palindrome contains two characters as the string is two # characters long. table[i][j] = string[i] + string[j] # Is the first and last letter the same? elif string[i] == string[j]: # Palindrome contains as many letters as the string that # did not contain the first and last letter we just compared # plus two, since we just found out that the first and last # letters are the same - so we need to add those. # As we have already found palindromes for all smaller strings # this is an easy look-up. table[i][j] = string[i] + table[i + 1][j - 1] + string[j] # First and last letters are not the same. elif sub_len == 2: table[i][j] = '' else: # Palindrome of this string is therefore the same length # as the one not containing either the first or the last # letter. So we need to find these. However, they have # already been found, so they are easy look-ups. if len(table[i][j - 1]) > len(table[i + 1][j]): table[i][j] = table[i][j - 1] else: table[i][j] = table[i + 1][j] return table[0][n - 1] def main(): if len(sys.argv) != 2: print('Error. Please provide a string to be checked for longest', 'palindrome.') print('Usage: $ python3 corrector.py <string>') sys.exit() palindrome = longestPalindrome(sys.argv[1]) if palindrome == '': print('Longest palindrome for %s: <no palindrome>' % (sys.argv[1])) else: print('Longest palindrome for %s: %s' % (sys.argv[1], longestPalindrome(sys.argv[1]))) ##### TESTS START # Tests written for timing the algorithm. # for j in range(10, 110, 10): # timeSTART = time.time() # table = longestPalindrome(sys.argv[1] * j) # timeSTOP = time.time() # print(timeSTOP - timeSTART) ##### TESTS END if __name__ == '__main__': main()
33ef7710ba42fcfe554a0e8eb24b573bdd5820aa
carodewig/advent-of-code
/advent-py/2019/day_11.py
3,360
3.5625
4
""" day 11: space police """ from enum import Enum import attr import math from day_05 import IntcodeComputer, test_intcode_computer class Color(Enum): BLACK = 0 WHITE = 1 def to_str(self): if self.value: return "+" return " " @attr.s(slots=True) class Location: # grid indexed from top left loc_x = attr.ib() loc_y = attr.ib() orientation = attr.ib(default=0) def get(self): return (self.loc_x, self.loc_y) def turn(self, direction): if direction: # turn right self.orientation += 90 else: # turn left self.orientation -= 90 def step(self): angle = math.radians(self.orientation) self.loc_x += round(math.sin(angle)) self.loc_y -= round(math.cos(angle)) @attr.s(slots=True) class PainterRobot: intcode_computer = attr.ib() robot_location = attr.ib(init=False) area_to_paint = attr.ib(init=False) def __attrs_post_init__(self): self.robot_location = Location(0, 0) self.area_to_paint = dict() def print_area(self): min_x = min([point[0] for point in self.area_to_paint.keys()]) max_x = max([point[0] for point in self.area_to_paint.keys()]) min_y = min([point[1] for point in self.area_to_paint.keys()]) max_y = max([point[1] for point in self.area_to_paint.keys()]) for y in range(min_y, max_y + 1): for x in range(min_x, max_x + 1): if (x, y) in self.area_to_paint: print(self.area_to_paint[(x, y)].to_str(), end="") else: print(Color.BLACK.to_str(), end="") print() def get_color(self): location = self.robot_location.get() if location in self.area_to_paint: return self.area_to_paint[location] return Color.BLACK def paint(self, color): self.area_to_paint[self.robot_location.get()] = color def run(self): panels_painted = set() while self.intcode_computer.is_alive(): self.intcode_computer.pass_in(self.get_color().value) new_color = self.intcode_computer.parse_and_get_next_value() turn_dir = self.intcode_computer.parse_and_get_next_value() if new_color is None or turn_dir is None: break self.paint(Color(new_color)) panels_painted.add(self.robot_location.get()) self.robot_location.turn(turn_dir) self.robot_location.step() return len(panels_painted) @classmethod def init_from_file(cls, program_file): return PainterRobot(IntcodeComputer.init_from_file(program_file)) @classmethod def init_from_mock(cls, program): return PainterRobot(MockIntcodeComputer(program)) @attr.s class MockIntcodeComputer: program = attr.ib() def is_alive(self): return len(self.program) def parse_and_get_next_value(self): return self.program.pop(0) def pass_in(self, value): pass MOCKED_ROBOT = PainterRobot.init_from_mock([1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0]) assert MOCKED_ROBOT.run() == 6 ROBOT = PainterRobot.init_from_file("data/11.txt") # set up starting white panel ROBOT.paint(Color.WHITE) ROBOT.run() ROBOT.print_area()
d986f207e36f2c459ad1419435d775faae24bdb5
mbwight/Python_Scripts
/Flask/km_to_miles.py
1,492
3.828125
4
__author__ = 'Mark' from flask import Flask from flask import request app = Flask(__name__) app.debug = True #####Creates the function form_example under the first forward slash in this path #####The function puts all of the html to ask the user to input a distance in kilometers #####There is a button that allows user to input a number and then it submits to the next page @app.route('/') def form_example(): html = '' html += "<hmtl> \n" html += "<body> \n" html += '<form method="POST" action="form_input">\n' html += 'Input a distance in kilometers: <input type="text" name ="kilometers" /> \n' html += "<p> \n" html += '<input type="submit" value="submit" /> \n' html += "</form> \n" html += "</body> \n" html += "</html> \n" return html #########the value is returned and then all of the variable math is done in this function @app.route('/form_input', methods=['POST']) def form_input(): kilometers = request.form['kilometers'] kilometers = int(kilometers) miles = 0.621371 * kilometers miles = str(miles) kilometers = str(kilometers) html = '' html += '<html> \n' html += '<body> \n' html += 'You entered:' + ' ' + kilometers + ' ' + "kilometers." + \ " " + ' The equivalent in miles is ' + " " + miles + " " + \ "miles" + '\n' html += '</body> \n' html += '</hmtl> \n' return html if __name__ == '__main__': app.run()
541989b0b36f05005356530baaf6424570924902
lennykey/Webprogrammierung
/src/fibonacciGenerator/fiboGenerator.py
425
3.734375
4
''' Generatorfunktion fuer Fibonaccizahlen ''' def fibogen(): step0 = 0 step1 = 1 step2 = step0 + step1 counter = 0 while True: if counter == 0: yield 0 counter += 1 elif counter == 1: yield 1 counter += 1 else: yield step2 step0 = step1 step1= step2 step2 = step0 + step1 if __name__ == "__main__": for i, fibo in enumerate(fibogen()): if i > 6: break print fibo
d31853d7676ffc28d916dada16454f3c8db0839f
morenoh149/learnPythonInOneHour
/helloworld10.py
2,281
4.09375
4
import random import sys import os class Animal: __name = "" # double underscore indicates this is a private variable __height = 0 __weight = 0 __sound = 0 def __init__(self, name, height, weight, sound): self.__name = name self.__height = height self.__weight = weight self.__sound = sound def set_name(self, name): # self works like `this` in other languages (java, javascript) self.__name = name def get_name(self): return self.__name def set_height(self, height): # self works like `this` in other languages (java, javascript) self.__height = height def get_height(self): return self.__height def set_weight(self, weight): # self works like `this` in other languages (java, javascript) self.__weight = weight def get_weight(self): return self.__weight def set_sound(self, sound): # self works like `this` in other languages (java, javascript) self.__sound = sound def get_sound(self): return self.__sound def get_type(self): print("Animal") def toString(self): return "{} is {} cm tall and {} kilograms and says \"{}\"".format(self.__name, self.__height, self.__weight, self.__sound) cat = Animal('Whiskers', 33, 10, 'Meow famz') print(cat.toString()) ### Inheritance class Dog(Animal): # extending a class __owner = "" def __init__(self, name, height, weight, sound, owner): self.__owner = owner super(Dog, self).__init__(name, height, weight, sound) def set_owner(self, owner): self.__owner = owner def get_owner(self): return owner def get_type(self): print("Dog") def toString(self): return "{} is {} cm tall and {} kilograms and says \"{}\". His owner is {}".format( self.__name, self.__height, self.__weight, self.__sound, self.__owner) def multiple_sounds(self, how_many=None): # default variable values, allow you to omit them when calling the function if how_many is None: print(self.get_sound()) else: print(self.get_sound() * how_many) madison = Dog('Maddie', 10, 10, 'wwwoof', 'Harry G Moreno') print(madison.toString()) print(madison.get_sound()) print(madison.multiple_sounds()) print(madison.multiple_sounds(2)) class AnimalTesting: def get_type(self, animal): animal.get_type() test_animals = AnimalTesting() test_animals.getType(cat) test_animals.getType(spot)
dae42c9d22b36e6e66241f702330220fb15daf49
vikkir/D2_project
/1. Read_csv_to_JSON_tw.py
2,599
3.59375
4
#Read CSV into JSON #Tom Wallace #Finished 21/09/18, annotations updated 26/09/18 #This file reads a CSV into a Pnadas dataframe, modifies it and saves it out to a JSON with the index format. It then reads it back in from JSON to a dataframe to test if the translation works. ################################# Import packages ################################# import csv # reads CSV import json # Handles JSON import pandas as pd # Managed the data while it's in memory and converts between CSV and JSON import os.path import datetime ################################# Read in CSV and save as JSON ################################# now = datetime.datetime.now() # Get the current date/time to display to the user print(' ') # White space used to increase readability of output window print('>>> Run started at ', now.strftime("%Y-%m-%d %H:%M") , ' <<<') # Print start time - serves as a header for the output window print(' ') projectpath = './' # Hold the current folder (where the .py file resides) in a variable as the project path datapath = 'Original data/' # Original data is held in another folder to make the git repo tider inputfilepath = projectpath + datapath + "CharityCharacteristics.csv" # Grab the filepath of the CSV to be imported df = pd.DataFrame.from_csv(inputfilepath) # Create a panda's dataframe from the CSV df.reset_index(inplace=True) # Remove the index of the frame which is asigned to column 0 on import (can be changed on import but we want a 2 level index) df.set_index(['ccnum', 'financial_year'], inplace=True) # Set the 2 level index. The data is longitudinal so charity number (ccnum) and period (financial_year) uniquiely identify each case for year in ['06-07', '07-08', '08-09', '09-10', '10-11', '12-13', '13-14']: # Drop periods not to be used in analysis - we want a cross section. '2011-12' is left out as this is the period we want to keep. df.drop(index='20' + year, level=1, inplace=True) df.reset_index(inplace=True) # 2 level index no longer needed df.set_index(['ccnum'], inplace=True) # Set index to charity number which is uniquely identifying within 1 time period df.to_json(path_or_buf= projectpath + 'active_data_file.json', orient='index') # Save the dataframe out to a JSON in the format 'index' which is easy to read and verify manually df1 = pd.read_json(path_or_buf= projectpath + 'active_data_file.json', orient ='index') # Check the JSON reads back into a data frame print(df1) # Print the frame to check nothing has been lost print('>>> Finished run at' , now.strftime("%H:%M:%S"),'<<<') # Footer the program with a finish time
cf18ae28b2108e98f3a8354d2611f5e16a3cedb6
kanybek740/Chapter4_Task1
/Task1.py
888
3.84375
4
# Создайте класс Student, конструктор которого имеет параметры name, lastname, # department, year_of_entrance. Добавьте метод get_student_info, который # возвращает имя, фамилию, год поступления и факультет в # отформатированном виде: “Вася Иванов поступил в 2017 г. на факультет: # Программирование.” class Student(): def __init__(self, name, last_name): self.name = name self.last_name = last_name self.department = 'Programmirovanie' self.year_of_entrance = 2017 def get_student_info(self): print(f'{self.name} {self.last_name} postupil v {self.year_of_entrance} godu na fakultet: {self.department}') object1 = Student('Vasya', 'Ivanov') object1.get_student_info()
83cff2e490205132301068417e0cbc1d582e5ffe
varshilgandhi/Introduction-of-K-Means-Clustering
/What is K-means clustering .py
1,291
3.65625
4
# -*- coding: utf-8 -*- """ Created on Sat May 8 02:08:26 2021 @author: abc """ import pandas as pd #read out dataset df = pd.read_excel('K_Means.xlsx') print(df.head()) #Plot our dataset import seaborn as sns sns.regplot(x=df['X'], y=df['Y'], fit_reg=False) #fit_reg means do you want to divide it or not ###################################################################################################### #Apply K-means clustering import pandas as pd df = pd.read_excel('K_Means.xlsx') #Apply k-means clustering using sklearn library from sklearn.cluster import KMeans #initiallized the k-means algorithm kmeans = KMeans(n_clusters=3,init='k-means++', max_iter=300, n_init=10, random_state=0) #fit the dataset model = kmeans.fit(df) #Predict our dataset predicted_values = kmeans.predict(df) #plot our dataset from matplotlib import pyplot as plt plt.scatter(df['X'], df['Y'], c=predicted_values, s=50, cmap='viridis') #put centers on our clustring plt.scatter(kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1], s=200, c='black', alpha=0.5) #################################################################################################### #THANK YOU
400ed8fa47d3d4c90488b381c07418b4711e1164
JpradoH/Ciclo2Java
/Ciclo 1 Phyton/Unidad 1/Ejercicios/clase 1.py
788
4.25
4
#comentarios """comentarios""" #formas de imprimir print("Hello world")#es la mas comun print('boba 70 hijueputa') print('''te amo y te extraño mucho''') print("""mi gorda bella""") #concatenar print("jorge2"+" "+"Prado") #tipos de variables A=3 #entero o int B=3.5 #decimal o float C=False #boleano o bool print(A) #identifica el tipo de variable Type() print(type(A)) print(type(B)) print(type(C)) #agrupacion de datos #List [] (lista de datos) [15.25,56,28] ["hola","adios"] ["codigo",123456,False #lista vacia] [] #tuplas () (lista que no se puede cambiar o inmutables) (10,20,30,) #tupla vacia () #Diccionario {} (almacena distintos tipos e datos con NOMBRE y CLAVE) { "nombre":"Jorge", "Apellido":"Prado", "Mascota":"Gato", "Casado":False, "Nota":1.2 }
8eabca456605dc4348b9c26c35aafd2c49d2703c
kiptetole/Ejercicios-POO-2
/Ejercicios Practicos/Python/Ejercicio_Tiempo/Tiempo.py
2,679
4.15625
4
''' Clase Tiempo tres variables locales Horas Minutos Segundos Metodos: - Suma minutos segundos. - Resta minutos segundos. @author: Jose Notario Millan. ''' class Tiempo(): ## Constructor de la clase Tiempo ## def __init__(self,h,mun,seg): contador = 0 while seg>59: contador += 1 seg = seg - 60 self.minutos = contador mun += contador contador = 0 while mun > 59: contador += 1 seg = seg - 60 h = h + contador while h > 23: h = h - 24 self.segundos = seg self.minutos = mun self.horas = h ## Menu de seleccion ## def menu(self): print("----Menu Tiempo-----") self.__str__() print("1. Sumar.") print("2. Restar.") print("3. Salir menu.") ## Muestra el estado del objeto ## def __str__(self): print('Hora:',self.horas,'h -',self.minutos,'min -',self.segundos,'segs') ## Suma una hora a la guardada por medio de parametro ## def sumar(self, h,mun,seg): ## Se le suman a los segundos guardados los segundos pedidos. ## seg += self.segundos contador = 0 while seg>59: contador = contador + 1 seg -= 60 ## Se le suman a los minutos guardados los minutos pedidos y los minutos extras de los segundos. ## mun = mun + contador + self.minutos contador = 0 while mun > 59: contador = contador + 1 mun -= 60 ## Se le suman a las horas guardados las horas pedidas y las Horas extras de los minutos. ## h = h + contador + self.horas while h > 23: h -= 24 self.segundos = seg self.minutos = mun self.horas = h ## Resta una hora a la guardada por medio de parametro ## def restar(self, h, mun, seg): ## Se le restan a los segundos guardados los segundos pedidos. ## seg += self.segundos contador = 0 while seg<0: contador -= 1 seg += 60 ## Se le restan a los minutos guardados los minutos pedidos y los minutos extras de los segundos. ## mun = self.minutos + mun + contador contador = 0 while mun<0: contador -= 1 mun += 60 ## Se le restan a las horas guardados las horas pedidas y las Horas extras de los minutos. ## h = self.horas + h + contador while h<0: h = h + 24 self.segundos = seg self.minutos = mun self.horas = h
5a6e073fea8640a8a765f131f58d504a915c80fd
bichwa/Examples
/python/examples/draw_text.py
1,129
3.640625
4
""" * scratch_n_ sketch * * simple demo scripting in python language * """ from board import * #init mbd = scratch_n_sketch() #connect board mbd.connect() #start print('Draw Text demo') #clear screen #myBoard.clearScreen() mbd.backGroundColor(20, 20, 20) mbd.textBackColor(20, 20, 20) mbd.setFont(mbd.font_big); mbd.rotateDisplay(mbd.rotate_270) #delay a bit wait(1) #draw rectangle mbd.penColor(0, 255, 255); mbd.drawRectangle(40, 70, 255, 160) wait(1); #write text 1 mbd.penColor(150, 150, 150) mbd.drawText('* Scratch-N-Sketch Demo', 50, 80) #delay wait(1) #print text 2 mbd.penColor(255, 55, 240) mbd.drawText('* Please wait ....', 50, 110) #delay wait(1) #print number 0 to 100 for x in range(0,101): #print new number mbd.drawText(join(x, ' %') , 210, 115) #generate a random colour """myBoard.penColor(randomNumber(0, 255), randomNumber(0, 255), randomNumber(0, 255))""" #a 200 ms short delay wait(20) #print text 3 wait(1) mbd.penColor(255, 255, 0) for i in range(1,3): mbd.drawText('* Done . Bye!', 50, 140) #disconnect board """ mbd.disconnect()
94eddac1115d9c1ecf2fba43ff4bc99faeae3505
dlordtemplar/python-projects
/Functions/is_member.py
700
4.1875
4
''' Implement a function is_member(x, somelist) that returns True if x is an element of somelist, False otherwise. (2 Points) >>> is_member(2, [1, 2, 3]) True >>> is_member(4, [1, 2, 3]) False Note that this is exactly what the in operator does. >>> 2 in [1, 2, 3] True >>> 4 in [1, 2, 3] False For the sake of the exercise you should not use this operator. ''' # ... your code ... def is_member(num, list): for i in list: if (i == num): return True return False if __name__ == '__main__': print('is_member') print('Test1', is_member(2, [1, 2, 3]) == True) print('Test2', is_member(4, [1, 2, 3]) == False) print('Test1', is_member(2, []) == False)
b46bfe05281d970506f7ff06d05b39addd3de653
rammanur/PYTHON_FUN
/socket_test_multiproc.py
1,860
3.59375
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 26 14:34:03 2013 Demo server to demonstrate accepting of incoming socket requests and responding to them with interesting stuff. @author: rammanur """ import socket, sys, time, os def standard_handler(pid, conn, addr_info): conn.send("%d: STD: You are connected from %s\n\n" % (pid, addr_info[0],)) conn.close() def slower_handler(pid, conn, addr_info): conn.send("%d: SLOW: You are connected from %s\n\n" % (pid, addr_info[0],)) conn.send("%d: Current time here is: %s\n" % (pid, time.ctime(), )) conn.send("%d: " % (pid,)) for i in range(10): time.sleep(1) conn.send("%d" % (i,)) conn.send("\n\n") conn.close() def socket_program(bind_address, port): s = socket.socket() s.bind( ( bind_address, port) ) s.listen(5) exit_status = 0 count = 1 try: while True: count += 1 conn = 0 conn, addr_info = s.accept() pid = os.fork() if pid: # I am the parent. free the useless connection print "%d: Started Child=%d. Closing my connection\n" % \ (os.getpid(), pid,) conn.close() else: # I am the child. do my thing if ((count % 2) == 0): standard_handler(os.getpid(), conn, addr_info) else: slower_handler(os.getpid(), conn, addr_info) os._exit(0) except KeyboardInterrupt: exit_status = 1 finally: if (conn != 0): conn.close() s.close() if exit_status: sys.exit(exit_status) #if __name__ == 'socket_test': # socket_program() #else: # print "%s: Hmm, how didwe end up here ?\n" % (__name__,)
25fb8391021e590426d416b8e4180375fcb95156
pactonal/cse231
/proj05.py
2,298
3.875
4
#!/usr/bin/python3 '''Put overall header comments here.''' import string def open_file(): '''Insert function DocString here.''' opened = 0 while opened != 1: try: filename = input("Enter a file name: \n") f = open(filename, "r") opened = 1 except IOError: print("Error. Please try again.") opened = 0 return f def print_headers(): '''Insert function DocString here.''' print('{:^49s}'.format("Maximum Population Change by Continent\n")) print("{:<26s}{:>9s}{:>10s}".format("Continent", "Years", "Delta")) def calc_delta(line, col): '''Insert function DocString here.''' change = 0 old = line[(17+6*(col - 1)):(22+6*(col - 1))] new = line[(17+6*(col)):(22+6*(col))] for i in " ": old = old.replace(i, "") new = new.replace(i, "") for i in string.punctuation: old = old.replace(i, "") new = new.replace(i, "") old = int(old) new = int(new) change = ((new - old) / old) return change def format_display_line(continent, year, delta): '''Insert function DocString here.''' yearstring = (str(year - 50) + "-" + str(year)) delta *= 100 delta = round(delta) displayline = "{:<26s}{:>9s}{:>9d}%".format(continent, yearstring, delta) return displayline def main(): '''Insert function DocString here.''' with open_file() as data: print_headers() next(data) next(data) maxofall = 0 for line in data: maxdelta = 0 maxyear = 0 continent = line[0:15].strip() for column in range(6): delta = calc_delta(line, column - 1) if delta > maxofall: maxcontinent = continent maxofall = delta maxofallyear = (1750 + 50 * (column + 1)) if delta > maxdelta: maxdelta = delta maxyear = (1750 + 50 * (column + 1)) print(format_display_line(continent, maxyear, maxdelta)) print("Maximum of all continents:") print(format_display_line(maxcontinent, maxofallyear, maxofall)) return 0 if __name__ == "__main__": main()