blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
e08823d01c100ab7697dd5a3c5ca6064f8704f54
pombredanne/Rusthon
/regtests/go/map_comprehension.py
171
3.859375
4
''' map comprehensions ''' def main(): m = map[int]string{ key:'xxx' for key in range(10) } assert m[0]=='xxx' assert m[9]=='xxx' print m print m[0] print m[1]
57bea64b67a95243bbf2067014887c4b2f4bf08c
Jamunashree/Experimenting
/ExperimentingIf.py
1,394
3.796875
4
x= "Analyse Survey Data with the scripts on ***link***" y= "Meet us in the lobby at 8.30" print("Do you analyze survey data for work?") ans1=input() if ans1=='yes': print("Do you speak any R?") ans2=input() if ans2=="yes": print(x) elif ans2=="no": print("Do you analyze survey data with SAS,SUDAAN,Stata or SPSS?") ans4=input() if ans4=="no": ans5=input("Does it bother you that your analyses might all be wrong?") elif ans4=="yes": ans7=input("Are you concerned that proprietary software makes statistical research difficult to reproduce?") if ans7=="no": print(ans6) elif ans7=="yes": print("Learn R by watching 2 minute videos",x) else: print('') if ans5=="no": ans6=input("Do you mind the price tag?") if ans6=="no": print("First round's on you",y) else: print('') else: print('') else: print('') else: print('') elif ans1=="no": print("Why are you here?") ans3=input() if ans3=="Heard there was beer": print(y) else: print("") else: print('')
15b1d2ade8b254c240485470ed1c3ee6d2031538
marcusorefice/-studying-python3
/Exe041.py
808
4.28125
4
'''A confederação Naciona de Natação precisa de um programa que leia o ano de nascimento de um atleta e mostre mostre sua categoria, de acordo com a idade: Até 9 anos:MIRIM Até 14 anos:INFANTIL Até 19 anos:Junior Até 25 anos:Sênior Acima:MASTER''' from datetime import date ano = int(input('Informe o ano de nascimento do atleta: ')) idade = date.today().year - ano if idade <= 9: print(f'O atleta tem {idade} anos e é da categoria MIRIM') elif idade <= 14: print(f'O atleta tem {idade} anos e é da categoria INFANTIL') elif idade <= 19: print(f'O atleta tem {idade} anos e é da categoria JUNIOR') elif idade <= 25: print(f'O atleta tem {idade} anos e é da categoria SÊNIOR') else: print(f'O atleta tem acima de {idade} anos e é da categoria MASTER')
863f27ae0745b09eecf25d60ee2484a8b64dce2b
anilkumar0470/git_practice
/mysqlpracfull.py
10,455
3.640625
4
""" sql = "select * from employee where income >= %d " %(2000) try: #excute the sql command print "==>",sql cursor.execute(sql) #fetch all the rows in alist of lists results = cursor.fetchall() print "===",results for row in results: print "---",row first_name = row[0] last_name = row[1] age = row[2] address = row[3] sex = row[4] income = row[5] # now print fetched result print "%s %s %d %s %s %f" % \ (first_name,last_name,age,address,sex,income) except : print "error : unable to fetch data" #disconnect from server db.close() """ def student_register(): f = True while f: name = raw_input ("enter the name of student:") regNo = raw_input ("enter the roll number:") address = raw_input ("enter the address:") standard = raw_input ("enter the section:") mobile = raw_input ("enter the mobile number:") dob = raw_input ("enter the date of bitrh :") std_list.append({'name':name,'reg':regNo,'address':address,'section':standard,'contact':mobile,'dob':dob}) ent=raw_input("Press y/yes for to enter another student details n/no for main menu:") if ent in ['yes','y','YES','Y']: f=True else: f=False def student_search_result(): name = raw_input("enter the student name:") for each_student in std_list: #[{name:shiva,reg:2},{name:anil,reg:1},{}] if each_student['name'] == name: p = "=" print p*50 print " Student search result " print p*50 print "Name Reg Address Section Contact DOB " print p*50 print "%s %s %s %s %s %s"%(each_student['name'],each_student['reg'],each_student['address'],each_student['section'],each_student['contact'],each_student['dob']) print p*50 print "name total marks sub1 sub2 sub3 sub4 sub5 sub6" print p*50 """ for j in std_marks : print "%s %d %d %d %d %d %d %d"%(j["name"],j["total marks"],j["sub1"],j["sub2"],j["sub3"],j["sub4"],j["sub5"],j["sub6"]) """ for student in std_marks: if student['name'] == name: print "%s %d %d %d %d %d %d %d"%(student["name"],student["total marks"],student["sub1"],student["sub2"],student["sub3"],student["sub4"],student["sub5"],student["sub6"]) def student_register(): f = True while f: name = raw_input ("enter the name of student:") regNo = raw_input ("enter the roll number:") address = raw_input ("enter the address:") section = raw_input ("enter the section:") mobile = raw_input ("enter the mobile number:") dob = raw_input ("enter the date of bitrh :") std_list.append({'name':name,'reg':regNo,'address':address,'section':section,'contact':mobile,'dob':dob}) ent=raw_input("Press y/yes for to enter another student details n/no for main menu:") if ent in ['yes','y','YES','Y']: f=True else: f=False def student_marks(): name = raw_input ("enter the name of the student ") sub1 = input("enter the marks of sub1:") sub2 = input("enter the marks of sub2:") sub3 = input("enter the marks of sub3:") sub4 = input("enter the marks of sub4:") sub5 = input("enter the marks of sub5:") sub6 = input("enter the marks of sub6:") total = sub1+sub2+sub3+sub4+sub5+sub6 if sub1<35: g = False elif sub2<35: g = False elif sub3<35: g = False elif sub4<35: g = False elif sub5<35: g = False elif sub6<35: g = False if g: print "........!!!!!!Congratulations!!!!!!!......" result = "pass" print "Result:",result else : result = "fail" print "result:",result print "@@@Better luck next time@@@" print "total marks :",total std_marks.append({"name":name,"total marks":total,"sub1":sub1,"sub2":sub2,"sub3":sub3,"sub4":sub4,"sub5":sub5,"sub6":sub6,"Result":result}) ent=raw_input("enter if you want to continue yes otherwise no:") if ent in ['yes','y','Y','YES']: student_marks() def student_report(): name = raw_input("enter the name of the student for report:") for each_student in std_list: #[{name:shiva,reg:2},{name:anil,reg:1},{}] if each_student['name'] == name: p="=" print p*50 print " Student report " print p*50 print "Name Reg Address Section Contact DOB " print p*50 print "%s %s %s %s %s %s"%(each_student['name'],each_student['reg'],each_student['address'],each_student['section'],each_student['contact'],each_student['dob']) print p*50 print "name total marks sub1 sub2 sub3 sub4 sub5 sub6" print p*50 for student in std_marks: if student['name'] == name: print "%s %d %d %d %d %d %d %d"%(student["name"],student["total marks"],student["sub1"],student["sub2"],student["sub3"],student["sub4"],student["sub5"],student["sub6"]) """for j in std_marks : print "%s %d %d %d %d %d %d %d"%(j["name"],j["total marks"],j["sub1"],j["sub2"],j["sub3"],j["sub4"],j["sub5"],j["sub6"]) """ """for i in std_list: print "%s %s %s %s %s %s"%(i['name'],i['reg'],i['address'],i['section'],i['contact'],i['dob']) print p*50 print "name total marks sub1 sub2 sub3 sub4 sub5 sub6" print p*50 for j in std_marks : print "%s %d %d %d %d %d %d %d"%(j["name"],j["total marks"],j["sub1"],j["sub2"],j["sub3"],j["sub4"],j["sub5"],j["sub6"]) """ def all_student_report(): p="=" print p*50 print " Student report " print p*50 #print "Name Reg Address Section Contact DOB " #print p*50 #print "%s %s %s %s %s %s"%(each_student['name'],each_student['reg'],each_student['address'],each_student['section'],each_student['contact'],each_student['dob']) print p*50 #print "name total marks sub1 sub2 sub3 sub4 sub5 sub6" print p*50 """for student in std_marks: if student['name'] == name: print "%s %d %d %d %d %d %d %d"%(student["name"],student["total marks"],student["sub1"],student["sub2"],student["sub3"],student["sub4"],student["sub5"],student["sub6"]) """ """for j in std_marks : print "%s %d %d %d %d %d %d %d"%(j["name"],j["total marks"],j["sub1"],j["sub2"],j["sub3"],j["sub4"],j["sub5"],j["sub6"]) """ for i in std_list: print "%s %s %s %s %s %s"%(i['name'],i['reg'],i['address'],i['section'],i['contact'],i['dob']) print p*50 print p*50 for student in std_marks: if student == i: print "name total marks sub1 sub2 sub3 sub4 sub5 sub6" print "%s %d %d %d %d %d %d %d"%(student["name"],student["total marks"],student["sub1"],student["sub2"],student["sub3"],student["sub4"],student["sub5"],student["sub6"]) """for j in std_marks : print "name total marks sub1 sub2 sub3 sub4 sub5 sub6" print "%s %d %d %d %d %d %d %d"%(j["name"],j["total marks"],j["sub1"],j["sub2"],j["sub3"],j["sub4"],j["sub5"],j["sub6"]) """ def fee_details(): p="=" print p*50 print " Student Fee Details " print p*50 name = raw_input("enter the student name:") t=total = input("enter the total fee") print "total fee is:",total p=pay = input("enter how much do you want to pay") due = t - p print "Due fee is :",due std_Fee.append({'name':name,'total Fee':total,"pay":pay,"Remaining Fee":due}) def menu(): global std_list std_list=[] global std_marks std_marks=[] global std_Fee std_Fee =[] global db global cursor import MySQLdb db = MySQLdb.connect("localhost","root","aneel","world") cursor = db.cursor() sql = """create table if not exists std_details2( first_name char(20) not null, last_name char(20), age int, address char(20), sex char(1), income float)""" cursor.execute(sql) p = """ 1.student register 2.student marks details 3.search for student 4.student report 5.all student report 6.fee collection 7.exit """ f = True while f: print p opt = input("choose option which ever you want from above menu:") if opt == 1: print "===student register===" student_register() elif opt == 2: print "****student marks details****" student_marks() elif opt == 3: print "!!!!search for student!!!!" student_search_result() elif opt == 4: print "@@@@student report@@@@" student_report() elif opt == 5: print "!@#$ALL Students Report%^&*" all_student_report() elif opt == 6: print "$$$$Fee Details$$$$" fee_details() elif opt == 7: print "Have a Nice Day" else : print "enter proper output" ent = raw_input("if you want Main Menu press yes/y or no/n:") if ent in ("yes","y","YES","Y"): f = True else : f = False menu () print " Bye Bye Thank You Use Again"
cccbf3dac8a8a109370593dd35e1ed8398e7d3c6
wangxiao4/programming
/Num6/6.2_PrintGradeFunction.py
255
3.96875
4
def printGrade(score): if score<60: print("F") elif score<70: print("D") elif score<80: print("C") elif score<90: print("B") else: print("A") score=eval(input("enter score\n")) printGrade(score)
7a9d382a3f902973ad48761c18cba24db2408197
teoim/learnPython
/c2_s3_strings.py
2,143
4.21875
4
# help(str) # string manual # print(dir(str)) # available functions for string # format method num1 = 100 num2 = 200 print("Num1 is {0} and num2 is {1}".format(num1,num2)) print("Num1 is {val1} and num2 is {val2}".format(val1=num1,val2=num2)) s1 = "make me capital one more time" print(id(s1)) s1 = s1.capitalize() # Converts the first letter of the string to UPPERCASE print(s1) print(id(s1)) # Strings are imutable, so every time you change it a new one will be created in a different memory space # upper() , isupper() # lower() , islower() # title() , istitle() # split() # join() s2 = s1.replace(" ", ",") print(s2) l1 = s1.split(" ") l2 = s2.split(",") print(l1,type(l1)) print(l2,type(l2)) s3 = ";".join( l2 ) print(s3) # maketrans() # translate() sampleStr = "Hello python sample string abcd" abc = "abcd" ijk = "1234" table = str.maketrans(abc,ijk) result = sampleStr.translate(table) # Hello python s1mple string 1234 print(result) # index() # find() # rfind() sampleStr2 = "HTML,CSS,PYTHON,JAVA,PYTHON" # yOU WANT TO CHECK IF PYTHON IS PART OF THE STRING print( "PYTHON" in sampleStr2) print( sampleStr2.index("PYTHON")) # 9 : start of the first "PYTHON" print( sampleStr2.find("PYTHON")) # 9 # print( sampleStr2.index("python")) # ValueError: substring not found print( sampleStr2.find("python")) # -1 print( sampleStr2.rfind("PYTHON")) # 21 : reverse-find - searches in reverse starting from the end of the string print( sampleStr2.rfind("python")) # -1 # strip() # lstrip() strips frpm the left # rstrip() strip from the right sampleStr3 = " ***Some string whatever******* " sampleStr4 = sampleStr3.strip(" ") print(sampleStr3) print(sampleStr4) sampleStr5 = sampleStr4.strip("*") print(sampleStr5) print(sampleStr4.lstrip("*")) print(sampleStr4.rstrip("*")) # center() # ljust() # rjust() str12 = "hello" print( str12.center(20,"#")) # #######hello######## print( str12.ljust(20,"#")) # hello############### print( str12.rjust(20,"#")) # ###############hello # replace() str1 = "html,java,python,html,css" str2 = str1.replace("html","HTML5") print(str2)
2aad76d109125e5a2ecf4a6894172bc9a0a7bf2a
juselius/python-tutorials
/Debugging/list_bug.py
265
4
4
def lists(): empty_list = [] list_of_lists = [] for x in range(0, 5): list_of_lists.append(empty_list) for index, list in enumerate(list_of_lists): list.append(index) print list_of_lists if __name__ == '__main__': lists()
f25c395e089bc0a60673cf19e8bf292885e79031
sonkadak/coding-practice
/Hackerrank/Interview-preparation-kit/Arrays/2D-Array-DS.py
787
3.5
4
#!/bin/python3 # Complete the hourglassSum function below. def hourglassSum(arr): sums = [] for i in range(0, 16): sums.append(0) # for sum of 1st line each glasshour n = 0 for i in range(0, len(arr)-2): for j in range(0, len(arr[i])-2): for k in range(j, j+3): sums[n] += arr[i][k] n += 1 # 2nd line n = 0 for i in range(1, len(arr)-1): for j in range(1, len(arr[i])-1): sums[n] += arr[i][j] n += 1 # 3rd line n = 0 for i in range(2, len(arr)): for j in range(0, len(arr[i])-2): for k in range(j, j+3): sums[n] += arr[i][k] n += 1 # return maximum value of list return max(sums)
7e0f49461272144753c1688587160c9c58941c2e
sainihimanshu1999/Leetcode-Interview-Questions
/word-break2.py
501
3.671875
4
''' simple recurssion ''' class Solution: def wordBreak(self,s,wordDict): if s == '': return [[]] ans = [] for word in wordDict: if s[:len(word)]==word: if len(s)==len(word): ans.append(word) else: suffix = s[word:] temp = self.wordBreak(suffix,wordDict) for t in temp: ans.append(word+' '+t) return ans
9493cd6863c1f260827bb2020e3a104c2f025fa7
ErikSteLarsen/Gruppe2EiT
/simulator/AdvancedSimulator.py
858
3.796875
4
import numpy as np class AdvancedSimulator: def __init__(self,truck): self.truck = truck def calculateWeights(self,valgfri=None): weights = [] axleCapacitiesTruck = self.truck.getMaxAxleWeights() axleCapacitiesTrailer = self.truck.trailer.getWeightDistribution() allCapacities = axleCapacitiesTruck for element in axleCapacitiesTrailer: allCapacities.append(element) print(allCapacities) print("The capacity on each axle is : ") # TODO Legg til at dette kan sjekkes på henger også print("Truck:", axleCapacitiesTruck, "\nTrailer:", axleCapacitiesTrailer) for i in range(len(allCapacities)): weight = int(input("What is the weights of the goods on axle "+ str(i) + "?")) weights.append(weight) return weights
ba7959983789faa6782953ddacfa8949c45bed93
JoachimIsaac/Interview-Preparation
/arrays_and_strings/integer_to_string.py
854
4.28125
4
""" Problem 2: Write a method that takes an integer as input and returns its string representation. For example: Input: 123 Output: "123" Input: -6714 Ouput: "-6714" UMPIRE: Understand: --> Can we use the built in str() method to change the entire integer? --> Can we get negative numbers ? yes --> can we get input that is not an integer? yes match: int() method Plan: --> check if the number is an integer, if it is we can continue , if not return "Not an integer value" --> if it is an integer value return that str representation of that O(1) constant time O(1) constant space """ class Solution: def integer_to_string(self, number): if isinstance(number, int): return str(number) else: return "Not an integer value" solution = Solution() print(solution.integer_to_string(-6714))
90da10cd0b9f4431e56dd9e911ed410c3272b555
Xuchaoqiang/Luffycity
/第二模块/第三章/局部变量.py
1,675
3.859375
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Irving # 局部变量 # 不加global修改names其实是在内存里重新创建了一个names变量,指向另外一块内存地址,id不一样, 加了global就是直接引用了names # names = ['alex', 'irving', 'eric'] # def change_name(): # global names # names = ['alex', 'irving'] # print(names) # # change_name() # print(names) # 在函数里面可以直接引用列表修改里面的元素, 但是不能对列表进行修改(重新赋值) # names = ['alex', 'irving', 'eric'] # def change_name(): # del names[1] # names.append('张三丰') # print(names) # change_name() # print(names) # 嵌套函数 # 函数内部可以再次定义函数, 执行需要被调用 # def func1(): # print('alex') # # def func2(): # print('eric') # # func2() # func1() # # age = 19 # def func1(): # age = 73 # def func2(): # print(age) # func2() # func1() # # age = 19 # # def func1(): # def func2(): # print(age) # age = 73 # func2() # func1() # # func1函数里面其实没有重新创建一个值age, 而是对全局变量age操作修改了 # age = 19 # def func1(): # global age # def func2(): # print(age) # age = 73 # func2() # func1() # print(age) # # age = 18 # # def func1(): # age = 73 # def func2(): # print(age) # return 666 # # va1 = func1() # print(va1) # 代码定义完成之后,作用域已经生产,作用域链向上查找 # # age = 18 # # def func1(): # age = 73 # def func2(): # print(age) # # return func2 # # va1 = func1() # va1()
665860acd0f1d47eea0694852d94397864251d6b
bsdharshini/Python-exercise
/task reverse.py
784
4.34375
4
''' Reverse array For a given array reverse order of its elements. Input The first line of input contains integer t,the number of test cases. In the next t lines t test cases follow. Each test case cosists of numbers separated by spaces. In each line, the first number ni is the length of an array. Next ni numbers are values of the array. Output For each test case print elements of the array in reversed order. Numbers should be separated by single space and answers for each test case should appear in a separate line. Example Input: 2 7 1 2 3 4 5 6 7 3 3 2 11 Output: 7 6 5 4 3 2 1 11 2 3 ''' n=int(input()) for i in range(0,n): string =input() word=string.split(" ") del word[0] word.reverse() print(" ".join(word))
6bb34f64c553a589207ad28a9d63c1351750b33b
lizerd123/github
/game compalation/Game compalation.py
16,455
3.578125
4
game_chosen=0 begin_game=0 running=0 while True: while begin_game!=1: print("play (1) motorman(one player) (2) Dungeon(one player) (3) Shop'n'Stab(one player) (4)Duel(two player)") game_chosen=input("what to play... ") if game_chosen==1 or 2: begin_game=1 running=1 if game_chosen==1: import sys, pygame, pygame.mixer from pygame.locals import * import random import time print("'You must hunt down the beast that has plauged this land, do so using arrow keys or A and D to accelerate or decellerate, use space to fire, take cation in doing so as it will prevent you from speeding up'") print("(1)easy,(2)medium,(3)hard,(4)NIGHTMARE") difficulty=input() pygame.init() pygame.key.set_repeat(25,25) person = pygame.image.load("motorman.png") deamon=pygame.image.load("deamon.png") bullet=pygame.image.load("bullet.png") ex=pygame.image.load("caution.png") doom=pygame.image.load("doom.png") go=0 dx=670 dy=100 posx=200 posy=460 bx=800 if difficulty==1 and go<1: bh=random.randrange(10,20) r1=12 r2=29 if difficulty==2 and go<1: bh=random.randrange(20,30) r1=11 r2=27 if difficulty==3 and go<1: bh=random.randrange(30,40) r1=10 r2=25 if difficulty==4 and go<1: bh=random.randrange(40,50) r1=10 r2=23 ticks=900/bh go=0 print(bh) screen=pygame.display.set_mode((900,700)) x=0 back=pygame.image.load("1.png") while running==1: if difficulty==1: firepiller=random.randrange(0,26) if difficulty==2: firepiller=random.randrange(0,23) if difficulty==3: firepiller=random.randrange(0,18) if difficulty==4: firepiller=random.randrange(0,13) pygame.draw.rect(screen,(225,0,0),(0,0,900,100)) pygame.draw.rect(screen,(0,225,0),(0,0,bh*ticks,100)) screen.blit(doom,(0,400)) if posx<=0: print('" __ __ _______ __ __ ______ ___ _______ ______ "') print('"| | | || || | | | | \ | | | || \ "') print('"| | | || _ || | | | | __ || | | ___|| __ |"') print('"| |_| || | | || | | | | | \ || | | |___ | | \ |"') print('" \ / | |_| || | | | | |__/ || | | ___|| |__/ |"') print('" | | | || |_| | | || | | |___ | |"') print('" |___| |_______||_______| |______/ |___| |_______||______/ "') running=0 if bh<=0: print("' ____ ______ _____ _______ _____ _ _____ _ _ '") print("'| _ \ | ____| /\ / ____|__ __| / ____| | /\ |_ _| \ | |'") print("'| |_) | | |__ / \ | (___ | | | (___ | | / \ | | | \| |'") print("'| _ < | __| / /\ \ \___ \ | | \___ \| | / /\ \ | | | . ` |'") print("'| |_) | | |____ / ____ \ ____) | | | ____) | |____ / ____ \ _| |_| |\ |'") print("'|____/ |______/_/ \_\_____/ |_| |_____/|______/_/ \_\_____|_| \_|'") running=0 if firepiller==1 and go<1: dy=350 fx=random.randrange(100,670) go=1 if go > 0: go+=1 if go < r1: screen.blit(ex,(fx,500)) if r1<go<r2: screen.blit(doom,(fx,400)) if posx-70<fx<posx+200: print("' __ __ _______ __ __ ______ ___ _______ ______ '") print("'| | | || || | | | | \ | | | || \ '") print("'| | | || _ || | | | | __ || | | ___|| __ |'") print("'| |_| || | | || | | | | | \ || | | |___ | | \ |'") print("' \ / | |_| || | | | | |__/ || | | ___|| |__/ |'") print("' | | | || |_| | | || | | |___ | |'") print("' |___| |_______||_______| |______/ |___| |_______||______/ '") running=0 if go >r2: go=0 dy=100 if x>450: no+=1 if no < 12: screen.blit(ex,(600,400)) if 12<no<25: screen.blit(doom,(600,400)) bx+=100 screen.blit(bullet,(bx,400)) screen.blit(deamon,(dx,dy)) pygame.display.flip() screen.blit(back,(0,0)) pygame.draw.rect(screen,(0,0,0),(0,0,900,100)) screen.blit(person,(posx,posy)) for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == KEYDOWN: if event.key==K_a or event.key==K_LEFT: posx=posx-40 if event.key==K_d or event.key==K_RIGHT: posx=posx+40 if event.key==K_SPACE and bx>700: bx=posx if dx<bx<dx+125 and dy<400<dy+100: bh-=1 x+=1 time.sleep(1/7) back=pygame.image.load(str(x)+".png") if x==54: x=1 if running==0: pygame.display.quit() if game_chosen==2: import sys, pygame, pygame.mixer from pygame.locals import * import random import time ground=pygame.image.load("begin.png") grave=pygame.image.load("grave.png") hero=pygame.image.load("hero.png") menu=pygame.image.load("menuNEXT.png") monster=pygame.image.load("monster.png") knife=pygame.image.load("knifew.png") ones=pygame.image.load("1n.png") tens=pygame.image.load("0n.png") pygame.init() hx=225 hy=100 fire=0 di=1 men=0 coinneeded=10 enemies=0 level=1 begin=0 r=1 coin=0 mx=300 my=300 screen=pygame.display.set_mode((500,500)) pygame.key.set_repeat(25,25) while running==1: ten=int(level/10) pygame.display.flip() screen.blit(ground,(0,0)) tens=pygame.image.load(str(ten)+"n.png") one=level-(ten*10+1) ones=pygame.image.load(str(one)+"n.png") screen.blit(ones,(110,0)) screen.blit(tens,(0,0)) if begin==1 and enemies>=0: screen.blit(monster,(mx,my)) if hx-mx>0: mx+=coinneeded/20 if hx-mx<0: mx-=coinneeded/20 if hy-my>0: my+=coinneeded/20 if hy-my<0: my-=coinneeded/20 if my<hy<my+75 and mx<hx<mx+50: print("you died at level " + str(level)) running=0 if fire==1: if di==1: ky-=25 if di==2: kx-=25 if di==3: ky+=25 if di==4: kx+=25 if mx-10<kx<mx+50 and my-10<ky<my+75: coin+=10 print("coins:" + str(coin)) mx=8000 my=8000 enemies-=1 screen.blit(knife,(kx,ky)) if kx<0 or kx>500 or ky<0 or ky>500: fire=0 if enemies <=0: screen.blit(grave,(225,225)) screen.blit(hero,(hx,hy)) if men==1 and enemies<=0: screen.blit(menu,(0,400)) for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == KEYDOWN: if event.key==K_a: knife=pygame.image.load("knifea.png") hx-=25 if fire!=1: di=2 if event.key==K_f: enemies-=1 if event.key==K_d: knife=pygame.image.load("knifed.png") hx+=25 if fire!=1: di=4 if event.key==K_w: knife=pygame.image.load("knifew.png") hy-=25 if fire!=1: di=1 if event.key==K_s: knife=pygame.image.load("knifes.png") hy+=25 if fire!=1: di=3 if event.key==K_LEFT: menu=pygame.image.load("menuNEXT.png") r=1 if event.key==K_RIGHT: menu=pygame.image.load("menuUP.png") r=0 if event.key==K_SPACE and fire==0 and enemies>0: kx=hx ky=hy screen.blit(knife,(kx,ky)) fire=1 if enemies <=0: if hx==225 and hy==225 and event.key==K_SPACE: men=1 if hx!=225 or hy!=225: men=0 if men==1 and event.key==K_RETURN and r==0 and coin>=coinneeded: level+=1 print("current level:" + str(level)) coin-=coinneeded coinneeded+=10 print("untill next level:" + str(coinneeded)) print("coins:" + str(coin)) if men==1 and event.key==K_RETURN and r==1: x=random.randint(1,5) ground=pygame.image.load(str(x)+"b.png") enemies=1 screen.blit(ground,(0,0)) begin=1 mx=random.randint(0,100) or random.randint(400,500) my=random.randint(0,100) or random.randint(400,500) if running==0: pygame.display.quit() if game_chosen==3: from random import randint as ri inv=[] st=1 sa=0 money=120 weapon="your an idiot" item="your an idiot" magic="your an idiot" print (money) print ("I better get some weapons items and magic") Inventory_Blacksmith=["wooden sword","Axe","longsword","knife","hammer","torch"] r = ri(0,5) print (Inventory_Blacksmith[r:r+3]) buy = raw_input("what to buy?") if buy == "wooden sword": inv.append("wooden sword") money=money-25 weapon="wooden sword" if buy == "Axe": inv.append("Axe") money=money-60 weapon="Axe" if buy == "longsword": inv.append("longsword") money=money-60 weapon="longsword" if buy == "knife": inv.append("knife") money=money-30 weapon="knife" if buy == "hammer": inv.append("hammer") money=money-60 weapon="hammer" if buy == "torch": inv.append("torch") money=money-30 weapon="torch" if len(inv) < 1: inv.append("FOOL") print(money) print(inv) Inventory_Shopkeep=["Potion","attack potion","defence potion"] print (Inventory_Shopkeep) buy = raw_input("what to buy?") if buy == "firebomb": inv.append("firebomb") money=money-30 item="firebomb" if buy == "Potion": inv.append("Potion") money=money-30 item="Potion" if buy == "attack potion": inv.append("attack potion") money=money-30 item="attack potion" if buy == "defence potion": inv.append("defence potion") money=money-30 item="defence potion" if len(inv) < 2: inv.append("FOOL") print(money) print(inv) Inventory_wizard=["energy","magic weapon","heal","stoneflesh" ] r = ri(0,5) print (Inventory_wizard[r:r+3]) buy = raw_input("what to buy?") if buy == "energy": magic="energy" inv.append("energy") money=money-25 if buy == "magic weapon": inv.append("magic weapon") money=money-30 magic="magic weapon" if buy == "heal": inv.append("heal") money=money-60 magic="heal" if buy == "stoneflesh": inv.append("stoneflesh") money=money-60 magic="stoneflesh" if buy == "thorns": inv.append("thorns") money=money-30 magic="thorns" if len(inv) < 3: inv.append("FOOL") print(inv) from random import randint as ri mg=0 eh = ri(150, 280) mh = 200 de=1 if weapon == "Axe": st = 1.8 if weapon == "longsword": st = 1.6 if weapon == "knife": st = 1.1 if weapon == "hammer": st = 1.7 if weapon == "wooden sword": st = 1 if weapon == "torch": st = 1.4 if item == "potion": mh=mh+30 if item == "potion": mh=mh+30 if item == "attack potion": st=st+.6 if item == "defence potion": de=de+.4 if magic == "energy": mg=5 if magic == "magic weapon": st=st+.6 if magic == "heal": mh=mh+30 if magic == "magic weapon": st=st+.6 if magic == "stoneflesh": de=de+.2 if magic == "thorns": cd=.5 while eh>0 and mh>0: counter = 0 ed=ri(9,30) print (" I can attack counter or use skill") if sa < 40: print ("I am too tired to use a skill") move = raw_input("move ") if move == "attack": at=ri(9,15) eh=eh-st*at+mg print ("enemy") print (eh) print ("the attack was successful") if move == ("inventory"): print ("I have") (inv) if move == ("skill") and sa > 40: if weapon == "Axe": eh = eh-st*2*at+mg mh = mh-20 sa=0 print("the attack was powerful but left your wrist injujred") if weapon == "longsword": ed = 0 sa=0 print("You were too far for the enemy to attack") if weapon == "knife": slash = ri(1,5) if slash == 1: eh = eh-40 sa=0 print("you slash at the enemy dealing heavy dammage") else: print("you miss the enemy") if weapon == "hammer": de = + .5 sa=0 print("you feel far more fortified") if weapon == "wooden sword": st = st-.75 mh = mh + .1*mh sa=0 print("somehow snaping your flimsy sword makes you feel better") if weapon == "torch": mg = 10 sa=0 print("you light the enemy ablaze") if move == "counter": counter = 1 ea = ri(0,4) if ea > 0: mh=mh-ed/de print ("me") print (mh) if counter == 1: eh=eh-st*ed*1.25+mg print ("enemy") print (eh) if ea == 0: if counter ==1: print("the counter fails") mh=mh-ri(10,20) print(mh) print ("enemy") print (eh) sa = sa +10 if game_chosen==4: p1h=5 p2h=5 p1p=4 p2p=2 moves1=3 moves2=3 space=1 p1w=raw_input("P1 Weapon: ") if p1w == "axe": p1min=-1 p1max=1 if p1w == "longsword": p1min=0 p1max=2 if p1w == "spear": p1min=1 p1max=3 p2w=raw_input("P2 Weapon: ") if p2w == "axe": p2min=-1 p2max=1 if p2w == "longsword": p2min=0 p2max=2 if p2w == "spear": p2min=1 p2max=3 while p1h>=0 or p2h>=0: moves1=3 moves2=3 while moves1>0: if p2p==1: if p1p==2: print("X O_ _ _") if p1p==3: print("X _ O _ _") if p1p==4: print("X _ _ O _") if p1p==5: print("X _ _ _ O") if p2p==2: if p1p==3: print("_ X O _ _") if p1p==4: print("_ X _ O _") if p1p==5: print("_ X _ _ O") if p2p==3: if p1p==4: print("_ _ X O _") if p1p==5: print("_ _ X _ O") if p2p==4: if p1p==5: print("_ _ _ X O") print ("moves:"+ str(moves1)) print("health1:"+str(p1h )) action1=raw_input("action P1") if action1 == "back": if p1p == 5: print("my back is against the wall") if p1p<5: moves1=moves1-1 p1p=p1p+1 space=space+1 if action1 == "forwards": if space == 0: print("cant move past the enemy") if space>0: space=space-1 p1p=p1p-1 print("I moved forwards") moves1=moves1-1 if action1 == "attack": if space>p1min and space<p1max: p2h=p2h-1 moves1=moves1-1 print("Hit") if space<=p1min or space>=p1max: print("out of my range") if action1 == "shove": if space==0: moves1=moves1-1 print("I shoved him back") p2p=p2p-1 space=space+1 while moves2>0: if p2h>0: if p2p==1: if p1p==2: print("X O_ _ _") if p1p==3: print("X _ O _ _") if p1p==4: print("X _ _ O _") if p1p==5: print("X _ _ _ O") if p2p==2: if p1p==3: print("_ X O _ _") if p1p==4: print("_ X _ O _") if p1p==5: print("_ X _ _ O") if p2p==3: if p1p==4: print("_ _ X O _") if p1p==5: print("_ _ X _ O") if p2p==4: if p1p==5: print("_ _ _ X O") print ("moves:"+ str(moves2)) print("health2:"+str(p2h) ) action2=raw_input("action P2") if action2 == "back": if p2p == 1: print("my back is against the wall") if p1p>1: moves2=moves2-1 p2p=p2p-1 space=space+1 if action2 == "forwards": if space == 0: print("cant move past the enemy") if space>0: space=space-1 p2p=p2p+1 print("I moved forwards") moves2=moves2-1 if action2 == "attack": if space>p2min and space<p2max: p1h=p1h-1 moves2=moves2-1 print("Hit") if space<=p2min or space>=p2max: print("out of my range") if action2 == "shove": if space==0: moves2=moves2-1 print("I shoved him back") p1p=p1p+1 space=space+1 begin_game=0
db1628e56fc0e723a08fa43c52d9aca5ad03c338
detcitty/100DaysOfCode
/python/unfinshed/largeprodsum.py
494
3.625
4
# https://www.codewars.com/kata/5c4cb8fc3cf185147a5bdd02/train/python import numpy as np def sum_or_product(array, n): a = np.array(array) a_sorted = np.argsort(a) potential_prod = a[a_sorted][:n] potenial_sum = a[a_sorted][-n:] prod = np.prod(potential_prod) sums = np.sum(potenial_sum) value = '' if prod > sums: value = 'product' elif prod < sums: value = 'sums' else: value = 'same' return(value)
48e04ebd079b65be5597e4e537327e215564c97d
vladvlad23/UBBComputerScienceBachelor
/FundamentalsOfProgramming/Assignment_05_07_refactored/Assignment_05_07_refactored/domain/Movie.py
839
3.5
4
class Movie: def __init__(self,movieId,movieTitle,movieDescription,movieGenre): self.__movieId = movieId self.__movieTitle = movieTitle self.__movieDescription = movieDescription self.__movieGenre = movieGenre def getMovieId(self): return self.__movieId def getMovieTitle(self): return self.__movieTitle def getMovieDescription(self): return self.__movieDescription def getMovieGenre(self): return self.__movieGenre def setMovieId(self,movieId): self.__movieId = movieId def setMovieTitle(self,movieTitle): self.__movieTitle = movieTitle def setMovieDescription(self,movieDescription): self.__movieDescription = movieDescription def setMovieGenre(self,movieGenre): self.__movieGenre = movieGenre
07ee18617da727499b7640f2d0de7da612bd0f50
kimurakousuke/MeiKaiPython
/chap07/list0701.py
506
3.8125
4
# 读取5个人的分数并输出总分以及平均分 print('计算5个人分数的总分以及平均分。') tensu1 = int(input('第1名分数:')) tensu2 = int(input('第2名分数:')) tensu3 = int(input('第3名分数:')) tensu4 = int(input('第4名分数:')) tensu5 = int(input('第5名分数:')) total = 0 total += tensu1 total += tensu2 total += tensu3 total += tensu4 total += tensu5 print('总分是{}分。'.format(total)) print('平均分是{}分。'.format(total / 5))
6744d0bdb06ba5c605ae6d2c319c228f203bdbf4
Gobika25/py
/paranthesis.py
304
3.703125
4
a=input() c=0 for i in a: if i=='{': c+=1 elif i=='(': c+=1 elif i=='[': c+=1 elif i==']': c-=1 elif i==')': c-=1 elif i=='}': c-=1 if c==0 : print("Balanced") else: print("Un Balanced") i/p:{([])} o/p:Balanced
f17812aa89d3a25f9809dcd866e531c98b5719b8
thuurzz/Python
/curso_em_video/mundo_02/repetições_em_python_(while)/ex061.py
636
4
4
# Exercício Python 51: Desenvolva um programa que leia o # primeiro termo e a razão de uma PA. No final, # mostre os 10 primeiros termos dessa progressão. # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # a1 = int(input('Digite o primeiro termo da PA: ')) r = int(input('Digite a razão da PA: ')) n = 10 # mostra os 10 primeiros elementos ult = a1 + (n - 1) * r ult += 1 print('=' * 30) print('10 PRIMEIROS TERMOS DE UMA PA') print('=' * 30) # com for ''' for i in range(a1, ult, r): print(i, end='=> ') ''' # com while i = 0 while i < n: an = a1 + (i * r) print(an, end='=> ') i += 1 print('FIM')
92c94da6496e53a8b3cfe9a1a1c1fe319208b8e3
allankeiiti/Python_Studying
/CursoDePythonUdemy_DiegoMendes/Exercicios/Exercicios_O_Arquivo/Exercicio_O2.py
464
3.671875
4
carro = str(input('Digite o nome de um carro | Digite nada para parar: ')) arq = open('carros.txt','w') if carro != "": arq.write(carro+'\n') while carro != "": carro = str(input('Digite o nome de um carro | Digite nada para parar: ')) arq.write(carro + '\n') arq.close() #Realizando leitura do carros.txt arq = open('carros.txt','r') linha = arq.readline() print(linha) while len(linha) > 0: linha = arq.readline() print(linha)
6a91e093619795ccde23a4cfe8dc487a2e23b3fa
Haut-Stone/study_Python
/base_test/my_json.py
798
3.796875
4
# -*- coding: utf-8 -*- # @Author: Haut-Stone # @Date: 2017-07-05 18:21:08 # @Last Modified by: Haut-Stone # @Last Modified time: 2017-07-05 20:59:34 import json # 读写json文件 numbers = [2,3,5,7,11,13] filename = 'numbers.json' with open(filename, 'w') as f_obj: json.dump(numbers, f_obj) tests = [] filename = 'numbers.json' with open(filename, 'r') as f_obj: tests = json.load(f_obj) print(tests) # test def greet_user(): filename = 'username.json' try: with open(filename) as f_obj: username = json.load(f_obj) except IOError: username = input("What is yor name? ") with open(filename, 'w') as f_obj: json.dump(username, f_obj) print("We'll remember you when you come back, " + username + "!") else: print("Welcome back, " + username + "!") greet_user()
b86acf81921914ef59936210ab0c1ece1324a666
Vitmambro/Python9
/Exercicios/ex013.py
178
3.546875
4
salario = float(input('Salario do funcionario: ')) aum = salario + (salario * 15 / 100) print('O salario era R${:.2f}, com aumento de 15% ficaria R${:.2f}'.format(salario, aum))
b0bca9757d93155e8fd404a2901aa253bdb0e1e5
AdamBrauns/CompletePythonUdemyCourse
/section_13/generator.py
1,756
4.5625
5
''' Generators allow us to generate a sequence of values over time The main difference in syntax will be the use of a yield statement The advantage is that instead of having to compute an entire series of values up front, the generator computes one value, waits until the next value is called for An example is the range() function: - It just keeps track of the last number and the step size to provide a flow of numbers ''' # Without generators, we have to store the item in memory def create_cubes(n): result = [] for x in range(n): result.append(x ** 3) return result print(create_cubes(10)) for x in create_cubes(10): print(x) print() # With generators, we do not have to store the entire list def create_cubes_gen(n): for x in range(n): yield x ** 3 print(create_cubes_gen(10)) for x in create_cubes_gen(10): print(x) print() # Fibonacci series generator def gen_fib(n): a = 1 b = 1 for _ in range(n): yield a a, b = b, a + b for number in gen_fib(10): print(number) print() # Example with the next iterator def simple_gen(): for x in range(3): yield x for number in simple_gen(): print(number) g = simple_gen() print(g) print(next(g)) print(next(g)) print(next(g)) # This will throw a StopIteration error because it doesn't have another one # The for loop already catching this exception # print(next(g)) print() # String iteration example s = 'hello' for letter in s: print(letter) print() # This will fail because you can't use next with string by default # next(s) # Make it iterable by using the iter() function s_iter = iter(s) print(next(s_iter)) print(next(s_iter)) print(next(s_iter)) print(next(s_iter)) print(next(s_iter))
939dfc7402d80f7dfef028715de0f6febc07bcf4
apterek/python_lesson_TMS
/lesson_09/solution_home_02.py
414
3.96875
4
from solution_home_01 import Car def main(): new_car = Car('Mercedes', 'E500', 2000, 0) if new_car.speed < 100: while new_car.speed < 100: new_car.speed_up() elif new_car.speed > 100: while new_car.speed > 100: new_car.speed_down() return print(f'the car accelerated to {new_car.speed} km per hour') if __name__ == "__main__": main()
6695598c3c7529b6c4034e51b8190216c01d3bcb
RookieZhang/LearnPython
/print.py
197
3.90625
4
print "Hello, welcome to Python world" print "hello" + "Python" #without any space between the two string str1 = "Python" print "hello" + str1 #even if with a variable there is still no space
01e1daa27d67c71e868a1feecfd28643421c2ac6
Parth731/Python-Tutorial
/Durga Software/Datatype/5_str_datatype.py
283
3.796875
4
''' char datatype is not available long data type available in python2 but not in python3 ''' s1 = "durga soft" print(s1) s1 = 'durga soft' print(s1) s1 = '''durga soft''' print(s1) print(s1[0]) print(s1[1]) print(s1[-1]) print(s1[1:40]) print(s1[1:]) print(s1[:4]) print(s1[:])
d71b006c9d2428ef8e2b82dbc35e7e92a30798f4
speyermr/primes
/primes/v5_sieve.py
865
3.71875
4
# Fastest: The Sieve of Eratosthenes # # https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes # # Invented around 2200 years ago! # def upto(limit): # Fill our sieve with "True", meaning a number at index=N will be prime if # sieve[n] == True. sieve = [True] * limit # 0 and 1 are not prime, so poke those holes in the sieve right away. sieve[0] = False sieve[1] = False for number, is_prime in enumerate(sieve): if is_prime: # (1) This number is prime, so yielded it: yield number # (2) All integer multiples of this number in the sieve (2n, 3n, # 4n, etc.) will not be prime, because of course they will be # divisible by n. So poke holes for 2n, 3n, 4n, etc. onwards!: for mul in range(2 * number, limit, number): sieve[mul] = False
8a8acda9971f4a899bb67dcba701a1027c878ffe
Aakancha/Python-Workshop
/Jan13/Classwork/Classwork.py
1,287
3.546875
4
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 22:20:52) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> print('hello world!') hello world! >>> print('hello'*10) hellohellohellohellohellohellohellohellohellohello >>> name= input('enter your name:') enter your name:Aakancha >>> age= input('enter your age:') enter your age:print('your name is' + name + "and age is" + age) >>> print('your name is {} and age is {}'.format(name,age)) your name is Aakancha and age is print('your name is' + name + "and age is" + age) >>> import keyword >>> print(keyword.kwlist) ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] >>> a= input('enter the age') enter the age18 >>> int (a) 18 >>> print(bool(x)) Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> print(bool(x)) NameError: name 'x' is not defined >>> x= True >>> print(bool(x)) True >>> x= 3 >>> y=4 >>> print(x/y) 0.75 >>> print(x//y) 0 >>> print(x%y) 3 >>>
365d5c1b57e9bc68c883f390361956483d3be7dd
jhidding/talk-python-typing
/examples/generic.py
379
3.5
4
# ~\~ language=Python filename=examples/generic.py # ~\~ begin <<README.md|examples/generic.py>>[0] from typing import (Iterable) def word_lengths(words: Iterable[str]) -> Iterable[int]: return (len(w) for w in words) words = "The quick brown fox jumps over the lazy dog".split() print(word_lengths(words)) print(word_lengths(w.upper() for w in words)) # passes # ~\~ end
6bdb3ada958c92f5acaf77d2a499b8ab462268e3
CrouzetC/Mon_GitHub_Public
/Python/Misc/Jeu_de_bataille.py
2,923
3.53125
4
import random as rnd ### def melange(L) : N = len(L) for i in range(N-1) : echange = rnd.randint(i,N-1) tmp = L[i] L[i] = L[echange] L[echange] = tmp ### ### deck1 = [] for couleur in [" <3", " <>", " -8o", " -8>"] : deck1.append("AS"+couleur) deck1.append("Roi"+couleur) deck1.append("Dame"+couleur) deck1.append("Valet"+couleur) for num in range(2,11,1) : deck1.append(str(num)+couleur) melange(deck1) deck2 = deck1[26:] deck1 = deck1[:26] ### print("Appuyez sur Entrée pour jouer une carte") print("(saisir exit pour abandonner)") print() pile1 = [] pile2 = [] fin = False while fin == False: if input()=="exit" : fin = True print("vous avez abandonné (appuyer sur Entrée pour quitter)") input() else : print("Vous jouez :") print(" "+deck1[0]) print("L'adversaire joue :") print(" "+deck2[0]) print() # On vérifie qui a gagné la manche cartes = [deck1[0][0], deck2[0][0]] for i in [0,1] : if cartes[i]=="V": cartes[i] = 11 elif cartes[i]=="D": cartes[i] = 12 elif cartes[i]=="R": cartes[i] = 13 elif cartes[i]=="A": cartes[i] = 14 else : cartes[i] = int(cartes[i]) if cartes[0] > cartes[1] : victoire = 1 # ce n'est pas un compteur de victoires, juste une variable temporaire defaite = 0 elif cartes[0] < cartes[1] : victoire = 0 defaite = 1 else : victoire = 0 defaite = 0 # on modifie les decks et piles(=défausses) en conséquences pile1 = pile1 + deck1[0:1-defaite] + deck2[0:victoire] # c'est un peu tordu ici, mais ça marche pile2 = pile2 + deck2[0:1-victoire] + deck1[0:defaite] deck1 = deck1[1:] # fonctionne même s'il ne reste qu'un seul élément deck2 = deck2[1:] # on traite le cas où un(des) deck(s) est(sont) vide(s) : if len(deck1) == 0 : if len(pile1) == 0 : fin = True print("Vous avez perdu ! (saisir Entrée pour quitter)") input() deck1 = pile1[:] melange(deck1) pile1 = [] print("Vous mélangez votre défausse et la récupérez !") input() if len(deck2) == 0 : if len(pile2) == 0 : fin = True print("Vous avez gagné ! (saisir Entrée pour quitter)") input() deck2 = pile2[:] melange(deck2) pile2 = [] print("Votre adversaire mélange sa défausse et la récupère !") input() print("Vous : "+str(len(deck1)+len(pile1))+" cartes ; adversaire : "+str(len(deck2)+len(pile2))+" cartes.") print()
3b798711863796cf974928626d02cf45d9246402
hktamzid/Python-Mosh
/numerical.py
92
3.546875
4
a = 2 b = 4 print(a+b) print(a-b) print(a*b) print(a/b) print(a//b) print(a**b) print(3**3)
32fcfb37f061fbdadcae67e620a0d5d2b1ed41cd
michelmedeiros/udacity-python
/aula_procedures.py
573
3.8125
4
#Soma de dois numeros def sum(a, b): a = a+ b return a a =5 b = 2 print(sum(a,b)) print (a) a = sum(a,b) print(a) #Quiz 1 - Calculo de um quadrado def square(a): b = a*a return b print(square(5)) # Define a procedure, abbaize, that takes # two strings as its inputs, and returns # a string that is the first input, # followed by two repetitions of the second input, # followed by the first input. def abbaize(a, b) : s1 = a + b s2 = b + a return s1 + s2 print (abbaize('a','b')) #>>> 'abba' print (abbaize('dog','cat')) #>>> 'dogcatcatdog'
abadd7d589958ac07f0e66c973961d8326edc489
jfalkowska/pyladies-start
/Day_1/Task4.py
514
3.671875
4
import math r = float(input('Podaj promień podstawy w centymetrach ')) l = float(input('Podaj tworzącą stożka w centymetrach ')) h = float(input('Podaj wysokość stożka w centymatrach ')) pole_podstawy = math.pi * r ** 2 pole_powierzchni_bocznej = math.pi * r * l objetosc = 1/3 * math.pi * r ** 2 * h print() print('Pole podstawy stożka wynosi ' + str(pole_podstawy)) print('Pole powierzchni bocznej bocznej wynosi ' + str(pole_powierzchni_bocznej)) print('Objętość stożka wynosi ' + str(objetosc))
14b267de0c16bacb7f82055fc7273f9492e2ce47
rpnpackers/database
/database.py
3,148
4.125
4
import csv import sqlite3 import sys import inp import db def main(): # While loop so that multiple operations can be performed. while True: # Gets input from the user about what they want to do options = ["j", "m", "o", "q"] text = ["Import Jobs", "Import Montly Data", "Import Original Data", "Quit"] choice = inp.user_choice(options, text) # Runs the specific methods for each operation if choice == "j": jobs() elif choice == "m": monthly() elif choice == "o": original() elif choice == "q": break else: print ("Input error, review code") break # Method for importing jobs def jobs(): import os # Gets the file name from the user while True: a = input("Csv File Path: ") try: t = open(a, 'r') except IOError: print("File not found, type exact path.\nExample: import_files\\file.csv") else: break # Establish a connection to the database while True: a = input("Database File Path: ") # Check that the file exists if os.path.isfile(a): break else: print("File must exist, check spelling") conn = sqlite3.connect(a) c = conn.cursor() # Read the csv into a dictionary names = csv.DictReader(t) # Get names of the column titles print("Input the title names from the csv file.\nBe sure to omit all spaces") print ("Use ID column then Name column.") titles = db.column_name(2, names) # Iterate through each row of the system. for row in names: # Search the Database for jobs with the samvae first word or id x = [row[titles[0]], row[titles[1]]] database = db.check_similar(x, a) # prompt user to change if database != None: print("Are these two projects the same?") print(f"Database: {database}") print(f"CSV: {row[titles[1]]} {row[titles[0]]}") # Ask user to verify if they're the same project options = ["y", "n"] print("Yes for the same, and No for different") if inp.user_choice(options) == "y": # if yes, offer to modify entry if inp.user_choice(["d", "c"], ["Database", "Csv"]) == "d": continue else: # Change Name in Database usint tid databases[0][2] c.execute("""UPDATE projects SET name = ?, id = ? WHERE tid ==?;""", (row[titles[1]], row[titles[0]], database[2])) else: c.execute("INSERT INTO projects (name, id) VALUES (?, ?);", (row[titles[1]], row[titles[0]])) # Save and close t.close() conn.commit() conn.close() # Method for importing monthly data def monthly(): print("Added monthly data!!!\n\n") # Method for importing data from the original file def original(): print("Added data from original!!!\n\n") jobs()
362d2aa8f3bbaf538b7c1bb7a6442c7d245c669d
ElAntagonista/progress-devops
/Lectures/Python-Intro/python_basics_4.py
380
3.828125
4
""" File I/O Using python for File I/O is a relatievly straight-forward """ # Write to file # Let's make simple list groceries = ["beer", "pasta", "bread"] with open("sample.txt", 'w+') as file_: for item in groceries: file_.writelines(item + "\n") # Read from a file with open("sample.txt", 'r') as file_: for line in file_.readlines(): print(line)
49eaa6eb95e0b4f0e3cd44a0cd16e5e37f478c99
nyhyang/Info206-Python
/HW3_Binary/hw3_starter_pack/hw3test.py
500
3.5
4
#--------------------------------------------------------- # Nancy Yang # [email protected] # Homework #3 # September 20, 2016 # hw3test.py # Test #--------------------------------------------------------- from BST import * from hw3 import * T = BSTree() T.add("4") T.add("2") T.add("3") T.add("5") T.add("1") T.add("6") T.in_order_print() T.add("hello") T.add("goodbye") T.add("paul") T.add("summer") T.add("paul") T.add("goodbye") print(T.find("hello")) print(T.size()) print(T.height()) T.in_order_print()
7e30b00c505084c53c236b1133dc10fd845d2234
a31415926/geekhub
/HT_4/2.py
1,532
3.984375
4
"""Створіть функцію для валідації пари ім'я/пароль за наступними правилами: - ім'я повинно бути не меншим за 3 символа і не більшим за 50; - пароль повинен бути не меншим за 8 символів і повинен мати хоча б одну цифру; - щось своє :) Якщо якийсь із параментів не відповідає вимогам - породити виключення із відповідним текстом.""" class UserValidation(Exception): pass def check_username_pass(username, password): if len(username) < 3 or len(username) > 50: raise UserValidation('Длина логина должна быть от 3 до 50-ти символов') #проверка на наличие цифры elif not list(i for i in password if i.isdigit()): raise UserValidation('Пароль должен содержать хотя бы одну цифру') elif len(password) < 8: raise UserValidation('Пароль должен быть не менее 8-ми символов') elif username == password: raise UserValidation('Логин и пароль не должны совпадать') else: return True print(check_username_pass('wwq', 'qwedsdsd23')) #print(check_username_pass('loginpass12', 'loginpass12')) #print(check_username_pass('lo', 'loginpass12')) #print(check_username_pass('log', 'loginpass'))
47d8e447b710866ab457a6bfe88305950c2cffa8
jaychsu/algorithm
/lintcode/450_reverse_nodes_in_k_group.py
1,155
3.640625
4
""" Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None """ class Solution: """ @param: head: a ListNode @param: k: An integer @return: a ListNode """ def reverseKGroup(self, head, k): if not head: return dummy = ListNode(0) dummy.next = head head = dummy while head: head = self.reverse_next_kth(head, k) return dummy.next def find_kth(self, head, k): for i in range(k): if not head: return head = head.next return head def reverse(self, head): pre = nxt = None while head: nxt = head.next head.next = pre pre = head head = nxt return pre def reverse_next_kth(self, head, k): nk = self.find_kth(head, k) if not nk: return nk_nxt = nk.next n1_pre = head n1 = head.next nk.next = None self.reverse(n1) n1_pre.next = nk n1.next = nk_nxt return n1
1935a55d7baa0c6323c1b21d823c1dac54f0342b
Murali1125/Fellowship_programs
/DataStructurePrograms/calender_weakday_obj.py
2,429
4.25
4
"""----------------------------------------------------------------------------- -->Create the Week Object having a list of WeekDay objects each storing the day --(i.e S,M,T,W,Th,..) and the Date (1,2,3..) . The WeekDay objects are stored in --a Queue implemented using Linked List. Further maintain also a Week Object in --a Queue to finally display the Calendar ----------------------------------------------------------------------------""" from Fellowship_programs.DataStructurePrograms.Calender import calender from Fellowship_programs.DataStructurePrograms.Queue import Queue class Node: def __init__(self,day,date): self.day = day self.date = date self.next = None class weak: # creating head variable and initialize as none def __init__(self): self.head = None #creating the weak day objects def add(self,day,date): # creating node for day objects node = Node(day,date) node.day = day node.date = date # if the head is none means it starting day of the weak, assign the node to head if self.head == None: self.head = node # else traverse to the end of the list and add the node at end else: n = self.head while n.next != None: n = n.next n.next = node # function for print the weak def show(self): # Traversing from head to end and Printing the elements sh = self.head while sh.next != None: print(sh.date, end=" ") sh = sh.next print(sh.date) # function for getting day and dates def weak(self,dates): # creating a list of days with keys days = {1: "Sunday", 2: "Monday", 3: "Tuesday", 4: "Wednesday", 5: "Thursday", 6: "Friday", 7: "Saturday"} # declaring an iterator count count = 1 for i in dates: weak.add(self,days[count],i) count+=1 #---------------------------------------------------- # Driver program # creating an object for Queue class que = Queue() # getting inputs from user year = int(input("year = ")) month = int(input("month = ")) # creating an object for calender to get the dates cal = calender() dates = cal.month(year,month) # creating weak objects for i in dates: w = weak() w.weak(i) # adding the weak objects in to queue que.enqueue(w.show())
b7d767c0e2865ae21696af7454f37b089868daf2
lr154lrose/Project-Euler
/python solutions/problem_18.py
1,573
3.984375
4
# Program finding the path with the biggest sum in a triangle. It works by # starting at the top of the triangle and moving to adjacent numbers of the # row below. def maximum_sum(matrix): M = len(matrix) for i in range( M - 2, -1, -1 ): # from the penultimate row until the first one, at position 0 for j in range(len(matrix[i]) - 1): matrix[i][j] = int(matrix[i][j]) + max( int(matrix[i + 1][j]), int(matrix[i + 1][j + 1]) ) # adding the biggest number matrix.remove(matrix[i + 1]) return matrix[0][0] def triangle_to_regular_matrix(triangle): for row in triangle: while len(row) != len(triangle[-1]): row.append(0) return triangle if __name__ == "__main__": triangle = """ 75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40 31 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23""" triangle = triangle.replace(" ", "").splitlines() matrix = [row.split(" ") for row in triangle] result = triangle_to_regular_matrix(matrix) print(maximum_sum(result))
d2d18f1ec3e4aedcddeb229df9e8e535b5fe066b
ank26it/python_biginner
/CSV/CSVModule.py
1,289
3.609375
4
import csv import os os.chdir('/Users/User/Desktop/hi/CSV') # # Read CSV file: # with open('names.csv', 'r') as csv_file: # csv_reader = csv.reader(csv_file) # next(csv_reader) # for line in csv_reader: # print(line[2]) # # Write new CSV file: # with open('names.csv', 'r') as csv_file: # csv_reader = csv.reader(csv_file) # with open('new_names.csv', 'w') as new_file: # csv_writer = csv.writer(new_file, delimiter='\t') # for line in csv_reader: # #print(line) # csv_writer.writerow(line) # # Write new CSV file2: # if you have new csv file with blank lines this is for you # # Python 2: # with open('new_names.csv', 'wb') as outfile: # writer = csv.writer(outfile) # # Python 3: # with open('new_names.csv', 'w', newline='') as outfile: # writer = csv.writer(outfile) with open('names.csv', 'r') as csv_file: csv_reader = csv.DictReader(csv_file) with open('new_names.csv', 'w', newline='') as new_file: fieldnames = ['first_name', 'last_name'] csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames, delimiter='\t') csv_writer.writeheader() for line in csv_reader: del line['email'] print(line) csv_writer.writerow(line)
60a06c78595e4c57632e8ccb7b50ae812703b0c4
GloriaAnholt/PythonProjects
/Algorithms-DataStructures/test_BinaryTreeClass.py
2,356
3.921875
4
# Algorithms and Data Structures: Quick Sort # 07.20.2016 # @totallygloria import unittest from BinaryTreeClass import BinaryTree class BinaryTreeTester(unittest.TestCase): def test_BinaryTree(self): # Check if you can make a new node of different types, or change types t1 = BinaryTree("maple") self.assertEquals(t1.key, "maple") t1.key = "oak" self.assertEquals(t1.key, "oak") t1.key = 0 self.assertEquals(t1.key, 0) t1.key = [1, 2, 3] self.assertEquals(t1.key, [1, 2, 3]) t2 = BinaryTree(0) self.assertEquals(t2.key, 0) t3 = BinaryTree([]) self.assertEquals(t3.key, []) # Check that you can set the nodes t1.lc = "left leaf" t1.rc = "right leaf" self.assertEquals(t1.lc, "left leaf") self.assertEquals(t1.rc, "right leaf") def test_insert_left(self): t1 = BinaryTree("redwood") t1.insert_left("left branch") self.assertEquals(t1.lc.key, "left branch") t1.insert_left("new branch") self.assertEquals(t1.lc.key, "new branch") self.assertEquals(t1.lc.lc.key, "left branch") def test_insert_right(self): t1 = BinaryTree("cypress") t1.insert_right("right branch") self.assertEquals(t1.rc.key, "right branch") t1.insert_right("new branch") self.assertEquals(t1.rc.key, "new branch") self.assertEquals(t1.rc.rc.key, "right branch") def test_set_root(self): t1 = BinaryTree("cedar") t1.key = "oak" self.assertEquals(t1.key, "oak") t1.set_root("maple") self.assertEquals(t1.key, "maple") t1.set_root(100) self.assertEquals(t1.key, 100) def test_get(self): t1 = BinaryTree("pine") t1.insert_right("right branch") t1.insert_left("left branch") self.assertEquals(t1.get_rc(), "right branch") self.assertEquals(t1.get_lc(), "left branch") self.assertEquals(t1.get_root(), "pine") t1.insert_right("right stick") t1.insert_left("left stick") t1.set_root("hemlock") self.assertEquals(t1.get_rc(), "right stick") self.assertEquals(t1.get_lc(), "left stick") self.assertEquals(t1.get_root(), "hemlock") if __name__ == '__main__': unittest.main()
9254499cea5fcdaa4a6872741b1b0e38601caa9e
Jugveer-Sandher/PythonProjects
/Dictionaries/main.py
3,867
3.84375
4
import utilities_set import utilities_dict def main(): """ Main Program """ # PART A set1 = {'apple', 'banana', 'orange', 'peach'} set2 = {'banana', 'pineapple', 'peach', 'watermelon'} set1_count = utilities_set.get_total_items(set1) print("The total number of items in set1 is:", set1_count) print() print("Displaying the items of the set1:") utilities_set.display_all_items(set1) print() utilities_set.add_item("grape", set1) print("Added a grape, new set items are: ") utilities_set.display_all_items(set1) print() utilities_set.remove_item("orange", set1) print("Removed orange, new set items are: ") utilities_set.display_all_items(set1) print() set3 = utilities_set.get_the_union_of(set1, set2) print("The union of set1 and set2 is: ") utilities_set.display_all_items(set3) print() # # PART B provinces = {"alberta": "edmonton", "ontario": "toronto", "quebec": "quebec city", "nova scotia": "halifax", "new brunswick": "fredericton", "manitoba": "winnipeg", "prince edward island": "charlottetown", "saskatchewan": "regina", "newfoundland and labrador": "st. john's", "yukon": "whitehorse", "nunavut": "iqaluit", "northwest territories": "yellowknife", "british columbia": "victoria"} print("The current dictionary contains: ") utilities_dict.display_all(provinces) print() print("The capital for Yukon is:", utilities_dict.get_capital_city("yukon", provinces)) print() print("removing Manitoba from list: ") utilities_dict.remove_province("manitoba", provinces) utilities_dict.display_all(provinces) print() print("Adding Manitoba back: ") utilities_dict.add_province("manitoba", "winnipeg", provinces, ) utilities_dict.display_all(provinces) print() # PART C canada = { "alberta": {"capital": "edmonton", "largest": "calgary", "population": 3645257}, "ontario": {"capital": "toronto", "largest": "toronto", "population": 12851821}, "quebec": {"capital": "quebec city", "largest": "montreal", "population": 7903001}, "nova scotia": {"capital": "halifax", "largest": "halifax", "population": 921727}, "new brunswick": {"capital": "fredericton", "largest": "saint john", "population": 751171}, "manitoba": {"capital": "winnipeg", "largest": "winnipeg", "population": 1208268}, "prince edward island": {"capital": "charlottetown", "largest": "charlottetown", "population": 140204}, "saskatchewan": {"capital": "regina", "largest": "saskatoon", "population": 1033381}, "newfoundland and labrador": {"capital": "st. john's", "largest": "st. john's", "population": 514536}, "yukon": {"capital": "whitehorse", "largest": "whitehorse", "population": 33897}, "nunavut": {"capital": "iqaluit", "largest": "iqaluit", "population": 31906}, "northwest territories": {"capital": "yellowknife", "largest": "yellowknife", "population": 41462}, "british columbia": {"capital": "victoria", "largest": "vancouver", "population": 4400057} } print("The total population of the provinces are:", utilities_dict.get_total_population(canada)) print() print("The smallest province is:", utilities_dict.get_smallest_province(canada)) print() print("The largest province is:", utilities_dict.get_largest_province(canada)) print() print("The capital of Yukon is:", utilities_dict.get_another_capital_city ("yukon", canada)) print() print("The largest city of Quebec is:", utilities_dict.get_largest_city("quebec", canada)) if __name__ == '__main__': main()
26c9c4342e83cd84a233052dc541ccda80ce2a6a
andrefalken/CV_Python
/08 - Utilizando módulos/desafio017.py
604
4.1875
4
# Desafio 017 # Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo e # calcule e mostre o comprimento da hipotenusa # Importando toda a biblioteca de matemática import math # Declarando a variável para receber o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo a = float(input('Digite o comprimento do cateto oposto: ')) b = float(input('Digite o comprimento do cateto adjacente: ')) # Calculando e imprimindo o comprimento da hipotenusa print(f'O comprimento da hipotenusa é igual a {math.hypot(a, b):.2f}.')
86594b2d4267e79d699f872711a742b1aecea526
igarciru/per19ejerciciofiguras1
/Ejercicio_figuras.py
1,073
3.546875
4
class figura: def __init__(self): pass def dame_area(self): return print("Esta figura no tiene area") def dame_perimetro(self): return print("Esta figura no tiene perímetro") class cuadrado(figura): def __init__(self,lado): self.lado=lado super().__init__() def dame_perimetro(self): perimetro = 4 * self.lado return perimetro def dame_area(self): area = self.lado**2 return area class rectangulo(figura): def __init__(self,largo,ancho): self.largo=largo self.ancho=ancho super().__init__() def dame_area: area=self.largo*self.ancho return area def dame_perimetro: perimetro=2*self.largo+2*self.ancho return perimetro class circulo(figura): def __init__(self,radio): self.radio=radio super().__init__() def dame_area(self): area=math.pi*(self.radio**2) return area def dame_perimetro(self): perimetro=2*math.pi*self.radio return perimetro
b63a4228151fd96a622524c2afab2da4194bab39
djbrown31/webscraper
/Week_Two_Challenges/linked-list-sum.py
1,190
3.859375
4
class Node: def __init__(self, value, next): self.value = value self.next = next def linked_list_sum_iterative(list1, list2): res = Node() p1 = list1 p2 = list2 curr = res carry = 0 while p1 is not None or p2 in not None or carry != 0: sum = carry if p1: sum += p1.value p1 = p1.next if p2: sum += p2.value p2 = p2.next curr.value = sum % 10 carry = sum // 10 if p1 is not None or p2 is not None carry != 0: curr.next = Node() curr = curr.next return res def linked_list_sum(list1, list2, carry=0): if list1 is None and list2 is None and carry == 0: return None next1 = None next2 = None sum = carry if list1: sum += list1.value next1 = list1.next if list2: sum += list2.value next1 = list2.next return Node(sum % 10, linked_list_sum(next1, next2, sum // 10))
759929f2a09dd4e71e4934c64f00a66015d079b9
pmaywad/DataStructure-Algo
/Trees/BinayTree/level_order_insertion.py
1,077
3.875
4
""" Insertion in binary tree in level order in Python """ from queue import Queue class Node: def __init__(self, key): self.data = key self.left = None self.right = None def inorder(root): if not root: return None inorder(root.left) print(root.data, end=' ') inorder(root.right) def insert(root, key): if not root: return queue = Queue() temp = root while temp: if not temp.left: temp.left = Node(key) break else: queue.put(temp.left) if not temp.right: temp.right = Node(key) break else: queue.put(temp.right) temp = queue.get() if __name__=='__main__': root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) print("Inorder before insertion", end=' ') inorder(root) insert(root, 7) print() print("Inorder after insertion", end=' ') inorder(root)
1ed8501fb777b0591909c8fb810f525a63a2a06d
krithika-srinivasan/data-structures-and-algorithms
/linked lists/concatenation.py
1,434
4.09375
4
class LinkedList: class _Node: __slots__ = '_element', '_next' def __init__(self, element, next): self._element = element self._next = next def __init__(self): self._head = self._Node(None, None) self._tail = self._Node(None, None) self._size = 0 def is_empty(self): return self._size == 0 def add_to_list(self, e): newnode = self._Node(e, None) if self.is_empty(): self._head = newnode else: self._tail._next = newnode self._tail = newnode self._size += 1 def head(self): return self._head def print(self): elements = [] node = self._head while node is not None: elements.append(node._element) node = node._next print(elements) def concatenate(head1, head2): newlist = LinkedList() node = head1 while node is not None: newlist.add_to_list(node._element) node = node._next node = head2 while node is not None: newlist.add_to_list(node._element) node = node._next return newlist l1 = LinkedList() l2 = LinkedList() l1.add_to_list(1) l1.add_to_list(2) l1.add_to_list(3) l2.add_to_list(4) l2.add_to_list(5) l2.add_to_list(6) conlist = concatenate(l1.head(), l2.head()) conlist.print()
f43b17d7347cb4e1ea8f1b69cb0e561e4e621b6d
iadel93/MachineLearning
/KNN/KNN_sklrn_2.py
1,671
3.796875
4
# this is a more advanced implementation of KNN using Numpy # import neccesary libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import LabelEncoder from sklearn.utils import shuffle from sklearn.model_selection import train_test_split #import dataset data = pd.read_csv('iris.csv') #print the species / target labels print(data['species'].unique()) # Encode the labels into numbers so we be able to use into the algorithm le = LabelEncoder() data['species'] = le.fit_transform(data['species']) print(data['species'].unique()) #printing the correlation between the data feaures print(data.corr()) # plot the data to the target plt.scatter(data['petal_length'],data['petal_width'],c=data['species']) plt.show() # Split the data into features and targets x= np.array(data) x= x[:,:4] y = np.c_[data['species']] x_trn,x_tst,y_trn,y_tst = train_test_split(x,y,test_size = 0.2) # import the sklearn KNN class from sklearn.neighbors import KNeighborsClassifier accl =[] # start the training algoritgh for different number of K neighbors 1 to 10 for k in range(1,10): # initialise the classifier classifier = KNeighborsClassifier(n_neighbors=k) # training on data classifier.fit(x_trn,y_trn.reshape(-1,)) true = 0 r=0 # start calculating the accurace for each number of K for sample in x_tst: result = classifier.predict(sample.reshape(1,-1)) if result == y_tst[r]: true +=1 r+=1 print("Accuracy = ", true) accl.append(true) # plot the accuracy resulted from each K number of neighbors plt.plot(range(1,10),accl) plt.show()
e04becb568fb432004b232b2763beace27b1cd2f
xiaole0310/leetcode
/352. Data Stream as Disjoint Intervals/Python/Solution.py
2,456
3.765625
4
# Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class SummaryRanges(object): def __init__(self): """ Initialize your data structure here. """ self.intervals = [] def addNum(self, val): """ :type val: int :rtype: void """ intervals = self.intervals if not intervals: intervals.append(Interval(val, val)) else: low = 0 high = len(intervals) - 1 while low < high: mid = (low + high) // 2 if intervals[mid].start <= val and intervals[mid].end >= val: return if intervals[mid].start > val: high = mid else: low = mid + 1 current_interval = intervals[low] left_neighbor = intervals[low - 1] if low > 0 else None if current_interval.start <= val and val <= current_interval.end: return elif val < current_interval.start: if not left_neighbor: if current_interval.start == val + 1: current_interval.start = val else: intervals.insert(0, Interval(val, val)) else: if left_neighbor.end + 1 == current_interval.start - 1: left_neighbor.end = current_interval.end intervals.remove(current_interval) else: if left_neighbor.end + 1 == val: left_neighbor.end = val else: if current_interval.start == val + 1: current_interval.start = val else: intervals.insert(low, Interval(val, val)) else: if current_interval.end + 1 == val: current_interval.end = val else: intervals.append(Interval(val, val)) def getIntervals(self): """ :rtype: List[Interval] """ return self.intervals # Your SummaryRanges object will be instantiated and called as such: # obj = SummaryRanges() # obj.addNum(val) # param_2 = obj.getIntervals()
b89ac1d8e0c302bdf36b13d02b96b6d816de1c63
mafdezmoreno/HackerRank_Callenges
/Practice/ProblemSolving/QueueUsingTwoStacks.py
1,179
4.34375
4
#https://www.hackerrank.com/challenges/queue-using-two-stacks/problem ''' A basic queue has the following operations: Enqueue: add a new element to the end of the queue. Dequeue: remove the element from the front of the queue and return it. In this challenge, you must first implement a queue using two stacks. Then process queries, where each query is one of the following types: 1 x: Enqueue element into the end of the queue. 2: Dequeue the element at the front of the queue. 3: Print the element at the front of the queue. ''' from collections import deque import os if __name__ == '__main__': q = deque() #with open('QueueUsingTwoStacks_Test.txt') as file: with open('QueueUsingTwoStacks_Test.txt') as file: #n_queries = int(input()) n_queries = int(next(file)) for _ in range(n_queries): #temp = input().split() temp = next(file).split() if temp[0] == "1": q.append(temp[1]) elif temp[0] == "2": q.popleft() elif temp[0] == "3": if len(q[0])>0: print(q[0]) #file.write(q[0] + '\n')
7bfe6b6a5e440120022e8e0486072cebd3d4d33e
ShehrozeEhsan086/ICT
/Exercise/Calculator.py
1,227
4.46875
4
# Basic Calculator with 2 or 3 operands (INCOMPLETE) operands = input("Enter the numbers of operands you want to use(2 OR 3): ") print("Use + , - , x , / when asked for which operation to perform") if(operands=="2"): num1,num2= eval(input("Enters numbers seperated by ',' : ")) operation = input("Enter which operation you want to perform: ") if(operation=="+"): answer=num1+num2 else: pass if(operation=="-"): answer=num1-num2 else: pass if(operation=="x"): answer=num1*num2 else: pass if(operation=="/"): answer=num1/num2 else: pass else: pass if(operands=="3"): num1,num2,num3= eval(input("Enters numbers seperated by ',' : ")) operation = input("Enter which operation you want to perform: ") if(operation=="+"): answer=num1+num2+num3 else: pass if(operation=="-"): answer=num1-num2-num3 else: pass if(operation=="x"): answer=(num1*num2*num3) else: pass if(operation=="/"): answer=num1/num2/num3 else: pass else: pass print(f"Answer = {answer}") # end of program
15291112e4d78facf787445583d1bec1fe535fa3
AZICO/lambdata-azico
/lambdata_azico2/helper_functions.py
1,064
3.75
4
def null_count(df): return df.isnull().sum().sum() # Split addresses into three columns (df['city'], df['state'], and df['zip']) # def addy_split(add_series): # df[len_str] = df['owner city state zip'].str.split(',').apply(len) # df['num_commas'] = df['Owner City State Zip'].str.count(',') # return df # Return a new column with the full name from # a State abbreviation column -> An input of FL would return Florida def add_state_names_column(my_df): ''' add a column of corrsponding state names to a dataframe' Pramas (my_df) a DataFrame with a column called "abbrev" that has state abbrevations Return a copy of the original dataframe,but with an extra column. ''' new_df = my_df.copy() states = {"CA": "California", "CO": "Cplorado", "CT": "Conn"} new_df["st_name"] = new_df["abbrev"].map(states) breakpoint() return my_df if __name__ == "__main__": df = DataFrame({"abrev": ["CA", "CO", "CT", "DC", "TX"]}) print(df.head()) add_state_names_column(my_df) print(df.head())
c191eb28cb62febcbb39d878bf786d4f5fc90888
oknono/Project_Euler
/Problem01.py
634
4.0625
4
# Update using PDF from Euler Website 28 September # This works with larger numbers as well! # Two importan steps: # 1. sum of all numbers divisible by x or y is equal to # ( sum of all numbers divisible by x + # sum of all numbers divisible by x ) - # sum of all numbers divisible by x * y # 2. The sum of all multiples of x can be rewritten from # - [x, 2x, 3x, 4x, ...] to # - x * [1,2,3,4... floor(target / x) ] import math target = 999 def sum_divisible_by(n): p = math.floor(target / n) # step 2 return n * ((p * (p + 1)) / 2) print(sum_divisible_by(3) + sum_divisible_by(5) - sum_divisible_by(15)) # step 1
b375c7a2d9d5b33986e31a190d6ce7d0d04052db
abriggs914/Coding_Practice
/Python/Codecademy_machine_learning/Tennis Aces/tennis_aces.py
12,835
3.6875
4
# Tennis Ace # Overview # This project is slightly different than others you have encountered thus far on Codecademy. Instead of a step-by-step tutorial, this project contains a series of open-ended requirements which describe the project you’ll be building. There are many possible ways to correctly fulfill all of these requirements, and you should expect to use the internet, Codecademy, and other resources when you encounter a problem that you cannot easily solve. # Project Goals # You will create a linear regression model that predicts the outcome for a tennis player based on their playing habits. By analyzing and modeling the Association of Tennis Professionals (ATP) data, you will determine what it takes to be one of the best tennis players in the world. # Setup Instructions # If you choose to do this project on your computer instead of Codecademy, you can download what you’ll need by clicking the “Download” button below. If you need help setting up your computer, be sure to check out our setup guide. # Tasks # 8/8 Complete # Mark the tasks as complete by checking them off # Prerequisites # 1. # In order to complete this project, you should have completed the Linear Regression and Multiple Linear Regression lessons in the Machine Learning Course. # Project Requirements # 2. # “Game, Set, Match!” # No three words are sweeter to hear as a tennis player than those, which indicate that a player has beaten their opponent. While you can head down to your nearest court and aim to overcome your challenger across the net without much practice, a league of professionals spends day and night, month after month practicing to be among the best in the world. Today you will put your linear regression knowledge to the test to better understand what it takes to be an all-star tennis player. # Provided in tennis_stats.csv is data from the men’s professional tennis league, which is called the ATP (Association of Tennis Professionals). Data from the top 1500 ranked players in the ATP over the span of 2009 to 2017 are provided in file. The statistics recorded for each player in each year include service game (offensive) statistics, return game (defensive) statistics and outcomes. Load the csv into a DataFrame and investigate it to gain familiarity with the data. # Open the hint for more information about each column of the dataset. # Hint # The ATP men’s tennis dataset includes a wide array of tennis statistics, which are described below: # Identifying Data # Player: name of the tennis player # Year: year data was recorded # Service Game Columns (Offensive) # Aces: number of serves by the player where the receiver does not touch the ball # DoubleFaults: number of times player missed both first and second serve attempts # FirstServe: % of first-serve attempts made # FirstServePointsWon: % of first-serve attempt points won by the player # SecondServePointsWon: % of second-serve attempt points won by the player # BreakPointsFaced: number of times where the receiver could have won service game of the player # BreakPointsSaved: % of the time the player was able to stop the receiver from winning service game when they had the chance # ServiceGamesPlayed: total number of games where the player served # ServiceGamesWon: total number of games where the player served and won # TotalServicePointsWon: % of points in games where the player served that they won # Return Game Columns (Defensive) # FirstServeReturnPointsWon: % of opponents first-serve points the player was able to win # SecondServeReturnPointsWon: % of opponents second-serve points the player was able to win # BreakPointsOpportunities: number of times where the player could have won the service game of the opponent # BreakPointsConverted: % of the time the player was able to win their opponent’s service game when they had the chance # ReturnGamesPlayed: total number of games where the player’s opponent served # ReturnGamesWon: total number of games where the player’s opponent served and the player won # ReturnPointsWon: total number of points where the player’s opponent served and the player won # TotalPointsWon: % of points won by the player # Outcomes # Wins: number of matches won in a year # Losses: number of matches lost in a year # Winnings: total winnings in USD($) in a year # Ranking: ranking at the end of year # 3. # Perform exploratory analysis on the data by plotting different features against the different outcomes. What relationships do you find between the features and outcomes? Do any of the features seem to predict the outcomes? # Hint # We utilized matplotlib’s .scatter() method to plot different features against different outcomes. Check out the documentation here for a refresher on how to utilize it. # We found a strong relationship between the BreakPointsOpportunities feature and the Winnings outcome. # 4. # Use one feature from the dataset to build a single feature linear regression model on the data. Your model, at this point, should use only one feature and predict one of the outcome columns. Before training the model, split your data into training and test datasets so that you can evaluate your model on the test set. How does your model perform? Plot your model’s predictions on the test set against the actual outcome variable to visualize the performance. # Hint # Our first single feature linear regression model used 'FirstServeReturnPointsWon' as our feature and Winnings as our outcome. # features = data[['FirstServeReturnPointsWon']] # outcome = data[['Winnings]] # We utilized scikit-learn’s train_test_split function to split our data into training and test sets: # features_train, features_test, outcome_train, outcome_test = train_test_split(features, outcome, train_size = 0.8) # We then created a linear regression model and trained it on the training data: # model = LinearRegression() # model.fit(features_train,outcome_train) # To score the model on the test data, we used our LinearRegression object’s .score() method. # model.score(features_test,outcome_test) # We then found the predicted outcome based on our model and plotted it against the actual outcome: # prediction = model.predict(features_test) # plt.scatter(outcome_test,prediction, alpha=0.4) # 5. # Create a few more linear regression models that use one feature to predict one of the outcomes. Which model that you create is the best? # Hint # We found that our best single feature linear regression model came from using 'BreakPointsOpportunities' as the feature to predict 'Winnings'. # 6. # Create a few linear regression models that use two features to predict yearly earnings. Which set of two features results in the best model? # Hint # We followed the same steps as in the last exercise to create a linear regression model with 'BreakPointsOpportunities' and 'FirstServeReturnPointsWon' as our features to predict 'Winnings'. # features = data[['BreakPointsOpportunities', # 'FirstServeReturnPointsWon']] # outcome = data[['Winnings']] # 7. # Create a few linear regression models that use multiple features to predict yearly earnings. Which set of features results in the best model? # Head to the Codecademy forums and share your set of features that resulted in the highest test score for predicting your outcome. What features are most important for being a successful tennis player? # Hint # We created a linear regression model with the below features to predict 'Winnings': # features = players[['FirstServe','FirstServePointsWon','FirstServeReturnPointsWon', # 'SecondServePointsWon','SecondServeReturnPointsWon','Aces', # 'BreakPointsConverted','BreakPointsFaced','BreakPointsOpportunities', # 'BreakPointsSaved','DoubleFaults','ReturnGamesPlayed','ReturnGamesWon', # 'ReturnPointsWon','ServiceGamesPlayed','ServiceGamesWon','TotalPointsWon', # 'TotalServicePointsWon']] # outcome = players[['Winnings']] # Solution # 8. # Great work! Visit our forums to compare your project to our sample solution code. You can also learn how to host your own solution on GitHub so you can share it with other learners! Your solution might look different from ours, and that’s okay! There are multiple ways to solve these projects, and you’ll learn more by seeing others’ code. import codecademylib3_seaborn import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression # load and investigate the data here: df = pd.read_csv("tennis_stats.csv") print(df.head()) print("column names:", df.columns) players = df[["Player"]] print("players:\n", players) # perform exploratory analysis here: def show_scatters(): variables = ["Year", "Aces", "DoubleFaults", "FirstServe", "FirstServePointsWon", "SecondServePointsWon", "BreakPointsFaced", "BreakPointsSaved", "ServiceGamesPlayed", "ServiceGamesWon", "TotalServicePointsWon", "FirstServeReturnPointsWon", "SecondServeReturnPointsWon", "BreakPointsOpportunities", "BreakPointsConverted", "ReturnGamesPlayed", "ReturnGamesWon", "ReturnPointsWon", "TotalPointsWon"] outcomes = ["Wins", "Losses", "Winnings", "Ranking"] for outcome in outcomes: for var in variables: plt.clf() plt.scatter(df[[outcome]], df[[var]], alpha=0.4) plt.ylabel(var) plt.xlabel(outcome) plt.title(outcome + " vs " + var) plt.show() # show_scatters() ## perform single feature linear regressions here: def single_linear_regression(feature, outcome): feature_train, feature_test, outcome_train, outcome_test = train_test_split(df[[feature]], df[[outcome]], train_size = 0.8, test_size = 0.2, random_state=6) model = LinearRegression() model.fit(feature_train, outcome_train) outcome_predictions = model.predict(feature_test) # print(outcome + " predict: (" + str(len(outcome_predictions)) + ")\n", outcome_predictions) score = model.score(feature_test, outcome_test) print("Score:\n", score) plt.clf() plt.scatter(outcome_test, outcome_predictions, alpha=0.4) plt.xlabel(feature) plt.ylabel(outcome + " predictiona") plt.title(feature + " tests VS. " + outcome + " predicitons") plt.show() # Comparing Losses to DoubleFaults single_linear_regression("DoubleFaults", "Losses") # losses_train, losses_test, df_train, df_test = train_test_split(df[["Losses"]], df[["DoubleFaults"]], train_size = 0.8, test_size = 0.2, random_state=6) # l_df_lr = LinearRegression() # l_df_lr.fit(losses_train, df_train) # losses_predictions = l_df_lr.predict(losses_test) # print("losses predict: (" + str(len(losses_predictions)) + ")\n", losses_predictions) # score = l_df_lr .score(losses_test, df_test) # print("Score:\n", score) # plt.clf() # plt.scatter(df_test, losses_predictions, alpha=0.4) # plt.xlabel("df_test") # plt.ylabel("losses_predictiona") # plt.title("double fault tests VS. losses_predicitons") # plt.show() ## perform two feature linear regressions here: # Comparing Wins to Aces single_linear_regression("Aces", "Wins") # Comparing Winnings to BreakPointsOpportunities single_linear_regression("BreakPointsOpportunities", "Winnings") ## perform multiple feature linear regressions here: def multi_linear_regression(features, outcome): features = [features] if not isinstance(features, list) else features print("\tMulti Linear Regression\nComparing features:\n-\t" + "\n-\t".join(features) + "\nto outcome:\n-\t" + outcome) features_train, features_test, outcome_train, outcome_test = train_test_split(df[features], df[[outcome]], train_size = 0.8, test_size = 0.2, random_state=6) model = LinearRegression() model.fit(features_train, outcome_train) outcome_predictions = model.predict(features_test) # print(outcome + " predict: (" + str(len(outcome_predictions)) + ")\n", outcome_predictions) score = model.score(features_test, outcome_test) print("Score:\n", score) plt.clf() plt.scatter(outcome_test, outcome_predictions, alpha=0.4) plt.xlabel(" ".join(features)) plt.ylabel(outcome + " predictiona") plt.title(str(features) + " tests VS. " + outcome + " predicitons") plt.show() multi_linear_regression(["Aces", "TotalServicePointsWon"], "Wins") multi_linear_regression(["Aces", "BreakPointsOpportunities"], "Wins") multi_linear_regression(["Aces", "BreakPointsOpportunities", "TotalServicePointsWon",], "Wins") # predict winnings winnings_variables = ['FirstServe','FirstServePointsWon','FirstServeReturnPointsWon', 'SecondServePointsWon','SecondServeReturnPointsWon','Aces', 'BreakPointsConverted','BreakPointsFaced','BreakPointsOpportunities', 'BreakPointsSaved','DoubleFaults','ReturnGamesPlayed','ReturnGamesWon', 'ReturnPointsWon','ServiceGamesPlayed','ServiceGamesWon','TotalPointsWon', 'TotalServicePointsWon'] multi_linear_regression(winnings_variables, "Winnings")
e845aeca37bd0f7c64dcb3c4730fc135cda66c5a
kaharkapil/Python-Programs
/wrtefile1.py
443
3.90625
4
import csv name=input("enter name") email=input("enter eamil") with open('wrtefile.csv','w') as csvfile: fieldnames=['first_name','email'] writer=csv.DictWriter(csvfile,fieldnames=fieldnames) writer.writeheader() writer.writerow({'first_name':'kapil','email':'[email protected]'}) writer.writerow({'first_name':'rana','email':'[email protected]'}) writer.writerow({'first_name':'tina','email':'[email protected]'}) writer.writerow({'first_name':name,'email':email})
f4d65439c6ff9fc1da80e09b7cb0ca0800182503
Bobbybushe/HW
/task_4_1.py
260
3.734375
4
spis_1=[1,2,3,4,5] spis_n=[] i=0 for i in range(len(spis_1)): spis_n.append(spis_1[i] * -2) print(spis_n) #Все тоже с while spis_2=[2,3,4,5,6] spis_n_2=[] i_2=0 while i_2<len(spis_2): spis_n_2.append(spis_2[i_2] * -2) i_2+=1 print(spis_n_2)
931242546c6e2efb57a73f6784777bebf5bfda57
LazarusCoder/Problem_Solving_with_Python
/LAB3/prac31.py
332
3.640625
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 6 10:00:00 2020 @author: Admin """ from random import * ran=randint(1,52) rank=ran%13 category=ran//13 if(rank==0): s="ACE" elif(rank==10): s="Jack" elif(rank==11): s="Queen" elif(rank==12): s="King" else: s=str(rank+1) print("The Card you Picked is ",s)
7db9ae02aa4a656aa95957e99bbf54cd9253af7e
saurabhm3hra/pyFolder
/ticTacToe.py
2,812
3.5625
4
import sys class Board: # TicTacToe Board board = {"TL": ' ', "TM": ' ', "TR": ' ', "ML": ' ', "MM": ' ', "MR": ' ', "LL": ' ', "LM": ' ', "LR": ' '} def __str__(self): # Print Board contents return self.board['TL'] + '|' + self.board['TM'] + '|' + self.board['TR'] + '\n' + \ '-+-+-' + '\n' + self.board['ML'] + '|' + self.board['MM'] + '|' + self.board['MR'] + '\n' + \ '-+-+-' + '\n' + self.board['LL'] + '|' + self.board['LM'] + '|' + self.board['LR'] def CheckWin(self): # Check if player won if self.board["TL"] == "X" and self.board["TM"] == "X" and self.board["TR"] == "X": print("Player 1 won") sys.exit() elif self.board["TL"] == "O" and self.board["TM"] == "O" and self.board["TR"] == "O": print("Player 2 won") sys.exit() elif self.board["ML"] == "X" and self.board["MM"] == "X" and self.board["MR"] == "X": print("Player 1 won") sys.exit() elif self.board["ML"] == "O" and self.board["MM"] == "O" and self.board["MR"] == "O": print("Player 2 won") sys.exit() elif self.board["LL"] == "X" and self.board["LM"] == "X" and self.board["LR"] == "X": print("Player 1 won") sys.exit() elif self.board["LL"] == "O" and self.board["LM"] == "O" and self.board["LR"] == "O": print("Player 2 won") sys.exit() elif self.board["TL"] == "X" and self.board["ML"] == "X" and self.board["LL"] == "X": print("Player 1 won") sys.exit() elif self.board["TL"] == "O" and self.board["ML"] == "O" and self.board["LL"] == "O": print("Player 2 won") sys.exit() elif self.board["TM"] == "X" and self.board["MM"] == "X" and self.board["LM"] == "X": print("Player 1 won") sys.exit() elif self.board["TM"] == "O" and self.board["MM"] == "O" and self.board["LM"] == "O": print("Player 2 won") sys.exit() elif self.board["TR"] == "X" and self.board["MR"] == "X" and self.board["LR"] == "X": print("Player 1 won") sys.exit() elif self.board["TR"] == "O" and self.board["MR"] == "O" and self.board["LR"] == "O": print("Player 2 won") sys.exit() elif self.board["TL"] == "X" and self.board["MM"] == "X" and self.board["LR"] == "X": print("Player 1 won") sys.exit() elif self.board["TL"] == "O" and self.board["MM"] == "O" and self.board["LR"] == "O": print("Player 2 won") sys.exit() elif self.board["TR"] == "X" and self.board["MM"] == "X" and self.board["LL"] == "X": print("Player 1 won") sys.exit() elif self.board["TR"] == "O" and self.board["MM"] == "O" and self.board["LL"] == "O": print("Player 2 won") sys.exit() board1 = Board() print("Player 1: X | Player 2: O") while True: p1 = input("Player 1 Turn: ") board1.board[p1] = "X" print(board1) board1.CheckWin() p2 = input("Player 2 Turn: ") board1.board[p2] = "O" print(board1) board1.CheckWin()
4ca10c7c9d43240774db9ca34f715bed7ea1ea6d
nikitasyrtsov/DZ
/dz3/Домашка 3/#9.py
285
3.609375
4
'''Упражнение 9 Напечатать числа Фибоначчи от 1 до 50. Числа напечатать в одну строку. ''' fib1 = 1 fib2 = 1 for i in range(1,50): fib_sum = fib1 + fib2 fib1 = fib2 fib2 = fib_sum print(fib_sum, end = ' ')
ec6881c45a38763368eea0312612cb16d5244f96
yavaralikhan/proj
/25FebC.py
331
3.9375
4
import matplotlib.pyplot as plt """ Y = [0, 1, 2, 3, 4, 5] plt.plot(Y) plt.show() """ X = list(range(1, 11)) Y1 = [n for n in X] Y2 = [n*n for n in X] Y3 = [n*n*n for n in X] print(Y1) print(Y2) print(Y3) plt.plot(X, Y1, label="Y1") plt.plot(X, Y2, label="Y2") plt.plot(X, Y3, label="Y3") plt.grid(True) plt.legend() plt.show()
fa26f98ea19e5e07c603a82bee4ae98608736995
tyao117/AlgorithmPractice
/randomizeList.py
265
3.859375
4
import random array = [1,2,3,4,5,6,7,8,9] def randomizeList(lst): b = len(lst) -1 for d in range(b,0,-1): e = random.randint(0,d) if e == d: continue lst[d], lst[e] = lst[e], lst[d] randomizeList(array) print(array)
9cac58b35c1a9cc9b97c9bc6fc85564f8ade9311
isleong/python_finance
/myscript.py
855
3.734375
4
import numpy as np import pandas as pd from pandas import Series, DataFrame series_obj = Series(np.arange(8), index=['row 1', 'row 2', 'row 3', 'row 4', 'row 5', 'row 6', 'row 7', 'row 8']) print(series_obj) print(series_obj['row 7']) print(series_obj[[0,7]]) np.random.seed(25) df_obj = DataFrame(np.random.rand(36).reshape(6,6), index=['row 1', 'row 2', 'row 3', 'row 4','row 5', 'row 6'], columns=['column 1', 'column 2', 'column 3', 'column 4','column 5', 'column 6']) print(df_obj) # using ix() print(df_obj.ix[['row 2', 'row 5'], ['column 5', 'column 2']]) #slicing data print(series_obj['row 3' : 'row 7']) # comparison operators work on all elements in arrays print(df_obj < 0.2) # Find all rows with a value greater than 6 print(series_obj[series_obj > 6]) series_obj['row 1', 'row 5', 'row 8'] = 8 print(series_obj)
f30e565d8ec99b696cf2d16ec84ab27eb4fd0ab5
thomps51/ProjectEulerSolutions
/problem47.py
975
3.53125
4
import math import sys def primeTest(N): if N==1: return False for i in xrange(2,int(math.sqrt(N))+1): if N % i == 0: return False return True def findPrimeFactors(N): primeFactors = [] for i in xrange(2,int(math.sqrt(N))+1): if N % i == 0: if primeTest(i): primeFactors.append(i) if primeTest(N/i): primeFactors.append(N/i) return sorted(primeFactors) #print findPrimeFactors(646) #sys.exit(0) sameFactors = [] last = [1] for i in range(10,1000000): primeFactors = findPrimeFactors(i) if primeFactors == []: last = [1] sameFactors = [] continue #print primeFactors if len(primeFactors) == 3: sameFactors.insert(0,primeFactors) if len(primeFactors) != 3: sameFactors = [] if len(sameFactors) == 3: print i print sameFactors break last = primeFactors
dfbcd7782b8264567bed14a62117b0e6b7e1dbe8
K021/search_bible
/search_bible_2.0/functions.py
5,871
3.609375
4
def search_scripture(scripture_path, sub_scripture_path=None, is_lower=True, number_of_lines_to_print=1): """ file type 의 scripture 객체를 받는다 사용자에게서 검색어를 입력 받아 검색을 수행한다 :param scripture_path: 검색을 수행할 txt 파일 path :param sub_scripture_path: scripture 와 비교할 파일 path :param is_lower: Capital letter 무시 여부 :param number_of_lines_to_print: 검색된 구절부터 몇 구절을 출력할 것인가 :return: 검색 조건과 일치하는 line 의 index 리스트 """ scripture = open(scripture_path, 'r') plus_keys, minus_keys = get_keyword_input(is_lower=is_lower) number_of_result = 0 line_index = 0 line_index_list = list() print('=================================================') for line in scripture: line_index += 1 line_temp = line.lower() if is_lower else line for i, plus_key in enumerate(plus_keys): if plus_key not in line_temp: break elif i == (len(plus_keys) - 1): if not minus_keys: number_of_result += 1 line_index_list.append(line_index) print() print(line, end='') print_scripture_by_line( scripture_path, [line_index + x for x in range(1, number_of_lines_to_print)] ) print_scripture_by_line( sub_scripture_path, [line_index + x for x in range(0, number_of_lines_to_print)] ) else: for k, minus_key in enumerate(minus_keys): if minus_key in line_temp: break elif k == (len(minus_keys) - 1): number_of_result += 1 line_index_list.append(line_index) print() print(line, end='') print_scripture_by_line( scripture_path, [line_index + x for x in range(1, number_of_lines_to_print)] ) print_scripture_by_line( sub_scripture_path, [line_index + x for x in range(0, number_of_lines_to_print)] ) print('-------------------------------------------------') print('{} verses'.format(number_of_result)) print('=================================================') scripture.close() return line_index_list def print_scripture_by_line(scripture_path=None, linenos=None): """ int 또는 list 형태의 line number 를 받아 scripture 파일에서 해당하는 라인을 출력해주는 함수 :param scripture_path: line number 가 linenos 와 일치하는 문자열을 출력할 파일 객체 :param linenos: 출력하려는 line number 리스트 :return: line number 인자 수, 출력된 줄 수 튜플 scripture 가 없을 경우, None 출력 """ if not scripture_path or not linenos: return False scripture = open(scripture_path, 'r') if type(linenos) not in [int, list]: raise ValueError('The argument "lineno" must be int or list type.') linenos = [linenos] if type(linenos) == int else linenos scripture_lineno = 0 num_of_printed_line = 0 for verse in scripture: scripture_lineno += 1 for lineno in linenos: if lineno == scripture_lineno: num_of_printed_line += 1 print(verse, end='') linenos.remove(lineno) break if not linenos: break scripture.close() return len(linenos), num_of_printed_line def get_keyword_input(is_lower=False): """ plus_keys = (+)키워드를 담는 리스트 minus_keys = (-)키워드를 담는 리스트 :param is_lower: Capital letter 무시 여부 :return: plus_keys, minus_keys """ # 키워드를 담을 리스트 plus_keys = list() minus_keys = list() # 최초의 검색어를 받아서 plus_keys 에 넣는다 append_input_to_key(plus_keys, is_lower=is_lower) # 사용자 입력에 따라 추가적인 (+)키워드 또는 (-)키워드를 각각의 리스트에 저장한다 while True: stop_or_go = input('Type 1 to add (+)keyword, 2 for (-)keyword, 0 to search now: ') if stop_or_go in ['0', '']: break elif stop_or_go == '1': append_input_to_key(plus_keys, is_lower=is_lower) elif stop_or_go == '2': append_input_to_key(minus_keys, is_minus=True, is_lower=is_lower) else: print('Invalid value. Try again.') return plus_keys, minus_keys def append_input_to_key(key_list, is_minus=False, is_lower=False): """ 검색을 위한 키워드를 담는 리스트인 key_list 를 인자로 받아 input 함수를 실행해서 얻은 문자열을 key_list 에 추가하여 return :param key_list: 검색어 리스트 :param is_minus: (-)검색어 여부 :param is_lower: Capital letter 무시 여부 :return: (input 문자열이 추가된) key_list """ # input 함수 실행시 출력될 문구. is_minus 여부에 따라 문자열이 달라진다. plus_string = '(+)keyword: ' minus_string = '(-)keyword: ' ask_string = plus_string if not is_minus else minus_string user_input = '' while not user_input: user_input = input(ask_string) if is_lower: user_input = user_input.lower() return key_list.append(user_input)
82ff85ec44a600511835c70fb1958d65cb561c31
ARuhala/PythonProjects
/ViolentPythonCookBook/PortScanner/sysExperiment.py
1,317
3.6875
4
''' This file is part of examples shown in a book "Violent Python Cookbook for Hackers, Forensic Analysts, Penetration Testers and Security Engineers" Most of the code is copied as is, or with minor changes to make naming easier to understand and some comments may have been added where i explain to myself how everything works ( the code is not just blindly copied ). The purpose of these files is for me to understand how the code works and become better at the security field. ------------ Antti Ruhala, Tampere University of Technology ------------ ''' import sys ''' sys is used to parse commandline arguments at runtime > programmer$ python vuln-scanner.py vuln-banners.txt sys.argv[0] == vuln-scanner.py sys.argv[1] == vuln-banners.txt ''' import os ''' os is used for filepath management and checking rights ''' if len(sys.argv) == 2: filename = sys.argv[1] if not os.path.isfile(filename): print( '[-]' + filename + ' does not exist.') # in this directory exit(0) if not os.access(filename, os.R_OK): # checks if user had READ rights to the file # Chmod 000 filename.txt # for setting the rights on unix print( '[-]' + filename + ' access denied.') exit(0) print ("[+] Reading Vulnerabilities From: " + filename)
f84424134fe87e031935ebd4447912c9ee56ea04
arpitpardesi/Advance-Analytics
/Python/Basics/Day2/For Loop/Ex2.py
65
3.53125
4
a = "My name Arpit Pardesi" for i in a.split(" "): print(i, end=" ")
aec51814ff162e4076ffbd2cc5f9513ea9bdf35a
dgquintero/holbertonschool-higher_level_programming
/0x03-python-data_structures/5-no_c.py~
165
3.75
4
#!/usr/bin/env python3 def no_c(my_string): new_s = "" for tmp in my_string: if tmp != 'c' or tmp != 'C': new_s = new_s return new_s
5b85031d8c28adcab1f4d2f144b5c2a1f59e328c
HIjack2015/showLastEvent
/mm/tests.py
289
3.796875
4
# Function defined outside the class def f1(self, x, y): return min(x, x+y) class C: f = f1 def g(self): return 'hello world' h = g int class D: f = f1 def g(self): return 'hello world' h = g f1(C,1,2) c=C() c.f1(1,3) d=D() d.f1(1,3)
fd1f0ef96e43629cec62995b3c46eae67d45b0c9
rijumone/compete_code
/edX/UCSanDiegoX-ALGS200x/AlgorithmicDesignandTechniques/4-1.binary_search.py
639
3.546875
4
from loguru import logger def binary_search(a, x): left, right = 0, len(a) # logger.info(f'{a}, {x}') while left < right: mid = int((left + right) / 2) # logger.info(f'{left}, {right}, {mid}') if a[mid] == x: return mid if a[mid] > x: right = mid else: left = mid + 1 # logger.info(f'{left}, {right}') return -1 def main(): for x in [int(_) for _ in '8 1 23 1 11'.split(' ')]: o = binary_search(a, x) logger.info(f'o, {o}') if __name__ == '__main__': a = [int(_) for _ in '1 5 8 12 13'.split(' ')] main()
ce44a701eb015d53cd9908e207ab9ca9cc2ff4d1
Jairofontalvo/exercism
/python/collatz-conjecture/collatz_conjecture.py
321
4.125
4
def steps(number): if number <= 0: raise ValueError("numero negativo") contador = 0 while number != 1: if number % 2 == 1: number = number * 3 + 1 contador += 1 if number % 2 == 0: number = number / 2 contador += 1 return contador
1dec86936d04e3d45ab67b09d35112b3a1c179cb
ShivDj/Python_Basic
/Functional_Programm/​ Quadratic.py
1,156
4.3125
4
""" +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * Purpose: Program To calculate the roots of the equation * @author: Sheevendra Singh Singraul * @version: 3.8.6 * @since: 21-03-2021 * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ """ import math #math module imported class Quadratic: def cal(self): try: #try block is used to limiting value of b more then a and c a=int(input("enter the value of a=")) b=int(input("enter the value of B=")) c=int(input("enter the value of C=")) delta = b*b - 4*a*c root1_Of_x = (-b + (math.sqrt(delta))/(2*a)) root2_Of_x = (-b - (math.sqrt(delta))/(2*a)) print("first Quadratic root_1=",root1_Of_x) print("second Quadratic root_2=",root2_Of_x) except ValueError: #if b value is given less then a and c then ValueError occure that handled in here print("you have to give b value more then a and c") except: #all other exceptions are handled here print("something wenrt wrong") q=Quadratic() q.cal()
cc84b7c8974b63a4bbac73d53f3e5e2162e3d9c1
thevivekcode/MachineLearning
/Assignment1/q3/part3.py
2,887
3.515625
4
# coding: utf-8 # In[1]: import numpy as np import pandas as pd import matplotlib.pyplot as plt from time import time from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import matplotlib.animation as animation import math import sys # In[2]: # In[3]: def normalize(data): mean = np.mean(data) std = np.std(data) data = data -mean data = data/std return data # In[4]: def inputData(): dfX1 = pd.read_csv(sys.argv[1],usecols=[0],names=["X1"],header=None) dfX2 = pd.read_csv(sys.argv[1],usecols=[1],names=["X2"],header=None) dfY = pd.read_csv(sys.argv[2],usecols=[0],names=["Y"],header=None) #creating the intercept term X_0 = np.ones((len(dfX1),1)) #normalizing the data X_1 = normalize(dfX1["X1"].to_numpy()).reshape(-1,1) X_2 = normalize(dfX2["X2"].to_numpy()).reshape(-1,1) # print(X_1.shape) Y = dfY.to_numpy().reshape(-1,1) #joining the training example as one numpy Narray X0X1 = np.append(X_0,X_1, axis=1) X0X1X2 = np.append(X0X1,X_2,axis = 1) X0X1X2Y = np.append(X0X1X2,Y, axis=1) np.random.shuffle(X0X1X2Y) #shuffling data to make it random for better distribution # print(X0X1X2Y) return X0X1X2Y # In[5]: def sigmoid(X0X1X2Y,theta): # calculating sigmoid function ita = np.dot(X0X1X2Y[:,0:3],theta) return 1/(1+np.exp(-ita)) # In[6]: def newtonUpdate(): theta = np.zeros((3,1)) # initialize theta to zeros X0X1X2Y = inputData() # oldTheta= np.ones((3,1)) # epsilon = 1e-100 for i in range(20): # while(abs(theta[0,0] - oldTheta[0,0]) > epsilon or abs(theta[1,0] - oldTheta[1,0]) > epsilon or abs(theta[2,0] - oldTheta[2,0]) > epsilon): #calculating the hessian matrix sigma = sigmoid(X0X1X2Y,theta)*(1-sigmoid(X0X1X2Y,theta)) hessian = np.dot(np.dot(X0X1X2Y[:,0:3].T,np.diag(sigma[:,0:1].flat)),X0X1X2Y[:,0:3]) # gradient of log likelyhood Jcost =np.dot( X0X1X2Y[:,0:3].T,(sigmoid(X0X1X2Y,theta) - X0X1X2Y[:,3:4])) #calculating theta theta -= np.dot(np.linalg.inv(hessian),Jcost) # oldTheta = theta.copy() return theta # In[7]: def plot(): theta= newtonUpdate() print(theta) X0X1X2Y = inputData() x2 = -(np.dot(X0X1X2Y[:,0:2],theta[0:2,:])/theta[2:3,:]) # a,=plt.plot(X0X1X2Y[:50,1:2],X0X1X2Y[:50,2:3],"rx",label ="negative") a,=plt.plot((X0X1X2Y[np.where(X0X1X2Y[:,3]==0)])[:,1],(X0X1X2Y[np.where(X0X1X2Y[:,3]==0)])[:,2],"rx",label ="negative") b,=plt.plot((X0X1X2Y[np.where(X0X1X2Y[:,3]==1)])[:,1],(X0X1X2Y[np.where(X0X1X2Y[:,3]==1)])[:,2],"b^",label ="positive") c,=plt.plot(X0X1X2Y[:,1:2],x2 ) plt.legend() plt.xlabel("Feature X1",color="r") plt.ylabel("Feature X2",color="r") plt.title("Logistic regression",color="b") plt.show() return a,b,c # In[8]: (a,b,c)=plot()
a0dd0562c533da9f2c7589925488d2b11c0e6d3c
Marghrid/Foundations-of-Programming
/Exercicios/a02_12.py
335
4.21875
4
print ('\n') numero='' digito='' while (digito!='-1'): digito = input('Escreva um dgito\n(-1 para terminar)\n') if (digito!='-1'): if (eval(digito)<=0): print('No pode colocar dgitos negativos num nmero inteiro') else: numero=numero+digito print ('o numero e:', numero)
9a1167136730ea4da1b6fa621033f21cc274a777
Nukeguy5/OperatingSystems
/threadingx/nthread.py
411
3.671875
4
import time import threading class CountdownThread(threading.Thread): def __init__(self, acount): threading.Thread.__init__(self) self.count = acount def run(self): while self.count > 0: print(self.getName(), ": Counting down", self.count) self.count -= 1 time.sleep(1) print("exit thread", self.getName()) return
c95b592447cbe3e13a0651216006471fb6656188
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/3113/codes/1594_1800.py
136
3.890625
4
a=float(input("valor de a:")) b=float(input("valor de b:")) c=float(input("valor de c:")) X=(a**2+b**2+c**2)/(a+b+c) print(round(X,7))
9690d4fbf10f21a92d44ac0344aa83a97155f18c
adityasriv22/Python-Drilling
/minelementoflist.py
478
3.828125
4
""" Write two Python functions to find the minimum number in a list. The first function should compare each number to every other number on the list. O(n^2).The second function should be linear O(n). """ import time from random import randrange def findmin(l): overallmin=l[0] for i in l: issmallest=True for j in l: if i > j: issmallest=False if issmallest: overallmin=i return overallmin print(findmin([5,4,2,1,0]))
a3f090471bcc501a1d0b762cd2a15264f467f755
SWMGroup11/XiaoMiOJ
/小米兔跳格子.py
413
3.5625
4
import sys def solution1(line): nums = [int(x) for x in line.rstrip().split()] current = 1 while 1: if current -1 == len(nums) - 1: return "true" elif nums[current - 1] == 0: return "false" elif current -1>len(nums): return "false" else: current += nums[current -1] for line in sys.stdin: print(solution1(line))
16bcff98521e09820019e11e388ae94819f78f92
groovallstar/test2
/python/example/p_chapter02_03.py
2,904
4.28125
4
# Chapter02-03 # 파이썬 심화 # 클래스 메소드, 인스턴스 메소드, 스테이틱 메소드 # 기본 인스턴스 메소드 # 클래스 선언 class Car(object): ''' Car Class Author : Me Date : 2019.11.08 Description : Class, Static, Instance Method ''' # Class Variable price_per_raise = 1.0 def __init__(self, company, details): self._company = company self._details = details def __str__(self): return 'str : {} - {}'.format(self._company, self._details) def __repr__(self): return 'repr : {} - {}'.format(self._company, self._details) # Instance Method # self : 객체의 고유한 속성 값 사용 def detail_info(self): print('Current Id : {}'.format(id(self))) print('Car Detail Info : {} {}'.format(self._company, self._details.get('price'))) # Instance Method def get_price(self): return 'Before Car Price -> company : {}, price : {}'.format(self._company, self._details.get('price')) # Instance Method def get_price_calc(self): return 'After Car Price -> company : {}, price : {}'.format(self._company, self._details.get('price') * Car.price_per_raise) # Class Method @classmethod def raise_price(cls, per): if per <= 1: print('Please Enter 1 or More') return cls.price_per_raise = per return 'Succeed! price increased.' # Static Method @staticmethod def is_bmw(inst): if inst._company == 'Bmw': return 'OK! This car is {}.'.format(inst._company) return 'Sorry. This car is not Bmw.' # 자동차 인스턴스 car1 = Car('Bmw', {'color' : 'Black', 'horsepower': 270, 'price': 5000}) car2 = Car('Audi', {'color' : 'Silver', 'horsepower': 300, 'price': 6000}) # 기본 정보 print(car1) print(car2) print() # 전체 정보 car1.detail_info() car2.detail_info() print() # 가격 정보(인상 전) print(car1.get_price()) print(car2.get_price()) print() # 가격 인상(클래스 메소드 미사용) Car.price_per_raise = 1.2 # 가격 정보(인상 후) print(car1.get_price_calc()) print(car2.get_price_calc()) print() # 가격 인상(클래스 메소드 사용) Car.raise_price(1.6) print() # 가격 정보(인상 후 : 클래스메소드) print(car1.get_price_calc()) print(car2.get_price_calc()) print() # Bmw 여부(스테이틱 메소드 미사용) def is_bmw(inst): if inst._company == 'Bmw': return 'OK! This car is {}.'.format(inst._company) return 'Sorry. This car is not Bmw.' # 별도의 메소드 작성 후 호출 print(is_bmw(car1)) print(is_bmw(car2)) print() # Bmw 여부(스테이틱 메소드 사용) print('Static : ', Car.is_bmw(car1)) print('Static : ', Car.is_bmw(car2)) print() print('Static : ', car1.is_bmw(car1)) print('Static : ', car2.is_bmw(car2))
0fc5fb6cca78f5a59778b6cfb3f38131eae186ec
childe/leetcode
/add-digits/solution.py
1,380
3.9375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ https://leetcode.com/problems/add-digits/ Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. For example: Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. Follow up: Could you do it without any loop/recursion in O(1) runtime? Hint: A naive implementation of the above process is trivial. Could you come up with other methods? Show More Hint Credits: Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. """ import unittest class Solution(object): def addDigits(self, num): """ :type num: int :rtype: int """ if num == 0: return 0 rst = num % 9 return rst if rst > 0 else 9 class TestSolution(unittest.TestCase): def test_addDigits(self): s = Solution() import random for num in range(10): while(num >= 10): num = num/10 + num % 10 self.assertEqual(num, s.addDigits(num)) for i in range(1000): num = random.randint(1, 10**9) print num while(num >= 10): num = num/10 + num % 10 self.assertEqual(num, s.addDigits(num)) if __name__ == '__main__': unittest.main()
b58b0dbd0d8180852362bbe7fa889fbc8506e80b
santhosh-kumar/AlgorithmsAndDataStructures
/python/problems/dynamic_programming/wildcard_matching.py
2,662
4.125
4
""" Wildcard Matching Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). Note: s could be empty and contains only lowercase letters a-z. p could be empty and contains only lowercase letters a-z, and characters like ? or *. Example 1: Input: s = "aa" p = "a" Output: false Explanation: "a" does not match the entire string "aa". Example 2: Input: s = "aa" p = "*" Output: true Explanation: '*' matches any sequence. Example 3: Input: s = "cb" p = "?a" Output: false Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'. Example 4: Input: s = "adceb" p = "*a*b" Output: true Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce". Example 5: Input: s = "acdcb" p = "a*c?b" Output: false """ from common.problem import Problem class WildcardMatching(Problem): """ WildcardMatching """ PROBLEM_NAME = "WildcardMatching" def __init__(self, input_string, pattern): """StrStr Args: input_string: haystack pattern: to be searched in the haystack Returns: None Raises: None """ super().__init__(self.PROBLEM_NAME) self.input_string = input_string self.pattern = pattern def solve(self): """Solve the problem Note: O(mn), space complexity: O(mn), where n = len(s), m = len(p). Args: Returns: boolean Raises: None """ print("Solving {} problem ...".format(self.PROBLEM_NAME)) input_string_length = len(self.input_string) pattern_length = len(self.pattern) match_matrix = [[False] * (input_string_length + 1) for _ in range(pattern_length + 1)] match_matrix[0][0] = True for i in range(1, pattern_length + 1): match_matrix[i][0] = match_matrix[i - 1][0] and self.pattern[i - 1] == '*' for i in range(1, pattern_length + 1): for j in range(1, input_string_length + 1): if self.pattern[i - 1] != '*': match_matrix[i][j] = (self.pattern[i - 1] == self.input_string[j - 1] or self.pattern[ i - 1] == '?') and match_matrix[i - 1][j - 1] else: match_matrix[i][j] = match_matrix[i][j - 1] or match_matrix[i - 1][j] return match_matrix[-1][-1]
3a1b03bbe91fccda2bd5396b0dac5c927b2b536a
halysl/python_module_study_code
/src/study_cookbook/3数字日期和时间/精准的浮点数运算.py
1,811
3.765625
4
# -*- coding: utf-8 -*- from decimal import Decimal from decimal import localcontext def unprecision(): a = 4.2 b = 2.1 print("{0}\n{1}\n{2}\n".format(a, b, a+b)) print("(a + b) == 6.3 >>> {0}".format((a + b) == 6.3)) def precision(): # decimal 模块的一个主要特征是允许你控制计算的每一方面,包括数字位数和四舍五入运算。 a = Decimal('4.2') b = Decimal('2.1') print("{0}\n{1}\n{2}\n".format(a, b, a+b)) print("(a + b) == 6.3 >>> {0}".format((a + b) == Decimal('6.3'))) def control_your_number(): a = Decimal('1.3') b = Decimal('1.7') print("a / b = {}".format(a / b)) with localcontext() as ctx: ctx.prec = 3 print("3位小数 a / b = {}".format(a / b)) with localcontext() as ctx: ctx.prec = 50 print(a / b) print("50位小数 a / b = {}".format(a / b)) def description(): # decimal 模块实现了IBM的”通用小数运算规范”。不用说,有很多的配置选项这本书没有提到。 # Python新手会倾向于使用 decimal 模块来处理浮点数的精确运算。 # 然而,先理解你的应用程序目的是非常重要的。 # 如果你是在做科学计算或工程领域的计算、电脑绘图,或者是科学领域的大多数运算, # 那么使用普通的浮点类型是比较普遍的做法。 # 其中一个原因是,在真实世界中很少会要求精确到普通浮点数能提供的17位精度。 # 因此,计算过程中的那么一点点的误差是被允许的。 # 第二点就是,原生的浮点数计算要快的多-有时候你在执行大量运算的时候速度也是非常重要的。 pass if __name__ == "__main__": unprecision() precision() control_your_number()
f6ff9a6f67ef5ea319001ea4a89d51e5ced373d1
gabrielsalless/python-tutor
/Exercicios anteriores/ex019.py
290
3.734375
4
import random primeiro=input('Digite o primeiro aluno: ') segundo=input('Digite o segundo aluno: ') terceiro=input('Digite o terceiro aluno: ') quarto=input("Digite o quarto aluno: ") lista = [primeiro,segundo,terceiro,quarto] print ('O aluno escolhido foi {}'.format(random.choice(lista)))
7d08ab38a7ef4ddcbce9b5916cc4177dc1c5f6ed
anchall21/HealthAccess
/API connection_1.py
1,843
4.0625
4
""" HealthAccess team Primary Author: Abhilash Biswas Objective: This program takes in 2 parameters a)User's location b)Destination location and uses Google Map's API to calculate the distance between the 2 locations For our app, we can use this program to create a travel time table for all hospitals nearby and then sort it on time to give a ranked set of hospitals Packages required: a. requests (should already be there) b. json (should already be there) Other instructions: a. The API KEY used is the author's google cloud API key. We should use that for all Google cloud based API requests but don't share outside of team b. The entire code is cased in a program so that the program can be used for our rest of app development """ def API_distance(): #Import required files import requests import json #Keys API_KEY = 'AIzaSyABxu5Q65XqI2ndTkA58OMs75ahlumci10' #User inputs user_address = input('Please enter your current street address: ') destination = input('Please enter the destination address: ') #Travel time function def time(x,y): url = 'https://maps.googleapis.com/maps/api/distancematrix/json?' search_address = url + 'origins=' + x + '&destinations=' + y \ + '&units=imperial&key=' + API_KEY payload={} headers = {} response = requests.request("GET", search_address, headers=headers, data=payload) data = json.loads(response.content.decode('utf-8')) travel_time = data['rows'][0]['elements'][0]['duration']['text'] return travel_time print('Travel time to chosen destination = ',time(user_address,destination)) if __name__=='__main__': API_distance()
1e711033434ac5d74dae39f7b9f5bd0812ef1565
guangfnian/PAT
/advanced/1108/1108.py
703
3.59375
4
n = int(input()) cnt, sum = 0, 0 for x in input().split(): f = 1 k = 0 try: k = float(x) except: f = 0 if f == 0: print('ERROR: %s is not a legal number' % x) continue if k > 1000 or k < -1000: print('ERROR: %s is not a legal number' % x) continue kk = x.split('.') if len(kk) == 2 and len(kk[1]) > 2: print('ERROR: %s is not a legal number' % x) continue cnt += 1 sum += k if cnt == 0: print('The average of 0 numbers is Undefined') elif cnt == 1: print('The average of 1 number is %.2f' % sum) else: print('The average of %d numbers is %.2f' % (cnt, sum/cnt))
f75d40528f9b271bd21854654f252442ed2abfdf
fordham-css/TryPy
/Tutorials/jeeves.py
3,214
4.15625
4
''' jeeves.py ---------- Robot to suggest outfit based on the weather - Variables - Conditionals ---------- Python Demo Workshop, March 22nd 2017 ''' #### Declaring variables in Python # Good news: No need to lock variable to a type! # Bad news: No real implementation of constant variable types... # Integer Data Type LOW_THRESHOLD = 35 HIGH_THRESHOLD = 80 JACKET_THRESHOLD = 40 SHORTS_THRESHOLD = 65 print('It is your robots first day on the job, so please introduce yourself: ') # Declare and initialize a variable from user input # String Data Type name = raw_input('> ') print('Great! He will be with you now..') # Format print statement with name as paramater print('Good day {0}'.format(name)) # Will place name in first position (zero indexed) print('My name is Jeeves, your personal robot butler. Shall we settle on an outfit for today?') # Get current weather temperature and condition temp = raw_input('Now what is the temperature outside today?\n > ') temp = int(temp) # IMPORTANT: raw_input returns a string, need to type cast to an int condition = raw_input('Now would you say it is clear, cloudy, or overcast?\n > ') # Error Checking on condition condition = condition.lower() # For the purposes of comparison if condition != 'clear' and condition != 'cloudy' and condition != 'overcast': print('You are being ridiculous..\nI shall not work with someone with such rude manner!') exit(1) # !! IF WE GOT HERE WE MESSED UP !! *# ### Branch to determine what outfit to wear # Report on current temperature if temp > HIGH_THRESHOLD: print('Goodness me it is hot today!') elif temp < LOW_THRESHOLD: print('Sounds like a cold day outside, better bundle up!') else: print('Seems like a moderate day today') # Decide on what to wear based on weather condition # Boolean Data Type good_weather = True if condition != 'clear': good_weather = False if good_weather: # Will execute if good_weather == True if temp >= SHORTS_THRESHOLD: print('Fabulous news! It is nice enough outside to wear shorts! Rock a clean tee and get outside!') elif temp <= JACKET_THRESHOLD: print('Better bundle up, if you have to go outside definitely bring a jacket') else: print('Your call, remember jeans and a sweater bring it together') else: # Executes on good_weather == False if temp >= SHORTS_THRESHOLD: print('Tough spot...try wearing dri fit shorts with a light rain jacket') elif temp <= JACKET_THRESHOLD: print('Gonna be a tough go. Definitely go with a jacket, hat, and boots if need be') else: print('Try the layered look. Lightweight sweater under a rain jacket') print('Hope you have a great day {0}!!!'.format(name)) ''' -- BONUS -- Obviously, having to enter your name every single time you run this program is woefully ineffecient. -> Try having the program save your name the first time you enter it (say into a text file) and in subsequent uses just read the name from the file Working with files in Python: http://pymbook.readthedocs.io/en/latest/file.html HINT: You can use a conditional to see if the name has been recorded already. If so, read the name from the file. Else... '''
fe1a760204cf99ccce7fccd1bf4bc59a800d330f
T-Corazon/CodeChallenge
/Hard/transactionsStability.py
2,705
4.0625
4
#~ You're working in a big bank with a lot of money transactions everyday. #~ Your boss gave you a task to increase the stability of your system. #~ After some thinking you came up with the following way for determining #~ the stability of the set of transactions: if you have n transactions, #~ ith of which was made for transactionsi dollars, #~ the stability coefficient is equal to the minimum to maximum #~ transaction amount ratio - the higher it is, #~ more stable all transactions are. For example, if transaction amounts #~ are transactions = [3, 6, 3, 4, 2], the stability coefficient is #~ equal 2 / 6 = 1 / 3, because the minimal transaction has amount #~ 2 dollars and maximal - 6 dollars. #~ To optimize the stability coefficient you decided to split up some #~ transactions into two parts. You can take any transaction for x dollars #~ and split it up into two parts y and z so that y + z = x #~ (note that y and z don't have to be integers - for example, #~ you can split x = 100 into y = 24.66 and z = 75.34). #~ But you can't split up one transaction more than once - otherwise it #~ will be quite suspicious. Given the array transactions representing #~ the amount of all transactions made in your bank yesterday, return #~ the maximal possible stability coefficient that can be obtained using #~ your optimizations. #~ Example #~ For transactions = [2, 2, 2], the output should be #~ transactionsStability(transactions) = 1.0. #~ The initial stability coefficient is equal 1.0 and can't be made bigger. #~ For transactions = [1, 2, 3], the output should be #~ transactionsStability(transactions) = 0.66667. #~ 3 can be splitted into 1.5 and 1.5 and 2 can be splitted into 1 and 1, #~ after that stability coefficient will be equal 1 / 1.5 = 0.(6). #~ Input/Output #~ [time limit] 4000ms (py3) #~ [input] array.integer transactions #~ Array, containing amounts of transactions made in your bank yesterday. #~ Guaranteed constraints: #~ 1 <= transactions.length <= 5.105, #~ 1 <= transactions[i] <= 104. #~ [output] float #~ The maximum value of stability coefficient. Your answer will be #~ considered correct if its absolute error doesn't exceed 10-5. def transactionsStability(transactions): t = list(set(transactions)) a = max(t)/2 t += [a] t.sort(reverse=True) t = t[1:] if a >min(t): return min(t)/a elif a==min(t): return 1 else: return a/min(t) transactions = [12, 9, 7, 6, 5] a = transactionsStability(transactions) print(a) import numpy as np def transactionsStability(transactions): t = np.array(transactions) half = t/2 if max(half)>=min(t): return min(t)/max(half) else: return min(t)/max(t)
43b2a69cc9becf71e19bc8ea5bbbf8ec3ffb7151
TomiSar/ProgrammingMOOC2020
/osa09-11_havaintoasema/src/havaintoasema.py
1,454
3.6875
4
# Luokan kaikkien attribuuttien pitää olla asiakkaalta piilossa. Saat itse päättää luokan sisäisen toteutuksen. # Havaintoasema, johon voidaan tallentaa säähavaintoja nimi (str), havainnot (int) ja viimeisin havainto (str) class Havaintoasema: def __init__(self, nimi: str): self.__nimi = nimi self.__havainnot_lkm = 0 self.__viimeisin_havainto = "" # metodi, joka lisää havainnon listan peräään def lisaa_havainto(self, havainto: str): self.__viimeisin_havainto = havainto self.__havainnot_lkm += 1 # metodi, joka palauttaa viimeksi lisätyn havainnon. Jos havaintoja ei ole tehty, metodi palauttaa tyhjän merkkijonon. def viimeisin_havainto(self): return self.__viimeisin_havainto # metodi, joka palauttaa havaintojen yhteismäärän def havaintojen_maara(self): return self.__havainnot_lkm # metodi, joka palauttaa aseman nimen ja havaintojen yhteismäärän alla olevan esimerkin mukaisessa muodossa. def __str__(self): return f"{self.__nimi}, {self.__havainnot_lkm} havaintoa" #main if __name__ == "__main__": asema = Havaintoasema("Kumpula") asema.lisaa_havainto("Sadetta 10mm") asema.lisaa_havainto("Aurinkoista") print(asema.viimeisin_havainto()) asema.lisaa_havainto("Ukkosta") print(asema.viimeisin_havainto()) print(asema.havaintojen_maara()) print(asema)
bfd4f6527a8e8a6a45b089399e8fdff0f900660a
lucashsbarros/Python_Curso
/Mundo 1/aula 08a UTILIZANDO MODULOS.py
1,374
4.59375
5
''' Nessa aula, vamos aprender como utilizar módulos em Python utilizando os comandos import e from/import no Python. Veja como carregar bibliotecas de funções e utilizar vários recursos adicionais nos seus programas utilizando módulos built-in e módulos externos, oferecidos no Pypi.''' '''Importa todas as "bebidas e doces" import bebida import doce Importar apenas 1 item, no caso abaixo seria o pudim from doce import pudim Exemplo de bibliote comum MATH >> math ceil - arredonda para cima floor - arredonda para baixo trunc - truncar o numero, elimina o numero após a virgula pow - potencia sqrt - calcula a raiz quadrada factorial - calcula fatoriais Se eu colocar o comando > import math < o sistema irá importar todas as funcões acima Para importar apenas um modulo > from math import sqrt < Para importar um ou mais modulo > from math import sqrt, pow < ''' '''import math num = int(input('Digite um número: ')) raiz = math.sqrt(num) print('A raiz de {} é igual a {:.2f}.'.format(num,raiz))''' '''from math import sqrt, floor num = int(input('Digite um número: ')) raiz = sqrt(num) print('A raiz de {} é igual a {:.2f}.'.format(num,floor(raiz)))''' '''import random num = random.randint(1, 10) print(num)''' import emoji print(emoji.emojize('Olá, Mundo! :earth_americas:', use_aliases=True))
340f27c3bbae962830f73671578325af1a2917fc
chamoddissanayake/Video-Editor-QA-Extractor
/model/speaker.py
378
3.5
4
class Speaker: def __init__(self): self.lecturerCount = 0 self.studentCount = 0 def increaseLecturerCount(self): self.lecturerCount += 1 def increaseStudentCount(self): self.studentCount += 1 def ifLecturer(self): if self.lecturerCount > self.studentCount: return True else: return False
a27ecb663f41e2421771329f8a8387340897bf4a
Marcopy123/EMDR
/Desktop/EMDR/EMDR.py
1,385
3.578125
4
import pygame import time pygame.init() FPS = 120 fpsClock = pygame.time.Clock() WIDTH = pygame.display.Info().current_w HEIGHT = pygame.display.Info().current_h screen = pygame.display.set_mode((WIDTH, HEIGHT)) done = False pos = [int(WIDTH/2), int(HEIGHT/2)] ballColor = (42, 68, 148) backgroundColor = (121, 199, 197) speedOfCircle = 50 radius = 50 numberOfLoops = 0 def moveCircle(screen, backgroundColor, color, position, radius): pos[0] += speedOfCircle # moves the ball onthe x axis using the speedOfCircle screen.fill(backgroundColor) # fills the screen with black ball = pygame.draw.circle(screen, color, position, radius) # draws the circle on the screen, in white, with the new position, and the radius while not done: numberOfLoops += 1 moveCircle(screen, backgroundColor, ballColor, pos, radius) if pos[0] <= radius or pos[0] + radius >= WIDTH: # if the ball touched the edges speedOfCircle = -speedOfCircle # change the speedOfCircle to -speedOfCircle if numberOfLoops >= 800: moveCircle(screen, backgroundColor, ballColor, pos, radius) if pos[0] <= radius or pos[0] + radius >= WIDTH: speedOfCircle = -60 for event in pygame.event.get(): if event.type == pygame.QUIT: done = True pygame.display.flip() fpsClock.tick(FPS) pygame.display.update()
1d5c069f108d49b463a047d002bbdfb76626088e
zjphftl/pychildren
/group2/pavement/main.py
681
3.515625
4
import pygame, sys pygame.init() screen = pygame.display.set_mode((480, 320)) class Tile(pygame.sprite.Sprite): def __init__(self, image): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(image) self.rect = self.image.get_rect() self.rect.bottom = 320 self.speed = 1 pavement = pygame.sprite.Group() for x in range (0, 480 + 32, 32): tile = Tile("pavement.png") tile.rect.left = x pavement.add(tile) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() pavement.draw(screen) pygame.display.update()
23031f003a00ca6a0ea0a3879e343ad11862d6eb
ishaniray/Python-Basics
/rovarspraket.py
2,037
4.125
4
""" Rövarspråket (English: The Robber Language) is a Swedish language game. Every consonant is doubled, and an 'o' is inserted in-between. Vowels are left intact. For example, 'stubborn' in Rövarspråket would be expressed as 'sostotubobboborornon'. """ # Function to check if the character passed is a vowel def isVowel(c): c = c.lower() if(c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u'): return True else: return False # end of isVowel # Function to check if the character passed is a punctuation mark def isPunctuation(c): if(c == ' ' or c == ',' or c == ';' or c == '.' or c == '!' or c == '-' or c == '"' or c == '\'' or c == ':' or c == '(' or c == ')'): return True else: return False # end of isPunctuation choice = int(input("ROVARSPRAKET\n------------\n\n1. Encode\n2. Decode\n\nEnter your choice (1 or 2): ")) if choice == 1: string = input("\nEnter a string: ") rs_list = [] # list to hold output for letter in string: if isVowel(letter) or isPunctuation(letter): rs_list.append(letter) else: rs_list.append(letter) rs_list.append('o') rs_list.append(letter) rs_string = ''.join(rs_list) # converting list to string if string.isupper(): rs_string = rs_string.upper() print("\n" + string + " in Rövarspråket: " + rs_string) else: rs_string = input("\nEnter a Rövarspråket string: ") str_list = [] # list to hold output i = 0 while i < len(rs_string): str_list.append(rs_string[i]) if isVowel(rs_string[i]) or isPunctuation(rs_string[i]): i = i + 1 else: i = i + 3 # if a consonant is encountered, skip the next two letters string = ''.join(str_list) # converting list to string if rs_string.isupper(): string = string.upper() print("\nThe decoded string is: " + string) # end of program
b28bb1ed72898f4b61787cf2ec04577dc0685abb
Erritro/zadania_p
/zadanie23.py
793
3.828125
4
# Napisz funkcję, która pobiera # macierz i oblicza średnią wszystkich # jej elementów wiersze = int(input("Podaj liczbę wierszy macierzy: \n")) macierz = [] def srednia(macierz): lista = [] #lista to macierz spłaszczona do 1 wymiaru for wiersz in range(len(macierz)): for kolumna in range(len(macierz[wiersz])): lista.append(macierz[wiersz][kolumna]) return sum(lista)/len(lista) for i in range(wiersze): w = input("Podaj elementy " + str(i+1) + " wiersza oddzielone spacją: ") w = w.split(" ") w = [int(i) for i in w] # zmieniam elementy na str macierz.append(w) # dodaję całą liste jako pierwszy wiersz print("Średnia wszystkich elementów macierzy: ", srednia(macierz))
54fc05d0bad363e1aa47e1621c4bff8fb74e6bde
phyogitty/rass-ciscohackathon
/track1/buildDatabase.py
1,473
3.53125
4
import sqlite3 import mysql.connector # TODO: Write proper documentation class DatabaseHandler: def __init__(self): self.conn = sqlite3.connect('rass.db') self.cur = self.conn.cursor() self.cur.execute(""" CREATE TABLE IF NOT EXISTS emails( id INT PRIMARY KEY, label_ids TEXT, date TEXT, fro TEXT, recv TEXT, subject TEXT, body TEXT ) """) self.conn.commit() # Checking that the table was created exists = self.cur.execute("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='emails'") if not exists: raise Exception def close(self): self.conn.commit() self.conn.close() def insert(self, message): """ WARNING: Security not tested, use at your own risk! """ labs = ''.join(message['labelIds']) dat = message['date'] fro = message['from'] recv = message['to'] subj = message['subject'] bod = message['body'] self.cur.execute(""" INSERT INTO emails (label_ids, date, fro, recv, subject, body) VALUES (?,?,?,?,?,?) """, (labs, dat, fro, recv, subj, bod)); self.conn.commit() return self.cur.rowcount # TODO: Set up procedure for adding new emails to the machine def retrieveNext(self): """ :return: """ print()
7c0a8bf323ebd2e147f2a26ff4546eb7f9c05d2d
nsbhoangmai/Ph20
/load.py
298
3.6875
4
def load_num(filename): """ Load variables x0, v0, t, h from a plain-text file and return these as a list. """ with open(filename) as vari: A0 = vari.read().split() A1 = [] for i in A0: i1 = float(i) A1.append(i1) return A1
b1d78a7dde7d8c2f39256d180b884267ea145a56
Rijipuh/pythonCIT
/Class/Python/numberTypes.py
582
3.84375
4
x = 1 y = 2.8 z = 1j print(type(x)) print(type(y)) print(type(z)) stringThree = "3" numberThree = 3 stringTwo = "2" numberTwo = 2 print (numberTwo + numberThree) print( stringTwo + stringThree) # print(numberTwo + stringTwo) : this code is not working becuase it adds string with number. # stringTwo = int(2) : not good enough print (int(stringTwo) + numberTwo) print(stringThree + str(numberThree)) a = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" print(a) a = "Hello, World!" print(a[0])
46157989652007add3e453a4da2ee08605cc8deb
jennyyu73/projecteuler
/truncatablePrimes.py
702
3.859375
4
def isPrime(n): if n < 2: return False elif n == 2: return True elif n % 2 == 0: return False maxFactor=round(n**0.5) for i in range(3, maxFactor+1, 2): if n % i == 0: return False return True def isRightTruncatablePrime(n): while n > 0: if not isPrime(n): print(n) return False n=n//10 return True def isLeftTruncatablePrime(n): strN=str(n) while strN != "": if not isPrime(int(strN)): return False strN=strN[1:] return True count=0 guess=10 primeSum=0 while count != 11: guess += 1 if isRightTruncatablePrime(guess) and isLeftTruncatablePrime(guess): count += 1 primeSum += guess print(count) print(primeSum)
0303d3442ddc58878d25b0a316b3a7b1912befb5
parksjsj9368/TIL
/ALGORITHM/BAEKJOON/SOURCE/02. Implemented(구현)/12. 문자가 몇갤까.py
136
3.671875
4
import re while 1: data = input() if data == '#': break print(len(set(re.sub('[^A-Z]', '', data.upper()))))
0e709f1b933447d013b954ca3e28cda2b40da513
Darya1501/Python-course
/lesson-14/Password-generator.py
2,848
3.765625
4
import random def ask_question(question, sets): global enabled_chars print('Если в пароле нужны', question, 'введите Да: ') answer = input().lower() if answer.strip() == 'да': enabled_chars += sets def generate_password(length, chars): password = ' ' if length > 0: for i in range(length): random_index = random.randint(0, len(chars)-1) password += chars[random_index] return password print('\nПривет. Я - генератор паролей. \nЯ задам несколько уточняющих вопросов,на основе которых сгенерирую пароль. \nДавай начнем!', end='\n\n') while True : print('Сколько паролей вы хотите сгенерировать? Введите число: ') count = input() if count.isdigit() and int(count) > 0: count = int(count) else: print('Неверный ввод, будет сгенерирован 1 пароль') count = 1 print('Введите длину паролей:') length = input() if length.isdigit() and int(length) > 0: length = int(length) else: print('Неверное значение длины, будут сгенерировны пароли длиной 7 символов') length = 7 enabled_chars = '0' digits = '1234567890' latin_lowercase_letters = 'abcdefghijklmnopqrstuvwxyz' latin_uppercase_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' russian_lowercase_letters = 'абвгдеёжзиклмнопрстуфхцчшщъыьэюя' russian_uppercase_letters = 'АБВГДЕЁЖЗИКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ' punctuation = '!#$%&*+-=?@^_' ask_question('цифры,', digits) ask_question('строчные латинские буквы,', latin_lowercase_letters) ask_question('заглавные латинские буквы,', latin_uppercase_letters) ask_question('строчные русские буквы,', russian_lowercase_letters) ask_question('заглавные русские буквы,', russian_uppercase_letters) ask_question('знаки пунктуации,', punctuation) for i in range(count): password = generate_password(length, enabled_chars) print('Сгенерированный пароль:', password) again = input('Еще раз? Да / нет: ') .lower() if again == 'нет': break elif again == 'да': continue else: print('Неизвестное значение, игра прекращена') break print('До новых встреч!')