blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
14eea1f6d940a4ee80968989e400f731806012f6
shreyakann/fa20
/assets/slides/fa20/11-Midterm_Review.py
1,331
4.09375
4
# Fall 2018 Midterm # This relies on "string slicing", something we haven't talked about this year. # s[0] is the first item # s[1:] is the second item until the end # s[start:end:step] to slice items. End is exclusive. def match(a, b): """Detect a match (a==b). Return 1 on match, otherwise 0 >>> match("a", "a") 1 >>> match("a", "b") 0 """ if a == b: return 1 else: return 0 def count_letter(s, c): """ Returns the number of times that character c occurs in string s >>> count_letter("banana", "a") 3 >>> count_letter("banana", "z") 0 """ pass def count_letter_r(s, c): """ Returns the number of times that character c occurs in string s >>> count_letter_r("banana", "a") 3 >>> count_letter_r("banana", "z") 0 """ def match_maker(c): """ >>> func = match_maker("c") >>> func("abc") 1 >>> func("def") 0 """ return def count_letter_hof(s, c): """ Returns the number of times that character c occurs in string s >>> count_letter_hof("banana", "a") 3 >>> count_letter_hof("banana", "z") 0 """ return def factorial(n): """ >>> factorial(0) 1 >>> factorial(4) 24 """ if n == 0: return 1 else: return n * factorial(n - 1)
8f03a3c9730403bd7a24e678ebccfd450115a2d8
duhq123/testDjango
/test/geussNubmer.py
686
3.921875
4
import random num = random.randint(1,100000) one = "I'm thinking of a number! Try to guess the number,You are thinking of:" print(one, end="") while 1: guessNumber = input() if guessNumber is not None: if guessNumber.isdigit(): # isdigit 判断输入是否全部为数字 guessNumber = int(guessNumber) if guessNumber > num: print("too high! Guess again:") elif guessNumber < num: print("too low! Guess again:") else: print("That's it! You're smart") break else: print('please input numbers') input("点击 enter 键退出")
7ca3eccfd6ca4482a5ae388232131f8bad425af8
RainKins/TextBasedGames
/main.py
10,274
4.40625
4
#Rain Kinsey #Lame Game – This program will display a game menu and allow the user to select their desired option #Then, let the user play Make Change, High Card, Deal Hand, Save Dream Cards, Display Dream Cards, Word Guess, or quit. import cardClass import random #Displays menu and runs the program def main(): try: #Let user select choice choice = menu() while choice >= 1 and choice < 8: #If the user chose option 1: Make Change if choice == 1: make_change() #The user will play a game of High Card elif choice == 2: high_card() #The user will play a game of Deal Hand elif choice == 3: deal_hand() #The user will play a game of Save Dream Hand elif choice == 4: save_dream_hand() #The user will be prompted to open a file then read it elif choice == 5: display_dream_hand() #The user will play a game of Word Guess elif choice == 6: word_guess() #This will print a message for the exiting user elif choice == 7: print("Thanks for stopping by. Have a nice day!") break choice = menu() except Exception as error: print(error) #Gives the user a description of the games and allows them to choose a game, validates the choice and returns it def menu(): #Initialize choice by adding a value to it in order to avoid an exception choice = 0 try: #This is the welcome statement print("Welcome to Lame Games!" "\n") #Display of the menu print("MAIN MENU") print("1. Make Change - Calculate How Much Change Is Due" "\n" "2. High Card - See If You Have The Highest Card" "\n" "3. Deal Hand - Deals Five Cards" "\n" "4. Save Dream Hand - Pick 5 Playing Cards and Save to a File" "\n" "5. Display Dream Hand - Read Your Dream Cards' File" "\n" "6. Word Guess - Guess The Word" "\n" "7. Quit") #Allows user to choose numbers 1, 2, or 3 only and re-enter if the user puts an invalid number choice = int(input("Choose an Option Number: ")) while choice > 7 or choice < 1: print("Invalid Option" "\n") main() except ValueError: print("Error: Invalid Data Entered") except: print("An Unknown Error Has Occurred") #Pass choice back to user if valid return choice #Allows user to Calculate How Much Change Is Due in dollars, quarters, dimes, nickels, and pennies def make_change(): #Asks for the amount owed and amount paid owed = float(input("\n" "Amount Owed: $")) paid = float(input("Amount Paid: $")) change_due = paid - owed #Display no amount due if applicable if change_due == 0: print("No Change Due") #Display not enough payment if applicable elif owed > paid: print("Insufficient Payment") #Displays amount of change due if applicable else: print("\nChange Due: $", format(change_due, ",.2f"), sep='') #Breaks down the change due dollars dollar = int(change_due) #Breaks down the change due quarters quarter = int((change_due - dollar) / 0.25) #Breaks down the change due dime dime = int(((change_due - dollar) - (quarter * 0.25)) / 0.10) #Breaks down the change due nickels nickel = int( ((change_due - dollar) - (quarter * 0.25) - (dime * 0.10)) / 0.05) #Breaks down the change due pennies penny = round(((change_due - dollar) - (quarter * 0.25) - (dime * 0.10) - (nickel * 0.05)) / 0.01) #Display dollar amount of change due if dollar > 1: print(format(dollar, ','), "dollars") elif dollar == 1: print(format(dollar, ','), "dollar") #Display quarter amount of change due if quarter > 1: print(format(quarter, ','), "quarters") elif quarter == 1: print(format(quarter, ','), "quarter") #Display dime amount of change due if dime > 1: print(format(dime, ','), "dimes") elif dime == 1: print(format(dime, ','), "dime") #Display nickel amount of change due if nickel > 1: print(format(nickel, ','), "nickels") elif nickel == 1: print(format(nickel, ','), "nickel") #Display penny amount of change due if penny > 1: print(format(penny, ','), "pennies") elif penny == 1: print(format(penny, ','), "penny\n") #Allows 2 users to see if one has the highest card by assigning a random number to the user and giving the number a card face value def high_card(): first_player = input("\nPlayer 1's Name:") second_player = input("Player 2's Name:") player1_card = cardClass.Card() player2_card = cardClass.Card() #Generate random cards and assign them to the players player1_card.deal() player2_card.deal() print("\nDealing Cards...\n") print(first_player, "has {}.".format(player1_card.get_face_value())) print(second_player, "has {}.".format(player2_card.get_face_value())) #Declare a winner or a tie if player1_card.get_value() > player2_card.get_value(): print(first_player, "Wins!\n") elif player1_card.get_value() < player2_card.get_value(): print(second_player, "Wins!\n") else: print("It's a Tie!\n") #Displays the card face value of each card def display_hand(card_list): #Read line of file, convert to interger, finally display face value for item in card_list: print(item.get_face_value()) #Displays the total and average of the card values def hand_stats(card_list): #Set total = 0, so it is assigned before it is called total = 0 #Caluculate the total of the list for i in range(len(card_list)): total = total + card_list[i].get_value() #Calculate the average of the card values average = total / len(card_list) #Print the sum and the average print("The Total of the Card Values:", total) print("The Average of the Card Values:", average) #Displays 5 face value cards using random number function and assigning the numbers a face value def deal_hand(): #Create list card_list = [] #Display a opening message print("\nDealing Cards...") for item in range(5): #Assign cards to random value card = cardClass.Card() card.deal() #Store the cards in a list and save in file card_list.append(card) print("Your Hand is ") #Display hand display_hand(card_list) #Display hand statistics hand_stats(card_list) print("") #Allows the user to choose and save their card hand, the cards are given numeric value def save_dream_hand(): #Create list card_list = [] try: print( "\nUsing Numbers 1-13, 1 = Ace and 13 = King, Enter Your 5 Dream Cards:\n" ) #Ask for dream cards for item in range(5): card = int(input("Card: ")) while card > 13 or card < 1: print("Invalid Choice. Try Again.\n") card = int(input("Card: ")) card_obj = cardClass.Card() card_obj.set_value(card) #Store the cards in a list card_list.append(card_obj) #Save user input to filename file = open(str(input("\nPlease Type File Path To Save Cards: ")), 'w') print("\nSaving Cards...") #Save file for item in card_list: file.write(str(item.get_value()) + '\n') #Close the file print("\nCards Are Saved!\n") file.close() print("") # Error trap for invalid value for card except ValueError: print("Error: Invalid Input") except: print("An Unknown Error Has Occurred") #Allows the user to retrieve and display their dream card hand in face card value def display_dream_hand(): #Create list card_list = [] try: #Prompt user to open file card_file = open(str(input("\nYour Dream Card File Name: ")), 'r') for line in card_file: card = int(line) card_obj = cardClass.Card() card_obj.set_value(card) card_list.append(card_obj) #Call lines of file display_hand(card_list) #Close file card_file.close() print("") # Check for invalid file name except FileNotFoundError: print("Error: File Does Not Exist") #Allows user to guess a word chosen by another user, exposiong the correct guess until the entire word is uncovered def word_guess(): print("") #Ask for word to guess word = str(input("Type a Word to Guess: ")) #make the case the same, so all input will be valid word = word.lower() #Display enough space to hide the word print("\n" * 100) #Display astericks the length of the word blank = "*" * len(word) print(blank) #Make sure that the variable is set to string string = "" guessed = "" #Ask for a letter until word is complete while string != word: #Ask user for letter to guess guess = str(input("Guess a Letter: ")) print("") string, guessed = hide_word(string, word, guess, guessed) print(string) if string == word: print("You Win!\n") def hide_word(string, word, guess, guessed): #Add results result = "" #Make sure this will translate into string character ch = "" #Adds new character to guessed if guess not in guessed: guessed += str(guess) else: print("You Have Already Guessed This Letter\n") #Tell the user if they already guessed for letter in word: if letter in guessed: result += letter else: result += "*" return result, guessed main()
20ec41b4c1c9dd067fed66326dc3337e4fa343bb
danrodaba/Python_PixelBlack
/Python_PixelBlack/Aprende con Alf/06 Funciones/06media.py
300
4
4
''' Escribir una función que reciba una muestra de números en una lista y devuelva su media. ''' def media(lista): promedio=sum(lista)/len(lista) return promedio lista=[] for i in range(10): lista.append(float(input('Introduce un nuevo valor ({0}): '.format(i+1)))) print(media(lista))
1f4e376bc17b82ec7607824a7b4aa0ada7374be4
ksc5496/hw3python
/main.py
270
3.5625
4
# Author: Krish Choudhary ksc5496@psu.edu def digit_sum(n): if n==0: return 0 else: return int((n%10) + digit_sum(n//10)) def run(): getInp = int(input("Enter an int: ")) print(f"sum of digits of {getInp} is {digit_sum(getInp)}.") if __name__ == "__main__": run()
2cae88755dcad7f3ad3315bed667042ce02c4a4c
dungnguyentien0409/competitive-programming
/Python/22. Generate Parentheses.py
639
3.515625
4
class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ def backtrack(res, cur, op, cp): if op == cp == 0: if len(cur) > 0: res.append(cur) return if op == 0: backtrack(res, cur + ")", op, cp - 1) elif op == cp: backtrack(res, cur + "(", op - 1, cp) else: backtrack(res, cur + "(", op - 1, cp) backtrack(res, cur + ")", op, cp - 1) res = [] backtrack(res, "", n, n) return res
bd5826ee798b88e98d38cd1ae7818ab819515b31
eman19-meet/YL1-201718
/lab1/lab1.py
449
3.90625
4
import turtle #problem 1: print("eman") print("eman "*3) print("eman "*100) #problem 2: number1=10 print(number1) number2=number1/2 print(number2) #problem 3: my_list=[1,2,3] for i in range(len(my_list)): print(my_list[i]) for k in range(len(my_list)): A+=my_list[k] print(A) #problem 4: turtle.penup() turtle.goto(100,100) for i in range(4): turtle.forward(50) tutle.left(90) turtle.mainloop()
09fd869d02ed947fd26f4bd607e9f7ff503226f4
WilsonZhong01/testwechat
/timer.py
465
3.59375
4
import threading import time # count = 0 def main(): global count, timer count += 1 print('timer runs every 1 min, and this is the %s' %count +' time') # rebuild timer timer = threading.Timer(1,main) timer.start() def timer_fun(): timer = threading.Timer(1, main) timer.start() if __name__ == '__main__': # run fun every 1 min count = 0 timer_fun() time.sleep(5 * 1) timer.cancel()
c67d78034867f9e12a716157ebb4795b0574adef
brady-wang/mac_home
/python/test/test_yield.py
333
4.03125
4
# *_*coding:utf-8 *_* def test(n): print("start") for i in range(1,n+1): print('yield start') yield i*i print("=======i*i========",i*i) print("yield end") item = test(2) item.__next__() item.__next__() a = [1,2,3,4] b = ['a','b','c','d'] print(zip(a,b)) for i,j in zip(a,b): print (i,j)
4ef6a6319d0914413c87ee122cb0dd0f58d68570
adriansr/challenges
/codejam/2008/1B. Milkshakes/solve.py
2,844
3.5
4
import sys import itertools class Problem: def __init__(self,nflavors): self.N = nflavors self.customers = [] #self.result = [0] * self.N def addCustomer(self,line): part = map(int,line.split()) num = part[0] constrains = [] for i in xrange(num): constrains.append((part[1+i*2],part[2+i*2]!=0)) self.customers.append(constrains) def evaluate(self,result): for c in self.customers: for rule in c: if result[rule[0]-1] == int(rule[1]): break else: return False return True def solve(self): mandatory = {} choices = {} # # start with no malted flavours # result = [0] * self.N for c in self.customers: # # please customers with only one choice and detect contradictions # if len(c) == 1: rule = c[0] if rule[0] in mandatory: if mandatory[rule[0]] != rule[1]: # already exists with opposite maltedness return None else: mandatory[rule[0]] = rule[1] else: # # customers with multiple choices and some malted are a problem # for rule in c: if rule[1]: if rule[0] not in mandatory: choices[rule[0]] = True # # enforce mandatory flavours # for key in mandatory: result[key-1] = int( mandatory[key] ) # check if sufficient by forcing mandatory flavors if self.evaluate(result) == True: return result # bruteforce choices, picking the least possible malted flavours NC = len(choices) for nmalted in xrange(1,NC-1): for c in itertools.combinations(choices,nmalted): r = result for ci in c: r[ci-1] = 1 if self.evaluate(result) == True: return result # last chance: all choices malted for key in choices: result[key-1] = 1 if self.evaluate(result) == True: return result return None f = open(sys.argv[1],'r') C = int(f.readline()) for testn in xrange(C): N = int(f.readline()) # flavors M = int(f.readline()) # customers P = Problem(N) for i in xrange(M): P.addCustomer(f.readline()) result = P.solve() print 'Case #%d:' % (testn+1), if result is None: print 'IMPOSSIBLE' else: print ' '.join(map(str,result))
822cd5c10e8eff4785ce31659764d35b6198ecd2
rverma23/Compiler
/SeawolfParser.py
24,855
3.5625
4
#!/usr/bin/env python """ AUTHOR: RAHUL VERMA """ import math import operator import string import sys import tpg import traceback import copy d = {} v = {} fd = {} functions = [] funccounter=-1 stackcount = -1 stack = [] class SemanticError(Exception): """ This is the class of the exception that is raised when a semantic error occurs. """ # These are the nodes of our abstract syntax tree. class Node(object): """ A base class for nodes. Might come in handy in the future. """ def evaluate(self): """ Called on children of Node to evaluate that child. """ raise Exception("Not implemented.") class ListLit(Node): """ A node representing List literals. """ def __init__(self): self.value = [] def evaluate(self): return self.value def ap(self,v): if ((type(v) is not str) and (type(v) is not Variable)): m = v.evaluate() self.value.append(m) else: self.value.append(v) class StringLiteral(Node): """ A node representing String literals. """ def __init__(self): self.value = "" def evaluate(self): return self.value def ap(self,v): if type(v) is not str: self.value = self.value + str(v.evaluate()) else: self.value = self.value + v class FloatLiteral(Node): """ A node representing Float literals. """ def __init__(self, value): self.value = float(value) def evaluate(self): return self.value class IntLiteral(Node): """ A node representing integer literals. """ def __init__(self, value): self.value = int(value) def evaluate(self): return self.value class Add(Node): """ A node representing addition. """ def __init__(self, left, right): # The nodes representing the left and right sides of this # operation. self.left = left self.right = right def evaluate(self): if type(self.left) is not str: left = self.left.evaluate() else: left = self.left if type(self.right) is not str: right = self.right.evaluate() else: right = self.right if isinstance(left,int) or isinstance(left, float): if isinstance(right,int) or isinstance(right,float): return left + right raise SemanticError() if isinstance(left,str) and isinstance (right, str): return left + right if isinstance(left,list) and isinstance (right, list): return left + right raise SemanticError() class Sub(Node): """ A node representing subtraction. """ def __init__(self, left, right): # The nodes representing the left and right sides of this # operation. self.left = left self.right = right def evaluate(self): left = self.left.evaluate() right = self.right.evaluate() p=(str,int,list,float) while not isinstance(left, p): left = left.evaluate() while not isinstance(right, p): right = right.evaluate() if not isinstance(left, int): if not isinstance(left,float): raise SemanticError() if not isinstance(right, int): if not isinstance(right,float): raise SemanticError() return left - right class Multiply(Node): """ A node representing multiplication. """ def __init__(self, left, right): # The nodes representing the left and right sides of this # operation. self.left = left self.right = right def evaluate(self): left = self.left.evaluate() right = self.right.evaluate() if not isinstance(left, int): if not isinstance(left,float): raise SemanticError() if not isinstance(right, int): if not isinstance(right,float): raise SemanticError() return left * right class POW(Node): """ A node representing multiplication. """ def __init__(self, left, right): # The nodes representing the left and right sides of this # operation. self.left = left self.right = right def evaluate(self): left = self.left.evaluate() right = self.right.evaluate() if not isinstance(left, int): if not isinstance(left,float): raise SemanticError() if not isinstance(right, int): if not isinstance(right,float): raise SemanticError() return math.pow(left,right) class Divide(Node): """ A node representing division. """ def __init__(self, left, right): # The nodes representing the left and right sides of this # operation. self.left = left self.right = right def evaluate(self): left = self.left.evaluate() right = self.right.evaluate() if not isinstance(left, int): if not isinstance(left,float): raise SemanticError() if not isinstance(right, int): if not isinstance(right,float): raise SemanticError() if right == 0: raise SemanticError() return left / right class FloorDivide(Node): """ A node representing division. """ def __init__(self, left, right): # The nodes representing the left and right sides of this # operation. self.left = left self.right = right def evaluate(self): left = self.left.evaluate() right = self.right.evaluate() if not isinstance(left, int): if not isinstance(left,float): raise SemanticError() if not isinstance(right, int): if not isinstance(right,float): raise SemanticError() if right == 0: raise SemanticError() return left//right class Modulus(Node): """ A node representing division. """ def __init__(self, left, right): # The nodes representing the left and right sides of this # operation. self.left = left self.right = right def evaluate(self): left = self.left.evaluate() right = self.right.evaluate() if not isinstance(left, int): if not isinstance(left,float): raise SemanticError() if not isinstance(right, int): if not isinstance(right,float): raise SemanticError() if right == 0: raise SemanticError() return left%right class Find(Node): """ A node representing array indexing. """ def __init__(self, left, right): # The nodes representing the left and right sides of this # operation. self.left = left self.right = right def evaluate(self): left = self.left.evaluate() right = self.right.evaluate() if len(right)==1: right1 = right[0] if type(right1) is Variable: right1 = right1.evaluate() if not isinstance(right1, int): raise SemanticError() else: raise SemanticError() try: answer = left[right1] return answer except IndexError: raise SemanticError() except TypeError: raise SemanticError() class NOT(Node): """ A node representing boolean not. """ def __init__(self, left): # The nodes representing the left and right sides of this # operation. self.left = left def evaluate(self): if type(self.left.evaluate()) is not int: raise SemanticError() left = self.left.evaluate() if left == 0: return 1 else: return 0 class GT(Node): """ A node representing greater than function. """ def __init__(self, left, right): # The nodes representing the left and right sides of this # operation. self.left = left self.right = right def evaluate(self): if type(self.left.evaluate()) is int: if type(self.right.evaluate()) is int: left = self.left.evaluate() right = self.right.evaluate() if left > right: return 1 else: return 0 raise SemanticError() class LT(Node): """ A node representing less than function. """ def __init__(self, left, right): # The nodes representing the left and right sides of this # operation. self.left = left self.right = right def evaluate(self): if type(self.left.evaluate()) is int: if type(self.right.evaluate()) is int: left = self.left.evaluate() right = self.right.evaluate() if left < right: return 1 else: return 0 raise SemanticError() class GTE(Node): """ A node representing greater than or equal to. """ def __init__(self, left, right): # The nodes representing the left and right sides of this # operation. self.left = left self.right = right def evaluate(self): if type(self.left.evaluate()) is int: if type(self.right.evaluate()) is int: left = self.left.evaluate() right = self.right.evaluate() if left >= right: return 1 else: return 0 raise SemanticError() class LTE(Node): """ A node representing less than or equal to. """ def __init__(self, left, right): # The nodes representing the left and right sides of this # operation. self.left = left self.right = right def evaluate(self): if type(self.left.evaluate()) is int: if type(self.right.evaluate()) is int: left = self.left.evaluate() right = self.right.evaluate() if left <= right: return 1 else: return 0 raise SemanticError() class ET(Node): """ A node representing equal to. """ def __init__(self, left, right): # The nodes representing the left and right sides of this # operation. self.left = left self.right = right def evaluate(self): if type(self.left.evaluate()) is int: if type(self.right.evaluate()) is int: left = self.left.evaluate() right = self.right.evaluate() if left == right: return 1 else: return 0 raise SemanticError() class NOTE(Node): """ A node representing equal to. """ def __init__(self, left, right): # The nodes representing the left and right sides of this # operation. self.left = left self.right = right def evaluate(self): if type(self.left.evaluate()) is int: if type(self.right.evaluate()) is int: left = self.left.evaluate() right = self.right.evaluate() if left == right: return 0 else: return 1 raise SemanticError() class AND(Node): """ A node representing the and function. """ def __init__(self, left, right): # The nodes representing the left and right sides of this # operation. self.left = left self.right = right def evaluate(self): if type(self.left.evaluate()) is int: if type(self.right.evaluate()) is int: left = self.left.evaluate() right = self.right.evaluate() if (left and right) > 0: return 1 else: return 0 raise SemanticError() class OR(Node): """ A node representing the or unction. """ def __init__(self, left, right): # The nodes representing the left and right sides of this # operation. self.left = left self.right = right def evaluate(self): if type(self.left.evaluate()) is int: if type(self.right.evaluate()) is int: left = self.left.evaluate() right = self.right.evaluate() if (left or right) > 0: return 1 else: return 0 raise SemanticError() class PrintNode(Node): def __init__(self): self.value = "" def add(self, s): self.value = s def evaluate(self): x = self.value.evaluate() p=(str,int,list,float) if isinstance(x, p): print(x) elif x == None: print(x) else: print(self.value.evaluate().evaluate()) class VariableAssignState(Node): def __init__(self, a=None, e=None,c=None): self.name = a self.value = e self.ind = c def evaluate(self): global d global funccounter global stackcount global stack if self.ind != None: d[self.name][self.value.evaluate()] = self.ind.evaluate() else: if funccounter == -1: d[self.name]=self.value.evaluate() else: if stackcount == -1: fd[functions[funccounter]].variables[self.name]=self.value else: stack[stackcount].variables[self.name]=self.value.evaluate() class Variable(Node): def __init__(self, a=None,h=-1): self.name = a self.h=h def evaluate(self): global d global funccounter global stackcount global stack if funccounter == -1: return d[self.name] else: if stackcount == -1: return fd[functions[funccounter]].variables[self.name] else: return stack[stackcount].variables[self.name] raise SemanticError class WhileNode(Node): def __init__(self, c=0): self.condition = c self.statements = [] def addstatements(self,a): self.statements.append(a) def evaluate(self): global d global v while(self.condition.evaluate()): for x in self.statements: x.evaluate() class IfNode(Node): def __init__(self, c=0): self.condition = c self.statements = [] self.elsestate = [] def addstatements(self,a): self.statements.append(a) def addelsestate(self,a): self.elsestate.append(a) def evaluate(self): if(self.condition.evaluate()): for x in self.statements: if type(x) is Return: return x.evaluate() else: v=x.evaluate() if type(v) is not type(None): return v else: if [] != self.elsestate: for x in self.elsestate: if type(x) is Return: return x.evaluate() else: v=x.evaluate() if type(v) is not type(None): return v class FuncNode(Node): def __init__(self, a, fcount=0): self.name = a self.argu=[] self.statements=[] self.argcounter=0 self.variables={} self.fcount = fcount def addargs(self,a): self.argu.append(a) self.variables[a.name]=a def setargs(self,o): if self.argcounter>=len(self.argu): raise SemanticError else: self.variables[self.argu[self.argcounter].name]=o self.argcounter+=1 def addstatements(self,a): self.statements.append(a) def evaluate(self): global funccounter for x in self.statements: funccounter = self.fcount if type(x) is Return: return x.evaluate() else: v=x.evaluate() if type(v) is not type(None): return v class FuncCall(Node): def __init__(self,n): global fd self.n = n self.f = object() self.args = [] def setargsf(self,a): self.args.append(a) def setargs(self): h = self.f for x in self.args: h.variables[h.argu[h.argcounter].name]=x.evaluate() h.argcounter+=1 def launch(self): self.f = copy.deepcopy(fd[self.n]) self.setargs() print(self.f) def evaluate(self): self.f = copy.deepcopy(fd[self.n]) self.setargs() global stackcount global stack stackcount+=1 stack.append(self.f) v=self.f.evaluate() if type(v) is not type(None): return v class Return(Node): def __init__(self): self.link = Node() self.statement = Node() def setlinl(self,l): self.link = l def addstatement(self,s): self.statement = s def evaluate(self): global stack global stackcount v=self.statement.evaluate() stack.pop() stackcount-=1 return v class BodyNode(Node): def __init__(self): self.statements = [] def addstatements(self,a): self.statements.append(a) def evaluate(self): global funccounter for x in self.statements: funccounter = -1 x.evaluate() # This is the TPG Parser that is responsible for turning our language into # an abstract syntax tree. class Parser(tpg.Parser): r""" separator spaces: '\s+'; token real: '\d*\.\d+' FloatLiteral; token number: "\d+" IntLiteral; token word: '[a-zA-z][a-zA-Z0-9_!@#$:]*'; Pick/a -> word/a | number/a | real/a | '[\\]["]' $ a = "\""$; String/s -> '\"' $s= StringLiteral() (Pick/a $s.ap(a+" ") )* '\"' ; Pick2/a -> String/a | number/a | real/a; other/s -> number/a $ s = a '\]' $ ; START/a -> ((func/a)*(Body/a)+)* ; expression/a -> If/a | While/a | printstate/a | Vari/a | VariList/a | funCall/a | addsub/a |ret/a; fexpression/a -> If/a | While/a | printstate/a | Vari/a | VariList/a | funCall/a | addsub/a |ret/a; addsub/a -> muldivbool/a ("\+" muldivbool/b $ a = Add(a, b) $| "\-" parens/b $ a = Sub(a, b) $)* ; muldivbool/a -> parens/a( "\*\*" parens/b $ a = POW(a,b) $| "\*" parens/b $ a = Multiply(a, b) $| "\/\/" parens/b $ a = FloorDivide(a, b) $| "\/" parens/b $ a = Divide(a, b) $| "\%" parens/b $ a = Modulus(a, b) $| parens/b $ a = Find(a,b) $| "[&][&]" parens/b $ a = AND(a,b) $| "[o][r]" parens/b $ a = OR(a,b) $| "[>][=]" parens/b $ a = GTE(a,b) $| "[<][=]" parens/b $ a = LTE(a,b) $| "[<][>]" parens/b $ a = NOTE(a,b) $| "[=][=]" parens/b $ a = ET(a,b) $| "[>]" parens/b $ a = GT(a,b) $| "[<]" parens/b $ a = LT(a,b) $)* ; parens/a -> "\(" expression/a "\)" | literal/a | "[n][o][t]" expression/b $ a = NOT(b) $; literal/a -> String/a | List/a | number/a | real/a |funCall/a | Varl/a; List/l -> '\[' $ l = ListLit() expression/a $ l.ap(a) ( ',' expression/a $ l.ap(a) )* '\]' ; Body/a-> '\{' $a=BodyNode() $self.resetfunc() (expression/b $a.addstatements(b) )* '\}' $a.evaluate() $print("\n") ; printstate/a -> 'print\s*\(' $a = PrintNode() expression/b $a.add(b) '\)' '\;' ; While/a -> 'while\s*\(' expression/b $a=WhileNode(b) '\)' '\{' (expression/c $a.addstatements(c) )* '\}' ; If/a -> 'if\s*\(' expression/b $a=IfNode(b) '\)' '\{' (expression/c $a.addstatements(c) )* '\}' ('else\s*\{' (expression/c $a.addelsestate(c) )* '\}' )? ; funCall/a -> word/d'\(' $a = FuncCall(d) expression/b? $a.setargsf(copy.deepcopy(b)) ( ',' expression/b $a.setargsf(copy.deepcopy(b)) )* '\)' ; ret/a -> 'return' $a=Return() expression/c? $a.addstatement(c) '\;' ; func/a -> word/d'\(' $a=FuncNode(d) $self.getfd()[a.name]=a $self.getfunctions().append(a.name) VarId/b? $a.addargs(b) ( ',' VarId/b $a.addargs(b) )* '\)' '\{' $self.funcinc() $global funccounter $a.fcount=funccounter (fexpression/c $a.addstatements(c)$| ret/c $a.addstatements(c) )* '\}' $self.getfd()[a.name]=a ; Vari/a -> VarId/v '\=' expression/e '\;' $a = VariableAssignState(v.name,e) $self.getv()[v.name]=v ; VariList/a -> Varl/v '\[' expression/x '\]' '\=' expression/e '\;'$ a = VariableAssignState(v.name,x,e) ; VarId/v -> String2/x $global funccounter $v = Variable(x,funccounter) ; String2/s -> $a=StringLiteral() (word/t $a.ap(t) )+ $s=a.evaluate() ; Varl/x -> String2/v $if v in self.getv(): $ x=self.getv()[v] $else: $ x="" ; """ def getv(self): global v global funccounter global fd global functions if funccounter == -1: return v else: return fd[functions[funccounter]].variables def getfd(self): global fd return fd def resetfunc(self): global funccounter funccounter=-1 def funcinc(self): global funccounter funccounter+=1 def getfunctions(self): global functions return functions verbose = 2 # Make an instance of the parser. This acts like a function. parse = Parser() # This is the driver code, that reads in lines, deals with errors, and # prints the output if no error occurs. # Open the file containing the input. parse = Parser() try: f = open(sys.argv[1], "r") except(IndexError, IOError): print("No file found.") sys.exit(0) # For each line in f try: # Try to parse the expression. print("HW (HW test)") node = parse(f.read()) # If an exception is thrown, print the appropriate error. except tpg.Error: print("SYNTAX ERROR") # Uncomment the next line to re-raise the syntax error, # displaying where it occurs. Comment it for submission. # raise except SemanticError: print("SEMANTIC ERROR") print(traceback.format_exc()) # Uncomment the next line to re-raise the semantic error, # displaying where it occurs. Comment it for submission. # raise f.close()
8a6bff166e4c0901e0f69d7289a14b3b1628f00a
moqi112358/leetcode
/solutions/0207-course-schedule/course-schedule.py
3,145
3.953125
4
# There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1. # # Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] # # Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? # #   # Example 1: # # # Input: numCourses = 2, prerequisites = [[1,0]] # Output: true # Explanation: There are a total of 2 courses to take. #   To take course 1 you should have finished course 0. So it is possible. # # # Example 2: # # # Input: numCourses = 2, prerequisites = [[1,0],[0,1]] # Output: false # Explanation: There are a total of 2 courses to take. #   To take course 1 you should have finished course 0, and to take course 0 you should #   also have finished course 1. So it is impossible. # # #   # Constraints: # # # The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented. # You may assume that there are no duplicate edges in the input prerequisites. # 1 <= numCourses <= 10^5 # # class Solution: # DFS def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: pre = [[] for _ in range(numCourses)] for item in prerequisites: pre[item[0]].append(item[1]) visited = [0] * numCourses for node in range(numCourses): if not self.dfs(visited, pre, node): return False return True def dfs(self, visited, pre, node): if visited[node] == -1: return False if visited[node] == 1: return True visited[node] = -1 for i in pre[node]: if not self.dfs(visited, pre, i): return False visited[node] = 1 return True # Kahn's algorithm # def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: # repre = [set() for _ in range(numCourses)] # repre[i] - the next to course i # pre = [set() for _ in range(numCourses)] # pre[i] - the previous to course i # res = [] # Empty list that will contain the sorted elements # graph = set() # start = set([i for i in range(numCourses)]) # Set of all nodes with no incoming edge # for item in prerequisites: # pre[item[0]].add(item[1]) # repre[item[1]].add(item[0]) # if item[0] in start: # start.remove(item[0]) # graph.add((item[1], item[0])) # while len(start) != 0: # node = list(start)[0] # start.remove(node) # res.append(node) # for nxt_node in repre[node]: # graph.remove((node, nxt_node)) # pre[nxt_node].remove(node) # if len(pre[nxt_node]) == 0: # start.add(nxt_node) # if len(graph) > 0: # return False # else: # return True
15e8951ad267f02e1fcd9cf34af41a6e12b26f3a
boyang-ml/TSP
/dijkstra/src/dijkstra.py
3,557
3.5625
4
#!/usr/bin/python3 # coding: utf-8 ''' Name: Michael Young Email: michaelyangbo@outlook.com Date: 2019/2/8 Ref.: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm ''' import networkx as nx import matplotlib.pylab as plt def draw_pic(graph, color_map): # store the edge has been add to G edge = [] width=[] G = nx.Graph() # store the edge need to be color red target_edges = [] # add node for node in graph: G.add_node(node) # pick the edge need to color red into target_edge for index, node in enumerate(shortest_path_pic): if index < len(shortest_path_pic) - 1: target_edges.append([node, shortest_path_pic[index + 1]]) target_edges.append([shortest_path_pic[index + 1], node]) for outerNode in graph.items(): for innerNode in outerNode[1].items(): if [innerNode[0], outerNode[0]] not in edge: edge.append([outerNode[0], innerNode[0]]) G.add_edge(outerNode[0], innerNode[0], length=innerNode[1]) width.append(innerNode[1]/150) edge_color_map.append('black') for target_edge in target_edges: if [outerNode[0], innerNode[0]] == target_edge: edge_color_map.pop() edge_color_map.append('red') pos = nx.spring_layout(G) nx.draw(G, pos, with_labels=True, edge_color=edge_color_map,width=width) plt.show() def dijkstra(graph, src, dest, visited=[], distances={}, predecessors={}): global shortest_path_pic if src not in graph: raise TypeError('the root of the shortest path tree cannot be found in the graph') if dest not in graph: raise TypeError('the target of the shortest path cannot be found in the graph') # ending condition if src == dest: # build the shortest path and display it path = [] pred = dest while pred != None: path.append(pred) pred = predecessors.get(pred, None) shortest_path_pic = path print('shortest path: ' + str(path) + " cost=" + str(distances[dest])) else: # if it is the initial run, initializes the cost if not visited: distances[src] = 0 # visit the neighbors for neighbor in graph[src]: if neighbor not in visited: new_distance = distances[src] + graph[src][neighbor] if new_distance < distances.get(neighbor, float('inf')): distances[neighbor] = new_distance predecessors[neighbor] = src # mark as visited visited.append(src) # now that all neighbors have been visited: recurse # select the non visited node with lowest distance 'x' # run Dijkstra with src='x' unvisited = {} for k in graph: if k not in visited: unvisited[k] = distances.get(k, float('inf')) x = min(unvisited, key=unvisited.get) dijkstra(graph, x, dest, visited, distances, predecessors) if __name__ == "__main__": # store shortest path shortest_path_pic = [] # store color edge_color_map = [] graph = {'a': {'b': 100, 'c': 200}, 'b': {'a': 100, 'c': 300, 'd': 500}, 'c': {'a': 200, 'b': 300, 'e': 600}, 'd': {'b': 500, 'e': 400, 'f': 200}, 'e': {'c': 1000, 'd': 400, 'f': 100}, 'f': {'d': 200, 'e': 100}} dijkstra(graph, 'a', 'f') draw_pic(graph, edge_color_map)
b88bb8737c4aa8961f7b74c51e31c203ea883caf
hjh0915/study-python-struction
/search/order_search.py
795
3.828125
4
def sequentialSearch(alist, item): """无序列表的顺序搜索""" pos = 0 found = False while pos < len(alist) and not found: if alist[pos] == item: found = True else: pos = pos + 1 return found def orderdSequentialSearch(alist, item): """有序列表的顺序搜索""" pos = 0 found = False stop = False while pos < len(alist) and not found and not stop: if alist[pos] == item: found = True else: if alist[pos] > item: stop = True else: pos = pos + 1 return found if __name__ == '__main__': x = [1, 9, 2, 4, 8] print(sequentialSearch(x, 4)) y = [1, 2, 3, 4, 5] print(orderdSequentialSearch(y, 8))
13ac337c86d6fe4a67e30fe1b142b1ebec09aa11
Rubbic/Python
/Unidad07/Errores.py
496
3.953125
4
print("Hola"#Error en sitaxis prin("Hola")#error de nombre #Errores semanticos lista = [1,2,3] for i in range(4): if len(lista)>0: lista.pop() print(lista) else: print("la lista ya esta vacia") """ lista.pop() lista.pop() lista.pop() print(lista) lista.pop() """ #Errores de tipo de dato n = input("Introduce un numero") print(n + 5) #se convierte en int o float pero tambien tener cuidado si se trabajara con una cadena de datos
f84476a434bc20a53ee311368bdf5a87b4ec66f9
ShiningLo/Hello-Python
/pt.py
537
3.765625
4
def addToInventory(inventory, addedItems): for item in addedItems: inventory.setdefault(item,0) inventory[item]+=1 return inventory pass # your code goes here def displayInventory(dic): count=0 for k,v in dic.items(): print(str(v)+' '+str(k)) count+=v print('Toltal number of items:'+str(count)) inv = {'gold coin': 42, 'rope': 1} dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] inv = addToInventory(inv, dragonLoot) displayInventory(inv)
32d321a835debaf977c3996806b364cd8e51d686
keshavkummari/python-nit-7am
/DataTypes/Strings/TRIPLE_QUOTES_1.py
582
4.0625
4
#!/usr/bin/python3 para_str = '''this is a long string that is made up of several lines and non-printable characters such as TAB ( \t ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this within the brackets [ \n ], or just a NEWLINE within the variable assignment will also show up. ''' print ("Lets access triples",para_str,type(para_str),id(para_str),sep="\n") # Below is the multiline comment ''' Some text linux unix ''' # Below is the multiline comment """ Some text perl python django """
3bd46f443a7edc70d84b34e304368d7f3a3f74ab
hanbinchoi/Python_practice
/judge_import.py
65
3.765625
4
import math as m radius=float(input()) print(radius*radius*m.pi)
e69c7a13efc1f7ce72cfd149919e98ecd16f4580
ducquang2/Python
/Basic_on_HackerRank/string-validators.py
267
3.5
4
if __name__ == '__main__': s = input() print(any(temp.isalnum() for temp in s)) print(any(temp.isalpha() for temp in s)) print(any(temp.isdigit() for temp in s)) print(any(temp.islower() for temp in s)) print(any(temp.isupper() for temp in s))
bb2cae34c0f8373294fe1076460cccb687ba805f
mfmaiafilho/arquivos_python
/Questao3-arvoreBinariaDeBusca.py
2,321
4.15625
4
""" QUESTAO 3 Desenvolva uma árvore binária de Busca em Python. E em seguida nesta mesma árvore binária desenvolva a busca pela chave de número 5. """ import random # NO class Node: def __init__(self, dado): self.dado = dado self.dir = None self.esq = None def __str__(self): return str(self.dado) ##################################### #ARVORE BINARIA class ArvoreB: def __init__(self, dado=None, node=None): if node: self.root = node elif dado: node = Node(dado) self.root = node else: self.root = None '''percurso simetrico''' def percuso_simetrico(self, node=None): if node is None: node = self.root if node.esq: self.percuso_simetrico(node.esq) print(node, end=' ') if node.dir: self.percuso_simetrico(node.dir) ##################################### #ARVORE BINARIA DE BUSCA class BinarySearchTree(ArvoreB): """Inserir na arvore""" def insere(self, valor): pai = None aux = self.root while(aux): pai = aux if valor < aux.dado: aux = aux.esq else: aux = aux.dir if pai is None: self.root = Node(valor) elif valor < pai.dado: pai.esq = Node(valor) else: pai.dir = Node(valor) """Buscar na arvore""" def busca(self, valor): return self._buscar(valor, self.root) def _buscar(self, valor, node): if node is None: return node if node.dado == valor: return BinarySearchTree(node) if valor < node.dado: return self._buscar(valor, node.esq) return self._buscar(valor, node.dir) ######################################## #### TESTE Busca #random.seed(77) valores = random.sample(range(1, 40), 10) bst = BinarySearchTree() for i in valores: bst.insere(i) bst.percuso_simetrico() chave = [5] for item in chave: r = bst.busca(item) print("") if r is None: print("(",item, ") nao encontrou") else: print("(",r.root.dado, ") encontrou")
24f7306489a3227a932fd0ad8f6c8c98666c6a8e
chenran1/leetcode
/note/24_交换链表中的节点.py
822
4.03125
4
""" 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。   示例: 给定 1->2->3->4, 你应该返回 2->1->4->3. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def swapPairs(self, head: ListNode) -> ListNode: if not (head and head.next): return head tmp = head.next head.next = self.swapPairs(tmp.next) tmp.next = head return tmp
c6a25890053b2c81e03e4df98c01a10125569109
NonCover/-
/leetcode.面试题62.圆圈中最后剩下的数字.py
770
3.640625
4
''' @author:noc @time:2020年3月30日 @url:https://leetcode-cn.com/problems/yuan-quan-zhong-zui-hou-sheng-xia-de-shu-zi-lcof/ ''' ''' 最优解发:参考约瑟夫环问题,因为我们删除至剩下一个数时,这个数必然在数组的 0 位置,然后我们可以反推出这个位置在一开始的位置,这个位置就是最终答案 ''' class Solution: def lastRemaining(self, n: int, m: int) -> int: ret = 0 for i in range(2, n + 1): ret = (ret + m) % i # 反推公式,每次我们删除的数是上一次删除数在数 3个,那么我们 +3 在对当前数组取模就是上一次的位置。 return ret if __name__ == '__main__': out = Solution().lastRemaining(10, 17) print(out)
13650302c05cbbad870286b9cda4d49dc5c693db
zgcgreat/PRML-1
/prml/neural_networks/layers/relu.py
851
3.84375
4
from .layer import Layer class ReLU(Layer): """ Rectified Linear Unit y = max(x, 0) """ def forward(self, x, training=False): """ element-wise rectified linear transformation Parameters ---------- x : ndarray input Returns ------- output : ndarray rectified linear of each element """ if training: self.output = x.clip(min=0) return self.output else: return x.clip(min=0) def backward(self, delta): """ backpropagation of errors Parameters ---------- delta : ndarray output errors Returns ------- delta_in : ndarray input errors """ return (self.output > 0) * delta
4c6cd85e6f6874deaa73d17e2f39aeda39dffb17
josecaromuentes2019/CursoPython
/practicaGeneradores.py
722
4.09375
4
def numerosPares(numero): num = 1 while num<numero: yield num * 2 num +=1 pares = numerosPares(10) print(next(pares)) print(next(pares)) print(next(pares)) print('') print('') #cuando el parametro es presedido por un * significa que la funncion resibe varios parametros def ciudades(*mis_ciudades): for elemento in mis_ciudades: yield from elemento city = ciudades('Medellin','Barranquilla','Cali','Monteria','ibague','bogota','pasto') print(next(city)) print(next(city)) print(next(city)) mi_lista =[3,6,7,1,5,4,2] print(mi_lista) mi_lista.pop(0) print('eliminamos elemento en posicion 0 con pop(0) ',mi_lista) print(sorted(mi_lista)) #invierte la lista print(mi_lista[::-1])
2675627344adb318eda2ab8c1901eae2455ba638
Neelros/Tisn
/ex1 11.py
146
3.65625
4
nb=int(input("Entrer une année")) if nb%400==0 or (nb % 4 == 0 and nb %100 !=0) : print("bissextile") else: print("pas bissextile")
17decb83e449daae6addcce2735bd4c86679f267
eep0x10/Pyton-Basics
/5/py2.py
394
4.1875
4
""" Faça um programa para imprimir: 1 1 2 1 2 3 ..... 1 2 3 ... n para um n informado pelo usuário. Use uma função que receba um valor n inteiro imprima até a n-ésima linha. """ def piramide(n): m=n+1 for i in range(m): k=i+1 for j in range(k): print(j,end=" ") print("") piramide(5)
51c5e0c750f4e5b1aea3b3ec58c0126a8c1550c8
joeybaba/mywork
/algorithm/shellsort1.py
756
3.84375
4
#!/usr/bin/env python # coding: UTF-8 # https://www.bilibili.com/video/av94166791?from=search&seid=12118334399760597355 def h_sorting(alist, alen, ah): # 做一次排序 i = h = ah while i < alen: key = alist[i] j = i - h while j >= 0 and alist[j] > key: alist[j + h] = alist[j] j -= h alist[j + h] = key i += 1 def shellsort(alist, alen): # 做h次增量递减序列排序 h = alen / 2 while h >= 1: h_sorting(alist, alen, h) h = h / 2 # # h=[8, 4, 2, 1] # # for i in h: # h_sorting(alist, alen, i) if __name__ == '__main__': alist = [1, 3, 2, 5, 4, 6, 8, 9, 2, 9] shellsort(alist, len(alist)) print(alist)
b5fd3e9e70c31b26df72ba3b29772b4166899fc1
PenelopeJones/conditional_nps
/conditional_nps/encoder.py
2,091
3.5625
4
""" Function for 'encoding' context points (x, y)_i using a fully connected neural network. Input = (x, y)_i; output = r_i. """ import torch.nn as nn import torch.nn.functional as F class Encoder(nn.Module): """The Encoder.""" def __init__(self, input_size, output_size, encoder_n_hidden=4, encoder_hidden_size=8): """ :param input_size: An integer describing the dimensionality of the input to the encoder; in this case the sum of x_size and y_size :param output_size: An integer describing the dimensionality of the embedding, r_i :param encoder_n_hidden: An integer describing the number of hidden layers in the neural network :param encoder_hidden_size: An integer describing the number of nodes in each layer of the neural network """ super().__init__() self.input_size = input_size self.output_size = output_size self.n_hidden = encoder_n_hidden self.hidden_size = encoder_hidden_size self.fcs = nn.ModuleList() for i in range(encoder_n_hidden + 1): if i == 0: self.fcs.append(nn.Linear(input_size, encoder_hidden_size)) elif i == encoder_n_hidden: self.fcs.append(nn.Linear(encoder_hidden_size, output_size)) else: self.fcs.append(nn.Linear(encoder_hidden_size, encoder_hidden_size)) def forward(self, x): """ :param x: A tensor of dimensions [context_set_samples, number of context points N_context, x_size + y_size]. In this case each value of x is the concatenation of the input x with the output y (confusingly) :return: The embeddings, a tensor of dimensionality [context_set_samples, N_context, r_size] """ #Pass (x, y)_i through the fully connected neural network. x = x.view(-1, self.input_size) for fc in self.fcs: x = F.relu(fc(x)) return x
5986e92a96594d13b913bffe59dcd961b7a92a0c
codxse/mitx6001
/2016/WEEK_2/ex2-3.py
718
4
4
false_guess = True _min = 0 _max = 100 initial = 0 str1 = 'Enter \'h\'' str2 = 'to indicate the guess is too high. Enter \'l\' ' str3 = 'to indicate the guess is too low. Enter \'c\' ' str4 = 'to indicate I guessed correctly. ' print('Please think of a number between 0 and 100!') while(false_guess): guess = initial + (_max - _min) // 2 print('Is your secret number ' + str(guess) + '?') i = input(str1 + str2 + str3 + str4) if (i == 'c'): print('Game over. Your secret number was:', guess) false_guess = False elif (i == 'l'): _min = guess initial = _min elif (i == 'h'): _max = guess else: print('Sorry, I did not understand your input.')
230217187af7422d51e61407fb0a632442858d1f
atraore1/poetry-slam-abba
/main.py
694
3.703125
4
from random import choice def get_file_lines(filename): in_file = open(filename, "r") lines = in_file.readlines() in_file.close() return lines def lines_printed_backwards(lines_list): lines_list.reverse() lines_length = len(lines_list) for i in range(lines_length): line = lines_list[i] line_num = lines_length - i print(f"{line_num} {line}") def lines_printed_random(lines_list): for line in lines_list: print(choice(lines_list)) for line in open('poem.txt'): if line.startswith('I') or line.startswith('You'): print(line) poem_lines = get_file_lines('poem.txt') lines_printed_backwards(poem_lines)
d883a6bf48aa7fe2c8d6ecfe0ef5b23d319b4b76
FaisanL/simplecode
/calcularDescuento.py
244
3.71875
4
def calcularDescuento(): precio = int(input('ingrese el precio de su producto: ')) descuento = precio * 0.30 print(f'el descuento aplicado es de: {descuento}') ptotal = precio-descuento print(f'El precio total es: {ptotal}')
17320ad79f063d36b3df8292e874392a679c4790
GabrielNagy/Year3Projects
/PE/Lab5/ex1.py
583
3.6875
4
import unittest import unittest.mock class MyClass: def set_string(self): self.string = str(input("Enter string: ")) def to_uppercase(self): return self.string.upper() class Test(unittest.TestCase): def setUp(self): pass def test_capitalization(self): with unittest.mock.patch('builtins.input', return_value='capitalize this'): line = "CAPITALIZE THIS" mock = MyClass() mock.set_string() self.assertEqual(mock.to_uppercase(), line) if __name__ == "__main__": unittest.main()
375b0a95524762c849040ed9ab624c6db8bd0890
vivekkhimani/Python_Learning_Practice
/OOP_Basics_and_AdvancesSyntax/ELpractice.py
462
4
4
class EnglishLength: def __init__(self, yards=0, feet=0, inches=0): self.__yards = yards + feet//3 self.__feets = feet + inches//12 self.__inches = inches%12 self.__feets%=3 def __add__ (self,other): return (self.__inches + other.__inches, self.__yards + other.__yards, self.__feets + other.__feets) test1 = EnglishLength(25,15,14) test2 = EnglishLength(30,15,14) print(test1.__add__(test2))
d85f99fed1a3ca00fa2a6693dc76b1bda1931397
HarsimratKohli/Algorithms
/EPI/Chapter 8/10.py
1,416
4.125
4
#not completed class Node: def __init__(self,val): self.val=val self.next =None class LinkedList: def __init__(self): self.head=None def insert(self,val): temp = Node(val) if self.head ==None: self.head= temp else: temp.next=self.head self.head=temp def print_list(self): temp=self.head while temp!=None: print(temp.val) temp =temp.next def even_odd(self): even_head=odd_head=None t=1 temp=self.head while temp!=None: Next = temp.next t^=1 if t ==0: if even_head==None: even_head =temp even_head.next=None else: t1=even_head while t1!=None" temp.next=None even_head.next=temp # even_head=temp else: if odd_head==None: odd_head=temp # else: # temp.next=odd_head # even_head=temp temp=Next print(odd_head.val) print(even_head.val) ll=LinkedList() ll.insert(1) ll.insert(2) ll.insert(3) ll.insert(4) # ll.print_list() ll.even_odd()
aae4fe3990b21268f4e27b59d6cc0aab9386c116
JurgenKniest/TICT-V1PROG-15
/Les 04/Oefening 4_4.py
123
3.671875
4
def f(x): res = x * 2 + 10 return res resultaat =f(2) print (resultaat) y = 4 resultaat1 = f(y) print(resultaat1)
46f42ac972936e179b044b74448e5a944cd2316d
Say10IsMe/SVBA-ED
/Practica 12-Cola Circular (Pop).py
9,221
3.578125
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 16 18:12:36 2018 @author: pc """ cola=[] def metodocreate(): global cola cola=[0,0,0,0,0] global rear global front rear=-1 front=0 print("Se ha creado la cola circular con longitud de 5 espacios") print(cola) #en el metodo push, usamos los indices de front y rear def metodopushjojo(): global front global rear #primero comparamos si en la posición actual de front #se encuentra un 0, de ser así, se entiende que no se #han introducido elementos en la cola, por lo que se procede #a capturar el primer valor para la cola y ponerlo en #la posición de rear, que primero se incrementa en 1 if front==5: front=0 if cola[front]==0: print("Introduzca un valor para la cola") v=input(); #Usaremos la siguiente comparación para evitar el #overflow en el indice rear if rear==5: rear=-1 rear+=1 cola[rear]=v print(cola) else: rear+=1 if rear==5: rear=0 cola[rear]=v print(cola) else: cola[rear]=v print(cola) #Si en la posicion de front, no se encuentra un 0 (que quiere #decir que ya se inserto el primer elemento), pasamos # a la siguiente comparación, en la cual verificamos si el #valor del indice de rear es menor a 4, lo que quiere decir que #aun no se desborda del limite de nuestro arreglo else: #de ser así, verificamos si la posición de rear+1 es igual #a la posición del front, lo que quiere decir que la cola #se encuentra llena ya que el flujo de datos dio la vuelta #hasta llegar de nuevo al front if rear<4: if rear+1==front: print("La cola se encuentra llena!") #si la condición no se cumple, se entiende que todavía #podemos seguir almacenando elementos hasta que #el valor de rear ya no sea menor a 4 else: print("Introduzca un valor para la cola") v=input(); rear+=1 cola[rear]=v print(cola) #una vez que el valor de rear ya no es menor que 4 #es decir, que alcanzó el valor de 5, comparamos si #en la posición de front-1 se encuentre un 0 (esto sucederá #si antes se realizó un pop en la estructura, lo que quiere #decir que se dejó un 0 en la posición de front-1) lo que #significa que hay espacio disponible para un elemento else: #entonces, igualamos el valor de rear a -1 y pedimos #el dato para almacenar, incrementamos el valor #de rear en 1 y almacenamos el dato en la posición #de rear actual es decir, 0, y entonces empieza de nuevo #el orden de las condiciones que nos han conducido aquí if cola[front-1]==0: rear=-1 print("Introduzca un valor para la cola") v=input(); rear+=1 cola[rear]=v print(cola) #si en la posición de front-1 no hay un 0 (es decir, hay #un valor) entonces se entiende que no hay espacio para #meter mas elementos, por lo que se dice que la cola #esta llena else: print("La cola se encuentra llena!!") #definimos nuestro metodo pop, el cual se encargará de sacar los elementos #de nuestra cola def metodopopjojo(): #usaremos las variables de rear y front global rear global front #primero comparamos si el valor actual de rear es menor a 5, osea #que no se ha desbordado, entonces comparamos si en la actual posición #de front hay un 0, de ser así, entonces no hay elementos por salir #por consecuencia, la cola se encuentra vacia if front<5: if (cola[front]==0): print("La cola se encuentra vacia!") #si no hay un 0, procedemos a hacer las siguientes comparaciones: #si el valor de front es menor a 5 (que no se ha desbordado) #imprimimos el valor que esta por salir (el valor que se encuentra #en la posicion de front), seguido, reemplazamos ese dato en esa #posicion con un 0 e incrementamos el valor de front en 1, ya que #la posición de front se moverá al siguiente elemento else: if front<5: print("El valor que sera borrado de la cola es el:") print(cola[front]) cola[front]=0 print(cola) front+=1 #si el valor de front no es menor a 5, es decir, que es 5 #verificamos si en la posición de rear se encuentra un 0 #si se cumple la condición, entonces se sabe que se han eliminado #todos los elementos y por consecuencia la cola esta vacia else: if cola[rear]==0: print("La cola se encuentra vacia!!!") #si es diferente de 0, reiniciamos el valor de front #ya que el flujo de datos ya dio la vuelta a la cola else: #reiniciamos el valor de front, y entonces "vaceamos" #el espacio de este, aumentamos su valor en 1 para que #el front pase al siguiente elemento de la lista front=0 print("El valor que sera borrado de la cola es el:") print(cola[front]) cola[front]=0 print(cola) front+=1 #si la primera condicón no se cumple, entonces comparamos si en #rear se encuentra un 0, de ser así, se entiende que la cola #esta vacía else: if cola[rear]==0: print("La cola se encuentra vacia!!") #si no es así, entonces reiniciamos el valor de front y reiniciamos #el flujo de datos (porque el flujo ya dio la vuelta a la cola) else: #mostramos el valor que esta en front y lo reemplazamos #con un 0, es decir, un espacio vacio front=0 print("El valor que sera borrado de la cola es el:") print(cola[front]) cola[front]=0 print(cola) front+=1 def opciones(): print("\nIntroduzca la opcion que desee") print("1:Crear la cola") print("2:Metodo Push") print("3:Metodo Pop") print("5:Para salir") e=int(input()) if (e==1): if len(cola)==5: print("Ya se ha creado una cola anteriormente!") opciones(); else: metodocreate(); opciones(); if(e==2): if len(cola)==5: metodopushjojo(); else: print("No se ha creado una cola anteriormente!") opciones(); #si el usuario eligió hacer un pop, lo primero es verificar si #la cola existe con la comparación de len(cola)==5, si es así, #entonce es posible ejecutar el metodo pop, pero si la longitud no es #5, se entiende que no se ha creado la cola, por lo tanto, no se puede #proseguir hasta que se haya creado la cola if (e==3): if len(cola)==5: metodopopjojo(); opciones(); else: print("No se ha creado una cola anteriormente") opciones(); """ if (e==4): if len(cola)==5: metodopeekJOJO(); opciones(); else: print("No se ha creado una cola anteriormente!") opciones(); """ if (e==5): print("Que tenga buen dia:D") opciones();
f5e200c783d70cf22dca9b62de2b691e338e9d8a
HeyAnirudh/leetcode
/birthday date.py
597
3.984375
4
import datetime from datetime import date import calendar def find(date): born = datetime.datetime.strptime(date, '%d %m %Y').weekday() return (calendar.day_name[born]) i = 0 while i < 2: day = input() month = input() year = input() date = day + " " + month + " " + year day = {1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thrusday", 5: "Friday", 6: "Saturday", 7: "Sunday"} key_list = list(day.keys()) val_list = list(day.values()) if find(date) in val_list: position = val_list.index(find(date)) print(key_list[position]) i += 1
cc3accd3b0f337605a0d456048c0722f69754a56
medwards147/Udacity_Data_Analyst_Nanodegree
/Project5_Enron_Machine_Learning/final_project/explore_enron_data.py
10,115
3.65625
4
#!/usr/bin/python """ Starter code for exploring the Enron dataset (emails + finances); loads up the dataset (pickled dict of dicts). The dataset has the form: enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } {features_dict} is a dictionary of features associated with that person. You should explore features_dict as part of the mini-project, but here's an example to get you started: enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000 """ from feature_format import featureFormat, targetFeatureSplit import pickle enron_data = pickle.load(open("../final_project/final_project_dataset.pkl", "r")) # Number of people in dataset - ANS 146 print("The number of people in the dataset: %d" % len(enron_data.keys())) # Number of features for an individual (all are the same so I choose one) - ANS 21 print("The number of features for each person are: %d" % len(enron_data['METTS MARK'])) # The features provided are enron_data['METTS MARK'].keys() # For loop that counts pois - ANS 18 count = 0 for person in enron_data.keys(): if enron_data[person]["poi"] == 1: count += 1 else: continue print("The number of POI's in the dataset is %d " % count) # Count pois in poi_names.txt poi_yes = 0 poi_total = 0 with open("../final_project/poi_names.txt", "r") as text_file: text_file.readline() text_file.readline() for line in text_file: try: if line[1] == "y": poi_yes += 1 poi_total +=1 else: poi_total +=1 except: continue print(poi_yes) # 4 print(poi_total) # 35 # total value of stock of an individual - James Prentice #name = "Prentice James" name = "Colwell Wesley" name = name.upper() enron_data[name]['from_this_person_to_poi'] name = "SKILLING JEFFREY K" enron_data[name]['exercised_stock_options'] #largest total payments of fastow, lay, skilling names = ["SKILLING JEFFREY K", "FASTOW ANDREW S", "LAY KENNETH L"] ans = {} for name in names: ans[name] = enron_data[name]['total_payments'] print ans # how many folks in this dataset have a quantified salary or known email? count_non_nans = 0 count_nans = 0 for key in enron_data.keys(): if enron_data[key]['salary'] != 'NaN': count_non_nans += 1 else: count_nans += 1 print(count_non_nans) print(count_nans) # known email? count_non_nans = 0 count_nans = 0 for key in enron_data.keys(): if enron_data[key]['email_address'] != 'NaN': count_non_nans += 1 else: count_nans += 1 print(count_non_nans) print(count_nans) # Percentage of people who have "NaN" as their total payments count_non_nans = 0 count_nans = 0 for key in enron_data.keys(): if enron_data[key]['total_payments'] != 'NaN': count_non_nans += 1 else: count_nans += 1 print(count_non_nans) print(count_nans) print float(count_nans)/(float(count_non_nans) + float(count_nans)) # 14.4% # Percentage of people who have "NaN" as their total payments count_non_nans = 0 count_nans = 0 for key in enron_data.keys(): if enron_data[key]['poi'] == 1: if enron_data[key]['total_payments'] != 'NaN': count_non_nans += 1 else: count_nans += 1 else: continue print(count_non_nans) print(count_nans) print float(count_nans)/(float(count_non_nans) + float(count_nans)) # 0% # Percentage of POIs if added 10 POIs with NaN for total_payments poi_count = 10 count_nans = 0 count_non_nans = 0 for key in enron_data.keys(): if enron_data[key]['poi'] == 1: poi_count += 1 if enron_data[key]['total_payments'] != 'NaN': count_non_nans += 1 else: count_nans += 1 else: continue print(count_non_nans) print(count_nans) print float(count_nans+ 10)/(float(count_non_nans) + float(count_nans + 10)) # 35.7% # Outlier salary / bonus for key in enron_data.keys(): if enron_data[key]['salary'] > 1000000 and enron_data[key]['salary'] != 'NaN': print "name: " + key print "salary:", enron_data[key]['salary'] print "bonus: ", enron_data[key]['bonus'] # Result ("TOTAL" was really high!) DUH! # name: TOTAL # salary: 26704229 # bonus: 97343619 # Checking salary > $1M and bonus > $5M for key in enron_data.keys(): if enron_data[key]['salary'] > 1000000 and enron_data[key]['salary'] != 'NaN': if enron_data[key]['bonus'] > 5000000 and enron_data[key]['bonus'] != 'NaN': print "name: " + key print "salary:", enron_data[key]['salary'] print "bonus: ", enron_data[key]['bonus'] # Checking max and min values for exercised_stock_options stock_options = {} for key in enron_data.keys(): if enron_data[key]['exercised_stock_options'] != 'NaN': stock_options[key] = enron_data[key]['exercised_stock_options'] del stock_options['TOTAL'] max(stock_options.iteritems(), key=lambda x:x[1]) # ('LAY KENNETH L', 34348384) min(stock_options.iteritems(), key=lambda x:x[1]) #('BELFER ROBERT', 3285) # Checking max and min values for salary salary = {} for key in enron_data.keys(): if enron_data[key]['salary'] != 'NaN': salary[key] = enron_data[key]['salary'] del salary['TOTAL'] max(salary.iteritems(), key=lambda x:x[1]) # ('SKILLING JEFFREY K', 1111258) min(salary.iteritems(), key=lambda x:x[1]) # ('BANNANTINE JAMES M', 477) #count 'Nan' per key to see who is missing al ot of data #found 'THE TRAVEL AGENCY IN THE PARK with 18 NaNs count_dict = {} for name in enron_data.keys(): for value in enron_data[name].values(): if value == 'NaN': count += 1 count_dict[name] = count count = 0 # Create new feature of ratio of emails from a person to poi compared to total from emails for name in enron_data.keys(): from_to_poi_ratio = float(enron_data[name]['from_this_person_to_poi']) / float(enron_data[name]['from_messages']) enron_data[name]['from_to_poi_ratio'] = from_to_poi_ratio # Find way to combine finanical features features_financial = [ "bonus", "deferral_payments", "deferred_income", "director_fees", "exercised_stock_options", "expenses", "loan_advances", "long_term_incentive", "other", "restricted_stock", "restricted_stock_deferred", "salary", "total_payments", "total_stock_value", #'financial_value' # new feature ] # count of total financial features available for pois count_dict = {} count = 0 for name in enron_data.keys(): if enron_data[name]['poi'] == 1: for feature in features_financial: if enron_data[name][feature] != 'NaN': count += 1 count_dict[name] = count count = 0 # Percentage of people who have "NaN" as their total payments (POIs only) count_non_nans = 0 count_nans = 0 for feature in features_financial: for key in enron_data.keys(): if enron_data[key]['poi'] == 1: if enron_data[key][feature] != 'NaN': count_non_nans += 1 else: count_nans += 1 #print("for feature " + feature + " the non nan count is {}".format(count_non_nans)) print(feature + " nan count is {}".format(count_nans)) percentage = float(count_nans)/(float(count_non_nans) + float(count_nans)) # 0% #print("for feature " + feature + " the percentage of nans are {}".format(percentage)) # Percentage of people who have "NaN" as their total payments count_non_nans = 0 count_nans = 0 for feature in features_financial: for key in enron_data.keys(): if enron_data[key]['poi'] == 0: if enron_data[key][feature] != 'NaN': count_non_nans += 1 else: count_nans += 1 else: continue #print("for feature " + feature + " the non nan count is {}".format(count_non_nans)) #print("for feature " + feature + " the nan count is {}".format(count_nans)) percentage = float(count_nans)/(float(count_non_nans) + float(count_nans)) # 0% print("for feature " + feature + " the percentage of nans are {}".format(percentage)) # delete 'TOTAL' key prior to visualization data def deleteKey(data_dict, key): del data_dict[key] return data_dict #deleteKey(enron_data, 'TOTAL') # create plots to aid in feature engineering def visualize(data_dict, feature_x, feature_y): """ generates a plot of feature y vs feature x, colors poi """ import matplotlib.pyplot as plt data = featureFormat(data_dict, [feature_x, feature_y, 'poi'], remove_all_zeroes=False) for datum in data: x = datum[0] y = datum[1] poi = datum[2] color = 'blue' if not poi else 'red' plt.scatter(x, y, color=color) plt.xlabel(feature_x) plt.ylabel(feature_y) #plt.show() plt.savefig('../final_project/plots/plot_{0}_{1}'.format(feature_x, feature_y)) # save the figure to file plt.close() def visualizeFeatureCombinations(): from itertools import combinations for feature_1, feature_2 in combinations(features_financial, 2): visualize(enron_data, feature_1, feature_2) # Take note of plots where the pois seem to seperate themselves from the rest # 'total_stock_value', 'exercised_stock_options', 'bonus', 'salary' # Combination of features to create new 'financial_value' feature def addFinancialValueFeature(enron_data): financial_value_features = ['total_stock_value', 'exercised_stock_options', 'bonus', 'salary'] for name in enron_data: enron_data[name]['financial_value'] = 0 for feature in financial_value_features: if enron_data[name][feature] != 'NaN': enron_data[name]['financial_value'] += enron_data[name][feature] return enron_data
9886d8035f394f77c7f5891b6ca7fabe38b34d77
RanyellHenrique/exerciciosPython
/colecoesPython01.py
135
3.578125
4
lista = [1, 0, 5, -2, -5, 7] soma = lista[0] + lista[1] + lista[5] print(soma) lista[4] = 100 for numero in lista: print(numero)
f193ec7a8474995fdd361a6777e893d128de4add
Aasthaengg/IBMdataset
/Python_codes/p03285/s996631407.py
123
3.875
4
n=int(input()) if n==4 or n==7 or n==8 or n==11 or n==12 or n==15 or n==16 or n>=18: print("Yes") else: print("No")
adec6702a83b1676b337082d7eab0980b5c71cde
mo7amed3umr/new-task-sbme
/mtplt.py
600
3.53125
4
from numpy import * import plotly as py from plotly.graph_objs import * #just a sphere theta = linspace(0,2*pi,100) phi = linspace(0,pi,100) x = outer(cos(theta),sin(phi)) y = outer(sin(theta),sin(phi)) z = outer(ones(100),cos(phi)) # note this is 2d now data = Data([ Surface( x=x, y=y, z=z ) ]) layout = Layout( title='Bloch sphere', autosize=False, width=500, height=500, margin=Margin( l=65, r=50, b=65, t=90 ) ) fig = Figure(data=data, layout=layout) print (py.plot(fig, filename='bloch-sphere-surface'))
0394538f91891e64e90c3df59570df43e76de4a4
dudem8z7l/script-dictionary
/1a.data-preparation/check_missing_data.py
459
3.6875
4
def check_missing_data(data): ''' AIM -> Checking missing data INPUT -> df OUTPUT -> Missing data report ------ ''' # check for any missing data in the df (display in descending order) total = data.isnull().sum().sort_values(ascending = False) percent = (data.isnull().sum()/data.isnull().count()*100).sort_values(ascending = False) return pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])
c759993e14d199c2628344c82bdba1dd467982c5
ajamanjain/AI-with-WhiteHat-Junior
/Multiplying numbers of the list.py
512
4.15625
4
# Write your code here # Step 1: Define a list with some random numbers num_list = [2,3,7] # Step 2: Get the length of the list using 'len()' function length = len(num_list) # Step 3: Initialize two variables 'i' and 'result' i = 0 result = 1 # Step 4: Iterate while loop till the length of the list while i<length: # Step 5: Multiply the 'result' variable with each element of the list. Use list indexing result *= num_list[i] # Increment 'i' variable i += 1 # Step 6: Print the result print(result)
42f32b19c26c70a351718eabfaf47311cfb87e88
erdos-project/pylot
/pylot/planning/cost_functions.py
5,332
3.84375
4
import math from collections import namedtuple from pylot.planning.utils import BehaviorPlannerState VehicleInfo = namedtuple( "VehicleInfo", [ 'next_speed', # The next vehicle speed. 'target_speed', # The target speed of the vehicle. 'goal_lane', # The id of the goal lane. 'delta_s', # Delta s distance to the goal location. 'speed_limit', # Speed limit in the area. ]) Trajectory = namedtuple( "Trajectory", [ 'intended_lane', # The id of the lane change to (i.e., next lane). 'final_lane', # Resulting lane for the current behavior. ]) def get_trajectory_data(state, vehicle_info, trajectory): final_lane = trajectory[:-1] if state == BehaviorPlannerState.PREPARE_LANE_CHANGE_LEFT: intended_lane = final_lane + 1 elif state == BehaviorPlannerState.PREPARE_LANE_CHANGE_RIGHT: intended_lane = final_lane - 1 else: intended_lane = final_lane return Trajectory(intended_lane, final_lane) def cost_speed(vehicle_info, predictions, trajectory): """ Computes cost of driving at a given speed. Args: vehicle_info: A VehicleInfo tuple. predictions: A dict of predictions for vehicles. trajectory: A Trajectory tuple. Returns: A cost in [0, 1]. """ # Cost of the car stopping. STOP_COST = 0.7 # How many km/h to drive at bellow speed limit. BUFFER_SPEED = 5.0 vehicle_info.target_speed = vehicle_info.speed_limit - BUFFER_SPEED if vehicle_info.next_speed < vehicle_info.target_speed: # Cost linearly decreases the closer we drive to target speed. return (STOP_COST * (vehicle_info.target_speed - vehicle_info.next_speed) / vehicle_info.target_speed) elif (vehicle_info.next_speed >= vehicle_info.target_speed and vehicle_info.next_speed < vehicle_info.speed_limit): # Cost linearly increases if we drive above target speed. return (vehicle_info.next_speed - vehicle_info.target_speed) / BUFFER_SPEED else: # Cost is always 1 if we drive above speed limit. return 1 def cost_lane_change(vehicle_info, predictions, trajectory): """ Computes cost of changing lanes. Args: vehicle_info: A VehicleInfo tuple. predictions: A dict of predictions for vehicles. trajectory: A Trajectory tuple. Returns: A cost in [0, 1]. """ # We want to penalize lane changes (i.e., high delta_d). delta_d = (2.0 * vehicle_info.goal_lane - trajectory.intended_lane - trajectory.final_lane) # Ensure that max cost is in [0, 1]. if abs(vehicle_info.delta_s) < 0.0001: # We're very close to the goal. return 1 else: return 1 - math.exp(-abs(delta_d) / vehicle_info.delta_s) def cost_inefficiency(vehicle_info, predictions, trajectory): """ Computes cost of driving in the fastest lane. Args: vehicle_info: A VehicleInfo tuple. predictions: A dict of predictions for vehicles. trajectory: A Trajectory tuple. Returns: A cost in [0, 1]. """ # Cost becomes higher for trajectories with intended and final_lane # lane that have traffic slower than target_speed. proposed_speed_intended = get_lane_speed(predictions, trajectory.intended_lane) if not proposed_speed_intended: proposed_speed_intended = vehicle_info.target_speed proposed_speed_final = get_lane_speed(predictions, trajectory.final_lane) if not proposed_speed_final: proposed_speed_final = vehicle_info.target_speed cost = (2.0 * vehicle_info.target_speed - proposed_speed_intended - proposed_speed_final) / vehicle_info.target_speed return cost def cost_overtake(current_state, future_state, ego_info): if ego_info.current_time - ego_info.last_time_moving > 50000: # Switch to OVERTAKE if ego hasn't moved for a while. if future_state == BehaviorPlannerState.OVERTAKE: return 0 return 1 else: if current_state == BehaviorPlannerState.OVERTAKE: # Do not speed too long in OVERTAKE state. if ego_info.current_time - ego_info.last_time_stopped > 3000: if future_state == BehaviorPlannerState.OVERTAKE: return 1 else: return 0 else: if future_state == BehaviorPlannerState.OVERTAKE: return 0 else: return 1 else: # Do not switch to overtake because the ego is not blocked. if future_state == BehaviorPlannerState.OVERTAKE: return 1 return 0 raise NotImplementedError def get_lane_speed(predictions, lane_id): """ Returns the speed vehicles are driving in a lane. Assumes that all vehicles are driving at the same speed. Returns: The speed of an vehicle in lane_id, or None if no vehicle exists in lane lane_id. """ for vehicle_id, trajectory in predictions.items(): if trajectory[0].lane_id == lane_id and vehicle_id != -1: return trajectory[0].speed return None
a6cc83de1050888a021c24c3bab56b0f587e4c99
Hiteshsaai/AlgoExpert-CodingProblems-PythonSolution
/Medium/balancedBrackets.py
1,065
3.609375
4
class Solution: def balancedBrackets(self, string): # Time O(n) || Space O(n) if not string: return True if len(string) == 1: return False validOpenBracket = ["(", "{", "["] validCloseBracket = ["}", "]", ")"] matchingBracket = {")": "(", "]": "[", "}": "{"} stack = [] for char in string: if char in validOpenBracket: stack.append(char) elif char in validCloseBracket and len(stack) == 0: return False elif char in validCloseBracket: checkMatchingOpenBracket = matchingBracket[char] if checkMatchingOpenBracket == stack[-1]: stack.pop() else: return False return not stack if __name__ == "__main__": print( Solution().balancedBrackets( "(((((({{{{{safaf[[[[[([)]safsafsa)]]]]]}}}gawga}}))))))" ) ) print(Solution().balancedBrackets("(agwgg)([ghhheah%&@Q])"))
5e8af88e337a7030fb9ea92b57e872d13af2dd7c
mattheuslima/Projetos-Curso_Python
/Exercícios/Ex.89.py
1,134
3.765625
4
dados=list() temp=list() while True: temp.append(str(input('\nDigite o nome do aluno(a): '))) temp.append(float(input('Digite a primeira nota: '))) temp.append(float(input('Digite a segunda nota: '))) temp.append((temp[1]+temp[2])/2) dados.append(temp[:]) temp.clear() opt=str(input('Quer continuar? [S/N]')).strip().upper()[0] while opt not in 'SN': print('\nOpção inválida.') opt = str(input('Quer continuar? [S/N]')).strip().upper()[0] if opt=="N": break print('-='*30) print(f'{"NO.":<4}{"NOME":<20}{"MÉDIA":>8}') print('-'*60) for pos,c in enumerate(dados): print(f'{pos:<4}{dados[pos][0]:<20}{dados[pos][3]:>8.1f}') while True: aluno=int(input('\nMostrar notas de qual aluno ? ')) print(f'\nAs notas de {dados[aluno][0]} são:\n{dados[aluno][1]} e {dados[aluno][2]}') conti=str(input('Quer continuar? [S/N]')).strip().upper()[0] while conti not in 'SN': print('\nOpção inválida.') conti = str(input('Quer continuar? [S/N]')).strip().upper()[0] if conti=="N": break print('\nFim da amostragem de notas.\nVolte sempre.')
34506b39b4e98bd555c16ac0a50e3342ec832d6f
djshampz/atom
/pY4e/readingFiles/script3.py
145
3.671875
4
fname = input("Enter file name: ") openingFile = open(fname) readFile = openingFile.read() cleanFile = readFile.strip() print(readFile.upper())
729fd16097da24b9ec82222790a3b49c9dad9319
dm464/google-kickstart
/2019-round-a/parcels/solution.py
2,764
3.859375
4
import sys t = int(input()) def manhattan(r1, c1, r2, c2): return abs(r1- r2) + abs(c1 - c2) def hasOffice(r, c, grid, distance): row = len(grid) col = len(grid[0]) if distance == 0: return grid[r][c] elif distance >= (row + col - 2): return False else: quads = [[-1, -1], [-1, +1], [+1,+1], [+1, -1]] for quad in quads: for d in range(distance): x = d * quad[0] y = (distance - d) * quad[1] if r+x >= row or r+x < 0 or c+y >= col or c+y <= 0: continue if grid[r+x][c+y]: return True return False if grid[r][c]: return True def nearestOffice(r, c, grid): row = len(grid) col = len(grid[0]) if grid[r][c] == '1': return 0 else: distance = 1 while distance < (row + col - 2): # print("distance: {}".format(distance)) quads = [[1, 1], [1, -1], [-1,-1], [-1, 1]] for quad in quads: # print("quad: {}".format(quad)) for d in range(0, distance+1): x = r + (d * quad[0]) y = c + ((distance - d) * quad[1]) # print("[{}, {}] checking [{}, {}]".format(r, c, x, y)) if x >= row or x < 0 or y >= col or y < 0: continue if grid[x][y] == '1': return distance distance += 1 return -1 for case in range(1, t + 1): r, c = [int(i) for i in input().split(" ")] grid = [] gridDis = [] for row in range(r): grid.append(list(input())) for row in range(r): dis = [] for col in range(c): dis.append(nearestOffice(row, col, grid)) gridDis.append(dis) largest = 0 largestCell = [0, 0] for row in range(r): for col in range(c): if gridDis[row][col] > largest: largest = gridDis[row][col] largestCell = [row, col] # for x in gridDis: # print(*x, sep=" ") # print('===') if largest == 0: print("Case #{}: {}".format(case, 0)) continue grid[largestCell[0]][largestCell[1]] = '1' newGridDis = [] for row in range(r): dis = [] for col in range(c): dis.append(nearestOffice(row, col, grid)) newGridDis.append(dis) largest = 0 for row in range(r): for col in range(c): if newGridDis[row][col] > largest: largest = newGridDis[row][col] # for x in newGridDis: # print(*x, sep=" ") print("Case #{}: {}".format(case, largest))
94edfe3b5629b929c8a8f75c767494b29f822329
Mahantesh1729/python
/Activity_04.py
189
4.0625
4
print("Program to find sum of two numbers") a = int(input("a = ")) b = int(input("b = ")) print(f"{a} + {b} = {a + b}") print("%d + %d = %d" % (a, b, a+b)) print(a, "+", b, "=", a+b)
eb76972e937c710ed4b57482e2b126512333c25f
pavitraponns27/pavitra
/gui/begin/set1/q9/sum of k array.py
94
3.6875
4
array=[1,2,3,4,5] n=int(input(" ")) sum=0 for i in range(n): sum=sum+array[i] print(sum)
ae2bcac65dfd0de8f2ff8d175c2dd80fffdcf302
scps20625/B07090017_2020new
/20200407-1.py
2,320
3.953125
4
#!/usr/bin/env python # coding: utf-8 # # Numpy 套件 # In[1]: a=[1,2,3,4,5] print(a*3) # ## numpy套件的ndarray型態,提供element-wise的操作 # In[3]: import numpy as np b = np.array([1,2,3,4,5]) print(b*3) # In[4]: print(type(b)) print(b.ndim) #ndarray的維度 print(b.shape) #ndarray的形狀 print(b.dtype) #ndarray的資料型態 # In[6]: import numpy as np print(np.zeros(6)) #產生1維度的陣列 print(np.zeros((3,6))) #產生2維度的陣列 print(np.zeros((2,3,6))) #產生3維度的陣列| # In[7]: a=np.zeros(16) print(a) print(a.shape) b=a.reshape((4,4)) #改變資料的維度為4x4 print(b) print(b.shape) # ## ndarray的進階操作 # In[8]: my_array=np.arange(10) print(my_array) print(my_array[0]) print(my_array[0:5]) #取0 1 2 3 4 的位置值 # In[12]: a=np.array([[(0,1,2,3,4,)],[5,6,7,8,9]]) print(a) b=np.array([np.arange(0,5),np.arange(5,10)]) print(b) c=np.array([np.arange(0,10).reshape(2,5)]) print(c) # ## 二維ndarray取值 # In[15]: import numpy as np my_2d_array=np.array(np.arange(0,10).reshape((2,5))) print(my_2d_array) print(my_2d_array[0,:]) #第 0 列的元素 print(my_2d_array[1,:]) #第 1 列的元素 print(my_2d_array[:,0]) #第 0 欄的元素 print(my_2d_array[1,1]) #取第 2 列 第 2 欄的元素 # ## 假設六組"modern web","Devops","Big Data","cloud","Security"自我挑戰組 # ## 參與人數分別為56 8 19 14 6 71 # In[16]: import numpy as np groups=["modern web","Devops","Big Data","cloud","Security","自我挑戰組"] ironman=[56,8,19,14,6,71] groups_array=np.array(groups) ironman_array=np.array(ironman) print(groups_array) print(ironman_array) # In[18]: #用人數篩選組別 print(ironman_array >= 10) print(groups_array[ironman_array >= 10]) # In[20]: #用組別篩選組別 print(groups_array != "自我挑戰組") print(ironman_array[groups_array != "自我挑戰組"]) # ### ndarray 空值 nan 無限大 int # In[21]: nan_array=np.array([56,8,19,14,6,np.nan]) print(nan_array) # ## 生成10組標準常態(平均為0 標準差為1的常態變數) # In[23]: normal_samples=np.random.normal(size=10) print(normal_samples) # ## 生成10組介於0~1的隨機變數 # In[25]: uniform_samples=np.random.uniform(size=10) print(uniform_samples) # In[ ]:
e46e1fdfdb9ecc1e379c146e154a8aaaef2e2ca1
MartinTirtawisata/LeVinCoupe
/Regular Project/Association.py
11,885
4.09375
4
import pandas as pd import scipy.stats import seaborn import matplotlib.pyplot as plt from Menu import menu def association(): print("\n===============================================================================") print("a. Volatile Acidity and Wine Quality") print("b. Fixed Acidity and Wine Quality") print("c. Alcohol and Wine Quality") print("d. Residual Sugar and Wine Quality") print("===============================================================================") while True: association_choice = input("\nPlease select an option of which associations you would like to check (enter the letter): ").strip().lower() if association_choice == "a" or association_choice == "b" or association_choice == "c" or association_choice == "d": break else: print("\nYou must select only one menu choice from above by typing the letter. Please try again.") if association_choice == "a": while True: wine_choice = input("\nWould you like to test for red or white wine? (enter 'red' or 'white'): ").strip().lower() if wine_choice == "red": try: WineCharX = "quality" WineCharY = "volatile acidity" allWines = pd.read_csv('winequality-both.csv', sep=',', header=0) red = allWines.loc[allWines['type'] == 'red', :] getCorr = scipy.stats.pearsonr(red[WineCharX], red[WineCharY]) correlation = str(getCorr[0]) pValue = str(getCorr[1]) print("\nFor red wine, the correlation between " + WineCharX + " and " + WineCharY + " is: " + correlation) print("With p-value of: " + pValue) seaborn.lmplot(x=WineCharX, y=WineCharY, data=red) plt.xlabel(WineCharX) plt.ylabel(WineCharY) plt.title("Red Wine: " + WineCharX + " X " + WineCharY) plt.show() except (KeyError) as e: print("\nError. Please check that your spelling is correct of the wine characteristic you wish to test.") break if wine_choice == "white": try: WineCharX = "quality" WineCharY = "volatile acidity" allWines = pd.read_csv('winequality-both.csv', sep=',', header=0) white = allWines.loc[allWines['type'] == 'white', :] getCorr = scipy.stats.pearsonr(white[WineCharX], white[WineCharY]) correlation = str(getCorr[0]) pValue = str(getCorr[1]) print("\nFor white wine, the correlation between " + WineCharX + " and " + WineCharY + " is: " + correlation) print("With p-value of: " + pValue) seaborn.lmplot(x=WineCharX, y=WineCharY, data=white) plt.xlabel(WineCharX) plt.ylabel(WineCharY) plt.title("White Wine: " + WineCharX + " X " + WineCharY) plt.show() except (KeyError) as e: print("\nError. Please check that your spelling is correct of the wine characteristic you wish to test.") break if wine_choice != "red" or wine_choice != "white": print("\nYou must enter either 'red' or 'white' based on which wine you want to test associations for. Please try again.") if association_choice == "b": while True: wine_choice = input("\nWould you like to test for red or white wine? (enter 'red' or 'white'): ").strip().lower() if wine_choice == "red": try: WineCharX = "quality" WineCharY = "fixed acidity" allWines = pd.read_csv('winequality-both.csv', sep=',', header=0) red = allWines.loc[allWines['type'] == 'red', :] getCorr = scipy.stats.pearsonr(red[WineCharX], red[WineCharY]) correlation = str(getCorr[0]) pValue = str(getCorr[1]) print("\nFor red wine, the correlation between " + WineCharX + " and " + WineCharY + " is: " + correlation) print("With p-value of: " + pValue) seaborn.lmplot(x=WineCharX, y=WineCharY, data=red) plt.xlabel(WineCharX) plt.ylabel(WineCharY) plt.title("Red Wine: " + WineCharX + " X " + WineCharY) plt.show() except (KeyError) as e: print("\nError. Please check that your spelling is correct of the wine characteristic you wish to test.") break if wine_choice == "white": try: WineCharX = "quality" WineCharY = "fixed acidity" allWines = pd.read_csv('winequality-both.csv', sep=',', header=0) white = allWines.loc[allWines['type'] == 'white', :] getCorr = scipy.stats.pearsonr(white[WineCharX], white[WineCharY]) correlation = str(getCorr[0]) pValue = str(getCorr[1]) print("\nFor white wine, the correlation between " + WineCharX + " and " + WineCharY + " is: " + correlation) print("With p-value of: " + pValue) seaborn.lmplot(x=WineCharX, y=WineCharY, data=white) plt.xlabel(WineCharX) plt.ylabel(WineCharY) plt.title("White Wine: " + WineCharX + " X " + WineCharY) plt.show() except (KeyError) as e: print("\nError. Please check that your spelling is correct of the wine characteristic you wish to test.") break if wine_choice != "red" or wine_choice != "white": print("\nYou must enter either 'red' or 'white' based on which wine you want to test associations for. Please try again.") if association_choice == "c": while True: wine_choice = input("\nWould you like to test for red or white wine? (enter 'red' or 'white'): ").strip().lower() if wine_choice == "red": try: WineCharX = "quality" WineCharY = "alcohol" allWines = pd.read_csv('winequality-both.csv', sep=',', header=0) red = allWines.loc[allWines['type'] == 'red', :] getCorr = scipy.stats.pearsonr(red[WineCharX], red[WineCharY]) correlation = str(getCorr[0]) pValue = str(getCorr[1]) print("\nFor red wine, the correlation between " + WineCharX + " and " + WineCharY + " is: " + correlation) print("With p-value of: " + pValue) seaborn.lmplot(x=WineCharX, y=WineCharY, data=red) plt.xlabel(WineCharX) plt.ylabel(WineCharY) plt.title("Red Wine: " + WineCharX + " X " + WineCharY) plt.show() except (KeyError) as e: print("\nError. Please check that your spelling is correct of the wine characteristic you wish to test.") break if wine_choice == "white": try: WineCharX = "quality" WineCharY = "alcohol" allWines = pd.read_csv('winequality-both.csv', sep=',', header=0) white = allWines.loc[allWines['type'] == 'white', :] getCorr = scipy.stats.pearsonr(white[WineCharX], white[WineCharY]) correlation = str(getCorr[0]) pValue = str(getCorr[1]) print("\nFor white wine, the correlation between " + WineCharX + " and " + WineCharY + " is: " + correlation) print("With p-value of: " + pValue) seaborn.lmplot(x=WineCharX, y=WineCharY, data=white) plt.xlabel(WineCharX) plt.ylabel(WineCharY) plt.title("White Wine: " + WineCharX + " X " + WineCharY) plt.show() except (KeyError) as e: print("\nError. Please check that your spelling is correct of the wine characteristic you wish to test.") break if wine_choice != "red" or wine_choice != "white": print("\nYou must enter either 'red' or 'white' based on which wine you want to test associations for. Please try again.") if association_choice == "d": while True: wine_choice = input("\nWould you like to test for red or white wine? (enter 'red' or 'white'): ").strip().lower() if wine_choice == "red": try: WineCharX = "quality" WineCharY = "residual sugar" allWines = pd.read_csv('winequality-both.csv', sep=',', header=0) red = allWines.loc[allWines['type'] == 'red', :] getCorr = scipy.stats.pearsonr(red[WineCharX], red[WineCharY]) correlation = str(getCorr[0]) pValue = str(getCorr[1]) print("\nFor red wine, the correlation between " + WineCharX + " and " + WineCharY + " is: " + correlation) print("With p-value of: " + pValue) seaborn.lmplot(x=WineCharX, y=WineCharY, data=red) plt.xlabel(WineCharX) plt.ylabel(WineCharY) plt.title("Red Wine: " + WineCharX + " X " + WineCharY) plt.show() except (KeyError) as e: print("\nError. Please check that your spelling is correct of the wine characteristic you wish to test.") break if wine_choice == "white": try: WineCharX = "quality" WineCharY = "residual sugar" allWines = pd.read_csv('winequality-both.csv', sep=',', header=0) white = allWines.loc[allWines['type'] == 'white', :] getCorr = scipy.stats.pearsonr(white[WineCharX], white[WineCharY]) correlation = str(getCorr[0]) pValue = str(getCorr[1]) print("\nFor white wine, the correlation between " + WineCharX + " and " + WineCharY + " is: " + correlation) print("With p-value of: " + pValue) seaborn.lmplot(x=WineCharX, y=WineCharY, data=white) plt.xlabel(WineCharX) plt.ylabel(WineCharY) plt.title("White Wine: " + WineCharX + " X " + WineCharY) plt.show() except (KeyError) as e: print("\nError. Please check that your spelling is correct of the wine characteristic you wish to test.") break if wine_choice != "red" or wine_choice != "white": print("\nYou must enter either 'red' or 'white' based on which wine you want to test associations for. Please try again.") while True: after = input("\nWould you like to test more associations or return to the main menu? (enter 'test' or 'main'): ").lower().strip() if after == "test": association() break if after == "main": break else: print("\nYou must enter either 'test' or 'main' based on what you want to do. Please try again.")
f49fb4d38ff7d65dc9a296834789e7f551a8e11e
sanchaymittal/FarmEasy
/WhatsApp_FarmEasy/env/lib/python3.6/site-packages/multiaddr/exceptions.py
2,283
3.546875
4
class Error(Exception): pass class LookupError(LookupError, Error): pass class ProtocolLookupError(LookupError): """ MultiAddr did not contain a protocol with the requested code """ def __init__(self, proto, string): self.proto = proto self.string = string super(ProtocolLookupError, self).__init__( "MultiAddr {0!r} does not contain protocol {1}".format(string, proto) ) class ParseError(ValueError, Error): pass class StringParseError(ParseError): """ MultiAddr string representation could not be parsed """ def __init__(self, message, string, protocol=None, original=None): self.message = message self.string = string self.protocol = protocol self.original = original if protocol: message = "Invalid MultiAddr {0!r} protocol {1}: {2}".format(string, protocol, message) else: message = "Invalid MultiAddr {0!r}: {1}".format(string, message) super(StringParseError, self).__init__(message) class BinaryParseError(ParseError): """ MultiAddr binary representation could not be parsed """ def __init__(self, message, binary, protocol, original=None): self.message = message self.binary = binary self.protocol = protocol self.original = original message = "Invalid binary MultiAddr protocol {0}: {1}".format(protocol, message) super(BinaryParseError, self).__init__(message) class ProtocolManagerError(Error): pass class ProtocolExistsError(ProtocolManagerError): """ Protocol with the given name or code already exists """ def __init__(self, proto, kind="name"): self.proto = proto self.kind = kind super(ProtocolExistsError, self).__init__( "Protocol with {0} {1!r} already exists".format(kind, getattr(proto, kind)) ) class ProtocolNotFoundError(ProtocolManagerError): """ No protocol with the given name or code found """ def __init__(self, value, kind="name"): self.value = value self.kind = kind super(ProtocolNotFoundError, self).__init__( "No protocol with {0} {1!r} found".format(kind, value) )
a21c23e40bde6d6381ddd273b84afd8159d70e5a
maee-in-mind/python-Exercise-21-onwards
/hangman (1).py
2,085
4.0625
4
from random import randint WORD_LIST = { 'rand_word_1': 'keystone', 'rand_word_2': 'boy', 'rand_word_3': 'girl', 'rand_word_4': 'india', 'rand_word_5': 'third', 'rand_word_6': 'year', 'rand_word_7': 'batch', 'rand_word_8': 'python', 'rand_word_9': 'java', 'rand_word_10': 'danger' } HANGMAN = ( """ x-------x """, """ x-------x | | | | | """, """ x-------x | | | 0 | | | """, """ x-------x | | | 0 | | | | """, """ x-------x | | | 0 | /|\\ | | """, """ x-------x | | | 0 | /|\\ | / | """, """ x-------x | | | 0 | /|\\ | / \\ | GAME OVER """ ) MAX = len(HANGMAN) - 1 num = randint(1, 10) num_string = str(num) words = 'rand_word_{}'.format(num_string) WORD_TO_GUESS = WORD_LIST[words] HIDDEN = ['_'] * len(WORD_TO_GUESS) LETTERS_GUESSED = [] def begin_game(): hang_size = 0 print "\tHANGMAN by DANGARE SIR!" word_arr = list(WORD_TO_GUESS) while hang_size < MAX: print str(HIDDEN) user_guess = raw_input('Guess a letter: ') if user_guess in LETTERS_GUESSED: print 'You already guessed that.. PAY ATTENTION!' user_guess = raw_input('Guess a letter: ') if user_guess in word_arr: print "Yeah yeah... It's in the word....Very Good!" for num in range(len(word_arr)): if user_guess == word_arr[num]: HIDDEN[num] = user_guess if HIDDEN.count('_') == 0: print '--------------YOU WIN..!-------------' print '************CONGRATULATION***********' quit() else: print "{}.. Really? That's the best you can do.. Not in my word..".format(user_guess) hang_size += 1 print HANGMAN[hang_size] begin_game()
c2dc1325ff1ea886ef9e297b5a71e0754a076c66
rneher/augur
/augur/tree_util.py
1,108
4.125
4
# tree class # each node is a dict in which the key 'children' is used to reference more dicts from io_util import * def tip_descendants(node): """Take node, ie. dict, and return a flattened list of all tips descending from this node""" if 'children' in node: for child in node['children']: for desc in tip_descendants(child): yield desc else: yield node def all_descendants(node): """Take node, ie. dict, and return a flattened list of all nodes descending from this node""" yield node if 'children' in node: for child in node['children']: for desc in all_descendants(child): yield desc def get_dates(node): """Return ordered list of dates of descendants of a node""" return sorted([n['date'] for n in tip_descendants(node)]) def main(): tree = read_json('tree.json') # print "Whole tree" # for tip in descendants(tree): # print tip['date'] # node = tree['children'][0] # dates = get_dates(tree) # print dates for node in all_descendants(tree): dates = get_dates(node) print str(node['clade']) + ": " + str(len(dates)) if __name__ == "__main__": main()
a3ecbd36cf1782f17da90ae746c08129bdd94b9a
alovena/Cpp
/선택정렬.py
550
4.0625
4
def find_smallest(arr):#최소값 찾는 함수 smallest =arr[0] smallest_index=0 for i in range(1,len(arr)): if arr[i]< smallest: smallest=arr[i] smallest_index =i return smallest_index def selection_sort(arr):# arr : 배열을 매개변수로 입력 받음 newArr=[] for i in range(len(arr)): #0,len(arr)-1 만큼 반복합니다 smallest =find_smallest(arr) newArr.append(arr.pop(smallest)) return newArr myArr=[5,3,6,2,10] selection_sort(myArr)
e2c6db6a14f0e3bb784cb6dace4e6df46c987ec4
daniel-reich/turbo-robot
/uAZcCxNj3TtqvxP34_22.py
965
4.34375
4
""" The _mode_ of a group of numbers is the value (or values) that occur most often (values have to occur more than once). Given a sorted list of numbers, return a list of all modes in ascending order. ### Examples mode([4, 5, 6, 6, 6, 7, 7, 9, 10]) ➞ [6] mode([4, 5, 5, 6, 7, 8, 8, 9, 9]) ➞ [5, 8, 9] mode([1, 2, 2, 3, 6, 6, 7, 9]) ➞ [2, 6] ### Notes In this challenge, all group of numbers will have at least one mode. """ def mode(nums): temp_set = set() for i in range(len(nums) - 1): if(nums[i] == nums[i + 1]): temp_set.add(nums[i]) unique_multiples = list(temp_set) unique_multiples.sort() count = [0] * len(unique_multiples) for i in range(len(nums)): if nums[i] in unique_multiples: count[unique_multiples.index(nums[i])] += 1 max_count = max(count) result = [] for i in range(len(count)): if count[i] == max_count: result.append(unique_multiples[i]) return result
33882b0ae781a03c6bbe2b0b75c06243be2697b4
lukeyeh/leetcode
/easy_collection/array/remove_duplicates_from_sorted_array.py
1,241
3.875
4
from typing import List # Question # -------------- # Remove Duplicates from Sorted Array # -------------- # # Link # -------------- # https://leetcode.com/problems/remove-duplicates-from-sorted-array/ # -------------- # # Description # -------------- # Given a sorted array nums, remove the duplicates in-place such that each # element appear only once and return the new length. # # Do not allocate extra space for another array, you must do this by modifying # the input array in-place with O(1) extra memory. # -------------- class Solution: def removeDuplicates(self, nums: List[int]) -> int: left: int = 0 for right in range(1, len(nums)): if nums[left] != nums[right]: left += 1 nums[left] = nums[right] return left + 1 def test1(): solution = Solution() answer = [1, 1, 2] length = solution.removeDuplicates(answer) assert length == 2 for i, num in enumerate([1, 2]): assert answer[i] == num def test2(): solution = Solution() answer = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4] length = solution.removeDuplicates(answer) assert length == 5 for i, num in enumerate([0, 1, 2, 3, 4]): assert answer[i] == num
12778c252b40d075f4bcf488dec2f65f20ab185e
mohammadasim/python-course
/set.py
560
4.15625
4
# Sets are unordered collections of unique elements. # Meaning there can only be one representative of the same object # Set like Maps is represented by {}, however they don't have key:value pair. my_set = {1,2,3,4,5} print(type(my_set)) print(my_set) my_set.add(6) print(my_set) print(len(my_set)) my_list = [1,1,1,2,2,2,3,4,5] # Casting a list into a set print(set(my_list)) your_lottery_numbers = {1,2,3,4,5} winning_numbers = {1,3,5,7,9,11} print(your_lottery_numbers.intersection(winning_numbers)) print(your_lottery_numbers.difference(winning_numbers))
6d3bfbb03cad12f994b2442204ba5930797c2016
Shiwank19/p5-examples
/basics/math/polar_to_cartesian.py
868
4.28125
4
# Polar to Cartesian # by Daniel Shiffman # # Python port: Abhik Pal # # Convert a polar coördinate (r, theta) to cartesian (x, y): # # x = r * cos(theta) # y = r * sin(theta) from p5 import * r = None # angle, angular velocity, accleration theta = 0 theta_vel = 0 theta_acc = 0.0001 def setup(): global r size(640, 360) title("Polar to Cartesian") fill(200) no_stroke() r = height * 0.45 def draw(): global theta global theta_vel background(0) # Translate the origin point to the center of the screen. translate(width / 2, height / 2) # Convert polar to cartesian x = r * cos(theta) y = r * sin(theta) circle((x, y), 30) # Apply acceleration and velocity to angle (r remains static in # this example) theta_vel += theta_acc theta += theta_vel if __name__ == '__main__': run()
d373445bd7e1d8ad5216cf2dbac34acfb0c90572
Vedaang-Chopra/Python_Codes_Practiced
/f-20.py
1,701
4.34375
4
# Python program to find maximum sum path # This function returns the sum of elements on maximum path from # beginning to end def maxPathSum(ar1, ar2, m, n): # initialize indexes for ar1[] and ar2[] i, j = 0, 0 # Initialize result and current sum through ar1[] and ar2[] result, sum1, sum2 = 0, 0, 0 # Below 3 loops are similar to merge in merge sort while (i < m and j < n): # Add elements of ar1[] to sum1 if ar1[i] < ar2[j]: sum1 += ar1[i] i += 1 # Add elements of ar2[] to sum1 elif ar1[i] > ar2[j]: sum2 += ar2[j] j += 1 else: # we reached a common point # Take the maximum of two sums and add to result result += max(sum1, sum2) # Update sum1 and sum2 for elements after this intersection point sum1, sum2 = 0, 0 # Keep updating result while there are more common elements while (i < m and j < n and ar1[i] == ar2[j]): result += ar1[i] i += 1 j += 1 # Add remaining elements of ar1[] while i < m: sum1 += ar1[i] i += 1 # Add remaining elements of b[] while j < n: sum2 += ar2[j] j += 1 # Add maximum of two sums of remaining elements result += max(sum1, sum2) return result # Driver function size1 = int(input()) n1= input() n1 = n1.strip() b1 = n1.split(" ") for i in range(0, size1): b1[i] = int(b1[i]) size2 = int(input()) n2 = input() n2 = n2.strip() b2 = n2.split(" ") for i in range(0, size2): b2[i] = int(b2[i]) b1.sort() b2.sort() print(maxPathSum(b1,b2,len(b1),len(b2)))
5bab8d590bee2e89e6fdec396ffb9835e1cf2b4d
jjudykim/PythonGameProject
/Practice_for_noob/131_140.py
712
3.671875
4
#131 과일 = ["사과", "귤", "수박"] for 변수 in 과일: print(변수) #132 과일 = ["사과", "귤", "수박"] for 변수 in 과일: print("#####") #133 print("A") print("B") print("C") #134 print("출력:", "A") print("출력:", "B") print("출력:", "C") #135 변수 = "A" b = 변수.lower() print("변환:", b) 변수 = "B" b = 변수.lower() print("변환:", b) 변수 = "C" b = 변수.lower() print("변환:", b) #136 변수 = [10, 20, 30] for i in 변수: print(변수) #137 for a in [10, 20, 30]: print(a) #138 for a in [10, 20, 30]: print(a) print("---------") #139 print("++++") for a in [10, 20, 30]: print(a) #140 for a in range(4): print("---------")
3ebcd7d1661947aba74a58b51d28a7e6fa837793
FooBarQuaxx/exercism-py
/anagram/anagram.py
182
3.734375
4
def detect_anagrams(S, L): return [word for word in L if len(word) == len(S) and S.lower() != word.lower() and sorted(S.lower()) == sorted(word.lower())]
0e737d6ac95b4704da6bef31445490fe9f3eddc3
jereneal20/TIL
/ps/find-nearest-right-node-in-binary-tree.py
727
3.859375
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 findNearestRightNode(self, root: TreeNode, u: TreeNode) -> Optional[TreeNode]: deq = deque([(root, 0)]) while deq: node, depth = deq.popleft() if node == u: if deq and deq[0][1] == depth: return deq[0][0] else: return None if node.left: deq.append((node.left, depth + 1)) if node.right: deq.append((node.right, depth + 1)) return None
ba5c8ef7661e05446d802c1bd37136e361896987
Ulset/Win-cron-converter
/cron.py
4,909
3.546875
4
from datetime import datetime, timedelta class CronConverter: IS_ALWAYS = "stringFillaBadManKilla" def __init__(self, cron_string, dt_input=None): self.minute, self.hour, self.day_date, self.month, self.day_weekday = cron_string.split(" ") if dt_input is None: dt_input = datetime.now().replace(minute=0, second=0) if self.minute == "*" and self.hour == "*": # If both is '*' need to test every minute and every hours td_args = { "minutes": 1 } elif self.str_is_int(self.minute) and self.hour == "*": # If onluy hour is '*' just need to test a single specific time an hour dt_input = dt_input.replace(minute=int(minute)) td_args = { "hours": 1 } elif self.str_is_int(self.minute) and self.str_is_int(self.hour): # If neither minute or hour is '*', only need to test once a day. dt_input = dt_input.replace(minute=int(self.minute), hour=int(self.hour)) if self.str_is_int(self.day_weekday): td_args = { "days": 1 } else: td_args = { "days": self.__cron_to_interval(self.day_weekday) } elif self.__cron_to_interval(self.minute) > 1 and (self.hour == "*" or "-" in self.hour): # Causes a error. td_args = { "minutes": self.__cron_to_interval(self.minute) } else: # Else should use the interval for both minute and hour defined. if self.str_is_int(self.minute): dt_input = dt_input.replace(minute=int(self.minute)) if self.str_is_int(self.hour): dt_input = dt_input.replace(hour=int(self.hour)) td_args = { "minutes": self.__cron_to_interval(self.minute), "hours": self.__cron_to_interval(self.hour) } self.td_obj = timedelta(**td_args) self.dt_obj = dt_input @staticmethod def str_is_int(string): try: int(string) return True except ValueError: return False def __cron_to_interval(self, subcron_slice): subcron_slice: str if subcron_slice == "*": return 1 elif self.str_is_int(subcron_slice): return 0 elif "/" in subcron_slice: # If interval counter (ie */30) should return 30 since thats the interval return int(subcron_slice.split("/")[1]) elif "-" in subcron_slice: # ie(1-5) should return 1 but needs another check later if time is inside range. return 1 def __cron_to_range(self, subcron_string, inclusive=True): """ Converts a subcron string to a range of accepted values :param inclusive if the range should include the last integer (IE '2-4' -> [2,3](not inclusive), [2,3,4](inclusive) """ subcron_string: str if self.str_is_int(subcron_string): return [int(subcron_string)] elif "-" in subcron_string: start, stop = subcron_string.split("-") start = int(start) stop = int(stop) if not inclusive else int(stop) + 1 return [x for x in range(start, stop)] else: return IS_ALWAYS def __time_accepted(self, new_dt): new_dt: datetime day_weekday_range = self.__cron_to_range(self.day_weekday) day_date_range = self.__cron_to_range(self.day_date) month_range = self.__cron_to_range(self.month) minute_range = self.__cron_to_range(self.minute) hour_range = self.__cron_to_range(self.hour, inclusive=False) minute_acccepted = new_dt.minute in minute_range if minute_range != IS_ALWAYS else True hour_accepted = new_dt.hour in hour_range if hour_range != IS_ALWAYS else True clock_accepted = minute_acccepted and hour_accepted day_weekday_accepted = new_dt.weekday() in day_weekday_range if day_weekday_range != IS_ALWAYS else True day_date_accepted = new_dt.day in day_date_range if day_date_range != IS_ALWAYS else True month_accepted = new_dt.month in month_range if month_range != IS_ALWAYS else True return day_weekday_accepted and day_date_accepted and month_accepted and clock_accepted def get_next_time(self) -> datetime: t_now = datetime.now() self.dt_obj = self.dt_obj + self.td_obj while self.dt_obj < t_now or not self.__time_accepted(self.dt_obj): self.dt_obj = self.dt_obj + self.td_obj return self.dt_obj def test(): cron_string = "*/30 * * * *" c = CronConverter(cron_string) for _ in range(50): print(c.get_next_time().strftime("%d/%m/%Y, %H:%M:%S"))
a663522124dde3d849556bd8e5c8c6387c3194c5
wpinheiro77/python
/Estudos/exercicios/L01ex08.py
400
3.90625
4
#Receber a altura do degrau de uma escada e a altura que o usuario deseja alcançar #Calcular quantos degraus o usuário deve subir para atingir a meta degrau = float(input('Digite a altura dos degraus: ')) altura = float(input('Digite a altera que deseja alcançar: ')) qtdDegraus = int(altura / degrau) print('Você terá que subir {} degraus para subir {} metros!' .format(qtdDegraus, altura))
05873fa41e739d41c063907ecf7b871354e05e22
idunnowhy9000/Projects
/SOURCE/Python/Numbers/Next Prime Number.py
684
3.890625
4
# Next Prime Number: Have the program find prime numbers # until the user chooses to stop asking for the next one. # Uses the Lucas–Lehmer primality test, based on http://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test#The_test's pseudocode import math def isPrime(n): s = 4 M = math.pow(2, n) - 1 it = 0 while it < (n - 2): s = ((s * s) - 2) % M return s == 0 def primeNumbers(l): for i in range(l): if isPrime(i): yield i def main(): l = 0 while True: try: l = int(input("Enter number: ")) except ValueError: print("Enter a valid number.\n") continue break for _ in primeNumbers(l): print(_) if __name__ == "__main__": main()
0b9f47d914c63b87ee77e1a8dadb5167837acf06
tima-akulich/lesson8
/homework/task3.py
868
3.875
4
import math class Figure: def square(self): raise NotImplementedError def _get_value(self, other): value = other if isinstance(other, Figure): value = other.square() return value def __lt__(self, other): return self.square() < self._get_value(other) def __add__(self, other): pass __iadd__ = __add__ def __gt__(self, other): return self.square() > self._get_value(other) class Triangle(Figure): def __init__(self, a, b, c): self.a = a self.b = b self.c = c def square(self): return self.a * self.b * self.c class Circle(Figure): def __init__(self, r): self.r = r def square(self): return self.r ** 2 * math.pi if __name__ == '__main__': c = Circle(5) t = Triangle(1, 2, 3) print(c < t)
0e17eebc438c942a030d8cd76ca0c51551a5ab27
MonoNazar/MyPy
/0.8/Segment length.py
577
4.09375
4
x1 = int(input()) x2 = int(input()) y1 = int(input()) y2 = int(input()) def distance(x1, y1, x2, y2): s = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 return s print(distance(x1, y1, x2, y2)) # Даны четыре действительных числа: x1, y1, x2, y2. Напишите функцию distance(x1, y1, x2, y2), вычисляющая расстояние между точкой (x1,y1) и (x2,y2). # Считайте четыре действительных числа и выведите результат работы этой функции.
59d0b88f2b5b2ab615cb44184b600e77a04c76d4
ruz023/YelpDataChallenge
/src/helpers.py
526
3.65625
4
from typing import * import numpy as np def get_top_values(lst: Iterable, n: int , labels: Dict[int, Any]): #Give a list of values, find the indices with the highest n values #Return the labels for each of the indices return [labels[i] for i in np.argsort(lst)[::-1][:n]] def get_bottom_values(lst: Iterable, n: int , labels: Dict[int, Any]): #Give a list of values, find the indices with the lowest n values #Return the labels for each of the indices return [labels[i] for i in np.argsort(lst)[:n]]
4f38b5a7cf316ec6411af352cf2019a10e75e6a5
yoyonel/OpenCV_OMR_MusicSheet
/omr_musicsheet/texture_synthesis/plot_inpaint_efros.py
1,937
3.765625
4
""" ========================= Textural Image Inpainting ========================= Image Inpainting is the process of reconstructing lost or deteriorated parts of an image. In this example we wll show Textural inpainting. Textures have repetitive patterns and hence cannot be restored by continuing neighbouring geometric properties into the unknown region. The correct match is found using the minimum Sum of Squared Differences (SSD) between a patch about the pixel to be inpainted and all other patches in the image which do not contain any boundary region and no unknown or masked region. This implementation updates 1 pixel at a time. Un peu technique l'install. Ne passe pas avec un interpreteur python >= 3.7 car la version spécifique scikit-image du dépot: https://github.com/chintak/scikit-image nécessite une version (ancienne) de cython==0.17 qui ne semble pas compatible avec python 3.7. Faudrait tenter un autre interpréteur, on cherchait une version compatible de Cython qui peut etre avec py3.7 et faire tourner la lib scikit-image ... """ import numpy as np # import matplotlib.pyplot as plt # from skimage import datasets from skimage.filter.inpaint_texture import inpaint_efros import cv2 filename = "../Page_09_Pattern_24_rot.png" image = cv2.imread(filename, cv2.IMREAD_GRAYSCALE) # image = datasets.camera()[300:500, 350:550] mask = np.zeros_like(image, dtype=np.uint8) # paint_region = (slice(125, 145), slice(20, 50)) # image[paint_region] = 0 # mask[paint_region] = 1 image_copy = image.copy() image[image_copy == 255] = 0 mask[image_copy == 255] = 255 painted = inpaint_efros(image, mask, window=7) # fig, (ax0, ax1) = plt.subplots(ncols=2) # ax0.set_title('Input image') # ax0.imshow(image, cmap=plt.cm.gray) # ax1.set_title('Inpainted image') # ax1.imshow(painted, cmap=plt.cm.gray) # plt.show() cv2.imshow('image', image) cv2.imshow('mask', mask) cv2.imshow('painted', painted) cv2.waitKey(0)
2def8e071a6f9588ed62849bc24afe5c302a7b03
mmosc/pyph
/3/gauss_midpoint.py
565
3.96875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Numerical Integration of the normal distribution with the midpoint rule """ import math sigma = 0.5 # Standard deviation x_max = 3 # Integration domain from -x_max to +x_max dx = 0.01 # Width of the Integration interval def f(x): """ Normal distribution. Standard deviation: sigma, Mean: 0 """ a = 1 / (math.sqrt(2 * math.pi) * sigma) return a * math.exp(- x**2/(2 * sigma**2)) x = -x_max p = 0. while x < x_max: p += f(x + dx/2) * dx x += dx print(p)
a214dc98e805972c811be9137285eb0b0b0300a1
howardh0214/Algorithms-Homework
/HW5/closest.py
2,202
3.625
4
import math def Brute_Force(Array): size = len(Array) minimum_distance = Euclidean_Distance(Array[0],Array[1]) if len(Array) == 2: return minimum_distance for i in range(0,size): for j in range(i+1,size): distance = Euclidean_Distance(Array[i],Array[j]) if distance < minimum_distance: minimum_distance = distance return minimum_distance def Initial_sort(a): Px = sorted(a, key=lambda x: x[0]) Py = sorted(a, key=lambda x: x[1]) return Px, Py def og(Px): midpoint_x = len(Px) // 2 Qx = Px[:midpoint_x] Qx_og = Qx[:] return Qx_og def Closest_Pair(Px, Py): midpoint_x = len(Px) // 2 Qx = Px[:midpoint_x] if len(Px) <= 3: return Brute_Force(Px) else: Rx = Px[midpoint_x:] median_x = Px[midpoint_x] Qy,Ry = [], [] for point in Py: if point[0] < int(median_x[0]): Qy.append(point) else: Ry.append(point) min_distance_Left = Closest_Pair(Qx,Qy) min_distance_Right = Closest_Pair(Rx,Ry) min_distance = min(min_distance_Left,min_distance_Right) return min_distance def Closest_Split_Pair(min_distance, Qx, Py): x_bar = Qx[-1][0] Sy = [] for y in Py: if (x_bar - min_distance) < y[0] < (x_bar + min_distance): Sy.append(y) for i in range(len(Sy) - 1): for j in range(i+1, min(i + 7, len(Sy))): P = Sy[i] Q = Sy[j] dist = Euclidean_Distance(P,Q) if dist < min_distance: min_distance = dist return min_distance def Euclidean_Distance(P,Q): return math.sqrt((P[0]-Q[0])**2 + (P[1]-Q[1])**2) if __name__ == '__main__': n_tests = int(input()) for _ in range(n_tests): n_points = int(input()) points = [] array = [0,0] for _ in range(n_points): points.append(list(map(int,input().split(' ')))) Px, Py = Initial_sort(points) array = og(Px) dist = Closest_Pair(Px, Py) print("{:.3f}".format(Closest_Split_Pair(dist, array, Py)))
fb5448760c740e656f952f4cc84af46c7ee64afc
Vaibhav2002/Python-codes
/algorithms/linear search.py
212
3.953125
4
a = list(map(int, input("Enter numbers :").split())) x = int(input("Enter element to be searched : ")) for i in a: if i == x: print("Element found") break else: print("Element not found")
c357f8238f755de64e92f209fd0c284f1a062726
josephj02233/joseph0426
/pylesson11/11ex2.py
815
3.96875
4
import math class distance: def __init__(self, x1, y1, x2, y2): self.xone = x1 self.yone = y1 self.xtwo = x2 self.ytwo = y2 self.distance = 0 def setvalue(self,newx1,newy1,newx2,newy2): self.xone = newx1 self.yone = newy1 self.xtwo = newx2 self.ytwo = newy2 self.distance = 0 def getmph(self): self.distance= Math.sqrt((self.xtwo-self.xone)*(self.xtwo-self.xone)+(self.ytwo-self.yone)*self.ytwo-self.yone)) return self.mph def main(): x1=int(input("enter a num for x1: ")) y1=int(input("enter a num for y1: ")) x2=int(input("enter a num for x2: ")) y2=int(input("enter a num for y2: ")) newuser = distance(x1, y1, x2, y2) print("distance = ", newuser.getmph()) main()
e8e273b93d98b481b8b933e41371a74eaa4065ff
engr-sakil/Python_Basic
/Logical operator.py
392
4.21875
4
#AND operator num1 = 20 num2 = 50 num3 = 40 if num1> num2 and num1 >num2: print(num1) elif num2>num1 and num2 >num3: print(num2) else: print(num3) #OR operator ch = 'b' if ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u': print("vowel") else: print('consonant') #NOT operator num = 2 if not num != 20: print(" equal") else: print("not equal")
c18dc8619da762a49e5084a8525bb9db9b072e8d
luiz-amboni/curso-python
/EstruturaDeDados/Exercicio3/item1.py
696
4.03125
4
def ordVetSelect(): lista_nomes = [] limite_max = 13 posicao = 0 while posicao < limite_max: nomes = input("Digite um nome para ser adicionado a lista: ") posicao = posicao + 1 lista_nomes.append(nomes) def ordListaNomesInsert(listaNomes): for i in range(1, len(listaNomes)): vAtual = listaNomes[i] posicao = i while posicao > 0 and listaNomes[posicao - 1] > vAtual: listaNomes[posicao] = listaNomes[posicao - 1] posicao = posicao - 1 listaNomes[posicao] = vAtual ordListaNomesInsert(lista_nomes) print('Nomes em ordem alfabética: ', lista_nomes)
70600d808b2282fd57ff5c7e4c5a670eebdba1b4
amaurya9/Python_code
/is_rotate.py
412
4.34375
4
def ISRotateString(string1,string2): string1+=string1 return string2 in string1 if __name__=="__main__": string1=input("Enter Input string") string2=input("Enter string to be checked as rotation or not") if ISRotateString(string1,string2): print("{} is a rotation of {}".format(string1,string2)) else: print("{} is not a rotation of {}".format(string1,string2))
58346bdb5940460b43505537ee56427ccda03036
ncwillner/python-tutorial
/classes.py
342
3.90625
4
# new types using classes class Point: #define new types def move(self): #methods that we define print('move') def draw(self): print('draw') point1 = Point() point1.x = 10 #attributes point1.y = 20 print(point1.x) point1.draw() point2 = Point() point2.x = 1 print(point2.x)
d07f6eb57ea9bbba97c39f079a6072c874cf0c90
MenacingManatee/holbertonschool-interview
/0x22-primegame/0-prime_game.py
1,146
3.9375
4
#!/usr/bin/python3 '''Runs the checker for prime game''' def isWinner(x, nums): ''' Usage: isWinner(rounds, numarray) Return: name of the player that won the most rounds ''' if x <= 0 or nums is None or nums == []: return None ben, maria = 0, 0 for num in nums: count = 0 rnd = [i for i in range(1, num + 1)] for i in rnd.copy(): if i not in rnd: continue if isPrime(i): rnd.remove(i) for j in rnd: if j > 1 and j % i == 0 and i != j: rnd.remove(j) count += 1 if count % 2 == 1: ben += 1 else: maria += 1 if maria > ben: return "Maria" elif ben > maria: return "Ben" else: return None def isPrime(num): ''' Checks if a number is prime ''' if num < 2: return 0 if num % 2 == 0: return 0 if num is not 2 else 1 for i in range(3, num // 2, 2): if i ** 2 > num: return 1 if num % i == 0: return 0 return 1
a2bfb43f522bf131a0953db2c0361c0219fb5540
brainygrave/file_rename
/main.py
479
3.625
4
import os path_way = os.getcwd() images = os.listdir(path_way) text_one = "" text_two = "" # OLD Text you want to change answer_one = input("\nFIND TEXT: ").lower() text_one = answer_one # NEW Text you want to change answer_two = input("\nCHANGE TEXT TO: ").lower() text_two = answer_two # Calling function to find and replace words in a directory for images in images: os.rename(images, images.replace(text_one, text_two)) print("DONE, KYLE! PLEASE CHECK YOUR FILES")
947243254430b2952aca0896589b067591bdda3a
ChenLaiHong/pythonBase
/test/leetcode/X的平方根.py
513
4
4
""" 实现 int sqrt(int x) 函数。 计算并返回 x 的平方根,其中 x 是非负整数。 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 示例 1: 输入: 4 输出: 2 示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。 """ import math def mySqrt(x): """ :type x: int :rtype: int """ result = math.sqrt(x) return int(result) x = int(input()) print(mySqrt(x))
98013e5e5ceac6cc103c33145c55920edb744536
AdamZhouSE/pythonHomework
/Code/CodeRecords/2604/60835/253543.py
263
3.546875
4
tem = input().split('"') letters = [] for n in range(len(tem)): if n%2==1: letters.append(tem[n]) target = input() result = '' for n in letters: if target < n: result = n break if result == '': result = letters[0] print(result)
7a0882804c197d5a21b2022b7e171dd7da730ee0
MrHamdulay/csc3-capstone
/examples/data/Assignment_6/klsada002/question1.py
388
4.03125
4
"""Adam Kaliski KLSADA002 CSC1015F Assignment 6 Question 1 Right justifies list of strings""" s = input('Enter strings (end with DONE):\n') listy = [] leng = 0 count=0 while s != 'DONE': listy.append(s) if len(s)>leng: leng = len(s) count+=1 s=input('') print('\nRight-aligned list:') for i in range(0,len(listy)): print (listy[i].rjust(leng))
4729f00b96c2e42436d7c7f0e9dcbd90da93754e
EricNg314/Code-Drills
/Interactive_Visualization/day-03/whale_watching/solved/whale_watching_app/app.py
2,102
3.53125
4
# import necessary libraries from flask import ( Flask, render_template, jsonify, request, redirect) from flask_pymongo import PyMongo import data_query import json import os # create instance of Flask app app = Flask(__name__) # TODO: Setup your connection to mongo with the database "whale_watching_app". # Use flask_pymongo to set up mongo connection app.config["MONGO_URI"] = os.environ.get('DATABASE_URL', '') or "mongodb://localhost:27017/whale_watching_app" mongo = PyMongo(app) # NOTE: We've given you this set of code to validate your database and run the query once. # TODO: However you'll need to update the file "data_query.py" to make the api call from the function. # Run the below once, to populate database from api. if ('whale_coll' not in mongo.db.collection_names()): print('adding whale_coll to db') data_query.get_api_whale_info(mongo) else: print('whale_coll is in db') # TODO: Update the function "get_all_whales" within "data_query.py" to retrieve all documents from your database. @app.route("/") def home(): whale_query = data_query.get_all_whales(mongo) # NOTE: Although we would like to use jsonify, we are going to use json.dumps. # Checkout the link below to review the difference. # https://stackoverflow.com/questions/7907596/json-dumps-vs-flask-jsonify # return render_template("index.html", whale_list = whale_query) # return render_template("index.html", whale_list = jsonify(whale_query)) return render_template("index.html", whale_list = json.dumps(whale_query)) # TODO: Create a route to send information to your database from your frontend. @app.route('/send', methods=["GET","POST"]) def send(): if request.method == "POST": whale_info= { "latitude": request.form["whaleLat"], "longitude": request.form["whaleLon"], "description": request.form["whaleDes"] } data_query.post_whale_info(mongo, whale_info) # TODO: Once you've made your post, redirect the user back to the root route. return redirect("/", code=302) if __name__ == "__main__": app.run(debug=True)
634699955c06a5edd012a51a172b9b954ff3a600
HaoLIU94/lpthw
/Pratice-exos/ex1.py
5,163
4.4375
4
#!/usr/bin/python import Tkinter top = Tkinter.Tk() # Code to add widgets will go here... top.mainloop() print "Hello World!" #good this is how we write comments print("Hao",25+30/6) print(3+2<5-7) print(5>-2) print(3+2+1-5+4%2-1/4+6) cars=100 space_in_a_car = 4.0 string = 'Nihao' print(space_in_a_car) print(string) print("let me say "+string) round(1.733333) #raw_input("\n\nPress the enter key to exit.") import sys; x = 'foo'; sys.stdout.write(x + '\n') counter = 100 # An integer assignment miles = 1000.0 # A floating point name = "John" # A string print counter print miles print name a,b,c = 1,2,"john" print a,b,c str = 'Hello World!' print str # Prints complete string print str[0] # Prints first character of the string print str[2:5] # Prints characters starting from 3rd to 5th print str[2:] # Prints string starting from 3rd character print str * 2 # Prints string two times print str + "TEST" # Prints concatenated string list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print list # Prints complete list print list[0] # Prints first element of the list print list[1:3] # Prints elements starting from 2nd till 3rd print list[2:] # Prints elements starting from 3rd element print tinylist * 2 # Prints list two times print list + tinylist # Prints concatenated lists tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] #tuple[2] = 1000 # Invalid syntax with tuple list[2] = 1000 # Valid syntax with list a = 1 b = 20 list = [1, 2, 3, 4, 5 ]; if ( a in list ): print "Line 1 - a is available in the given list" else: print "Line 1 - a is not available in the given list" count = 0 while (count < 9): print 'The count is:', count count = count + 1 print "Good bye!" ''' var = 1 while var == 1 : # This constructs an infinite loop num = raw_input("Enter a number :") print "You entered: ", num print "Good bye!" ''' count = 0 while count < 5: print count, " is less than 5" count = count + 1 else: print count, " is not less than 5" ''' flag = 1 while (flag): print 'Given flag is really true!' print "Good bye!" ''' for letter in 'Python': # First Example print 'Current Letter :', letter fruits = ['banana', 'apple', 'mango'] for liuhao in fruits: # Second Example print 'Current fruit :', liuhao print "Good bye!" fruits = ['banana', 'apple', 'mango'] for index in range(len(fruits)): print 'Current fruit :', fruits[index] print "Good bye!" for num in range(10,20): #to iterate between 10 to 20 for i in range(2,num): #to iterate on the factors of the number if num%i == 0: #to determine the first factor j=num/i #to calculate the second factor print '%d equals %d * %d' % (num,i,j) break #to move to the next number, the #first FOR else: # else part of the loop print num, 'is a prime number' var1 = 'Hello World!' var2 = "Python Programming" print "var1[0]: ", var1[0:5]+'NIhao' print "var2[1:5]: ", var2[5:] print "My name is %s and weight is %d kg!" % ('Zara', 21) para_str = """this is a long string that is made up of several lines and non-printable characters such as TAB ( \t ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this within the brackets [ \n ], or just a NEWLINE within the variable assignment will also show up. """ print para_str str = "this is string example....wow!!!"; print "str.capitalize() : ", str.capitalize() import time; # This is required to include time module. ticks = time.time() print "Number of ticks since 12:00am, January 1, 1970:", ticks import calendar cal = calendar.month(2008, 1) print "Here is the calendar:" print cal def printme( str ): "This prints a passed string into this function" print str return; # Now you can call printme function printme("nihao") def printinfo( name, age ): "This prints a passed info into this function" print "Name: ", name print "Age ", age return; # Now you can call printinfo function printinfo( age=50, name="miki" ) def printinfo( arg1, *vartuple ): "This prints a variable passed arguments" print "Output is: " print arg1 for var in vartuple: print var return; # Now you can call printinfo function printinfo( 10 ) printinfo( 70, 60, 50 ) import math content = dir(math) print content print math.pi str = input("Enter your input: "); print "Received input is : ", str try: fo = open("foo.dat", "r+") fo.write("This is my test file for exception handling!!") except IOError: print "Error: can\'t find file or read data" else: print "Written content in the file successfully" fo.close() fo = open("foo.dat", "r+") print "Name of the file: ", fo.name print "Closed or not : ", fo.closed print "Opening mode : ", fo.mode print "Softspace flag : ", fo.softspace close =int(raw_input()); if close==1: print "Close file",fo.name print fo.read(10) print fo.tell() fo.close() else: print "keep",close ,"open"
efb5eb89cc87d1e7787e279d2a1c5ac3551c0750
mayur1101/Mangesh
/Python/function decorator2.py
535
4.03125
4
# A Python program to demonstrate that a function # can be defined inside another function and a # function can be passed as parameter. # Adds a welcome message to the string def messageWithWelcome(str): # Nested function def addWelcome(): return "Welcome to " # Return concatenation of addWelcome() # and str. return addWelcome() + str # To get site name to which welcome is added def site(site_name): return site_name print (messageWithWelcome(site("the python world")))
96ce5d9ffb82306b6b4056f315a26d486abdc91c
yangzhao5566/go_study
/collections_learn.py
890
3.84375
4
# collections 模块学习 from collections import namedtuple from functools import partial from collections import deque from collections import OrderedDict from collections import defaultdict from collections import Counter point = namedtuple("Point", ["x", "y"]) # 创建一个具名元组 p2 = partial(point, x="2") pp = p2(y=3) p = point(1, 2) print(pp.x) print(p.x) print(p.y) q = deque(["a", "b", "c"]) q.append("x") q.appendleft("y") # 除此之外还有 pop popleft # defaultdict 给字典设置默认值 dd = defaultdict(lambda: "MB") dd["key1"] = "abc" print(dd["key"]) # 此时没有赋值会返回默认值 “MB" d = dict([("a",1), ("b", 2), ("c", 3)]) # 此时的字典是无须的 od = OrderedDict([("a", 1), ("b", 2), ("c", 3)]) # 这时候的字典是有序字典 # 简单计数器 Counter c = Counter() for ch in "programming": c[ch] = c[ch] + 1 print(c)
44768e37211923fa99fb7fcf47967287545eb8bf
ravi5921/LearningPython
/Tuples.py
564
3.71875
4
coordinates = (1,7) #tupples are defined by using ( ).They are static throughout the program coordinates2 =(4,5) #coordinates[0] = 3 this shows error as tuples' values can't be re-assigned or changed. print(coordinates) print(coordinates2) print(coordinates[0]) print(coordinates[1]) print(coordinates2[0], coordinates2[1]) coll_coor= [(1, 3),(4, 5)] print(coll_coor) print(coll_coor[0]) coll_coor[1] = 5 print(coll_coor[1]) #this happens because the entire tupple is replaced by another data item coll_coor[1] = "Possible." print(coll_coor[1])
06fc874f74dd0a4d86895f9851f1db9f02c11a86
AndrewC7/cs1.0
/custom_calculator/custom_calculator.py
3,022
4.5625
5
# this is a simple conversion calculator. It can handle seconds/minutes/hours print("Welcome to my simple conversion calculator! Simply:\n") print("1) Input the number of seconds/minutes/hours\n") print("2) Specify seconds/minutes/hours\n") print("3) Input your desired conversion\n") number = input("\nNumber of seconds/minutes/hours to convert:\n") # check to make sure user input is an int. If not, ask them to enter one while True: try: number = float(number) break except ValueError: print("Error: Please enter a valid number :)") break # if input is int, move on to next questions. if not, ask for a number before moving on to next questions if(isinstance(number, float)): convert = input("\nValue to convert:\n") desired = input("\nValue desired:\n") else: number = input("Number of seconds/minutes/hours to convert:\n") convert = input("\nValue to convert:\n") desired = input("\nValue desired:\n") # the next 2 if statements handle conversions into seconds. The 1st one checks if the user input minutes and the second # checks if the user input hours. Both convert number into a float, perform the required math, and print the result if((desired == 'Seconds' or desired =='seconds') and (convert == 'Minutes' or convert == 'minutes')): number = float(number) result = number * 60 print("\nThere are", result, "seconds in", number, "minutes.\n") if((desired == 'Seconds' or desired == 'seconds') and (convert == 'Hours' or convert == 'hours')): number = float(number) result = number * 3600 print("\nThere are", result, "seconds in", number, "Hours.\n") # the next 2 if statements handle conversions into minutes. The 1st one checks if the user input seconds and the second # checks if the user input hours. Both convert number into a float, perform the required math, and print the result if((desired == 'Minutes' or desired =='minutes') and (convert == 'Seconds' or convert == 'seconds')): number = float(number) result = number / 60 print("\nThere are", result, "minutes in", number, "seconds.\n") if((desired == 'Minutes' or desired == 'minutes') and (convert == 'Hours' or convert == 'hours')): number = float(number) result = number * 60 print("\nThere are", result, "minutes in", number, "Hours.\n") # the next 2 if statements handle conversions into hours. The 1st one checks if the user input seconds and the second # checks if the user input minutes. Both convert number into a float, perform the required math, and print the result if((desired == 'Hours' or desired =='hours') and (convert == 'Seconds' or convert == 'seconds')): number = float(number) result = number / 3600 print("\nThere are", result, "hours in", number, "seconds.\n") if((desired == 'Hours' or desired == 'hours') and (convert == 'Minutes' or convert == 'minutes')): number = float(number) result = number / 60 print("\nThere are", result, "hours in", number, "minutes.\n")
0d40965292a34b3fcb27f0717447ef2190f65776
AkulsysYT/chesscolourpicker
/ChessColourPicker.py
1,257
3.546875
4
import random import PySimpleGUI as sg # list shuffling import random colours = ['Black', 'White'] choices = random.choice(colours) if choices == "Black": var = "White" elif choices == "White": var = "Black" # gui sg.theme("DarkAmber") # This is the windows contents. layout = [[sg.Text( "Hello! This is a simple chess colour decider, used to help you when you can't decide what piece you want to play! It's easy! Just Write the name of Player1 in the first box and Player2 in the other!")], [sg.Input(key='-INPUT-')], [sg.Input(key='-INPUT1-')], [sg.Text(size=(150, 2), key='-OUTPUT-')], [sg.Button('Randomize!', bind_return_key=True), sg.Button('Cancel.')]] # Create the window window = sg.Window('Chess Colour Decider', layout) # This is the events (button presses) and values (input) infinite loop. while True: event, values = window.read() if event == sg.WINDOW_CLOSED or event == 'Cancel.': break # Output a message to the window window['-OUTPUT-'].update(values['-INPUT-'] + ' plays the ' + choices + ' pieces and ' + values['-INPUT1-'] + ' plays the ' + var + ' pieces!') # Finish up by removing from the screen window.close()
4617a952e4a3bd55163cbdcbb86fe0a0fa6579a6
mutoulovegc/gaochuang123
/桌面/day.3/maifangzi.py
501
3.671875
4
""" 买房子:500万能够买一环的房子,400万能够买二环,如果300万可以买三环的房子,如果有200万能够买四环的房子,如果小于200万,我只能睡大街 """ money = int(input("请输入存款金额")) if money>=500: print("可以购买一环的房子") elif money>=400: print("可以购买二环的房子") elif money>=300: print("可以购买三环的房子") elif money>=200: print("可以购买四环的房子") else: print("睡大街")
b48c97f5233f3406d755e33315526fd6728e3c0e
logan-anderson/competitive-programming
/aboveavarage.py
270
3.75
4
tests = int(input()) for i in range(tests): nums = [int(i) for i in input().split()][1:] average = sum(nums) / len(nums) above=0 for i in filter(lambda x: x > average, nums): above= above +1 print( '{:.3f}%'.format((above/len(nums))*100) )
dce96dd027151893a0e3d72f4a3ef6f002675b34
nkk0/battleships
/battleships.py
1,648
3.984375
4
from random import randint class Battleships: def __init__(self, turns=4): self.turns = turns self.board = [] def print_board(self): for row in self.board: print(' '.join(row)) def draw_board(self): for x in range(5): self.board.append(['O'] * 5) def random_row(): return randint(0, len(self.board) - 1) def random_col(): return randint(0, len(self.board) - 1) self.ship_row = random_row() self.ship_col = random_col() def play(self): self.draw_board() print('Let\'s play Battleships!') self.print_board() turn = 0 for _ in range(self.turns): turn += 1 print('Turn {}'.format(turn)) guess_row = int(input('Guess Row:')) - 1 guess_col = int(input('Guess Col:')) - 1 if guess_row == self.ship_row and guess_col == self.ship_col: print('You sunk my battleship!') break else: if (guess_row < 0 or guess_row > 4) \ or (guess_col < 0 or guess_col > 4): print('That\'s not in the ocean.') elif(self.board[guess_row][guess_col] == 'X'): print('You guessed that already.') else: print('You missed!') self.board[guess_row][guess_col] = 'X' self.print_board() if turn == self.turns: print('Game Over') if __name__ == '__main__': game = Battleships() game.play()
aaafa8fe034db0b73a479b7a9ade44cd1854ac44
AdamZhouSE/pythonHomework
/Code/CodeRecords/2591/60734/271562.py
227
3.765625
4
t = int(input()) for i in range(t): n = int(input()) if n==917 or n==51 or n==105 or n==101: print('Yes') elif n==109 or n==102 or n == 893 or n==103 or n==104: print('No') else: print(n)
b095747ee1f8bf44089cc80f5027426ecc1ad947
subreena10/function
/limitsum.py
278
3.921875
4
def numbers(limit): i=0 sum1=0 sum2=0 while i<=20: if i%3==0: sum1+=i print(i,"multiply of 3") elif i%5==0: sum2+=i print(i,"multiply of 5") i+=1 sum=sum1+sum2 print(sum) numbers(20)
1727659b4f1a8927713d1b58b702ebed2c1e4f11
SpencerEcho/LeetCode
/Python/AddTwoNumbers.py
1,413
3.875
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ return self.reversOfInt(self.sumOfList(l1) + self.sumOfList(l2)) def sumOfList(self, lt): numOfLt=0 i=0 while(lt != None): numOfLt += lt.val * pow(10,i) lt = lt.next i += 1 return numOfLt def reversOfInt(self, sumOfL): r=[] if (sumOfL == 0): r.append(0) return r while(sumOfL / 10 != 0): addition = sumOfL // 10 residue = sumOfL % 10 sumOfL = addition r.append(residue) return r class TestCase: def makeListNode(self, list): headNode = ListNode(0) curNode = headNode for num in list: newNode = ListNode(num) curNode.next = newNode curNode = newNode return headNode.next @classmethod def getSolution(cls, l1, l2): sl = Solution() return sl.addTwoNumbers(cls().makeListNode(l1), cls().makeListNode(l2)) print("[2,4,3], [5,6,4]: ", TestCase.getSolution([2,4,3], [5,6,4])) print("[0], [0]: ", TestCase.getSolution([0], [0]))
4cbc9d535c4109fd1a087e4fb8f79f5b5deab452
dongupak/Basic-Python-Programming
/Ch15_클래스와 객체지향 프로그래밍/human_ex6.py
602
3.8125
4
class Human: # 객체의 초기화를 담당하는 생성자 def __init__(self, name, age): self.__name = name # 인스턴스 메소드를 감추는 기능 self.__age = age # 아래와 같이 @property 지시자를 이용하여 외부에서 접근을 허 @property def age(self): return self.__age @age.setter def age(self, age): if age > 0 : self.__age = age else : self.__age = 0 person = Human("수지", 23) person.name = "수아" person.age = -30 print("이름 : ",person.name,"나이 :",person.age)
0d02519d834417b70944a756f3f2127d92336822
lydiahecker/exercises
/chapter-2/ex-2-10.py
974
4.1875
4
#Exercize 2-10 #Recipe calls for these ingredients: #1.5 cups of sugar #1 cup of butter #2.75 cups of flour #Produces 48 cookies. Ask the user how many cookies they want and #display the amount of ingredients they will need. sugar = 1.5 butter = 1 flour = 2.75 cookies = 48 sugar_for_one = sugar / cookies butter_for_one = butter / cookies flour_for_one = flour / cookies number_cookies = input("How many cookies would you like to make? ") f_number_cookies = float(number_cookies) amount_sugar = f_number_cookies * sugar_for_one amount_butter = f_number_cookies * butter_for_one amount_flour = f_number_cookies * flour_for_one print("To make", format(f_number_cookies, '.0f'), "you will need", format(amount_sugar, '.2f'), "cups of sugar") print("To make", format(f_number_cookies, '.0f'), "you will need", format(amount_butter, '.2f'), "cups of butter") print("To make", format(f_number_cookies, '.0f'), "you will need", format(amount_flour, '.2f'), "cups of flour")
f03ff08f0d70b90d6e3400a688724fe80d5de09a
EngrDevDom/Everyday-Coding-in-Python
/Check_date.py
482
4.0625
4
# This program checks if the date format input is correct. check = [ [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] ] day, month, year = map(int, input("Give a date: ").split()) feb_29 = int(year%400 == 0 or (year%4 == 0 and year%100 != 0)) if month < 13 and month > 0: if day > 0 and day <= check[feb_29][month]: print("CORRECT!") else: print("INCORRECT!") else: print("INCORRECT!")