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
98e28e359e25217a5e70f2c9669fab5d302f4f24
zhouyuhangnju/freshLeetcode
/Length of Last Word.py
319
3.9375
4
def lengthOfLastWord(s): """ :type s: str :rtype: int """ words = s.split(' ') res = 0 for i in range(len(words)-1, -1, -1): if len(words[i]) > 0: res = len(words[i]) break return res if __name__ == '__main__': print lengthOfLastWord('aaaa ')
64a2774b9be616d89077fdea4c6cffb974272981
zhouyuhangnju/freshLeetcode
/Multiply Strings.py
764
3.578125
4
def multiply(num1, num2): """ :type num1: str :type num2: str :rtype: str """ res = [0] * (len(num1) + len(num2)) for i in range(len(num1)-1, -1, -1): carry = 0 for j in range(len(num2)-1, -1, -1): print i, j, tmpres = int(num1[i]) * int(num2[j]) + carry print tmpres carry, res[i + j + 1] = divmod(res[i + j + 1] + tmpres, 10) res[i] += carry print res res = ''.join(map(str, res)) return '0' if not res.lstrip('0') else res.lstrip('0') if __name__ == '__main__': print multiply("581852037460725882246068583352420736139988952640866685633288423526139", "2723349969536684936041476639043426870967112972397011150925040382981287990380531232")
99f280cbf763611fd31ef647fe6aab135d54155a
zhouyuhangnju/freshLeetcode
/Best Time to Buy and Sell Stock.py
337
3.859375
4
def maxProfit(prices): """ :type prices: List[int] :rtype: int """ buyprice = 2**31-1 profit = 0 for i in range(len(prices)): buyprice = min(buyprice, prices[i]) profit = max(profit, prices[i] - buyprice) return profit if __name__ == '__main__': print maxProfit([7, 1, 5, 3, 6, 4])
1936d952a8761e5e73c9946fdc7d9bdc37886e9f
zhouyuhangnju/freshLeetcode
/Pascal's Triangle.py
480
3.578125
4
def generate(numRows): """ :type numRows: int :rtype: List[List[int]] """ res = [] if numRows <= 0: return res res.append([1]) for i in range(1, numRows): preres = res[-1] currres = [] currres.append(1) for j in range(len(preres)-1): currres.append(preres[j]+preres[j+1]) currres.append(1) res.append(currres) return res if __name__ == '__main__': print generate(5)
0437daed01bce0f5a3046616917a2c29a1ed15d0
zhouyuhangnju/freshLeetcode
/Combination Sum.py
1,252
3.71875
4
def combinationSum(candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ res = [] candidates = sorted(candidates) def combinationRemain(remain, curr_res): if remain == 0: res.append(curr_res) return for c in candidates: if c > remain: break if curr_res and c < curr_res[-1]: continue combinationRemain(remain - c, curr_res + [c]) combinationRemain(target, []) return res def combinationSum2(candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ res = [] candidates = sorted(candidates) def combinationRemain(remain, curr_res, curr_idx): if remain == 0: res.append(curr_res) return if remain < 0 or curr_idx >= len(candidates): return combinationRemain(remain-candidates[curr_idx], curr_res+[candidates[curr_idx]], curr_idx) combinationRemain(remain, curr_res, curr_idx + 1) combinationRemain(target, [], 0) return res if __name__ == '__main__': print combinationSum2([2, 3, 6, 7], 7)
de630b1e32d6ef9285d0b52a41c44c21395469b7
teckMUk/CodeWars
/RomanNumbers/RomanNumbers.py
1,499
3.609375
4
import sys def solution(n): # TODO convert int to roman string roman_dict = {1:"I",5:"V",10:"X",50:"L",100:"C",500:"D",1000:"M"} x = str(n) roman_value = "" for num in reversed(range(len(x))): postion = pow(10,num) res = int(n/postion) res = res*postion if res==0: continue n = int(n%postion) if res in roman_dict.keys(): roman_value += roman_dict[res] else: prevkey,nextkey = findsymbolkey(roman_dict,res) counter = 0 if prevkey==postion: counter+=1 z = prevkey while z!=res: z+=postion counter+=1 if counter>3: differnce = int((nextkey-res)/postion) roman_value += roman_dict[postion]*differnce roman_value+= roman_dict[nextkey] else: roman_value += roman_dict[prevkey] if prevkey==postion: counter-=1 roman_value += roman_dict[postion]*(counter) return roman_value def findsymbolkey(x,value): prev = 0 for num in x.keys(): if value < num: return (prev,num) prev = num return (prev,prev) #takes argument from cmd def main(args=None): if args is None: args = int(sys.argv[1]) print("Your Roman Numeric is: ",solution(args)) if __name__ == "__main__": main()
4e3523f91eb5fbc31870525547e6cdbb2288e39c
Code4Bugs/APSSDC-Python-Training-2019
/function.py
257
3.796875
4
def star(n): return "* "*n for i in range(6): for j in range(6): if i<=j: print(star(j)+" ") break for i in range(6): for j in range(6): if j<=i: print(star(5-i)) break
2f2020646ec5fd3b3b9a2b86819e568ac3acbb2c
Code4Bugs/APSSDC-Python-Training-2019
/whileloop.py
95
3.84375
4
n=int(input("enter number : ")) i=1 sum=0 while i<=n: sum=sum+i i+=1 print(sum)
589622c55a74eca1fc73975a0a765d941516878c
wohao/cookbook
/file5_1.py
1,759
3.515625
4
with open('somefile.txt','wt') as f: f.write('I Love You') f = open('somefile.txt','rt') data = f.read() f.close() with open('D:\python\cookbook\somefile.txt','wt') as f: print('Hello world!',file=f) print('ACME',50,91.5) print('ACME',50,91.5, sep='') print('ACME',50,91.5, sep=',') print('ACME',50,91.5, sep='',end='!!\n') for i in range(5): print(i,end=' ') rows = ('ACME',50,91.5) print(','.join(str(x) for x in rows)) print(*rows,sep=',') with open('somefile.bin','wb') as f: f.write(b'Hello world') with open('somefile.bin','rb') as f: data = f.read() print(data) b = b'hello world' for c in b : print(c) with open('somefile.bin','wb') as f : text = 'I love you' f.write(text.encode('utf-8')) with open('somefile.bin','rb') as f: data =f.read(16) text = data.decode('utf-8') print(text) import array nums = array.array('i',[1,2,3,4]) with open('data.bin','wb') as f: f.write(nums) a = array.array('i',[0,0,0,0,0,0,0]) with open('data.bin','rb') as f: f.readinto(a) print(a) # with open('D:\python\cookbook\somefile.txt','xt') as f: # f.write('I love you') import os if not os.path.exists('D:\python\cookbook\somefile.txt'): with open('D:\python\cookbook\somefile.txt','wt') as f: f.write('I love you') else: print('file already exists') import io s = io.StringIO() s.write('hello world\n') print('this is a test',file=s) print(s.getvalue()) s =io.StringIO('Hello\nworld\n') print(s.read(4)) print(s.read()) s = io.BytesIO() s.write(b'binary data') print(s.getvalue()) import gzip with gzip.open('somefile.gz','rt') as f: #f.write(text) text = f.read() print(text) import bz2 with bz2.open('somefile.bz2','wt') as f: f.write(text) f = open('somefile.gz','rb') with gzip.open(f,'rt') as g: text = g.read()
fb801c2f3b6afaab1a64650d8a10811d0726a5e7
wohao/cookbook
/counter1_12.py
563
4.15625
4
from collections import Counter words = [ 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', "you're", 'under' ] word_counters = Counter(words) top_three = word_counters.most_common(3) print(top_three) morewords = ['why','are','you','not','looking','in','my','eyes'] # for word in morewords: # word_counters[word] += 1 word_counters.update(morewords) print(word_counters['eyes'])
33786128937eb324ac6fed3d932c6ee6d3cc9e70
nsambold/solutions
/codewars/Python/5kyu/anagrams.py
491
4.09375
4
# anagrams.py __author__ = awakenedhaki from typing import List def anagrams(word: str, words: List[str]) -> List[str]: ''' Returns all anagrams of a word in a list of words. :param word: str :param words: List of str :return: Returns a list of words that are anagrams ''' word: str = sorted(word) anagrams: List[str] = [] for s in words: letters: str = sorted(s) if word == letters: anagrams.append(s) return anagrams
34ce63cd53249aba4a901cf6324418641fb2c822
masterace007/codeforces_harwest
/atcoder/abc186/C.py
461
3.734375
4
n = int(input()) count_7_decimal = 0 count_7_octal = 0 count = n; text = "" common_od = set() for i in range(1,n+1): text = str(i); if '7' in text: common_od.add(i) #count_7_decimal = count_7_decimal + 1 text = "" for i in range(1,n+1): text = str(oct(int(i))); if '7' in text: common_od.add(i) #count_7_octal = count_7_octal + 1 length_of_common = len(common_od); count = count - length_of_common; print(count)
afcfc4ab4dd8196bfe5ab57ae2ebe2a064e3840e
Im-Hal-9K/python_training
/ex40.py
707
3.78125
4
# This is the fortieth exercise. # Date: 2014-06-27 class Song(object): def __init__(self, lyrics): self.lyrics = lyrics def sing_me_a_song(self): for line in self.lyrics: print line def length(self): print len(self.lyrics) happy_bday = Song(["Happy birthday to you","I don't want to get sued", "So I'll stop right there."]) bulls_on_parade = Song(["They rally around the family", "With pockets full of shells"]) song_variable = ["First line", "Second line", "Third line"] song_var = Song(song_variable) song_var.sing_me_a_song() song_var.length() happy_bday.sing_me_a_song() bulls_on_parade.sing_me_a_song()
df4a4165ed70cee917e537eb19b1ed040703dbc7
Craby4GitHub/CIS129
/Mod 2 Pseudocode 2.py
2,879
4.3125
4
######################################################################################################################## # William Crabtree # # 27Feb17 # # Purpose: To figure out what the user will do for a week long vaction based on certain perferances # # and money avaiablity. # ######################################################################################################################## # Setting trip values florence = 1500 staycation = 1400 camping = 240 visitingParents = 100 kayakinginLake = 100 print("Oh, you are going on a vacation? Lucky you!") print("So we need to ask how much money you have to spend on this vacation") totalMoney = int(input("What disposable income do you have for this trip? ")) print("Ok, now that we know how much you have, lets figure out what some of your perferences are.") # Then we start asking questions goingAbroad = input("What about going abroad? ") if goingAbroad == "y": if florence <= totalMoney: print("Hey, you can go to Florence!") print("Going to Florence will cost a total of", florence) else: print("You can't go abroad because it will cost", florence) drivingLongDistance = input("Are you willing or capable of driving a long distance? ") if drivingLongDistance == "y": alone = input("Do you want to be alone? ") if alone == "y": if kayakinginLake <= totalMoney: print("You can go Kayaking in a remote lake.") print("That will only cost you gass money in the total of", kayakinginLake) else: print("You can't afford Kayaking in a lake becauseit costs", kayakinginLake) if camping <= totalMoney: print("You can go camping in a park.") print("That will cost you a total of", camping) else: print("You can't go camping because it costs", camping) if alone == "n": if visitingParents <= totalMoney: print("You can vist your parents, they miss you.") print("The only thing you need to buy is gas with a total cost of", visitingParents) else: print("You can't visit your parents because it costs", visitingParents) elif drivingLongDistance == "n": if staycation <= totalMoney: print("Hey, you can do a Staycation at a nearby resort.") print("A Staycation will cost you a total of", staycation) else: print("You cant do a Staycation because it costs", staycation)
4b1ae200aa26d0259e03ec346abdb42c4671b26b
Craby4GitHub/CIS129
/Final/Final.py
2,265
4.1875
4
######################################################################################################################## # William Crabtree # # 26Apr17 # # Purpose: The magic Triangle! # ######################################################################################################################## # Create list to show user where their input goes usersNum = ["First Entry", "Second Entry", "Third Entry"] genNum = ['Empty', 'Empty', 'Empty'] # Define how the triangle prints out def triangle(): # Basically, centering of the triangle so it always looks like a triangle fourth = '({}) [{}] ({})'.format(genNum[0], usersNum[1], genNum[2]) second = '[{}]'.format(usersNum[2]).center(int(len(fourth)/2), ' ') third = '[{}]'.format(usersNum[0]).center(int(len(fourth)/2), ' ') first = '({})'.format(genNum[1]).center(int(len(second) + len(third)), ' ') print(first) print(second, end="") print(third) print(fourth) def UserLoop(): # Loop three times for i in range(3): # Error Catch try: # Ask user for a number number = int(input("Enter a number between -40 and 40: ")) # if users number is less than -40 or greater than 40, kick em out if -40 <= number <= 40: usersNum[i] = number else: print("Number was not in the correct range.") print(len(usersNum)) exit() except ValueError: print("You did not enter a valid number.") exit() def Math(): # Get the total sum of numbers inputted and half it totalSum = int(sum(usersNum))/2 # Subtract the sum from the opposite number and input that value into genNum for generatedNumber in range(3): genNum[generatedNumber] = totalSum - int(usersNum[generatedNumber]) print("Here is the triangle:") triangle() UserLoop() Math() print("Here is your final triangle.") triangle()
0c6fcf179c696e2456889b9b608c3a40acc0d2e3
WarrenJames/LPTHWExercises
/morecodecademy.py
1,526
3.953125
4
# Conditional Statement Syntax """ 'if' is a conditional statement that executes some specified code after checking if its expression is True """ # define function(): which consists of # if True: return to the user "Success #1" def using_control_once(): if 32 <= 4**4: return "Success #1" # define function(): which consists of # if not False: return to the user "Success #1" def using_control_again(): if not 50 > 5**5: return "Success #2" print using_control_once() print using_control_again() """ An if/else pair says 'if this expression is true, run this indented code block; otherwise, run this code after the else statement'. Unlike if, else doesn't depend on an expression""" """Elif is short for 'else if' which means 'otherwise, if the following expression is true, do this'.""" def greater_less_equal_5(answer): if answer > 5: return 1 elif answer < 5: return -1 else: return 0 print greater_less_equal_5(4) print greater_less_equal_5(5) print greater_less_equal_5(6) """ define power(with two arguments): consists of result variable is equal to first argument to the power of second argument and prints "%\digit placeholder to the power of %\digit placeholder is %\digit placeholder" %\ placeholders are (first argument, second argument, and result variable) """ def power(base, exponent): result = base**exponent print "%d to the power of %d is %d." % (base, exponent, result) # calls power funtion with arguments as 37 and 4 power(37,4)
75c9f003fff66ac0040f72abcbf582ebeb098632
WarrenJames/LPTHWExercises
/exl12.py
950
3.84375
4
# Excercise 12: Prompting People # variable age is equal to raw_input with prompt of "How old are you? " age = raw_input("How old are you? ") # variable height is equal to raw_input with prompt of "How tall are you? " height = raw_input("How tall are you? ") # variable weight is equal to raw_input with prompt of "How much do you weigh? " weight = raw_input("How much do you weigh? ") # %r is equal to variables age, height, and weight. print "So you're %r old, %r tall and %r pounds." % (age, height, weight) # prints as "So you're" (user inputed information) old, (user inputed # information) tall and (user inputed information) pounds. # Study Drill # On windows powershell type python -m pydoc (file name) # pydoc command provides information from documentation for python # commands can be found at c:\Python27\Lib\(enter command here) # example of commands (open, file, os, and sys) # get out of pydoc by typing 'q' to quit
b0666fa53d392b325bafe7d6ae5f9f259cda7a13
WarrenJames/LPTHWExercises
/numgame.py
826
3.90625
4
import random secretNum = random.randint(1, 10) guesses = [] def game(): while len(guesses) < 5: try: guess = int(raw_input("Guess a number between 1 and 10: ")) except ValueError: print "That isn't a number." else: if guess == secretNum: print "You got it! The number was %d" % secretNum break elif guess < secretNum: print "Too low, try something higher." else: print "Too high, try something lower." guesses.append(guess) else: print "You did not get it, number was: %d" % (secretNum) play_again = raw_input("Do you want to play again: Y/N? ") if play_again.lower() != 'n': game() else: print "Exiting game." game()
0c7c129434bb1a73f9d5e70413356a68ccbe6541
WarrenJames/LPTHWExercises
/exl38.py
2,061
4.09375
4
# Exercise 38: Doing things to Lists import random # creates variable with string of text "Apples Oranges Crows Telephone Light Sugar" ten_things = "Apples Oranges Crows Telephone Light Sugar" # prints "Wait there are not 10 things in that list. Let's fix that." print "Wait there are not 10 things in that list. Let's fix that." # stuff variable is equal to ten_things variable with .split function(' ') # Argument lets split know to split string every time it finds a space. stuff = ten_things.split(' ') # more_stuff is equal to list made up of: # Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy" more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] """ while length of stuff variable is not equal to 10: next_one variable is equal to more_stuff with .pop() function to remove first entry. prints "Adding: ", next_one variable ("Adding: Day") stuff variable with .append function to append(next_one) variable to list. prints "There are %\digit items now." %\ len of (stuff) variable repeats until length of stuff variable is == to 10. """ while len(stuff) != 10: next_one = more_stuff.pop() print "Adding: ", next_one stuff.append(next_one) print "There are %d items now." % len(stuff) # prints "There we go: ", stuff variable print "There we go: ", stuff # prints "Let's do some things with stuff." print "Let's do some things with stuff." # prints stuff[1] spot 1 in list. or "Oranges" print stuff[1] # prints stuff[-1] last spot on list. or "Corn" print stuff[-1] # prints stuff.pop() pops the last spot on the list. Which is "Corn" print stuff.pop() # prints ' '.join(stuff). joins all list items using a space. print ' '.join(stuff) # prints '#'.join(stuff[3:5]) or joins items from stuff variable that are from # spot 3 to (but not including) 5. or Telephone#Light print '#'.join(stuff[3:5]) itemlist = ['alpha', 'bravo', 'charlie', 'apple'] def loopy(items): for i in items: if i[0] == 'a': continue else: print i loopy(itemlist)
f5f85d737006dc462254a2926d4d7db88db72cb6
WarrenJames/LPTHWExercises
/exl9.py
1,005
4.28125
4
# Excercise 9: Printing, Printing, Printing # variable "days" is equal to "Mon Tue Wed Thu Fri Sat Sun" days = "Mon Tue Wed Thu Fri Sat Sun" # variable "months" is Jan Feb Mar Apr May Jun Aug seperated by \n # \n means words written next will be printed on new a line months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nAug" # prints string of text "Here are the days: " and varible, days print "Here are the days: ", days # prints as "Here are the days: Mon Tue Wed Thu Fri Sat Sun" print "Here are the months: ", months # prints as "Here are the months: # Jan # Feb # Mar # Apr # Jun # Aug # prints """ triple double-quotes which is a long string capable of printing on multiple lines. print """ There's something going on here. With the three double-quotes. We'll be able to type as much as we like. Even 4 lines if we want, or 5 , or 6. """ # prints as # "There's something going on here. # With the three double-quotes. # We'll be able to type as much as we like. # Even 4 lines if we want, or 5 , or 6."
64303bcf3bb4a4f8750babc4a23940d19bcf1366
WarrenJames/LPTHWExercises
/exl19redone.py
1,370
4.03125
4
# Exercise 19: Study drill # Create a function of my own design and run it 10 different ways from sys import argv script, filename = argv def bottles_of_beer(on_the_wall, bottles_to_go): print """%s bottles of beer on the wall\n%s bottles of beer! Take one down, pass it around %s bottles of beer""" % (on_the_wall, on_the_wall, bottles_to_go) bottles = 99 bottlesLeft = bottles - 1 bottlefile = open(filename, 'r') bottles95 = bottlefile.read() bottles94 = 94 bottles_of_beer(bottles, bottlesLeft) bottles_of_beer(99 - 1, 98 - 1) bottles_of_beer(97, 96) bottles_of_beer(96, bottles95) bottles_of_beer(bottles95, bottles94) bottles_of_beer('94', '93') bottlefile.close # Today I Learned: # refer to lines 13 and 14. File must be opened before being read # consider python reading the code in numerical order. make a variable # open the filename in read mode before making a variable to have bottlefile # with the reader decimal operator with no parameters # ie. open(filename, 'r') comes before bottlefile.read() # when refering to a read file in an expression anything written is referred to # as a string. # ie. the number 95 written in file will not work with %d # # you cannot use /n linebreaks in expressions # ie. bottles_of_beer(96, bottles95\n) # you are able to call a function within a function
e6f1bf912c575ed81b4b0631514ee67943a26f2f
WarrenJames/LPTHWExercises
/exl18.py
1,977
4.875
5
# Excercise 18: Names, Variables, Code, Functions # Functions do three things: # They name pieces of code the way variables name strings and numbers. # They take arguments the way your scripts take argv # Using 1 and 2 they let you make your own "mini-scripts" or "tiny commands" # First we tell python we want to make a function using def for "define". # On the same line as def we give the function a name. In this case we just # called it print_two but it could also be "peanuts". It doens't matter, # except that the function should have a short name that says what it does. # without the asterisk, python will believe print_two accepts 1 variable. # Tells python to take all the arguments to the function and then put them in # args as a list. It's like agrv but for functions. not used too # often unless specifically needed ## def print_two(*args): ## arg1, arg2 = args ## print "arg1: %r, arg2: %r" % (arg1, arg2) # okay that *args is actually pointless # define(function) name is print_two_again(arg1, arg2): <-- don't forget the ":" # it tells what print_two_again consists of, which so happens to be printing # "Senor: (raw modulo), El: (raw modulo)" % modulo is (arg1, arg2) or # (James, Warren) def print_two_again(arg1, arg2): print "Senor: %r, El: %r" % (arg1, arg2) # this just takes one argument # define(function) print_one(variable arg1 which equals First): <-- consists of # print "the: %raw modulo" raw modulo is arg1 which is "first" def print_one(arg1): print "the: %r" % arg1 # this one takes no arguments # define print_none(): empty call expression consists of printing # "I got nothin'." def print_none(): print "I got nothin'." ## print_two("James","Warren") # lines 43 to 45 all call functions # calls print_two_again("James", "Warren") for arg1 and arg2 # calls print_one("First!") for arg1 # calls print_none() with no arguments print_two_again("James","Warren") print_one("First!") print_none()
fd90e5312f0798ca3eb88c8139bdd2fe17786654
SaloniSwagata/DSA
/Tree/balance.py
1,147
4.15625
4
# Calculate the height of a binary tree. Assuming root is at height 1 def heightTree(root): if root is None: return 0 leftH = heightTree(root.left) rightH = heightTree(root.right) H = max(leftH,rightH) # height of the tree will be the maximum of the heights of left subtree and right subtree return H+1 # +1 for the contribution of root # Check if tree is balanced or not def BalanceTree(root): if root is None: return True leftH = heightTree(root.left) rightH = heightTree(root.right) if abs(leftH-rightH)>1: return False isLeftBalance = BalanceTree(root.left) isRightBalance = BalanceTree(root.right) if isLeftBalance and isRightBalance: return True else: return False # Check if tree is balanced or not using single function def isBalanced(root): if root is None: return 0,True lh, leftisB = isBalanced(root.left) rh, rightisB = isBalanced(root.right) h = max(lh,rh)+1 if abs(lh-rh)>1: return h,False if leftisB and rightisB: return h,True else: return h,False
4af84efdf7b997185c340f2b69e7873d5b87df73
SaloniSwagata/DSA
/Tree/BasicTree.py
1,377
4.1875
4
# Creating and printing a binary tree # Creating a binary tree node class BinaryTreeNode: def __init__(self,data): self.left = None self.data = data self.right = None # Creating a tree by taking input tree wise (i.e, root - left subtree - right subtree) # For None, the user enters -1 def FullTreeInput(): rootdata = int(input()) if rootdata==-1: return None root = BinaryTreeNode(rootdata) leftChild = FullTreeInput() rightChild = FullTreeInput() root.left = leftChild root.right = rightChild return root # Printing tree simple way def printTree(root): if root==None: return print(root.data) printTree(root.left) printTree(root.right) # Detailed printing of tree def printDetailedTree(root): if root == None: return print(root.data, end=":") if root.left != None: print("L ",root.left.data, end=" ,") if root.right!=None: print("R ",root.right.data) print() printDetailedTree(root.left) printDetailedTree(root.right) # Counting the number of nodes in tree def numnodes(root): if root == None: return 0 left = numnodes(root.left) right= numnodes(root.right) return 1+left+right btn1 = BinaryTreeNode(2) btn2 = BinaryTreeNode(3) btn3 = BinaryTreeNode(4) btn1.left = btn2 btn1.right = btn3
c868093ac8ba3e14bad9835728fcc45598e0dfd5
SaloniSwagata/DSA
/Tree/levelOrder.py
1,309
4.25
4
# Taking input level order wise using queue # Creating a binary tree node class BinaryTreeNode: def __init__(self,data): self.left = None self.data = data self.right = None import queue # Taking Level Order Input def levelInput(): rootData = int(input("Enter the root node data: ")) if rootData ==-1: return None root = BinaryTreeNode(rootData) q = queue.Queue() q.put(root) while not(q.empty()): current_node = q.get() leftdata = int(input("Enter the left node data: ")) if leftdata!=-1: leftnode = BinaryTreeNode(leftdata) current_node.left = leftnode q.put(leftnode) rightdata = int(input("Enter the right node data: ")) if rightdata!=-1: rightnode = BinaryTreeNode(rightdata) current_node.right = rightnode q.put(rightnode) return root # Level Order Output def levelInput(root): if root is None: print("Empty tree") else: q = queue.Queue() q.put(root) while not(q.empty()): current_node = q.get() if current_node is not None: print(current_node.data,end=" ") q.put(current_node.left) q.put(current_node.right)
90120ad0fd9d5ffc0f4963c184a027fd32aa8f9d
SaloniSwagata/DSA
/Dynamic Programming/knapsack_memo.py
1,312
3.640625
4
#now we convert the recursive code into meoization #for memoization we have to make a matrix #where row and columns are the changable parameters arr = [] row = 4 #we take this value with the help of contstrains columns = 52 #this value also taken from constraints for i in range(row): col = [] for j in range(columns): col.append(-1) arr.append(col) def knapsackm(weights,profit,capacity,n,arr): if n==0 or capacity == 0: return 0 #here we write the memoization code for checking if the above value lies in the matrix or not #here n and capcaity are row and column if arr[n][capacity] != -1: return arr[n][capacity] if weights[n-1] <= capacity: #first we store the value in list which help in future if ask for same then we don't calculate arr[n][capacity] = max(profit[n-1]+knapsackm(weights,profit,capacity-weights[n-1],n-1,arr),knapsackm(weights,profit,capacity,n-1,arr)) return max(profit[n-1]+knapsackm(weights,profit,capacity-weights[n-1],n-1,arr),knapsackm(weights,profit,capacity,n-1,arr)) elif weights[n-1] > capacity: arr[n][capacity] = knapsackm(weights,profit,capacity,n-1,arr) return knapsackm(weights,profit,capacity,n-1,arr) weights = [10,20,30] profit = [60,100,120] capacity = 50 n = len(weights) print(knapsackm(weights,profit,capacity,n,arr))
064012613d9281287932b73cfd4db3c5d6055c83
woutboat/Project-Euler
/working/052.py
507
3.65625
4
def testMult(num, mux): return num * mux def sum_digits(n): s = 0 while n: s += n % 10 n //= 10 return s potato = True num = 125875 counter = 0 while potato: if sum_digits(num) == sum_digits(testMult(num, 2)): if sum_digits(num) == sum_digits(testMult(num, 3)): if sum_digits(num) == sum_digits(testMult(num, 4)): if sum_digits(num) == sum_digits(testMult(num, 5)): if sum_digits(num) == sum_digits(testMult(num, 6)): potato = False num += 1 print(num - 1) #answer 142857
526638e90298bbb4278bd5b234a375f931d59868
woutboat/Project-Euler
/027.py
988
3.734375
4
import time def primeFind(number): oldnum = number factor = 1 while number > 1: factor += 1 if number % factor == 0: if 1 < factor < oldnum: print("Returned False") return False # is not prime number //= factor return True # is prime! def count(numa, numb): su = 0 n = 0 tmp = 0 potat = True while potat == True: tmp = (n ** 2) + (numa * n) + numb if primeFind(abs(tmp)) == True: print(su) else: potat = False print("MADE FALSE") time.sleep(1) su = su + 1 for poo in range(0, 1000): tmp = (poo ** 2) + (numa * poo) + numb return(su) ma = 0 ars = 0 holder = 0 for i in range(-1000,1001): for o in range(-1000,1001): print("Checking: " + str(i) + ", " + str(o)) ars = count(i,o) if ars > ma: ma = ars holder = i * o print(holder)
80c5b40067d54f809a8dc24237b1aef8a77870b9
woutboat/Project-Euler
/working/029.py
282
3.875
4
#distinct answers for a^b where 2 <= a <= 100 and 2 <= b <= 100 numbers = [] for a in range(2,101): for b in range(2,101): print(str(a) + " " + str(b)) numbers.append(a ** b) print("Removing repeats") numbers = sorted(set(numbers)) print(str(len(numbers))) #Answeer 9183
7880ee09e3f4e8425a814265508135661127dada
arthurazs/uri
/c/1017.py
86
3.765625
4
time = int(input()) speed = int(input()) print('{:.3f}'.format((time * speed) / 12))
38b369d86a9fd1397d2edbfa25b9a7635b9d431c
kevhunte/Academic-Projects
/oop_city.py
2,292
3.890625
4
import random, sys firstnames = ['Bobby','James','Kevin','Lisa','Mary','Diane','Joan','Garret','Sila','Gordon','Michael','David'] lastnames = ['Johnson','Hunt','Katz','Marley','Roberson','Smith'] class Person(): population = 0 def __init__(self, first = None, last = None, age = None): if(first and last and age): #overloaded constructors self.first = str(first) self.last = str(last) self.name = str(first+' '+last) self.age = int(age) elif(first and last): self.first = str(first) self.last = str(last) self.name = str(first+' '+last) self.age = random.randint(1,86) else: self.first = firstnames[random.randint(0,len(firstnames)-1)] self.last = lastnames[random.randint(0,len(lastnames)-1)] self.name = self.first+' '+self.last self.age = random.randint(1,86) Person.population += 1 def introduce(self): print('Hi, my name is '+self.first+' of house '+self.last+' and I am '+str(self.age)+' years old.') def census(self): print('There are '+str(Person.population)+' people in this town') def rename_first(self,n): self.first = n def rename_last(self,n): self.last = n def grow(self): self.age += 1 def die(self): print(self.name+' died.') Person.population -=1 def joust(self, Person): print(self.name+' challenged '+Person.name+' to a joust!') outcome = random.randint(0,2) if(outcome == 1): print(self.first+' of house '+self.last+': I win!') Person.die() else: print(Person.first+' of house '+Person.last+': I win!') self.die() def handler(n): people = [] print('generating town') for i in range(int(n)): p = Person() p.introduce() people.append(p) """p = Person('Bobby','Johnson') p.introduce() people.append(p)""" #test for custom constructor people[0].census() people[0].joust(people[random.randint(1,num)]) num = random.randint(1,101) handler(num) """ if len(sys.argv) > 1: handler(int(sys.argv[1]) else: handler(5) """
c054ecfee06ec508de88efe67246bfa47ba93085
unicefuganda/rapidsms-generic
/generic/reports.py
3,232
3.75
4
from .utils import flatten_list, set_default_dates class Column(object): def add_to_report(self, report, key, dictionary): pass class Report(object): """ A report was found to be a useful callable for more complicated aggregate reports, in which each column of the report is a complicated query, but can be performed for every row of the table at once. Subclasses of this object can define tabular reports declaratively, by creating Column attributes. The main report class builds a dictionary of dictionaries. Each key is a unique identifier, and the dictionary value has the remaining column attributes. Each column is called in the order it was declared, adding its column value to each subdictionary in the main dictionary. The final product is then flattened. For instance, suppose we were aggregating stats by Locations. I might declare three columns: class MyCityReport(Report): population = PopulationColumn() crime = CrimeColumn() pollution = PollutionColumn() each Column knows how to add itself to the report structure following the same convention. So MyCityReport would start with an empty report dictionary, {}. After the call to PopulationColumn's add_to_report() method, the report dictionary might look like this: {'nairobi':{'pop':3000000}, 'kampala':{'pop':1420200}, 'kigali':{'pop':965398}} After Crime's add_to_report(), it would be: {'nairobi':{'pop':3000000, 'crime':'nairobbery'}, 'kampala':{'pop':1420200, 'crime':'lots of carjacking'}, 'kigali':{'pop':965398, 'crime':'ok lately'}} And so on. After all columns have been given a shot at adding their data, the report finally flattens this list into something that can be used by the generic view in the standard way (i.e., as an iterable that can be sorted, paginated, and selected): [{'key':'nairobi','pop':3000000, 'crime':'nairobbery'}, {'key':'kampala','pop':1420200, 'crime':'lots of carjacking'}, {'key':'kigali','pop':965398, 'crime':'ok lately'}] Reports also sort date filtering and drill-down by default, just be sure to set `needs_date` to True when passing a Report object to the generic view, and also set the base_template to be `generic/timeslider_base.html' rather than the standard `generic/base.html` """ def __init__(self, request=None, dates=None): datedict = {} set_default_dates(dates, request, datedict) self.drill_key = request.POST['drill_key'] if 'drill_key' in request.POST else None self.start_date = datedict['start_date'] self.end_date = datedict['end_date'] self.report = {} #SortedDict() self.columns = [] column_classes = Column.__subclasses__() for attrname in dir(self): val = getattr(self, attrname) if type(val) in column_classes: self.columns.append(attrname) val.add_to_report(self, attrname, self.report) self.report = flatten_list(self.report) def __iter__(self): return self.report.__iter__() def __len__(self): return len(self.report)
65db0ad60b8ae2b5e772ff2f19872703a517b089
Sudeep-K/hello-world
/Automating Tasks/Spreadsheet Cell Inverter.py
814
3.984375
4
#! python3 # Spreadsheet Cell Inverter.py - invert the row and column of the cells in the spreadsheet. import openpyxl # create two workbook 'wb' for original file and 'wb2' a blank workbook for storing inverted sheet wb = openpyxl.load_workbook('F:\\python\\example.xlsx') wb2 = openpyxl.Workbook() sheet1 = wb.active sheet2 = wb2.active # store maximum column and maximum row numbers from 'sheet1' column_maxnum = sheet1.max_column row_maxnum = sheet1.max_row # invert the row and column of the original 'sheet1' to blank 'sheet2' for column_num in range(1, column_maxnum+1): for row_num in range(1, row_maxnum+1): sheet2.cell(row=column_num, column=row_num).value = sheet1.cell(row=row_num, column=column_num).value # save the inverted worksheet wb2.save('F:\\example-Copy.xlsx')
bb658c8b753d83cd676804dbb504db3a659ff05c
Sudeep-K/hello-world
/Automating Tasks/multiplicationTable.py
1,260
4.0625
4
#! python3 # multiplicationTable.py - takes a number N from the command line and # creates an N×N multiplication table in an Excel spreadsheet. import openpyxl, sys from openpyxl.styles import NamedStyle, Font #store the N to variable named 'N' if len(sys.argv) > 1: N = int(sys.argv[1]) #create a new workbook and select the active sheet wb = openpyxl.Workbook() sheet = wb.active #style font to bold for header default_bold = NamedStyle(name='default_bold') default_bold.font = Font(bold=True) #initiate the values in row '1' and column 'A' and set them to 'bold' for row_num in range(2, N+2): sheet.cell(row = row_num, column = 1).value = row_num - 1 sheet.cell(row = row_num, column = 1).style = default_bold for column_num in range(2, N+2): sheet.cell(row = 1, column = column_num).value = column_num - 1 sheet.cell(row = 1, column = column_num).style = default_bold #fill up the N*N multiplication table for column_num in range(2, N+2): for row_num in range(2, N+2): sheet.cell(row = row_num, column= column_num).value = sheet.cell(row = row_num, column= 1).value * sheet.cell(row = 1, column= column_num).value #save your worksheet as 'multiplicationTable.xlsx' wb.save('F:\\multiplicationTable.xlsx')
dbd90779db40037c1cdf29d85485c84b397405fc
Sudeep-K/hello-world
/Automating Tasks/Mad Libs.py
1,445
4.5
4
#! python ''' Create a Mad Libs program that reads in text files and lets the user add their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. The program would find these occurrences and prompt the user to replace them. The results should be printed to the screen and saved to a new text file. ''' import re #textFile = input('Enter the name of path of your file:)') #TODO: read the content of file fileObject = open('F:\\python\\purre.txt') text = fileObject.read() fileObject.close() #TODO: replace the occurences of word ADJECTIVE, NOUN, ADVERB, or VERB appearing in the text file. adjective = input('Enter an adjective') noun1 = input('Enter a noun') verb = input('Enter a verb') noun2 = input('Enter a noun') #TODO: create regex to replace above occurences in text file #replace occurence of adjective text = re.sub(r'\b{}\b'.format('ADJECTIVE'), adjective, text) #replace occurence of noun text = re.sub(r'^(.*?)\b{}\b'.format('NOUN'), r'\1{}'.format(noun1), text) #replace occurence of verb text = re.sub(r'\b{}\b'.format('VERB'), verb, text) #replace occurence of noun text = re.sub(r'^(.*?)\b{}\b'.format('NOUN'), r'\1{}'.format(noun2), text) #TODO: print result to the screen print(text) #TODO: save result to the file fileObject = open('F:\\python\\textfile.txt', 'w') fileObject.write(text) fileObject.close() input('Enter \'ENTER\' to exit (:')
755371b69db100b2b309f216273a0bfa0a861d89
SohaHussain/Python-visualisation
/coursera_week3.py
12,383
4.46875
4
# Subplots import matplotlib.pyplot as plt import numpy as np # If we look at the subplot documentation, we see that the first argument is the number of rows, the second the number # of columns, and the third is the plot number. # In matplotlib, a conceptual grid is overlayed on the figure. And a subplot command allows you to create axis to # different portions of this grid. # For instance, if we want to to create two plots side by side, we would call subplot with the parameters 1, 2, and 1. # This would allow us to use 1 row, with 2 columns, and set the first axis to be the current axis. plt.figure() plt.subplot(1,2,1) linear_data=np.array([1,2,3,4,5,6,7,8]) plt.plot(linear_data,'-o') exponential_data = linear_data**2 # subplot with 1 row, 2 columns, and current axis is 2nd subplot axes plt.subplot(1, 2, 2) plt.plot(exponential_data, '-o') # plot exponential data on 1st subplot axes plt.subplot(1, 2, 1) plt.plot(exponential_data, '-x') plt.figure() # the right hand side is equivalent shorthand syntax plt.subplot(1,2,1) == plt.subplot(121) # create a 3x3 grid of subplots fig, ((ax1,ax2,ax3), (ax4,ax5,ax6), (ax7,ax8,ax9)) = plt.subplots(3, 3, sharex=True, sharey=True) # plot the linear_data on the 5th subplot axes ax5.plot(linear_data, '-') # set inside tick labels to visible for ax in plt.gcf().get_axes(): for label in ax.get_xticklabels() + ax.get_yticklabels(): label.set_visible(True) # necessary on some systems to update the plot plt.gcf().canvas.draw() # Histograms # repeat with number of bins set to 100 fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex=True) axs = [ax1,ax2,ax3,ax4] for n in range(0,len(axs)): sample_size = 10**(n+1) sample = np.random.normal(loc=0.0, scale=1.0, size=sample_size) axs[n].hist(sample, bins=100) axs[n].set_title('n={}'.format(sample_size)) # The GridSpec allows you to map axes over multiple cells in a grid. plt.figure() Y = np.random.normal(loc=0.0, scale=1.0, size=10000) X = np.random.random(size=10000) plt.scatter(X,Y) # it's not totally clear from looking at this plot what the actual distributions are for each axis, but we could add two # smaller plots, each histograms, to make this a bit more clear. # I'm going to define a 3x3 grid, nine cells in total. I want the first histogram to take up the top right space, and # the second histogram to take up the far left bottom two spaces, rotated on its side. # The original scatter plot can take up a two by two square in the bottom right. # When we add new items with the subplot, instead of specifying the three numbers of row, column and position, we pass # in the elements of the GridSpec object which we wish to cover. And very important here. Because we are using the # elements of a list, all of the indexing starts at zero, and is very reasonable to use slicing for the beginning or # ends of lists. import matplotlib.gridspec as gridspec plt.figure() gspec=gridspec.GridSpec(3,3) top_histogram = plt.subplot(gspec[0, 1:]) side_histogram = plt.subplot(gspec[1:, 0]) lower_right = plt.subplot(gspec[1:, 1:]) Y = np.random.normal(loc=0.0, scale=1.0, size=10000) X = np.random.random(size=10000) lower_right.scatter(X, Y) top_histogram.hist(X, bins=100) s = side_histogram.hist(Y, bins=100, orientation='horizontal') # clear the histograms and plot normed histograms top_histogram.clear() top_histogram.hist(X, bins=100) side_histogram.clear() side_histogram.hist(Y, bins=100, orientation='horizontal') # flip the side histogram's x axis side_histogram.invert_xaxis() # change axes limits for ax in [top_histogram, lower_right]: ax.set_xlim(0, 1) for ax in [side_histogram, lower_right]: ax.set_ylim(-5, 5) # Box and Whisker plots # A box plot. Sometimes called a box-and-whisker plot is a method of showing aggregate statistics of various samples # in a concise matter. # The box plot simultaneously shows, for each sample, the median of each value, the minimum and maximum of the samples, # and the interquartile range. import pandas as pd normal_sample = np.random.normal(loc=0.0, scale=1.0, size=10000) random_sample = np.random.random(size=10000) gamma_sample = np.random.gamma(2, size=10000) df = pd.DataFrame({'normal': normal_sample, 'random': random_sample, 'gamma': gamma_sample}) df.describe() # Like standard deviation, the interquartile range is a measure of variability of data. And it's common to plot this # using a box plot. # In a box plot, the mean, or the median, of the data is plotted as a straight line. Two boxes are formed, one above, # which represents the 50% to 75% data group, and one below, which represents the 25% to 50% data group. Thin lines # which are capped are then drawn out to the minimum and maximum values. # Like standard deviation, the interquartile range is a measure of variability of data. And it's common to plot this # using a box plot. # # In a box plot, the mean, or the median, of the data is plotted as a straight line. Two boxes are formed, one above, # which represents the 50% to 75% data group, and one below, which represents the 25% to 50% data group. Thin lines # which are capped are then drawn out to the minimum and maximum values. plt.figure() # create a boxplot of the normal data, assign the output to a variable to supress output _ = plt.boxplot(df['normal'], whis=10000.0) # whis tells the box plot to set the whisker values all the way out to the minimum and maximum values # clear the current figure plt.clf() # plot boxplots for all three of df's columns _ = plt.boxplot([ df['normal'], df['random'], df['gamma'] ], whis=10000.0) # if we look at the gamma distribution, for instance, we see the tail of it is very, very long. So the maximum values # are very far out. plt.figure() _ = plt.hist(df['gamma'], bins=100) # We can actually overlay an axes on top of another within a figure. Now, this functionality isn't in the basic # matplotlib space, but it's in the toolkits, which tend to ship with matplotlib. # # The toolkit that we're going to use is called the axes grid, and we import it from the # mpl_toolkits.axes_grid1.inset_locator. # We create a new figure and we put up our box plot. # # Then we just call the inset locator and pass it the current axes object we want composition on top of, followed by the # size of our new axis. And we can specify this as both a width and a height in percentage from the parent axes. Then we # give it a number from the place in which we wanted to drop the new axes. import mpl_toolkits.axes_grid1.inset_locator as mpl_il plt.figure() plt.boxplot([ df['normal'], df['random'], df['gamma'] ], whis=10000.0) # overlay axis on top of another ax2 = mpl_il.inset_axes(plt.gca(), width='60%', height='40%', loc=2) ax2.hist(df['gamma'], bins=100) ax2.margins(x=0.5) # switch the y axis ticks for ax2 to the right side ax2.yaxis.tick_right() # if `whis` argument isn't passed, boxplot defaults to showing 1.5*interquartile (IQR) whiskers with outliers plt.figure() _ = plt.boxplot([ df['normal'], df['random'], df['gamma'] ] ) # Heatmaps # Heatmaps are a way to visualize three-dimensional data and to take advantage of spatial proximity of those dimensions. plt.figure() Y = np.random.normal(loc=0.0, scale=1.0, size=10000) X = np.random.random(size=10000) _ = plt.hist2d(X, Y, bins=25) plt.figure() _ = plt.hist2d(X, Y, bins=100) # add a colorbar legend plt.colorbar() # Animation # The Maplotlib.animation module contains important helpers for building animations. # # For our discussion, the important object here is to call FuncAnimation. And it builds an animation by iteratively # calling a function which you define. Essentially, your function will either clear the axis object and redraw the next # frame, which you want users to see or will return a list of objects which need to be redrawn. # Let's see an example. First, let's import the animation module. # Next, let's define a cut-off for our animation. # I'd like to show you how the histogram is built from one sample through 100 samples. So let's set our cut off to 100 # then randomly pick 100 numbers and put them into a variable. # Okay, next we want to actually create a function which will do the plotting. We'll call this function update. Now the # matplotlib FuncAnimation object is going to call this every few milliseconds and pass in the frame number we are on # starting with frame zero. So we can use this is as the index into our array values, which we called x. # The very first thing we want to do is see if the current frame is at the end of our list. If so, we need to tell the # animation to stop. We do this by calling the stop object on the event source object attached to the FuncAnimation # object. # We're going to call our animation a. So, I'll just use that here. I didn't know we can just drop plot as per normal. # So lets first clear the current axis with cla, then create a histogram using a set of value in the x up to the current # value. Slicing is great for this. Now we also need to consider the bins. Previously we just passed a single number in # for the bins eg 10 or 100. # But we can also pass in the spacing in between bins. # # Since we want all of our bins set and evenly spaced, because we're redrawing the animation in each clock tick, we can # use the NumPy arange function. This will ensure that the bins don't change. We use the balance of minus 4 to plus 4, # in half-step increments. # # We also need to set the axis values since otherwise, the histogram will continually autoscale between frames which # could be annoying. So I'll just hard code some values here, often the bin sizes and use 30 as an x and a couple of # labels and titles to make the chart look a little better. # # Finally, let me show you another text function called annotate. # # This places text at a certain position in the chart and we'll use it to show how many samples are currently being # rendered to the screen. # # Now let's just generate a new figure, then call the FuncAnimation constructor and we'll assign this to variable a. # # The first parameter is the figure that we're working with. This isn't so important here, since we're using the pipe # plot scripting interface to manage the figure. Then the name of our function and then the amount of time we want # between updates. Let's set this to 100 milliseconds. # # Also, remember that we have to set this to variable a. Otherwise, our function isn't going to know how to stop the # animation. import matplotlib.animation as animation n = 100 x = np.random.randn(n) # create the function that will do the plotting, where curr is the current frame def update(curr): # check if animation is at the last frame, and if so, stop the animation a if curr == n: a.event_source.stop() plt.cla() bins = np.arange(-4, 4, 0.5) plt.hist(x[:curr], bins=bins) plt.axis([-4,4,0,30]) plt.gca().set_title('Sampling the Normal Distribution') plt.gca().set_ylabel('Frequency') plt.gca().set_xlabel('Value') plt.annotate('n = {}'.format(curr), [3,27]) fig = plt.figure() a = animation.FuncAnimation(fig, update, interval=100) # Interactivity plt.figure() data = np.random.rand(10) plt.plot(data) def onclick(event): plt.cla() plt.plot(data) plt.gca().set_title('Event at pixels {},{} \nand data {},{}'.format(event.x, event.y, event.xdata, event.ydata)) # tell mpl_connect we want to pass a 'button_press_event' into onclick when the event is detected plt.gcf().canvas.mpl_connect('button_press_event', onclick) from random import shuffle origins = ['China', 'Brazil', 'India', 'USA', 'Canada', 'UK', 'Germany', 'Iraq', 'Chile', 'Mexico'] shuffle(origins) df = pd.DataFrame({'height': np.random.rand(10), 'weight': np.random.rand(10), 'origin': origins}) df plt.figure() # picker=5 means the mouse doesn't have to click directly on an event, but can be up to 5 pixels away plt.scatter(df['height'], df['weight'], picker=5) plt.gca().set_ylabel('Weight') plt.gca().set_xlabel('Height') def onpick(event): origin = df.iloc[event.ind[0]]['origin'] plt.gca().set_title('Selected item came from {}'.format(origin)) # tell mpl_connect we want to pass a 'pick_event' into onpick when the event is detected plt.gcf().canvas.mpl_connect('pick_event', onpick)
f037ac24bce609e36980347f01fbb22e8be42657
nest-lab/Cosmic-Nestlab-FDay
/problem6.py
284
3.984375
4
def is_anagram(s1,s2): a = len(s1) b = len(s2) if a == b: for l in s1: if l in s2: return True return False string_1 = raw_input("Enter any string: ") string_2 = raw_input("Enter any string: ") print is_anagram(string_1, string_2)
b98306cce6acc5e3a85fc390204286ea7d39eba4
TimZeng/Python-practice
/Object_Oriented_Programming.py
2,171
4.0625
4
class Fraction(object): """ A number represented as a fraction """ def __init__(self, num, denom): """ num and denom are integers """ assert type(num) == int and type(denom) == int, "ints not used" self.num = num self.denom = denom self.reduce() def reduce(self): if (self.num == self.denom): self.num = 1 self.denom = 1 return low_value = min(self.num, self.denom) high_value = max(self.num, self.denom) common_denom = low_value count = 1 done = False while not done and common_denom >= 1: if high_value % common_denom == 0: done = True else: count += 1 common_denom = low_value / count while common_denom % 1 != 0 and common_denom >= 1: count += 1 common_denom = low_value / count if done: self.num = int(self.num / common_denom) self.denom = int(self.denom / common_denom) def __str__(self): """ Retunrs a string representation of self """ return str(self.num) + "/" + str(self.denom) def __add__(self, other): """ Returns a new fraction representing the addition """ top = self.num * other.denom + self.denom * other.num bott = self.denom * other.denom return Fraction(top, bott) def __sub__(self, other): """ Returns a new fraction representing the subtraction """ top = self.num * other.denom - self.denom * other.num bott = self.denom * other.denom return Fraction(top, bott) def __float__(self): """ Returns a float value of the fraction """ return self.num / self.denom def inverse(self): """ Returns a new fraction representing 1/self """ return Fraction(self.denom, self.num) a = Fraction(1, 4) b = Fraction(5, 4) c = a + b # c is a Fraction object d = b - a e = Fraction(15, 250) print('c =>', c) print('d =>', d) print('e =>', e) print(float(c)) print(Fraction.__float__(c)) print(float(b.inverse()))
626a4941c3ba6437fbd1301a1a12e05fbe0b284c
ruizj3/facebook_message_parser
/fb_chat.py
15,857
3.84375
4
import datetime class Chat(object): """An object to encapsulate the entire Facebook Message history. - Contains a list of Thread objects, which can be accessed using item accessing Chat["Thread Name"] style. - When initialising, 'myname' should be the name of the user, and 'threads' should be a list of Thread objects. - Provides useful functions for accessing messages.""" def __init__(self, myname, threads): self.threads = sorted(threads, key=len, reverse=True) self._thread_dict = {", ".join(thread.people): thread for thread in self.threads} self._total_messages = len(self.all_messages()) self._myname = myname self._all_people = {myname} for thread in self.threads: self._all_people.update(thread.people) def __getitem__(self, key): """Allow accessing Thread objects in the list using Chat["Thread Name"]. This method allows the threads list to be accessed using Chat["Thread Name"] or Chat[n] notation.""" if type(key) is int: return self.threads[key] elif type(key) is str: return self._thread_dict[key] def __repr__(self): """Set Python's representation of the Chat object.""" return "<{}'s CHAT LOG: TOTAL_THREADS={} TOTAL_MESSAGES={}>".format(self._myname, len(self.threads), self._total_messages) def __len__(self): """Return the total number of threads. Allows the len() method to be called on a Chat object. This could be changed to be the total number of messages, currently stored as Chat._total_messages()""" return len(self.threads) def _date_parse(self, date): """Allow dates to be entered as integer tuples (YYYY, MM, DD[, HH, MM]). Removes the need to supply datetime objects, but still allows dates to be entered as datetime.datetime objects. The Year, Month and Day are compulsory, the Hours and Minutes optional. May cause exceptions if poorly formatted tuples are used.""" if type(date) is datetime.datetime: return date else: return datetime.datetime(*date) def _recount_messages(self): """Update the count of total messages. Since Thread objects can be extended dynamically, this may prove necessary.""" self._total_messages = len(self.all_messages()) def all_messages(self): """Return a date ordered list of all messages. The list is all messages contained in the Chat object, as a list of Message objects.""" return sorted([message for thread in self.threads for message in thread.messages]) def all_from(self, name): """Return a date ordered list of all messages sent by 'name'. The list returned is a list of Message objects. This is distinct from Thread.by(name) since all threads are searched by this method. For all messages in one thread from 'name', use Thread.by(name) on the correct Thread.""" return sorted([message for thread in self.threads for message in thread.by(name)]) def sent_before(self, date): """Return a date ordered list of all messages sent before specified date. The function returns a list of Message objects. The 'date' can be a datetime.datetime object, or a three or five tuple (YYYY, MM, DD[, HH, MM]).""" return sorted([message for thread in self.threads for message in thread.sent_before(date)]) def sent_after(self, date): """Return a date ordered list of all messages sent after specified date. The list returned is a list of Message objects. The 'date' can be a datetime.datetime object, or a three or five tuple (YYYY, MM, DD[, HH, MM]).""" return sorted([message for thread in self.threads for message in thread.sent_after(date)]) def sent_between(self, start, end=None): """Return a date ordered list of all messages sent between specified dates. - The list returned is a list of Message objects. The 'start' and 'end' can be datetime.datetime objects, or a three or five tuple (YYYY, MM, DD[, HH, MM]). - Not entering an 'end' date is interpreted as all messages sent on the day 'start'. Where a time is specified also, a 24 hour period beginning at 'start' is used.""" return sorted([message for thread in self.threads for message in thread.sent_between(start, end)]) def search(self, string, ignore_case=False): """Return a date ordered list of all messages containing 'string'. This function searches in all threads, and returns a list of Message objects. - The function can be made case-insensitive by setting 'ignore_case' to True.""" return sorted([message for thread in self.threads for message in thread.search(string, ignore_case)]) def on(self, date): """Return the Chat object as it would have been on 'date'. The Chat object returned is a new object containing the subset of the Threads which contain messages sent before 'date', where each of these Threads is a new Thread with only these messages in. - 'date' can be a datetime.datetime object, or a three or five tuple (YYYY, MM, DD[, HH, MM]).""" threads_on = [t.on(date) for t in self.threads if len(t.on(date)) > 0] return Chat(self._myname, threads_on) class Thread(object): """An object to encapsulate a Facebook Message thread. - Contains a list of participants, a string form of the list and a list of messages in the thread as Message objects. - When initialising, 'people' should be a list of strings containing the names of the participants and 'messages' should be a list of Message objects.""" def __init__(self, people, messages): self.people = people self.people_str = ", ".join(self.people) self.messages = sorted(messages) def __getitem__(self, key): """Allow accessing Message objects in the messages list using Thread[n]. Beware out by one errors! The message numbers start counting at 1, but the list they are stored in is indexed from 0. - This behaviour could be corrected by either subtracting one from the key (which causes issues when slicing), or by counting messages from 0.""" return self.messages[key] def __repr__(self): """Set Python's representation of the Thread object.""" return '<THREAD: PEOPLE={}, MESSAGE_COUNT={}>'.format(self.people_str, len(self.messages)) def __len__(self): """Return the total number of messages in the thread.""" return len(self.messages) def _add_messages(self, new_messages): """Allow adding messages to an already created Thread object. This function is useful for merging duplicate threads together.""" self.messages.extend(new_messages) self.messages = sorted(self.messages) def _renumber_messages(self): """Renumber all messages in the 'messages' list. Message objects are are sorted after being added; but if messages are added using _add_messages() then the numbering may be incorrect. This function fixes that.""" i = 1 for message in self.messages: message._num = i i += 1 def by(self, name): """Return a date ordered list of all messages sent by 'name'. Returns a list of Message objects.""" return [message for message in self.messages if message.sent_by(name)] def sent_before(self, date): """Return a date ordered list of all messages sent before specified date. The function returns a list of Message objects. The 'date' can be a datetime.datetime object, or a three or five tuple (YYYY, MM, DD[, HH, MM]).""" return [message for message in self.messages if message.sent_before(date)] def sent_after(self, date): """Return a date ordered list of all messages sent after specified date. The list returned is a list of Message objects. The 'date' can be a datetime.datetime object, or a three or five tuple (YYYY, MM, DD[, HH, MM]).""" return [message for message in self.messages if message.sent_after(date)] def sent_between(self, start, end=None): """Return a date ordered list of all messages sent between specified dates. - The list returned is a list of Message objects. The 'start' and 'end' can be datetime.datetime objects, or a three or five tuple (YYYY, MM, DD[, HH, MM]). - Not entering an 'end' date is interpreted as all messages sent on the day 'start'. Where a time is specified also, a 24 hour period beginning at 'start' is used.""" return [message for message in self.messages if message.sent_between(start, end)] def search(self, string, ignore_case=False): """Return a date ordered list of messages in Thread containing 'string'. This function searches the current thread, and returns a list of Message objects. - The function can be made case-insensitive by setting 'ignore_case' to True.""" return sorted([message for message in self.messages if message.contains(string, ignore_case)]) def on(self, date): """Return the Thread object as it would have been on 'date'. The Thread object returned is a new object containing the subset of the messages sent before 'date'. - 'date' can be a datetime.datetime object, or a three or five tuple (YYYY, MM, DD[, HH, MM]).""" return Thread(self.people, self.sent_before(date)) class Message(object): """An object to encapsulate a Facebook Message. - Contains a string of the author's name, the timestamp, number in the thread and the body of the message. - When initialising, thread_name' should be the containing Thread.people_str, 'author' should be string containing the message sender's name, 'date_time' should be a datetime.datetime object, 'text' should be the content of the message and 'num' should be the number of the message in the thread.""" def __init__(self, thread, author, date_time, text, num): self.thread_name = thread self.author = author self.date_time = date_time self.text = text self._num = num def __repr__(self): """Set Python's representation of the Message object.""" return '<MESSAGE: THREAD={} NUMBER={} TIMESTAMP={} AUTHOR={} MESSAGE="{}">'.\ format(self.thread_name, self._num, self.date_time, self.author, self.text) def __str__(self): """Return a string form of a Message in format required for csv output.""" out = '"' + self.thread_name + '","' + str(self._num) + '","' + self.author + '","' + str(self.date_time) + '","' + self.text + '"\n' return out def __lt__(self, message): """Allow sorting of messages by implementing the less than operator. Sorting is by date, unless two messages were sent at the same time, in which case message number is used to resolve conflicts. This number ordering holds fine for messages in single threads, but offers no real objective order outside a thread.""" if self.date_time == message.date_time: if abs(self._num - message._num) > 9000: # If dates equal, but numbers miles apart return False # MUST be where two 10000 groups join: larger number actually smaller here! else: return self._num < message._num return self.sent_before(message.date_time) def __gt__(self, message): """Allow sorting of messages by implementing the greater than operator. Sorting is by date, unless two messages were sent at the same time, in which case message number is used to resolve conflicts. This number ordering holds fine for messages in single threads, but offers no real objective order outside a thread.""" if self.date_time == message.date_time: if abs(self._num - message._num) > 9000: # If dates equal, but numbers miles apart return True # MUST be where two 10000 groups join: smaller number actually larger here! else: return self._num > message._num return self.sent_after(message.date_time) def __eq__(self, message): """Messages are equal if their number, date, author and text are the same.""" equal = (self._num == message._num) and (self.author == message.author) equal = equal and (self.date_time == message.date_time) and (self.text == message.text) return equal def __len__(self): """Return the number of characters in the message body.""" text = self.text.replace("<|NEWLINE|>", "") # Undo adding extra characters text = text.replace('""', '"') # And escaping quote marks return len(text) def _date_parse(self, date): """Allow dates to be entered as integer tuples (YYYY, MM, DD[, HH, MM]). Removes the need to supply datetime objects, but still allows dates to be entered as datetime.datetime objects. The Year, Month and Day are compulsory, the Hours and Minutes optional. May cause exceptions if poorly formatted tuples are used.""" if type(date) is datetime.datetime: return date else: return datetime.datetime(*date) def sent_by(self, name): """Return True if the message was sent by 'name'.""" return self.author == name def sent_before(self, date): """Return True if the message was sent before the date specified. The 'date' can be a datetime.datetime object, or a three or five tuple (YYYY, MM, DD[, HH, MM]).""" date = self._date_parse(date) return self.date_time < date def sent_after(self, date): """Return True if the message was sent after the date specified. The 'date' can be a datetime.datetime object, or a three or five tuple (YYYY, MM, DD[, HH, MM]).""" date = self._date_parse(date) return self.date_time > date def sent_between(self, start, end=None): """Return True if the message was sent between the dates specified. - The 'start' and 'end' can be datetime.datetime objects, or a three or five tuple (YYYY, MM, DD[, HH, MM]). The start and end times are inclusive since this is simplest. - Not entering an 'end' date is interpreted as all messages sent on the day 'start'. Where a time is specified also, a 24 hour period beginning at 'start' is used.""" start = self._date_parse(start) if end is not None: end = self._date_parse(end) else: end = start + datetime.timedelta(1) # 1 day (24 hours) later than 'start' return start <= self.date_time <= end def contains(self, search_string, ignore_case=False): """Return True if 'search_string' is contained in the message text.""" if ignore_case: return search_string.lower() in self.text.lower() else: return search_string in self.text
11e03d080050f7c7e88648c68451d826820c95a1
andreatta/2D_matrix
/create2Dmatrix.py
3,379
3.546875
4
#!/usr/bin/env python """ Create 2D Matrix bitmpap from Ferag String. """ import re import os.path import argparse import codecs from PIL import Image PATTERN = r"\{SK\|(\d+)\|(\d+)\|(\d+)\|([\s\S]+)\}" FONT = [] parser = argparse.ArgumentParser() parser.add_argument('file', nargs='?', default='2DMatrix.bin') args = parser.parse_args() """ Create a list of bitmaps that represent a font. This font has 16 characters wich each represent half a character received from the Ferag String. """ def create_font(): dot = Image.new('RGB', (2, 2), "black") for halfchar in range(0, 16): img = Image.new('RGB', (2, 8), "white") for bit in range(0, 4): bits = str(bin(halfchar))[2:].zfill(4)[::-1] if bits[bit] == '1': img.paste(dot, (0, (2*bit))) img.save("bmp/%c.bmp" % chr(halfchar + ord('A'))) FONT.append(img) """ Read a file given as parameter or just try to open file with default name. """ if os.path.exists(args.file): print("converting Matrix '%s'" % (args.file)) else: print("file '%s' does not exist" % args.file) quit() create_font() """ Read file and parse Ferag String to create a 2D Matrix bitmap. Each module (1 square of the 2D Matrix) consists of 4 drops. Ferag String format for 2D Matrix: {SK|<LEN>|<HEIGHT>|<WIDTH>|<BYTE DATA>} """ with open(args.file, 'rb') as matrixfile: #with codecs.open(args.file, 'r', 'utf-8') as matrixfile: matrixstr = matrixfile.read() #print(matrixstr) #m = re.search(PATTERN, matrixstr.decode('utf-8')) if (matrixstr[0] == ord('{') and matrixstr[-2] == ord('}')): content = matrixstr.split(b'|') #print(content) length = int(content[1]) height = int(content[2]) width = int(content[3]) # get data bytes remove '}\n' at the end data = content[4:] data = b''.join(data)[:-2] #if m is not None and len(m.groups()) == 4: #data = m.group(4) #width = int(m.group(3)) #height = int(m.group(2)) #length = int(m.group(1)) print("length %d height %d width %d" % (length, height, width)) print(data) matrix = Image.new('RGB', (2*width, 2*height), "white") top_line = "" bot_line = "" # create list with separated rows to draw # a row consists of 'width' characters # filter out empty list matrixrowlist = filter(None, [data[i:i+width] for i in range(0, length, width)]) #matrixrowlist = filter(None, [data[i:i+height] for i in range(0, length, height)]) for offset, row in enumerate(matrixrowlist): #print(len(row)) #print(row) for i, char in enumerate(row): top = char & 0x0f bot = (char >> 4) & 0x0f top_line += chr(top + ord('A')) bot_line += chr(bot + ord('A')) #print("%c %d %d" % (char, top, bot)) matrix.paste(FONT[top], (2*i, 16*offset)) matrix.paste(FONT[bot], (2*i, 16*offset + 8)) print(top_line) print(bot_line) top_line = "" bot_line = "" matrix.save(args.file.replace('.bin', '.bmp')) else: print('Wrong format') print('Ferag String has to be in format: {SK|<LEN>|<HEIGHT>|<WIDTH>|<BYTE DATA>}')
3942be2adf64c4d9ff0ec29bc562014e7d6b43cb
JoneLn/project2_pandas
/Python数据分析从入门到精通/MR/Code/03/41/demo.py
293
3.78125
4
from pandas import Series #从pandas引入Series对象,就可以直接使用Series对象了,如Series([88,60,75],index=[1,2,3]) s1=Series([88,60,75],index=[1,2,3]) print(s1) print(s1.reindex([1,2,3,4,5])) #重新设置索引,NaN以0填充 print(s1.reindex([1,2,3,4,5],fill_value=0))
e1b59e4b26347d0e067fa73b68c4df8dba94a0d3
JoneLn/project2_pandas
/Python数据分析从入门到精通/MR/Code/08/46/demo.py
178
3.578125
4
import numpy as np #创建矩阵 data1= np.mat([[1, 2], [3, 4],[5,6]]) data2=np.mat([1,2]) print(data1-data2) #矩阵减法法运算 print(data1/data2) #矩阵除法运算
5a5941f0967ed5510e28f210dbc5dea3cafb4d01
JoneLn/project2_pandas
/Python数据分析从入门到精通/MR/Code/08/32/demo.py
136
3.734375
4
import numpy as np #创建3行4列的二维数组 n=np.array([[0,1,2,3],[4,5,6,7],[8,9,10,11]]) print(n[1]) print(n[1,2]) print(n[-1])
4b01fdcfb56d1acaf43d6601e9c836ecb5fe5410
JoneLn/project2_pandas
/Python数据分析从入门到精通/MR/Code/04/28/demo.py
286
3.5
4
import pandas as pd df = pd.DataFrame({'a':[1,2,3,4,5], 'b':[(1,2), (3,4),(5,6),(7,8),(9,10)]}) print(df) # apply函数分割元组 df[['b1', 'b2']] = df['b'].apply(pd.Series) print(df) #或者join方法结合apply函数分割元组 #df= df.join(df['b'].apply(pd.Series)) #print(df)
0696d0acdb4fa1b26b9f31760b6e01717f959bbf
JoneLn/project2_pandas
/Python数据分析从入门到精通/MR/Code/03/09/demo.py
295
3.8125
4
import pandas as pd data = [[110,105,99],[105,88,115],[109,120,130]] index = [0,1,2] columns = ['语文','数学','英语'] df = pd.DataFrame(data=data, index=index,columns=columns) print(df) #遍历DataFrame表格数据的每一列 for col in df.columns: series = df[col] print(series)
e10c4cd35fce90bc44dbb4dd3ffaf75b13adcaa9
harishvinukumar/Practice-repo
/Break the code.py
1,503
4.28125
4
import random print('''\t\t\t\t\t\t\t\t### --- CODEBREAKER --- ### \t\t\t\t\t1. The computer will think of 3 digit number that has no repeating digits. \t\t\t\t\t2. You will then guess a 3 digit number \t\t\t\t\t3. The computer will then give back clues, the possible clues are: \t\t\t\t\tClose: You've guessed a correct number but in the wrong position \t\t\t\t\tMatch: You've guessed a correct number in the correct position \t\t\t\t\tNope: You haven't guess any of the numbers correctly \t\t\t\t\t4. Based on these clues you will guess again until you break the code with a perfect match!''') digits = list(range(10)) random.shuffle(digits) list1 = digits[:3] #print(list1) string1 = "" random.shuffle(list1) for i in list1: string1 = string1 + str(i) # Another hint: string2 = "123" while string1 != string2: guess = int(input("What is your guess?: ")) string2 = str(guess) if string1[0] == string2[0]: print("Match (in first position!)") if string1[1] == string2[1]: print("Match (in second position!)") if string1[2] == string2[2]: print("Match (in third position!)") if (string2[0] in string1[1:]) or (string2[2] in string1[:2]) or (string2[1] == string1[0] or string2[1] == string1[2]): print("Close") if (string2[0] not in string1) and (string2[1] not in string1) and (string2[2] not in string1): print("Nope") if string1 == string2: print("You Broke the Code! (Code: {})".format(string1)) break
bc28d90671f845043771f4154ca9f227101bd521
weigelb1988/projectEuler
/python/problem19.py
972
3.859375
4
# You are given the following information, but you may prefer to do some research for yourself. # # 1 Jan 1900 was a Monday. # Thirty days has September, # April, June and November. # All the rest have thirty-one, # Saving February alone, # Which has twenty-eight, rain or shine. # And on leap years, twenty-nine. # A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. # # How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? import datetime from datetime import date from dateutil.relativedelta import relativedelta start_date = date(1901, 1, 1) print(start_date) end_date = start_date + relativedelta(years=99, days=365) delta = datetime.timedelta(days=1) print (end_date) d = start_date sunCount = 0 while d <= end_date: if d.weekday() == 6 and d.day == 1: sunCount = sunCount + 1 d = d + delta print(sunCount)
a70c316aaa8edc181caca26f2173c277d9813bde
weigelb1988/projectEuler
/python/problem24.py
1,324
4.03125
4
# function to swap array elements fullList = [] count = 0 def swap (v=[], i=0, j=0): t=0 t = v[i] v[i] = v[j] v[j] = t # recursive function to generate permutations def perm (v=[], n=0, i=0): # this function generates the permutations of the array # from element i to element n-1 # j=0 # if we are at the end of the array, we have one permutation # we can use (here we print it; you could as easily hand the # array off to some other function that uses it for something if i == n: num = '' for j in range(0,n): num = num + str(v[j]) # print(v[j], end="") # print("\n" + num) fullList.append(int(num)) else: # recursively explore the permutations starting # at index i going through index n-1 for j in range(i,n): # try the array with i and j switched swap (v, i, j); perm (v, n, i+1); # swap them back the way they were swap (v, i, j); # little driver function to print perms of first 5 integers PERM_NUM = 10 v = []; for i in range(0,PERM_NUM): v.append(i) perm(v, PERM_NUM, 0); fullList.sort() print("FULLLIST[999999]: " + str(fullList[999999]) + "FULLIST[1000000]: " + str(fullList[1000000]))
af069f0404ed5594b2fb77da8613ebda76b8c040
DreamHackchosenone/python-algorithm
/binary_tree/traversing.py
1,311
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/3/19 22:10 class TreeNode(object): # 定义树结构 def __init__(self, root=None, left=None, right=None): self.root = root self.left = left self.right = right def preorder_traverse(tree): # 递归遍历顺序:根->左->右 if tree is None: return print(tree.root) preorder_traverse(tree.left) preorder_traverse(tree.right) def inorder_traverse(tree): # 递归遍历顺序:左->根->右 if tree is None: return inorder_traverse(tree.left) print(tree.root) inorder_traverse(tree.right) def postorder_treverse(tree): # 递归遍历顺序:左->右->根 if tree is None: return postorder_treverse(tree.left) postorder_treverse(tree.right) print(tree.root) if __name__ == '__main__': node = TreeNode("A", TreeNode("B", TreeNode("D"), TreeNode("E") ), TreeNode("C", TreeNode("F"), TreeNode("G") ) ) preorder_traverse(node) inorder_traverse(node) postorder_treverse(node)
ddb08e49497c629955107ca654146485a21eaeab
balajisomasale/Hacker-Rank
/Python/03 Sets/01 Introduction to Sets.py
313
3.859375
4
def average(array): # your code goes here count=0 n1=0 s1=set(array) for item in s1: count+=item n1+=1 return count/n1 if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) result = average(arr) print(result)
432238cc169768713e448629b0c909d8577aa410
balajisomasale/Hacker-Rank
/30 Days of Code Python/06 Even and Odd Index Strings .py
325
3.71875
4
# Enter your code here. Read input from STDIN. Print output to STDOUT n=int(input()) for i in range(n): name=str(input()) mylist=list(name) result=("".join(mylist[::2])) result2=("".join(mylist[1::2])) print(result+" "+result2)
e8d1bdad2417a751ffe3baa29ffa62c8894c94f8
balajisomasale/Hacker-Rank
/Python/03 Sets/Set .union() Operation.py
200
3.578125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT n=input() students = set(map(int,input().split())) b=input() b1=set(map(int,input().split())) print(len(students.union(b1)))
d3b12b7ac69eb02b0f0416e90c96ccdd91a5d886
brandoncfsx/OpenCV
/simple_thresholding.py
2,234
3.65625
4
import numpy as np import argparse import cv2 ap = argparse.ArgumentParser() ap.add_argument('-i', '--image', required=True, help='Path to the image.') ap.add_argument('-t', '--threshold', type=int, default=128, help='Threshold value.') args = vars(ap.parse_args()) image = cv2.imread(args['image']) image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Apply a Gaussian blurring with sigma equal to radius of five to grayscale image. Applying Gaussian blurring helps remove some of the high frequency edges in the image. blurred = cv2.GaussianBlur(image, (5, 5), 0) cv2.imshow('Image', image) cv2.waitKey(0) # Args: grayscale image, threshold value, maximum value (any pixel intensity greater than our threshold is set to this value). So any pixel value greater than 155 is set to 255. Last arg is the thresholding method. Return values are our threshold value and the thresholded image. (T, threshold) = cv2.threshold(blurred, 155, 255, cv2.THRESH_BINARY) cv2.imshow('Threshold Binary', threshold) (T, thresholdInv) = cv2.threshold(blurred, 155, 255, cv2.THRESH_BINARY_INV) cv2.imshow('Inverse Threshold Binary', thresholdInv) # We reveal the objects in the image and hide everything else by masking the image with the inverted threshold image. This is because a mask only considers pixels in the original image where the mask is greater than zero. Since the inverted thresholded image can approximate the areas the objects are contained, we can use this inverted thresholded image as our mask. cv2.imshow('Coins', cv2.bitwise_and(image, image, mask=thresholdInv)) cv2.waitKey(0) # THRESH_TRUNC: leaves pixel intensities as they are if the source pixel is not greater than the supplied threshold. # THRESH_TOZERO: sets the source pixel to zero if the source pixel is not greater than the supplied threshold. otherMethods = [ ('THRESH_TRUNC', cv2.THRESH_TRUNC), ('THRESH_TOZERO', cv2.THRESH_TOZERO), ('THRESH_TOZERO_INV', cv2.THRESH_TOZERO_INV)] for (threshName, threshMethod) in otherMethods: (T, threshold) = cv2.threshold(image, args['threshold'], 255, threshMethod) cv2.imshow(threshName, threshold) cv2.waitKey(0) # Note: these methods require human-intervention: fine-tuing of the threshold value.
42cd6a6b4f83acd0f4ff49c8916b8c86ebaaf8bb
brandoncfsx/OpenCV
/shapedetector.py
1,248
3.75
4
import cv2 class ShapeDetector: def __init__(self): pass def detect(self, c): # Initialize shape's name and approximate contour based on the contour input. shape = 'Unknown' # First compute the perimeter of the contour. peri = cv2.arcLength(c, True) # Contour approximation reduces the number of points in a curve with a reduced set of points: split-and-merge algorithm. Common values for the second arg is between 1 and 5% of the original contour perimeter. approx = cv2.approxPolyDP(c, 0.04*peri, True) # A contour consists of a list of vertices so we can check the number of entries in the list to determine the shape. if len(approx) == 3: shape = 'Triangle' elif len(approx) == 4: # Compute bounding box of the contour and use it to compute the aspect ratio in order to determine if this is a square or a rectangle. (x, y, w, h) = cv2.boundingRect(approx) # Our aspect ratio. ar = w / h shape = 'square' if ar >= 0.95 and ar <= 1.05 else 'rectangle' elif len(approx) == 5: shape = 'Pentagon' else: shape = 'Circle' return shape
e2eae931e495e69dbebcd02835ef1779a5f95f15
weiyinfu/learnMatplotlib
/动画/掉在地上的皮球.py
815
3.515625
4
import pylab as plt from matplotlib.animation import FuncAnimation fig = plt.figure(figsize=(3, 3)) x, y = 0, 2 # 小球的位置 v = 0 # 小球的速度 p = plt.scatter(x, y, s=500) # 把小球画出来 plt.plot([-1, 1], (-0.25, -0.25)) # 画一条地平线 dt = 0.1 # 每个间隔的时间 g = 1 # 重力系数 def update(frame_index): global y, v need_time = ((v * v + 2 * g) ** 0.5 - v) / g # 到落地需要的时间 need_time = min(abs(need_time), dt) left_time = dt - need_time # 转向需要的时间 vv = v - g * need_time y += (vv + v) / 2 * need_time v = vv if y <= 1e-7: v *= -0.91 y += v * left_time p.set_offsets([x, y]) animation = FuncAnimation(fig, update, interval=50) plt.axis('off') plt.xlim(-1, 1) plt.ylim(-0.5, 2.5) plt.show()
c4084cb912f3cfb50941c976ef2d16120ff4b6b1
weiyinfu/learnMatplotlib
/110-cbook模块函数注册.py
432
3.515625
4
""" cbook即为cookbook,是一些小工具组成的库 """ from matplotlib.cbook import CallbackRegistry callbacks = CallbackRegistry() sum = lambda x, y: print(f'{x}+{y}={x + y}') mul = lambda x, y: print(f"{x} * {y}={x * y}") id_sum = callbacks.connect("sum", sum) id_mul = callbacks.connect("mul", mul) callbacks.process('sum', 3, 4) callbacks.process("mul", 5, 6) callbacks.disconnect(id_sum) callbacks.process("sum", 7, 8)
b099354a6fac9fee379d1b066c7b93bc329d0564
fudong1127/PyLimitBook
/orderList.py
1,861
3.71875
4
#!/usr/bin/python from order import Order class OrderList(object): def __init__(self): self.headOrder = None self.tailOrder = None self.length = 0 self.volume = 0 # Total share volume self.last = None def __len__(self): return self.length def __iter__(self): self.last = self.headOrder return self def next(self): if self.last == None: raise StopIteration else: returnVal = self.last self.last = self.last.nextOrder return returnVal def appendOrder(self, order): if len(self) == 0: order.nextOrder = None order.prevOrder = None self.headOrder = order self.tailOrder = order else: order.prevOrder = self.tailOrder order.nextOrder = None self.tailOrder.nextOrder = order self.tailOrder = order self.length += 1 self.volume += order.qty def removeOrder(self, order): self.volume -= order.qty self.length -= 1 if len(self) == 0: return # Remove from list of orders nextOrder = order.nextOrder prevOrder = order.prevOrder if nextOrder != None and prevOrder != None: nextOrder.prevOrder = prevOrder prevOrder.nextOrder = nextOrder elif nextOrder != None: nextOrder.prevOrder = None self.headOrder = nextOrder elif prevOrder != None: prevOrder.nextOrder = None self.tailOrder = prevOrder def moveTail(self, order): if order.prevOrder != None: order.prevOrder.nextOrder = self.nextOrder else: # Update the head order self.headOrder = order.nextOrder order.nextOrder.prevOrder = order.prevOrder # Set the previous tail order's next order to this order self.tailOrder.nextOrder = order self.tailOrder = order order.prevOrder = self.tailOrder order.nextOrder = None def __str__(self): from cStringIO import StringIO file_str = StringIO() for order in self: file_str.write("%s\n" % str(order)) return file_str.getvalue()
fed641241861ce73df700305c6926319647d5b39
JHorwitz1011/DFA2020-2021-UCP
/Experimental Input/PongOpenCV.py
6,730
3.53125
4
# Simple Pong in Python 3 for Beginners # By @TokyoEdTech # Part 10: Simplifying Your Code (One Year and a Half Later!) import turtle import imutils from cv2 import cv2 as cv FRAME_WIDTH = 800 FRAME_HEIGHT = 800 RADIUS = 25 FRAMES_NEEDED = 5 frame_count_up = 0 frame_count_down = 0 #Currently set to a green object for up and blue for down #(36, 202, 59, 71, 255, 255) # Green #(18, 0, 196, 36, 255, 255) # Yellow #(89, 0, 0, 125, 255, 255) # Blue #(0, 100, 80, 10, 255, 255) # Red colorUpLower = (36,202,59) colorUpUpper = (71,255,255) colorDownLower = (0,100,80) colorDownUpper = (10,255,255) camera = cv.VideoCapture(0) camera.set(cv.CAP_PROP_FRAME_WIDTH, FRAME_WIDTH) camera.set(cv.CAP_PROP_FRAME_HEIGHT, FRAME_HEIGHT) if not camera.isOpened(): print("Camera could not be referenced") exit(0) wn = turtle.Screen() wn.title("Pong by @TokyoEdTech") wn.bgcolor("black") wn.setup(width=800, height=600) wn.tracer(0) # Score score_a = 0 score_b = 0 # Paddle A paddle_a = turtle.Turtle() paddle_a.speed(0) paddle_a.shape("square") paddle_a.color("white") paddle_a.shapesize(stretch_wid=5, stretch_len=1) paddle_a.penup() paddle_a.goto(-350, 0) # Paddle B paddle_b = turtle.Turtle() paddle_b.speed(0) paddle_b.shape("square") paddle_b.color("white") paddle_b.shapesize(stretch_wid=5, stretch_len=1) paddle_b.penup() paddle_b.goto(350, 0) # Ball ball1 = turtle.Turtle() ball1.speed(0) ball1.shape("square") ball1.color("green") ball1.penup() ball1.goto(0, 0) ball1.dx = 3 ball1.dy = -3 balls = [ball1] # balls = [ball1, ball2, ball3, ball4] # Pen pen = turtle.Turtle() pen.speed(0) pen.color("white") pen.penup() pen.hideturtle() pen.goto(0, 260) pen.write("Player A: 0 Player B: 0", align="center", font=("Courier", 24, "normal")) # Function def paddle_a_up(): y = paddle_a.ycor() y += 20 if y > 305: paddle_a.sety(-300) paddle_a.sety(y) def paddle_a_down(): y = paddle_a.ycor() y -= 20 if y < -305: paddle_a.sety(300) paddle_a.sety(y) def paddle_b_up(): y = paddle_b.ycor() y += 20 paddle_b.sety(y) def paddle_b_down(): y = paddle_b.ycor() y -= 20 paddle_b.sety(y) def detectColor(colorLow, colorUpper): ret, frame = camera.read() if ret: # Process frame @ lower quality level frame = imutils.resize(frame, width=600) blurred = cv.GaussianBlur(frame, (11, 11), 0) hsv = cv.cvtColor(blurred, cv.COLOR_BGR2HSV) mask = cv.inRange(hsv, colorLow, colorUpper) mask = cv.erode(mask, None, iterations=2) mask = cv.dilate(mask, None, iterations=2) cv.imshow('Mask', mask) # Pull contours to draw contours = cv.findContours( mask.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) contours = imutils.grab_contours(contours) center = None if len(contours) > 0: maxC = max(contours, key=cv.contourArea) ((x, y), radius) = cv.minEnclosingCircle(maxC) M = cv.moments(maxC) center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"])) if radius > RADIUS: cv.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2) cv.circle(frame, center, 5, (0, 0, 255), -1) return 1 frame = cv.flip(frame, 1) cv.imshow('Frame', frame) return 0 def readFrame(): ret, frame = camera.read() if ret: # Process frame @ lower quality level frame = imutils.resize(frame, width=600) blurred = cv.GaussianBlur(frame, (11, 11), 0) hsv = cv.cvtColor(blurred, cv.COLOR_BGR2HSV) mask = cv.inRange(hsv, colorUpLower, colorUpUpper) mask = cv.erode(mask, None, iterations=2) mask = cv.dilate(mask, None, iterations=2) cv.imshow('Mask', mask) # Pull contours to draw contours = cv.findContours( mask.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) contours = imutils.grab_contours(contours) center = None if len(contours) > 0: maxC = max(contours, key=cv.contourArea) ((x, y), radius) = cv.minEnclosingCircle(maxC) M = cv.moments(maxC) center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"])) if radius > RADIUS: cv.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2) cv.circle(frame, center, 5, (0, 0, 255), -1) global frame_count_up frame_count_up = frame_count_up + 1 frame = cv.flip(frame, 1) cv.imshow('Frame', frame) # Keyboard binding wn.listen() wn.onkeypress(paddle_a_up, "w") wn.onkeypress(paddle_a_down, "s") wn.onkeypress(paddle_b_up, "Up") wn.onkeypress(paddle_b_down, "Down") # Main game loop while True: wn.update() readFrame() frame_count_up = frame_count_up + detectColor(colorUpLower,colorUpUpper) #frame_count_down = frame_count_down + detectColor(colorDownLower,colorDownUpper) if frame_count_up > FRAMES_NEEDED: paddle_a_up() frame_count_up = 0 wn.update() for ball in balls: # Move the ball ball.setx(ball.xcor() + ball.dx) ball.sety(ball.ycor() + ball.dy) # Border checking if ball.ycor() > 290: ball.sety(290) ball.dy *= -1 #os.system("afplay bounce.wav&") if ball.ycor() < -290: ball.sety(-290) ball.dy *= -1 #os.system("afplay bounce.wav&") if ball.xcor() > 390: ball.goto(0, 0) ball.dx *= -1 score_a += 1 pen.clear() pen.write("Player A: {} Player B: {}".format( score_a, score_b), align="center", font=("Courier", 24, "normal")) if ball.xcor() < -390: ball.goto(0, 0) ball.dx *= -1 score_b += 1 pen.clear() pen.write("Player A: {} Player B: {}".format( score_a, score_b), align="center", font=("Courier", 24, "normal")) # Paddle and ball collisions if (ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < paddle_b.ycor() + 40 and ball.ycor() > paddle_b.ycor() - 40): ball.setx(340) ball.dx *= -1 #os.system("afplay bounce.wav&") if (ball.xcor() < -340 and ball.xcor() > -350) and (ball.ycor() < paddle_a.ycor() + 40 and ball.ycor() > paddle_a.ycor() - 40): ball.setx(-340) ball.dx *= -1 #os.system("afplay bounce.wav&") cv.destroyAllWindows() camera.release()
00bbf91aae928270723a1fae3c252ab67929139c
111111xiao/tf_keras_cnn_handwritten_recognition
/module/calcul.py
8,926
3.578125
4
import math def calculator(l1): list_number = [] list_operator = [] list_power = [0] sum = j = flag = 0 power = 1 for i in l1: if i == '=': flag = 1 if i != '+' and i != '-' and i != '*' and i != '/' and i != '=' and i != '^': sum = sum * 10 + float(i) elif (i == '^'): if (list_power[0] == 0): list_power[0] = sum else: list_power.insert(0,sum) sum = 0 else: if (list_power[0] == 0): list_number.append(sum) else: list_power.insert(0,sum) for j in list_power: power = j ** power list_number.append(power) sum = 0 list_power = [0] power = 1 list_operator.append(i) if flag == 1: for i in list_operator: if i == '*': list_number[j] *= list_number[j + 1] del list_number[j + 1] j -= 1 elif i == '/': list_number[j] /= list_number[j + 1] del list_number[j + 1] j -= 1 j += 1 for i in list_operator: if i == '+': list_number[0] += list_number[1] del list_number[1] elif i == '-': list_number[0] -= list_number[1] del list_number[1] l1.append(str(list_number[0])) return l1 else: l1.append('$\n\n$No Equal') return l1 def equation(s1,l1): list_number = [] list_operator = [] list_x = ['0'] sum = flag = 0 x = '+' #xķλĬΪ+ for i in l1: if i == '=': flag = 1 if flag == 0: if i != '+' and i != '-' and i != '*' and i != '/' and i != '=' and i != s1 and i != '^': sum = sum * 10 + float(i) elif i == s1: if (sum == 0): sum = 1 list_x.append(x) list_x.append(sum) sum = 0 else: x = i list_number.append(sum) sum = 0 list_number.append(i) elif flag == 1: list_number.append(sum) sum = 0 list_number.append(i) calculator(list_number) flag = 2 elif flag == 2: if i != '+' and i != '-' and i != '*' and i != '/' and i != '=' and i != 'x' and i != '^': sum = sum * 10 + float(i) elif i == 'x': if (sum == 0): sum = 1 list_x.append(x) list_x.append(sum) sum = 0 else: if (i == '+'): x = '-' elif (i == '-'): x = '+' list_operator.append(sum) sum = 0 list_operator.append(i) list_operator.append(sum) list_operator.append('=') calculator(list_operator) list_x.append('=') calculator(list_x) if (list_x[-1] == '0'): l1.append('$\n\n$No Equal') return l1 x = (float(list_operator.pop())-float(list_number.pop())) / float(list_x.pop()) l1.append("$\n\n$") l1.append(s1) l1.append("=") l1.append(str(x)) return l1 def equation2(s1,l1): s_square = s1 + '^2' list_number = [] list_operator = [] list_x = ['0'] list_x2 = ['0'] sum = flag = 0 x = '+' #xķλĬΪ+ for i in l1: if i == '=': flag = 1 if flag == 0: if i != '+' and i != '-' and i != '*' and i != '/' and i != '=' and i != s1 and i != '^' and i != s_square: sum = sum * 10 + float(i) elif i == s1: if (sum == 0): sum = 1 list_x.append(x) list_x.append(sum) sum = 0 elif i == s_square: if (sum == 0): sum = 1 list_x2.append(x) list_x2.append(sum) sum = 0 else: x = i list_number.append(sum) sum = 0 list_number.append(i) elif flag == 1: list_number.append(sum) sum = 0 list_number.append(i) calculator(list_number) flag = 2 elif flag == 2: if i != '+' and i != '-' and i != '*' and i != '/' and i != '=' and i != s1 and i != '^' and i != s_square: sum = sum * 10 + float(i) elif i == s1: if (sum == 0): sum = 1 list_x.append(x) list_x.append(sum) sum = 0 elif i == s_square: if (sum == 0): sum = 1 list_x2.append(x) list_x2.append(sum) sum = 0 else: if (i == '+'): x = '-' elif (i == '-'): x = '+' list_operator.append(sum) sum = 0 list_operator.append(i) list_operator.append(sum) list_operator.append('=') calculator(list_operator) list_x.append('=') calculator(list_x) list_x2.append('=') calculator(list_x2) if (list_x2[-1] == '0'): equation(l1) return l1 c = (float(list_number.pop())-float(list_operator.pop())) b = float(list_x.pop()) a = float(list_x2.pop()) delta = b * b - 4 * a * c if (delta < 0): l1.append('$\n\n$Delta < 0$\nno real number$') return l1 elif (delta == 0): x1 = (0 - b + delta ** 0.5) / 2 / a l1.append("$\n\n$") l1.append(s1) l1.append("1 = ") l1.append(s1) l1.append("2 = ") l1.append(str(x1)) return l1 else: x1 = (0 - b + delta ** 0.5) / 2 / a x2 = (0 - b - delta ** 0.5) / 2 / a l1.append("$\n\n$") l1.append(s1) l1.append("1 = ") l1.append(str(x1)) l1.append("$\n\n$") l1.append(s1) l1.append("2 = ") l1.append(str(x2)) return l1 def judge(l1): m = n = t = b = 0 while (t < len(l1)): if l1[t] == 'x' and l1[t + 1] == '^': l1[t] = 'x^2' del(l1[t + 1]) if (l1[t + 1] != '2'): l1.append('$\n\n$No Equal') return l1 del(l1[t + 1]) t += 1 t = 0 while (t < len(l1)): if l1[t] == 'y' and l1[t + 1] == '^': l1[t] = 'y^2' del(l1[t + 1]) if (l1[t + 1] != '2'): l1.append('$\n\n$No Equal') return l1 del(l1[t + 1]) t += 1 t = 0 l = len(l1) l2 = {'e': math.e, '@': math.pi} l3 = [l2[i] if i in l2 else i for i in l1] l1 = l3 for i in l1: if i == 'x': m = 1 if i == 'y': m = 2 if i == 'x^2': t = 1 if i == 'y^2': t = 2 if i == '=': n = 1 if i == '(': b = 1 if b == 1 and n == 1: l1.append(calculator(temp(l1)).pop()) elif t == 1 and n == 1: l1 = equation2('x',l1) elif t == 2 and n == 1: l1 = equation2('y',l1) elif m == 1 and n == 1: l1 = equation('x',l1) elif m == 2 and n == 1: l1 = equation('y', l1) elif m == 0 and n == 1: l1 = calculator(l1) else: l1.append('$\n\n$No Equal') return l1[l:] def temp(l1): m = n = t = 0 list_number = [] list_brackets = [0] for i in l1: if i == '(': m += 1 if i == ')': n += 1 t = m if m > 0: list_brackets.append(i) else: list_number.append(i) if m != 0 and m == n: list_number.append(brackets(list_brackets, t).pop()) m = n = 0 list_brackets = [0] l1 = list_number return l1 def brackets(l1,n): list = [0] list_temp = [] a = 0 while n >= 0: for i in l1: if a - 1 < n : list_temp.append(i) if i != '(' and i != ')': list.append(i) elif i == '(': list = [0] a += 1 if a - 1 == n: list_temp.pop() elif i == ')': a -= 1 if a == n: list.append('=') list_temp.append(calculator(list)[-1]) list = [0] l1 = list_temp list_temp = [] n -= 1 return l1
228cb176446af1f696ea57220eedd81e0ab97f3b
zhouf1234/untitled8
/BeautifulSoup-demo30.py
3,597
3.796875
4
from bs4 import BeautifulSoup soup = BeautifulSoup('<p>Hello</p>','lxml') print(soup.p.string) #Hello print() html=''' <html><head><title>The Dormouse's story</title></head> <body> <p class="title" name="dormouse"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their name were <a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> ''' sou = BeautifulSoup(html,'lxml') #初始化 print(sou.prettify()) #把要解析的字符串以标准缩进形式输出 print(sou.title.string) #输出title节点中的文本内容:显示The Dormouse's story print() print(type(sou.prettify())) #str数据类型 print(type(sou.title.string)) #<class 'bs4.element.NavigableString'>数据类型 print() print(sou.title) #获取title节点:显示<title>The Dormouse's story</title> print(type(sou.title)) #<class 'bs4.element.Tag'>类型 print() print(sou.head) #获取head节点:显示<head><title>The Dormouse's story</title></head> print(sou.p) #获取p节点,结果只有一个<p class="title" name="dormouse"><b>The Dormouse's story</b></p> print() print(sou.title.name) #获取节点名称:显示title print(sou.p.attrs) #获取p节点所有属性,返回结果是字典形式{'class': ['title'], 'name': 'dormouse'},只拿到第一个p节点的 print(sou.p.attrs['name']) #显示:dormouse print(sou.p['name']) #显示:dormouse print(sou.p['class']) #显示一个列表:['title'] print(sou.p.string) #输出p节点文本内容,就一个 print() print(sou.head.title) #获取head节点下的title节点 print(type(sou.head.title)) #<class 'bs4.element.Tag'>类型 print() print(sou.p.contents) #返回p标签的直接子节点的列表,显示[<b>The Dormouse's story</b>] print(sou.p.children) #返回结果是迭代器 for i,child in enumerate(sou.p.children): #遍历迭代器,得到结果 print(i,child) print() print(sou.p.descendants) #返回结果是生成器 for i,child in enumerate(sou.p.descendants): #遍历生成器,得到结果 print(i,child) #0 <b>The Dormouse's story</b> 1 The Dormouse's story print() print(sou.p.parent) #返回父节点<body>所有内容了 print() print(sou.p.parents) #返回生成器 print() print(list(enumerate(sou.p.parents))) #列表输出索引和内容,此处三个列表。。。 print() print('next:',sou.a.next_sibling) #获取节点的下一个兄弟元素 print('pre:',sou.a.previous_sibling) #获取节点的上一个兄弟元素 print('next',list(enumerate(sou.a.next_sibling))) #获取后面的兄弟节点 print('pre',list(enumerate(sou.a.previous_sibling))) #获取前面的兄弟节点 print() print(type(sou.a.next_sibling)) #<class 'bs4.element.NavigableString'> print(sou.a.next_sibling.string) #, print(sou.a.previous_sibling.string) #上一个兄弟元素的文本内容:显示Once upon a time there were three little sisters; and their name were print(type(sou.a.parents)) #<class 'generator'>生成器类型 print(list(sou.a.parents)[0]) #父节点索引值为0的节点和内容 print(list(sou.a.parents)[0].attrs['class']) #父节点p的class属性值['story']
d68a6d351de04e57ba60432ac1e2e1191c68b238
zhouf1234/untitled8
/空值测试2.py
307
3.953125
4
# keys = ['a', 'b', 'c'] # values = [1, 2, 3] # v = [11, 22, 33] # dictionary = list(zip(keys, values,v)) # print(dictionary) # for i in dictionary: # for j in i: # print(j) # list = [] # for i in range(1,10): # print(i) # if i not in list: # list.append(i) # print(list)
2b25649637cefbdec2e8e389202a08fd82dbf1f0
ramyagoel98/acadview-assignments
/assignment11.py
651
4.28125
4
#Regular Expressions: #Question 1: Valid Emaild Address: import re as r email = input("Enter the E-mail ID: ") matcher = r.finditer('^[a-z][a-zA-Z0-9]*[@](gmail.com|yahoo.com)', email) count = 0 for i in matcher: count += 1 if count == 1: print('Valid E-mail Address') else: print('Invalid E-mail Address') #Question 2: Valid Phone Number: import re as r number = str(input('Enter the phone number: ')) matcher = r.finditer('^[+][9][1][-][6-9][\d]{9}', number) count = 0 for i in matcher: count += 1 if count == 1: print('Valid Phone Number.') else: print("Invalid Phone Number')
f880fb9bda8b4b9a9efe35ef53b62c9de6ed6caa
josterpi/AdventOfCode
/year2020/day7.py
1,182
3.59375
4
def parse_input(filename): rules = {} with open(filename) as f: for line in f: bag, spec = line.strip(".\n").split(" bags contain ") bag_rules = {} if spec != "no other bags": for part in spec.split(", "): part = part.split()[:-1] count = int(part[0]) name = " ".join(part[1:]) bag_rules[name] = count rules[bag] = bag_rules return rules def find_gold(bag, rules): if not rules: return False bag_names = rules[bag].keys() if "shiny gold" in bag_names: return True return any([find_gold(name, rules) for name in bag_names]) def fill_gold(bag, rules): if not rules[bag]: return 0 return sum([count + fill_gold(name, rules) * count for name, count in rules[bag].items()]) def main(): input = parse_input("input/day7.txt") gold_count = 0 for key in input.keys(): if find_gold(key, input): gold_count += 1 print(f"Part 1: {gold_count}") print("Part 2: %s" % fill_gold("shiny gold", input)) if __name__ == '__main__': main()
f875225db753a4100d62aa08f1a76db0bfbcf1cc
josterpi/AdventOfCode
/day2.py
523
3.59375
4
def main(): input = [line.strip().split() for line in open("input/day2.txt")] x, y = 0, 0 y2, aim = 0, 0 for direction, units in input: units = int(units) if direction == "forward": x += units y2 += units * aim if direction == "up": y -= units aim -= units if direction == "down": y += units aim += units print(f"Part 1: {x*y}") print(f"Part 2: {x*y2}") if __name__ == "__main__": main()
e031bcc758f86d335c787fe87cccc70cf37306e2
LucianoJunnior/Python
/Python/(média)ex008.py
258
3.765625
4
medida = float(input('Digite a Medida em Kilometros \n' )) cm = medida*100 mm = medida*1000 dc = medida/100 hc = medida/1000 print('A medida de {:.1f}km coresponden a {:.1f}cm , {:.1f}mm, {} Devimetros,{} Hectometros. '.format(medida, cm, mm, dc, hc))
0da902b8ef7b15740fa920bdd6c02fbc3d8daf6c
prkprime/trimester-8
/IS/rsa_implementation.py
1,627
3.84375
4
""" Name : Pratik Gorade Year : T.Y. B.Tech Panel : 2 Batch : B2 Roll No. : PB02 Usage : python3 rsa_implementation.py """ from math import sqrt from itertools import count, islice def gcd(a, b): #returns relative GCD of a and b if b == 0: return a else: return gcd(b, a%b) def isPrime(n): #retuns True if number is prime if n < 2: return False for number in islice(count(2), int(sqrt(n) - 1)): if n % number == 0: return False return True def main(): p = int(input("Enter any prime number : ")) while isPrime(p) == False: p = int(input("{} is not prime number, Enter again : ".format(p))) q = int(input("Enter one more prime number : ")) while isPrime(q) == False: q = int(input("{} is not prime number, Enter again : ".format(q))) #calculating n n = p*q print(" Value of \'n\' is :", n) #calculating phi phi = (p-1)*(q-1) print(" Value of \'phi\' is :", phi) #calculating value of public key 'e' for e in range(2, phi): if gcd(e, phi)==1: break print(" Value of \'e\' is :", e) #calculating value of private key 'd' for d in range(2, phi): if (d*e)%phi==1: break print(" Value of \'d\' is :", d) m = int(input("Enter any numerical message to encrypt : ")) encrypted_message = pow(m, e)%n print("Encrypted message is :", encrypted_message) decrypted_message = pow(encrypted_message, d)%n print("Decrypted message is : ", decrypted_message) #calculate d using (d*e) mod z = 1 if __name__ == '__main__': main()
97aa8452a4bab355d139eed764ebfd5f692ab06b
shaikzia/Classes
/yt1_cor_classes.py
691
4.21875
4
# Program from Youtube Videos - corey schafer """ Tut1 - Classes and Instances """ #Defining the class class Employee: def __init__(self,first,last,pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' def fullname(self): return '{} {}'.format(self.first, self.last) # Creating an instances of the class emp1 = Employee('Muhammad', 'Faiz', 60000) emp2 = Employee('Zairah', 'Shaik',50000) emp3 = Employee('Muhammad', 'Saad',50000) #Printing the email print(emp1.email) print(emp2.email) print(emp3.email) # Print the Full Name print(emp1.fullname()) print(emp2.fullname()) print(emp3.fullname())
94d737b1eb5d4fa7d9714e85c7c3fd2f925077a0
lukasbindreiter/enternot-pi
/enternot_app/pi/distance.py
774
4.125
4
from math import sin, cos, sqrt, atan2, radians def calculate_distance(lon1: float, lat1: float, lon2: float, lat2: float) -> float: """ Calculate the distance in meters between the two given geo locations. Args: lon1: Longitude from -180 to 180 lat1: Latitude from -90 to 90 lon2: Longitude from -180 to 180 lat2: Latitude from -90 to 90 Returns: Distance in meters """ earth_radius = 6371000 # meters delta_lon = radians(lon2 - lon1) delta_lat = radians(lat2 - lat1) a = sin(delta_lat / 2) ** 2 + cos(radians(lat1)) * cos(radians(lat2)) * sin( delta_lon / 2) ** 2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) distance = earth_radius * c return distance
ab105ea16b1b7eaa79ded84ca64dd55396f972e7
armenuhiarakelyan1978/python_task
/x.py
175
3.796875
4
#!/usr/bin/python n1 = int(input("Input int ")) n2 = 0 while n1 > 0: digit = n1 % 10 n1 = n1 / 10 print (n1) n2 = n2 * 10 n2 = n2 + digit print (n2)
1d7925d3427de20e82b1c1796e9d29468fe2dc59
amirkhan1092/competitive-coding
/leap_year.py
108
3.65625
4
def leap_year(y): return y%4 == 0 and y%100 != 0 or y%400 == 0 k = int(input()) print(leap_year(k))
86b51ad1d4b4282943a6e8282735985cecb6d6ea
amirkhan1092/competitive-coding
/jumbuled_sequence.py
503
4.09375
4
# This problem was asked by Pinterest. # # The sequence [0, 1, ..., N] has been jumbled, and the only clue you have for its order # is an array representing whether each number is larger or smaller than the last. Given this information, # reconstruct an array that is consistent with it. For example, given [None, +, +, -, +], # you could return [1, 2, 3, 0, 4] k = [None, '+', '+', '+', '-', '+' ] lst = [] c = 0 for i in k: if i: c = eval(str(c)+i+'1') lst.append(c) print(lst)
4e1c6f197f7e099b7ef3cc2c520343b5a48da64f
amirkhan1092/competitive-coding
/substring_anagram.py
551
3.984375
4
# substring anagram in a given string with all matches def substring_anagram(dictionary: list, sub: list) -> None: dictionary_sort = list(map(sorted, dictionary)) sub_sort = map(sorted, sub) m = [] for i in sub_sort: m.append(dictionary_sort.count(i)) return m # # all_word = ['abc', 'a', 'bca', 'abcd', 'dac', 'acd'] # query = ['abc', 'a', 'ada'] all_word = eval(input()) # user having all anagram pattern query = eval(input()) # user enter the sublist out_list = substring_anagram(all_word, query) print(out_list)
acfadec0f2eb814774cd1f07841af99a48afb5b8
Deepkumarbhakat/Python-Repo
/factorial of a nummber.py
236
3.921875
4
# n=5 # fact=1 # for i in range(n,0,-1): # if i==1: # fact=fact*1 # else: # fact=fact*i # print(fact) def fact(n): if n==1 or n==0: return 1 else: return n*fact(n-1) x=fact(5) print(x)
4e592149e3f98f2d428bb5a37dd85431ad7be763
Deepkumarbhakat/Python-Repo
/factorial.py
206
4.25
4
#Write a program to find the factorial value of any number entered through the keyboard n=5 fact=1 for i in range(0,n,-1): if i==1 or i==0: fact=fact*1 else: fact=fact*i print(fact)
866d38f72f63b3d2d1ec87bfd1b330f04cf33635
Deepkumarbhakat/Python-Repo
/Write a program to check if a year is leap year or not. If a year is divisible by 4 then it is leap year but if the year is century year like 2000, 1900, 2100 then it must be divisible by 400..py
320
4.28125
4
#Write a program to check if a year is leap year or not. y=int(input('enter any year : ')) if (y % 4 == 0): if (y % 100 == 0): if (y % 400 == 0): print('leap year') else: print('not a leap year') else: print('leap year') else: print('not a leap year')
27cd32606dddc864ce68c35f824a533e1467419d
Deepkumarbhakat/Python-Repo
/function3.py
243
4.28125
4
# Write a Python function to multiply all the numbers in a list. # Sample List : (8, 2, 3, -1, 7) # Expected Output : -336 def multiple(list): mul = 1 for i in list: mul =mul * i print(mul) list=[8,2,3,-1,7] multiple(list)
3a98e9a55e3217f3f4faa76b71ab08a75adf1d8e
Deepkumarbhakat/Python-Repo
/function9.py
434
4.25
4
# Write a Python function that takes a number as a parameter and check the number is prime or not. # Note : A prime number (or a prime) is a natural number greater than 1 and that has no positive divisors # other than 1 and itself. def prime(num): for i in range(2,num//2): if num % i == 0: print("not prime") break else: print("prime") num=int(input("enter any number : ")) prime(num)
63507dcd1e550687bbc7d6108211bd15cf2164af
Deepkumarbhakat/Python-Repo
/string15.py
282
4.15625
4
# Write a Python program that accepts a comma separated sequence of words as input # and prints the unique words in sorted form (alphanumerically). # Sample Words : red, white, black, red, green, black # Expected Result : black, green, red, white,red st=("input:"," , ") print(st)
2a6d1f1f594ba9b7f442b8dcb366e47aa51a2906
Deepkumarbhakat/Python-Repo
/Write a Python program that accepts a word from the user and reverse it.py
143
4.21875
4
#Write a Python program that accepts a word from the user and reverse it char = " abcde" y=char.split() print(y) char=char[-1::-1] print(char)
086d0231677f2cda2886ee87d302a4a223063565
Deepkumarbhakat/Python-Repo
/list4.py
164
4.0625
4
# Write a Python program to get the smallest number from a list. a=[int(b) for b in input("enter the number : ").split()] print("smallest number",min(a)) print(a)
d6c07b75b2300ffbe75848a01fb59252c778bfc5
Deepkumarbhakat/Python-Repo
/Write a program to print absolute vlaue of a number entered by user..py
152
4.1875
4
#Write a program to print absolute vlaue of a number entered by user. x = int(input('INPUT :')) if x < 0: y=x*(-1) print(y) else: print(x)
7a7827eedd2369dddd5165fff5cc972090a0c43d
Deepkumarbhakat/Python-Repo
/sum of 10 nnatural number.py
164
4
4
#Write a program to calculate the sum of first 10 natural number. n = int(input("enter any number : ")) sum = 0 for i in range(1,n+1): sum = sum + i print(sum)
85756f1b81c845de56bdd9b04134c7cce3b5f1ec
MersenneInteger/sandbox
/binary.py
581
4.03125
4
powers = [] for pow in range(15, -1,-1): powers.append(2 ** pow) binaryOutput = '' while True: decimalInput = int(input('Enter a number between 1 and 65535: ')) if decimalInput <= 65535 and decimalInput >= 1: for power in powers: binaryOutput = binaryOutput + str(decimalInput // power) decimalInput %= power print(binaryOutput) else: print('You did not enter a number between 1 and 65535') binaryOutput = '' print('Convert another number(y/n)?') ans = input() if ans != 'y': break
8e1573dc618a825cb850cd98db16867c9ee52a43
MersenneInteger/sandbox
/OOP/inheritance.py
1,761
3.96875
4
#!usr/bin/python import random class Date(object): def getDate(self): return '09-02-18' #time inherits Date class Time(Date): def getTime(self): return '07-07-07' dt = Date() print(dt.getDate()) tm = Time() print(tm.getTime()) print(tm.getDate()) #object.attribute lookup hierachy #1)the instance #2)the class #3)any class from which this class inherits class Animal(object): def __init__(self, name): self.name = name def eat(self, food): print('{0} is eating {1}'.format(self.name, food)) class Dog(Animal): def __init__(self, name): super(Dog, self).__init__(name) self.breed = random.choice(['Shih Tzu', 'Beagle', 'Mutt']) def bark(self): print('{} barked!'.format(self.name)) class Cat(Animal): def __init__(self, name): super(Cat, self).__init__(name) self.breed = random.choice(['Tabby', 'Mutt']) def meow(self): print('{} meowed!'.format(self.name)) class GuardDog(Dog): def __init__(self, name): super(Dog, self).__init__(name) print('{} is a guard dog'.format(self.name)) benji = Dog('Benji') garfield = Cat('Garfield') benji.eat('kibble') garfield.eat('birds') benji.bark() garfield.meow() #garfield.bark() #error print(benji.breed) print(garfield.breed) #for multiple inheritance, the method resolution order is depth-first then breadth fido = GuardDog('Fido') fido.eat('dog food') fido.bark() print('GuardDog class method resolution order: {}'.format(GuardDog.mro())) print() class A(object): def doThis(self): print('doing this in A') class B(A): pass class C(A): def doThis(self): print('doing this in C') class D(B, C): pass d = D() d.doThis() print(D.mro())
b936f7dc39b2a3a4a28e5e80bb9c70af4685d964
MersenneInteger/sandbox
/functional-py/optimizing.py
3,344
3.8125
4
#Implementing Utilities and Optimizing Storage ##composite design pattern #creates tree-like hierarchical structures #each component in a composite design may be a leaf node or a composite node #three elements #component: defines basic properties of all elements in structure #leaf: bottom-most element, contains functionality offered by component class #composite: contains leaf nodes and/or composite nodes class Component: def __init__(self, name, emp_id): self.name = name self.emp_id = emp_id def print_name(self): print('Name of Employee: ' + self.name) def print_id(self): print('ID of Employee: ' + str(self.emp_id)) #composite node class Manager(Component): #inherits from component def __init__(self, name, emp_id): super().__init__(name, emp_id) self.children = [] def manages(self, emp): self.children.append(emp) def display_working_under(self): print('employees working under ' + self.name + ' are: ') for emp in self.children: print(emp.name) #leaf node class Employee(Component): def __init__(self, name, emp_id, operation): super().__init__(name, emp_id) self.operation = operation def display_operation(self): print(self.name + ' does the operation: ' + self.operation) bobManager = Manager('Bob', 123) emp1 = Employee('Bob', 55, 'Cooking') emp2 = Employee('Sally', 44, 'Accounting') bobManager.manages(emp1) bobManager.manages(emp2) bobManager.display_working_under() emp1.display_operation() emp2.display_operation() bobManager.print_name() bobManager.print_id() emp1.print_name() emp1.print_id() emp2.print_name() emp2.print_id() ##caching in python #caching - store data in a temp container for later use #storing data that is freq used speeds up execution from functools import lru_cache @lru_cache(maxsize=100) def fibo_rec(n): if n==0: return 0 elif n==1: return 1 else: return fibo_rec(n-1) + fibo_rec(n-2) import time n = 100 start_t = time.time() result = fibo_rec(n) end_t = time.time() time_taken = end_t - start_t print('time elapsed is ' + str(time_taken) + ' seconds') ##memoization in python #technique for remembering results of function/method calls #a cache for function calls memo_cache = {} def fib_memo(n): if n==0: return 0 elif n==1: return 1 else: #check if value is already in cache if memo_cache.get(n, None): return memo_cache[n] result = fib_memo(n-1)+fib_memo(n-2) memo_cache[n] = result return result n = 500 start_t = time.time() result = fib_memo(n) end_t = time.time() time_taken = end_t - start_t print('time elapsed: ', time_taken, ' seconds') ##operator module import operator print(operator.mul(5,6)) print(operator.sub(5,6)) print(operator.add(5,6)) print(operator.lt(5,6)) #passing higher order functions my_list = [(1, 'hello'), (200, 'world'), (50, 'hi'), (179, 'bye')] #sort according to first value in tuple print(sorted(my_list, key=operator.itemgetter(0), reverse=True)) print(sorted(my_list, key=operator.itemgetter(0), reverse=False)) import timeit from functools import reduce timeit.timeit('reduce(lambda x, y: x * y, range(1,100))') timeit.timeit('reduce(mul, range(1,100))', setup='from operator import mul')
f7d5ccb63d48723c1596c5f6d126a76be881e5cb
MersenneInteger/sandbox
/functional-py/basics.py
6,543
3.890625
4
##functional programming import itertools ##recursion def factorial(n): result = 1 for x in range(1, n+1): result = result * x return result print(factorial(6)) def recuFactorial(n): if n <= 1: return n return n * recuFactorial(n-1) print(recuFactorial(6)) #fibonacci - iterative def fib(n): j = 0 k = 1 for _ in range(1, n+1): l = j + k k = j j = l return l #0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765 print(fib(8)) print(fib(9)) print(fib(11)) def printFib(n): num1 = 0 num2 = 1 count = 2 if n == 0: return elif n == 1: print(num1) elif n >= 2: print(num1, num2, end=' ') while count <= n: num3 = num1 + num2 print(num3, end=' ') count += 1 num1 = num2 num2 = num3 return printFib(13) print() #fibonacci - recursive def recFib(n): if n == 0: return 0 elif n == 1: return 1 else: return recFib(n-1) + recFib(n-2) for i in range(0,20): print(recFib(i), end=' ') print() ##immutability and mutability x = 123 y = 123 #both will have the same unique id print(id(x)) print(id(y)) x += 1 print(id(x)) print(id(y)) #lists are mutable zList = [1,2,3] print(id(zList)) zList.append(4) print(id(zList)) #immutable datatypes #integer, float, byte, string, double, range, complex, bool, frozenset #mutable datatypes #list, dictionary, set, byte array, user defined classes ##first-class functions #functions can be passed as parameters to other functions, assigned to variables, # can be used as a return type and stored in data structures my_var = 3 def my_func(var_x): var_result = var_x + 3 return var_result new_var = my_func(my_var) print(new_var) #likewise with functions def square(x): return x * x def func(x, function): result = function(x) return result new_var = func(6, square) print(new_var) #assigning functions to variables var = 3 new_var = var print(new_var) sq = square print(sq(5)) #using functions as return types to functions my_var = 3 def func2(x): ret_x = x + 2 return ret_x my_new_var = func2(my_var) print(my_new_var) def square_something(x): def func_square(y,z): return y * y + z return func_square(x, x+1) my_new_var = square_something(5) print(my_new_var) #can be stored in data structures def sqr(x): return x * x def cube(x): return x * x * x def four_pow(x): return x * x * x * x func_list = [sqr, cube, four_pow] for func in func_list: print(func(2)) ##lambda expressions #lambda expressions are anonymous functions that are typically used once square = lambda x: x * x print(square(5)) list_str = ['dddd', 'a', 'ccc', 'bb'] print(sorted(list_str, key = lambda x: len(x))) dict_str = {1: 'a', -2: 'bbbb', 3:'c', 4:'ddddd'} print(sorted(dict_str, key=lambda x: len(dict_str[x]))) ##classes, objects and functions #keyword args - default parameters def optArg(x=1): return x xx = optArg() print(xx) #assign to specific parameters def specArg(x, y, z): return x + y + z xx = specArg(x=1, z=3, y=2) print(xx) #variable arguments def varArg(*args): for arg in args: print(arg, end=' ') varArg(1) varArg(2,3,4,5, ) print() varArg('a', 'b', 'c') print() #variable keyword arguments def keyArg(**kwargs): for key in kwargs: print('Arg: ', key, ' is: ', kwargs[key], end=' ') keyArg(arg1=1) print() keyArg(arg1=2,arg2=3,ar3=4,arg4=5) print() keyArg(a='a', b='b', c='c') print() ##lists and tuples list1 = [1,2,3, 'a', 'b', 'c', True, 3.0] for elem in list1: print(elem, end=' ') print() print(list1[1:]) #print everything past the first element print(list1[2:5]) print(list1[-1]) #print last elem print('second to last: ' + str(list1[-2])) if True in list1: print('True is in list') #tuples are immutable lists tup1 = (1,2,3,4,5) for tup in tup1: print(tup) #error #tup1[1] = 6 #tup1.addend(6) ##dictionaries and sets #sets are ordered collections and are mmutable print() set1 = {1,2,3,'a','b','c'} set2 = set({7,8,9}) #sets dont support indexing #set1[1] #error def printSet(set): for s in set: print(s, end=' ') set1.add(5) printSet(set1) #all elements must be unique set1.add(5) print() printSet(set1) set1.update(set2) print() printSet(set1) set1.add(0) printSet(set1) #set operations set3 = {1,2,3,4,5} set4 = {1,3,5,7,9} set5 = {2,4,6,8,10} set6 = {1,2,3} set7 = {} print() print(set3 | set4) # '|' - union print(set3 & set4) # '&' - intersect print(set3 - set4) # '-' - difference print(set3 > set4) # '>' - superset print(set3 > set6) #two sets are disjoint if they have no elements in common print(set3.isdisjoint(set4)) print(set3.isdisjoint(set7)) setList = [set1, set2, set3, set4, set5, set6, set7] for s in setList: s.clear() #dictionaries store data in key-value pairs #keys are immutable but dictionaries themselves are mutable dict1 = {'a':1, 'b':2, 'c':3} print(dict1) print(dict1['b']) del dict1['c'] print(dict1) #get - gets a value or a default value if the key is not present print(dict1.get('d', None)) print(dict1.get('a', None)) for kvp in dict1.items(): print(kvp) for (k,v) in dict1.items(): print('key: {0}\nvalue: {1}'.format(k,v)) ##generators and yield #generators create iterators using yield def gen(a,b): yield a, b print('first') a+=1 b+=2 yield a, b print('second') a+=10 b+=20 yield a, b print('third') genEx = gen(3,7) for x, y in genEx: print(x, y) ##list and dictionary comprehension #creates a list based on an iterable #syntax: # resulting_list = [expression for item in iterable] nums = [1,2,3] numsTimesTwo = [x * 2 for x in nums] print(nums) print(numsTimesTwo) evens = [x for x in range(1,11) if x%2==0] odds = [x for x in range(1,11) if x%2!=0] print(evens) print(odds) strList = ['string', 'another string', 'str', 's'] strLenList = [len(x) for x in strList] print(strLenList) nums2 = [11,14,8,15,4,3,77,21,6] numsOverTen = list(filter(lambda x: x > 10, nums2)) print(numsOverTen) #dictionary comprehensions #syntax: # resulting_variable = {key: value for (key, value) in iterable} list99 = [1,2,3,4,5,6,7,8,9] list100 = {elem: elem**2 for elem in list99} print(list100) evenSquares = {elem: elem**2 for elem in list99 if elem%2==0} print(evenSquares) listA = [1,2,3] listB = ['a','b','c'] dictA = {key: value for (key, value) in zip(listA, listB)} print(dictA)
423ade86419e6532d864a6357ad33594368b9549
MersenneInteger/sandbox
/LeetCode/hammingDistance.py
562
3.5625
4
def intToBin(num): powers = [] for pow in range(255, -1,-1): powers.append(2 ** pow) binaryOutput = '' for power in powers: binaryOutput = binaryOutput + str(num // power) num %= power return binaryOutput class Solution(object): def hammingDistance(self, x, y): xBin = intToBin(x) yBin = intToBin(y) hDist = 0 for i in range(len(xBin)): if xBin[i] != yBin[i]: hDist += 1 return hDist exercise = Solution(); print(exercise.hammingDistance(1,4))
9fa4fb38ce6f4eb0d77ad39bff0fc0287430ced4
Aryasankar5/python-programs-2
/positive number list.py
355
4.09375
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 25 18:08:04 2020 @author: ARYA SHANKAR """ list=[] n=int(input("Enter the number of elements : ")) for i in range(1,n+1): a=int(input("Enter the %d element :" %i)) list.append(a) print("The list of positive numbers are : ") for num in range(n): if(list[num]>=0): print(list[num])
652d7afaa86a4297813f8051fe450816ab7fc1e9
ZheniaTrochun/embedded-systems
/neuron.py
792
3.5625
4
sigma = 0.1 x1 = (1, 5) x2 = (2, 4) p = 5 initial_w1 = 0 initial_w2 = 0 def delta(y, p): return int(p - y) def func(w1, w2, point): return point[0] * w1 + point[1] * w2 def update(w, x, delta): return w + delta * x * sigma def check(w1, w2): y1 = func(w1, w2, x1) y2 = func(w1, w2, x2) return (y1 > p) and (y2 < p) def learn_first(w1, w2): if check(w1, w2): return [w1, w2] else: y = func(w1, w2, x1) d = delta(y, p) return learn_second(update(w1, x1[0], d), update(w2, x1[1], d)) def learn_second(w1, w2): if check(w1, w2): return [w1, w2] else: y = func(w1, w2, x2) d = delta(y, p) return learn_first(update(w1, x2[0], d), update(w2, x2[1], d)) res = learn_first(initial_w1, initial_w2) print("w1 = " + str(res[0])) print("w2 = " + str(res[1]))
b70cb8128ef8ccabfd7b8e2620709777a5b0a088
Tanasiuk/Homework
/first and last ver2.py
517
3.546875
4
def firstnlast(a): try: new_list = list(int(item) for item in a.split()) print("Массив чисел:", new_list) print("Первый элемент списка:", new_list[0]) print("Последний элемент списка:", new_list[-1], "\n") except ValueError: print("Снова сломал?! Работаем с числами!\n") firstnlast (input("Введите последовательность цифр через пробел:\n"))
8b0dec00c444b34636b0d7d4775a48fa8829d633
Tanasiuk/Homework
/first and last ver1.py
493
3.703125
4
def firstnlast(a): newlist = " ".join(str(x) for x in a) print("Первый элемент списка:", newlist[0]) print("Последний элемент списка:", newlist[-1]) try: y = int(input("Укажите длину массива:\n")) a = [int(input("Введите число массива:\n")) for i in range(y)] print("\nМасссив чисел:\n", a) firstnlast(a) except ValueError: print("Опять сломал?!")
60587c257c99bd0e42d92e66d2ebe75eacbeab73
cloi1994/session1
/Uber/24.py
687
3.71875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ root = prev = ListNode(1) root.next = head while prev.next and prev.next.next: cur = prev.next curNext = cur.next cur.next = curNext.next curNext.next = cur prev.next = curNext prev = cur return root.next
067479493ca1e35a30bdcd26941ca3f3a32e1853
cloi1994/session1
/Amazon/138.py
971
3.6875
4
# Definition for singly-linked list with a random pointer. # class RandomListNode(object): # def __init__(self, x): # self.label = x # self.next = None # self.random = None class Solution(object): def copyRandomList(self, head): """ :type head: RandomListNode :rtype: RandomListNode """ hm = {} root = newcur = RandomListNode(1) cur = head while cur: newNode = RandomListNode(cur.label) hm[cur] = newNode cur = cur.next newcur.next = newNode newcur = newcur.next cur = head while cur: if cur.random: hm[cur].random = hm[cur.random] cur = cur.next return root.next
05d749540382f8e673991ff307f3762b358bf4b2
cloi1994/session1
/Facebook/680.py
778
3.5
4
class Solution(object): def validPalindrome(self, s): """ :type s: str :rtype: bool """ """ :type s: str :rtype: bool """ i = 0 j = len(s) - 1 allowOnce = 0 while i <= j: if s[i].lower() != s[j].lower(): return self.isPalindromeCheck(s,i+1,j) or self.isPalindromeCheck(s,i,j-1) i += 1 j -= 1 return True def isPalindromeCheck(self,s,i,j): while i <= j: if s[i].lower() != s[j].lower(): return False i += 1 j -= 1 return True
e4a8749cda9171f0332b15f56c0f65b69121a8ce
cloi1994/session1
/Amazon/160.py
1,234
3.71875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ if not headA or not headB: return None aLen = self.getLength(headA) bLen = self.getLength(headB) n = abs(aLen - bLen) if aLen > bLen: while aLen > bLen: headA = headA.next aLen -= 1 elif bLen > aLen: while bLen > aLen: headB = headB.next bLen -= 1 while headA and headB: if headA == headB: return headA headA = headA.next headB = headB.next n -= 1 return None def getLength(self,head): count = 0 while head: head = head.next count += 1 return count
09618d1974a7d16fd8593d8141aef9d3534850db
cloi1994/session1
/Facebook/277.py
635
3.703125
4
""" The knows API is already defined for you. @param a, person a @param b, person b @return a boolean, whether a knows b you can call Celebrity.knows(a, b) """ class Solution: # @param {int} n a party with n people # @return {int} the celebrity's label or -1 def findCelebrity(self, n): # Write your code here res = 0 for i in range(1,n): if Celebrity.knows(res, i): res = i for i in range(n): if res != i and (Celebrity.knows(res, i) or not Celebrity.knows(i, res)): return -1 return res
9c1e279e48c091090367f039361e43cad7a9a895
cloi1994/session1
/Amazon/102.py
735
3.734375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] self.res = [] self.dfs(root,0) return self.res def dfs(self,root,step): if not root: return if len(self.res) == step: self.res.append([]) self.res[step].append(root.val) self.dfs(root.left,step+1) self.dfs(root.right,step+1)
dc5203f536fbefe8ae06198b3c0cda6c6871690c
remix7/python3-nome
/learningpy3/线程与进程/22线程共享非全局变量.py
273
3.609375
4
from threading import Thread import time def test1(): g_num = 100 g_num += 1 print(" test 1 g_num is %d"%g_num) def test2(): g_num = 1 print(" test 2 g_num is %d"%g_num) p1 = Thread(target=test1) p1.start() #time.sleep(3) p2 = Thread(target=test2) p2.start()
e2c959e1a18bb0321d69ffa040f1d709d717c296
remix7/python3-nome
/learning/LenClass.py
360
3.921875
4
class myClass1: """A simple example class""" def __init__(self): # 构造函数 self.data = [] i = 12345 # 普通成员属性 def f(self): # 普通成员函数 return 'what fuck' class A: pass class myClass2: def __init__(self, r, i): self.r = r self.i = i x = myClass1() print(x.f())
fd172a7bbc1eb7a5fe0426f99302bca769d277bc
remix7/python3-nome
/learningpy3/raiseException.py
283
3.828125
4
class ShortInputException(Exception): def __init__(self,first,last): self.first = first self.last = last def main(): try: s = "an" if len(s) < 3: raise ShortInputException(len(s),3) except ShortInputException as res : print(res) else: print("no exception") main()