blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
b3c1c94a87340fa2537d644660798bb54ee2226e
N03230384/ELSpring2017
/code/CodeFinalProject/misc/mo_JS.py
817
4.03125
4
#!/usr/bin/python # Start by importing the libraries we want to use import RPi.GPIO as GPIO # This is the GPIO library we need to use the GPIO pins on the Raspberry Pi import time # This is the time library, we need this so we can use the sleep function import os GPIO.setmode(GPIO.BCM) channel = 17 GPIO.setup(channel, GPIO.IN) # This is our callback function, this function will be called every time there is a change on the specified GPIO channel, in this example we are using 17 try: print("Starting Soil Humidity Sensor") time.sleep(3) os.system('clear') print("Ready") while True: if GPIO.input(channel) == GPIO.HIGH: print("motor on") time.sleep(1) else: print("motor off") time.sleep(1) except KeyboardInterrupt: os.system('clear') print("exiting cleanly") GPIO.cleanup()
db68b60ae250d15d598ca0cf89f4688415e2ad42
rishavh/UW_python_class_demo.code
/chapter_13/obscure_words_13_4.py
1,046
4.34375
4
#! /usr/bin/env python # # # Exercise 13-4 # # Modify the previous program to read a word list (see Section 9.1) and then # print all the words in the book that are not in the word list. How many of # them are typos? How many of them are common words that should be in the word # list, and how many of them are really obscure? import critique_book_13_2 import sys # This is pretty much all of exercise 9.1 def read_word_list() : """This function opens the file word.txt and reads it in, stripping all of the newlines from it. It then returns the contents of the file as a list""" fin = open("words.txt", "r") word_list = [] for line in fin : word = line.strip() word_list.append(word) fin.close() return word_list if __name__ == "__main__" : word_list = read_word_list() doc_word_list = critique_book_13_2.file_to_word_list( sys.argv[1] ) census = critique_book_13_2.word_counter ( doc_word_list ) for word in census : if word not in word_list : print word
4d6968af52ffc06ba7b6d2653af0cd91f220b2e7
sK4ri/5-6TW-Codecool-Python
/guess.py
746
3.921875
4
from random import randint def get_random_numbers(random_range): rand_nums = [] for number in range(10): rand_nums.append(randint(1, random_range)) return rand_nums def get_guess(random_range, ranges, rand_nums): for i in range(ranges): while True: guess = int(input("Enter an integer from 1 to %d : " % random_range)) if guess < rand_nums[i]: print("guess is low") elif guess > rand_nums[i]: print("guess is high") else: print("you guessed it!") break def main(): get_guess(99, 1, get_random_numbers(99)) get_guess(49, 10, get_random_numbers(49)) if __name__ == "__main__": main()
412b7a7114411edc4a3955899d29aa8e40685b41
zjyExcelsior/python-commons
/python_commons/binary_search.py
1,104
3.953125
4
# coding=utf-8 """二分查找算法""" def binary_search(list_, item): """二分查找(非递归方式)""" start, end = 0, len(list_) - 1 while start <= end: mid = (start + end) // 2 if list_[mid] == item: return True elif item < list_[mid]: end = mid - 1 else: start = mid + 1 return False def binary_search2(list_, item): """二分查找(递归方式)""" start, end = 0, len(list_) - 1 if start > end: return False mid = (start + end) // 2 if list_[mid] == item: return True elif item < list_[mid]: return binary_search2(list_[:mid], item) else: return binary_search2(list_[mid + 1:], item) if __name__ == '__main__': list_ = [1, 2, 3, 4, 5, 6] assert False is binary_search(list_, 0) assert False is binary_search2(list_, 0) assert False is binary_search(list_, 10) assert False is binary_search2(list_, 10) for i in xrange(1, 7): assert True is binary_search(list_, i) assert True is binary_search2(list_, i)
426a0238d39eb9efec3fd37847017f80f8962d0c
minoritydev/fridepro
/numpad.py
1,585
3.625
4
from tkinter import * windowQty=Tk() vegSearchEntry = Entry(windowQty, width=50, font=("Helvetica", 20)) vegSearchEntry.place(x=0, y=120) def numpadInput(num): global pos # this will make sure that the increment following next line is on the variable that is outside the numpadInput() function # put this function in quantityWindow() and line # 17 inside the block of quantityWindow() # If this does not work in our ui.py file , try putting the line #17 of this file in the most outside scope in ui.py (preferrably below import lines) vegSearchEntry.insert(pos,num) pos+=1 pos=0 button0=Button(windowQty, text="0",command=lambda:numpadInput("0")).place(x=200, y=320) button1=Button(windowQty, text="1",command=lambda:numpadInput("1")).place(x=160, y=200) button2=Button(windowQty, text="2",command=lambda:numpadInput("2")).place(x=200, y=200) button3=Button(windowQty, text="3",command=lambda:numpadInput("3")).place(x=240, y=200) button4=Button(windowQty, text="4",command=lambda:numpadInput("4")).place(x=160, y=240) button5=Button(windowQty, text="5",command=lambda:numpadInput("5")).place(x=200, y=240) button6=Button(windowQty, text="6",command=lambda:numpadInput("6")).place(x=240, y=240) button7=Button(windowQty, text="7",command=lambda:numpadInput("7")).place(x=160, y=280) button8=Button(windowQty, text="8",command=lambda:numpadInput("8")).place(x=200, y=280) button9=Button(windowQty, text="9",command=lambda:numpadInput("9")).place(x=240, y=280) windowQty.mainloop()
a3c29c5fb9b04e6ffff3bab67c701358aab14256
nicolasgoris/advent_of_code_2020
/day1.py
611
3.640625
4
import sys def part1(numbers, target, left): right = len(numbers) - 1 while left < right: tuple = numbers[left], numbers[right] if sum(tuple) == target: return tuple[0] * tuple[1] if sum(tuple) > target: right -= 1 else: left += 1 def part2(numbers, target): for i, number in enumerate(numbers): result = part1(numbers, target - number, i + 1) if result: return result * number assert len(sys.argv) == 2 numbers = list(map(int, open(sys.argv[1]).read().split())) numbers.sort() print(f'Part 1: {part1(numbers, 2020, 0)} - Part 2: {part2(numbers, 2020)}')
489a1fd0195c6ed120df9bd09c7c5e6792151c56
mmikhalina/lab_10
/1.py
391
4
4
''' 1. Сформувати функцію, що буде обчислювати факторіал заданого користувачем натурального числа n. ''' def factorial(x): if x < 0: raise ValueError('Error') if x == 0: return 1 else: return x * factorial(x - 1) n = int(input("your num is ")) print(factorial(n))
b7f393b3ebafcb2cf2f2ff50eb06506db3f12d4e
simbachange/IntroPython2016
/students/simba_change/session_04/dict_lab.py
598
3.515625
4
city = {'name': 'Chris', 'city': 'Seattle', 'Cake': 'Chocolate'} print (city) city.pop('Cake') print (city) city.update{('fruit':'mango')} print (city) for k , v in city.items(): print('Key: ' + k + 'Value:' + v) 'Cake' in city.keys() 'Mango' in city.values() new_city = {'name':'0','fruit': '0', 'city': '2'} s2 = {"0","2","4","6","8","10","12","14","16","18","20"} s3 = {"0","3","6","9","12","15","18"} s4 = {"0","4","8","12","16","20"} s3.issubset(s2) s4.issubset(s2) p = {"P","y","t","h","o","n"} p.update("i") mr = frozenset(("marathon")) p.union(mr) p.intersection(mr)
d4fb7fed6e0d3b2b7b73d0abc15474e789a5bd63
Taoge123/OptimizedLeetcode
/LeetcodeNew/python2/LC_1206.py
1,834
3.859375
4
import random class Node: def __init__(self, val=-1, right=None, down=None): self.val = val self.right = right self.down = down class Skiplist: def __init__(self): self.head = Node() def search(self, target: int) -> bool: node = self.head while node: # move to the right in the current level while node.right and node.right.val < target: node = node.right if node.right and node.right.val == target: return True # move to the next level node = node.down return False def add(self, num: int) -> None: nodes = [] node = self.head while node: while node.right and node.right.val < num: node = node.right nodes.append(node) node = node.down insert = True down = None while insert and nodes: node = nodes.pop() node.right = Node(num, node.right, down) down = node.right insert = (random.getrandbits(1) == 0) # create a new level with a dymmy head # right = None # down = current head if insert: self.head = Node(-1, None, self.head) def erase(self, num: int) -> bool: node = self.head found = False while node: # move to the right in the current level while node.right and node.right.val < num: node = node.right # find the target node if node.right and node.right.val == num: # delete by skipping node.right = node.right.right found = True # move to the next level node = node.down return found
5b790140700cffab042e7b6e9d70c40553b6ea2e
geronimo0630/2021
/TALLERQUIZ2/quiz2punto3.py
300
3.53125
4
listaPesos = [20000,30000,4000,2500,1000,7600] mensajeMayot = 'El numero ingresad es : ' mensajeMenor = 'el numero ingresado es : ' mensajePromedio ='el promedio es : ' print (mensajeMayot,max(listaPesos)) print (mensajeMenor, min(listaPesos)) print (mensajePromedio,sum(listaPesos)/len(listaPesos))
9c80cadb34e77e141b558a7260ffa771824b2154
MartinMa28/Algorithms_review
/string/0014_longest_common_prefix.py
832
3.546875
4
class Solution: def _common_prefix(self, str1, str2): c_prefix = '' for i in range(min(len(str1), len(str2))): if str1[i] == str2[i]: c_prefix += str1[i] else: break return c_prefix def longestCommonPrefix(self, strs: List[str]) -> str: if strs == []: return '' if len(strs) == 1: return strs[0] c_prefix = self._common_prefix(strs[0], strs[1]) for i in range(2, len(strs)): if strs[i].startswith(c_prefix): continue else: c_prefix = self._common_prefix(c_prefix, strs[i]) if c_prefix == '': return '' return c_prefix
0c1c3f0c5e7f5188fca21e4a4b620dacc5f1e013
amanchadha/coursera_machine_learning_matlab_python
/algorithms_in_python/week_3/ex2/plotData.py
934
3.75
4
import matplotlib.pyplot as plt import numpy as np def plotData(X, y, xlabel, ylabel, posLineLabel, negLineLabel): """PLOTDATA Plots the data points X and y into a new figure PLOTDATA(x,y) plots the data points with + for the positive examples and o for the negative examples. X is assumed to be a Mx2 matrix.""" #for large scale data set use plt.plot instead of scatter! #training_data_plot = plt.scatter(X[:,0], X[:,1], 30, marker='x', c=y, label="Training data") #cbar= plt.colorbar() #cbar.set_label("Admission") pos = np.where(y == 1) neg = np.where(y == 0) line_pos = plt.plot(X[pos, 0], X[pos, 1], marker='+', color='black', label=posLineLabel , linestyle='None')[0] line_neg = plt.plot(X[neg, 0], X[neg, 1], marker='o', color='yellow', label=negLineLabel, linestyle='None')[0] plt.xlabel(xlabel) plt.ylabel(ylabel) return line_pos, line_neg
043d0b34178af54b1125fc53b0cb577a9900ea9a
ankitgupta123445/python
/circle.py
530
4.1875
4
x=int(input("enter the x coordinate of center")) y=int(input("enter the y coordinate of center")) r=int(input("enter the radius of circle")) x1=int(input("enter the x coordinate of arbitrary point")) y1=int(input("enter the y coordinate of arbitrary point")) z=((x-x1)**2+(y-y1)**2)**0.5 if z==0: print("point are lie on the center of cicle") elif z<r: print("points is lie inside the circle") elif z==r: print("points is lie on the circle") else : print("points is lie outside the circle")
3250e9b28e6c2d7b57fa3c30151acec1dc5a1864
tomlxq/ps_py
/leetcode/test_Leetcode1.py
1,046
3.53125
4
#!/usr/bin/python # -*- coding: utf-8 -*- import unittest from Leetcode1 import Leetcode1 class TestLeetcode1(unittest.TestCase): def test_two_sum(self): self.assertEquals(Leetcode1.twoSum(self, [2, 7, 11, 15], 9), [0, 1]) self.assertEquals(Leetcode1.twoSum(self, [3, 2, 4], 6), [1, 2]) self.assertEquals(Leetcode1.twoSum(self, [3, 3], 6), [0, 1]) self.assertEquals(Leetcode1.twoSum2(self, [2, 7, 11, 15], 9), [0, 1]) self.assertEquals(Leetcode1.twoSum2(self, [3, 2, 4], 6), [1, 2]) self.assertEquals(Leetcode1.twoSum2(self, [3, 3], 6), [0, 1]) self.assertEquals(Leetcode1.twoSum3(self, [2, 7, 11, 15], 9), [1, 2]) self.assertEquals(Leetcode1.twoSum3(self, [2, 3, 4], 6), [1, 3]) self.assertEquals(Leetcode1.twoSum3(self, [-1, 0], -1), [1, 2]) self.assertEquals(Leetcode1.twoSum4(self, [2, 7, 11, 15], 9), [1, 2]) self.assertEquals(Leetcode1.twoSum4(self, [2, 3, 4], 6), [1, 3]) self.assertEquals(Leetcode1.twoSum4(self, [-1, 0], -1), [1, 2])
14843bc9db87edc6e473fe46abebe1a6887b4dfa
wangxuan12/algorithm
/w3/78.subsets.py
1,103
3.578125
4
# # @lc app=leetcode id=78 lang=python3 # # [78] Subsets # # https://leetcode.com/problems/subsets/description/ # # algorithms # Medium (58.91%) # Likes: 3208 # Dislikes: 75 # Total Accepted: 520K # Total Submissions: 879K # Testcase Example: '[1,2,3]' # # Given a set of distinct integers, nums, return all possible subsets (the # power set). # # Note: The solution set must not contain duplicate subsets. # # Example: # # # Input: nums = [1,2,3] # Output: # [ # ⁠ [3], # [1], # [2], # [1,2,3], # [1,3], # [2,3], # [1,2], # [] # ] # # # @lc code=start class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: ans = [] if not nums: return ans self.dfs(ans, 1, nums, []) return ans def dfs(self, ans, level, nums, temp): if level == len(nums): ans.append(temp.copy()) return for i in range(len(nums)): if nums[i] in temp: continue self.dfs(ans, level + 1, nums, temp) temp.append(nums[i]) self.dfs(ans, level + 1, nums, temp) # @lc code=end
6fabcaba1ab2b1d4bc55133f3fd9a9aa091d847a
wilbertgeng/LintCode_exercise
/Two_Pointers/148.py
923
3.859375
4
"""148. Sort Colors """ class Solution: """ @param nums: A list of integer which is 0, 1 or 2 @return: nothing """ def sortColors(self, nums): # write your code here ### Practice r, w, b = 0, 0 , len(nums) - 1 while w <= b: if nums[w] == 0: nums[w], nums[r] = nums[r], nums[w] w += 1 r += 1 if nums[w] == 1: w += 1 if nums[w] == 2: nums[w], nums[b] = nums[b], nums[w] b -= 1 ### r, w, b = 0, 0, len(nums) - 1 while w <= b: if nums[w] == 0: nums[r], nums[w] = nums[w], nums[r] r += 1 w += 1 elif nums[w] == 1: w += 1 elif nums[w] == 2: nums[w], nums[b] = nums[b], nums[w] b -= 1
1a8c6f769b0657295f1cd09356a1122d9afa2b72
praveenv253/idsa
/12-2-13/palin2.py
6,487
3.6875
4
#!/usr/bin/env python def inc(char): if char not in list('123456789'): raise ValueError if char == '9': return 0 else: return str(int(char)+1) def main(): import sys # Throw away the first line sys.stdin.readline() for q in sys.stdin.readlines(): q = q[:-1] # Remove the trailing newline character l = len(q) if l == 1: # Take care of single digit input and single 9 if q == '9': sys.stdout.write('11\n') else: sys.stdout.write(str(int(q) + 1) + '\n') continue if l % 2 == 0: # Look at numbers from the middle outwards and compare i = l/2 j = i-1 while q[i] == q[j] and j: i += 1 j -= 1 # If the entire string is a palindrome, then j would have become 0 # and i would have become l-1 if j == 0 and q[i] == q[j]: # The next palindrome involves incrementing from the middle and # taking care of carry pos = l/2 - 1 replacement = inc(q[pos]) # Take care of possible nines in the middle while replacement == 0 and pos > 0: pos -= 1 replacement = inc(q[pos]) # By now, either replacement worked out, or pos is at zero. if pos == 0 and replacement == 0: # All nines! sys.stdout.write('1' + '0'*(len(q)-1) + '1\n') continue # Go on to next input line # Not all nines. pos points to where replacement worked out. # Print out everything upto pos, excluded. Then print the # replacement, and finally print a suitable number of zeros. half_string = q[:pos] + replacement + '0'*(l/2-1-pos) sys.stdout.write(half_string + half_string[::-1] + '\n') continue # The entire string is not a palindrome. j may be zero, but then # the last digit did not match. if q[i] < q[j]: # This is the simplest case where the first non-matching i is # less than j. Meaning, we can just make i=j and be done. sys.stdout.write(q[:i] + q[:j+1][::-1] + '\n') continue else: # Otherwise, we need to start incrementing from the middle. pos = l/2 - 1 replacement = inc(q[pos]) # Take care of possible nines in the middle while replacement == 0 and pos > 0: pos -= 1 replacement = inc(q[pos]) # By now, either replacement worked out, or pos is at zero. # Not all nines. pos points to where replacement worked out. # Print out everything upto pos, excluded. Then print the # replacement, and finally print a suitable number of zeros. half_string = q[:pos] + replacement + '0'*(l/2-1-pos) sys.stdout.write(half_string + half_string[::-1] + '\n') continue # Otherwise, string length is odd else: # Look at numbers from the middle outwards and compare i = l/2 + 1 j = i-2 while q[i] == q[j] and j: i += 1 j -= 1 # If the entire string is a palindrome, then j would have become 0 # and i would have become l-1 if j == 0 and q[i] == q[j]: # The next palindrome involves incrementing from the middle and # taking care of carry pos = l/2 replacement = inc(q[pos]) # Take care of possible nines in the middle while replacement == 0 and pos > 0: pos -= 1 replacement = inc(q[pos]) # By now, either replacement worked out, or pos is at zero. if pos == 0 and replacement == 0: # All nines! sys.stdout.write('1' + '0'*(len(q)-1) + '1\n') continue # Go on to next input line # Not all nines. pos points to where replacement worked out. # Print out everything upto pos, excluded. Then print the # replacement, and finally print a suitable number of zeros. if pos == l/2: half_string = q[:pos] sys.stdout.write(half_string + replacement + half_string[::-1] + '\n') else: half_string = q[:pos] + replacement + '0'*(l/2-pos) sys.stdout.write(half_string + '0' + half_string[::-1] + '\n') continue # The entire string is not a palindrome. j may be zero, but then # the last digit did not match. if q[i] < q[j]: # This is the simplest case where the first non-matching i is # less than j. Meaning, we can just make i=j and be done. sys.stdout.write(q[:i] + q[:j+1][::-1] + '\n') continue else: # Otherwise, we need to start incrementing from the middle. pos = l/2 replacement = inc(q[pos]) # Take care of possible nines in the middle while replacement == 0 and pos > 0: pos -= 1 replacement = inc(q[pos]) # By now, either replacement worked out, or pos is at zero. # Not all nines. pos points to where replacement worked out. # Print out everything upto pos, excluded. Then print the # replacement, and finally print a suitable number of zeros. if pos == l/2: half_string = q[:pos] sys.stdout.write(half_string + replacement + half_string[::-1] + '\n') else: half_string = q[:pos] + replacement + '0'*(l/2-1-pos) sys.stdout.write(half_string + '0' + half_string[::-1] + '\n') continue if __name__ == '__main__': main()
9e92718a4fc65c1e0fa7942b260d7380c9d72d92
leksiam/PythonCourse
/Practice/plotnikova/lecture6_task3.py
428
3.578125
4
import time class ContextManager(): def __init__(self): self.start_time = time.time() def __enter__(self): print('Starting code inside') def __exit__(self, exc_type, exc_val, exc_tb): print("--- %s seconds ---" % (time.time() - self.start_time)) with ContextManager(): for i in range(10000): # для нагрузки, чтобы на выходе был не 0 a = i ** 2
164e242d859fc7a3176f28e41f282093fe2034a8
FarrowGK/Python_OOP.py
/math_dojo.py
761
3.640625
4
class Mathdojo(object): def __init__(self): pass def add(self, addition, *args): if type(addition) is list or tuple: self.addition = sum(addition) arr1.append(self.addition) else: self.addition = addition arr1.append(self.addition) if type(args) is list or tuple and not int: self.args = sum(args) arr1.append(self.args) else: self.args = args[0] arr1.append(self.args) return self def result(self): self.sumthis = sum(arr1[3]) arr1[3] = self.sumthis print arr1 return self arr1 = [] md = Mathdojo() md.add([1],3,4).add([3,5,7,8], [2,4.3,1.25]).result()
717b570ffdf81f577eb130713101d6904324c3f8
mr-m0nkey/20-questions
/answers/Python/@oseme-techguy/05-temperature-unit-conversion.py
1,059
4.28125
4
""" Solution to Temperature Unit Conversion """ if __name__ == '__main__': selection = input( 'Select a Conversion Type Below:\n' + '\t1. Celsius to Fahrenheit\n' + '\t2. Fahrenheit to Celsius\n' ) # type checking here try: selection = int(selection) except ValueError: selection = 0 if selection == 1: value = input('Enter a celsius value: ') value = float(value) fahrenheit = (value * (9.0 / 5.0)) + 32.0 print('{celsius} degrees celsius is {fahrenheit} degrees fahrenheit\n'.format( celsius=value, fahrenheit=fahrenheit )) elif selection == 2: value = input('Enter a fahrenheit value: ') value = float(value) celsius = ((value - 32.0) * (5.0 / 9.0)) print('{fahrenheit} degrees fahrenheit is {celsius} degrees celsius\n'.format( fahrenheit=value, celsius=celsius )) else: print('Invalid Option Selected!\n')
7f6fe3ee265cb171da33282b1f601eb9e7d63372
Taeg92/Problem_solving
/SWEA/D3/SWEA_4047.py
1,585
3.625
4
# Problem [4047] : 영준이의 카드 카운팅 # 입력 : 가지고 있는 카드의 무늬 종류와 카드 숫자를 입력 # 각 무늬별로 13장의 카드를 만드는 데 부족한 카드 수를 출력 def my_card(cards): my_card = [[] for _ in range(4)] result = list() for card in cards: if card[0] == 'S': num = int(''.join(map(str,card[1]))) if num not in my_card[0]: my_card[0].append(num) else : return 'ERROR' elif card[0] == 'D': num = int(''.join(map(str,card[1]))) if num not in my_card[1]: my_card[1].append(num) else : return 'ERROR' elif card[0] == 'H': num = int(''.join(map(str,card[1]))) if num not in my_card[2]: my_card[2].append(num) else : return 'ERROR' elif card[0] == 'C': num = int(''.join(map(str,card[1]))) if num not in my_card[3]: my_card[3].append(num) else : return 'ERROR' for c in my_card: result.append(13-len(c)) result = ' '.join(map(str,result)) return result T = int(input()) for tc in range(1, T+1): data = input() data = data.replace('A','01') data = data.replace('J','11') data = data.replace('Q','12') data = data.replace('K','13') cards = [[data[i], data[i+1:i+3]] for i in range(0, len(data), 3)] result = my_card(cards) print('#{} {}'.format(tc,result))
43451c5776e2f13c8af48795305002a09843bff6
1MT3J45/pyprog
/exception.py
274
3.609375
4
a=int(raw_input('Enter a number ')) b=int(raw_input('Enter a number ')) try: x=a/b print x raise NameError('Hello') except ArithmeticError as a: print 'Program terminated : ',a except NameError as a: print 'Program terminated : ',a finally: print 'Done successfully'
975d02b137cad2c75ddb5942abda6e8872094245
alok1994/Python_Programs-
/overriding_function.py
166
3.546875
4
class A: def add_nums(self,a,b): return a+ b class B: def add_nums(self,a,b,c): return a + b + c a = A() print a.add_nums(2,3) b = B() print b.add_nums(2,3,4)
caa162557c1b0c2ac174d29eea6fb5d308644355
dsert1/Tetris-Solver
/game.py
3,741
3.75
4
"""DO NOT EDIT THIS FILE. YOU DON'T NEED TO READ THIS FILE. Useful function are documented and imported in the provided `solver.py` template that you need to implement. Main tetris game implementation. Handles game state, move making, and collision logic. Inspired by: https://gist.github.com/silvasur/565419/d9de6a84e7da000797ac681976442073045c74a4 """ # To make things look pretty. colors = [ (0, 0, 0), (255, 0, 0), (0, 150, 0), (0, 0, 255), (255, 120, 0), (255, 255, 0), (180, 0, 255), (0, 220, 220), ] # fmt: off tetris_shapes = { "T": [[1, 1, 1], [0, 1, 0]], "S": [[0, 2, 2], [2, 2, 0]], "SFlip": [[3, 3, 0], [0, 3, 3]], "L": [[4, 0, 0], [4, 4, 4]], "LFlip": [[0, 0, 5], [5, 5, 5]], "I": [[6, 6, 6, 6]], "O": [[7, 7], [7, 7]] } # fmt: on def rotate_clockwise(shape): return [ [shape[y][x] for y in range(len(shape))] for x in range(len(shape[0]) - 1, -1, -1) ] def check_collision(board, shape, offset): off_x, off_y = offset for cy, row in enumerate(shape): for cx, cell in enumerate(row): try: if cell and board[cy + off_y][cx + off_x]: return True except IndexError: return True return False def join_matrixes(mat1, mat2, mat2_off): off_x, off_y = mat2_off for cy, row in enumerate(mat2): for cx, val in enumerate(row): mat1[cy + off_y - 1][cx + off_x] += val return mat1 class Board(object): def __init__(self, rows, columns): self.rows = rows self.columns = columns self._board = [[0 for x in range(self.columns)] for y in range(self.rows)] self._board += [[1 for x in range(self.columns)]] def copy(self): board = Board(self.rows, self.columns) board._board = [row[:] for row in self._board] return board def skyline(self): skyline = [0 for _ in range(self.columns)] last_row = self.rows - 1 for column in range(self.columns): for row in range(self.rows): if self._board[row][column] != 0: skyline[column] = self.rows - row break return skyline def move(self, shape_name, x, rotation): shape = tetris_shapes[shape_name] for _ in range(rotation): shape = rotate_clockwise(shape) if x < 0 or x >= self.columns: raise ValueError("x has to be between 0 and number of columns-1.") if check_collision(self._board, shape, (x, 0)): raise ValueError("Invalid move!") final_y = self.rows - 1 for y in range(self.rows): if check_collision(self._board, shape, (x, y)): final_y = y break try: self._board = join_matrixes(self._board, shape, (x, final_y)) except IndexError: raise ValueError("Invalid move!") def print(self): for row in range(self.rows): row_string = "".join( [ "." if self._board[row][column] == 0 else "#" for column in range(self.columns) ] ) print(row_string) def board_from_heights(heights, rows, columns): board = Board(rows, columns) for column, h in enumerate(heights): for row in range(rows - h, rows): board._board[row][column] = 1 return board
0a426f20f96530f855ff71f1c07da94c42f99608
ee08b397/Introduction-to-Algorithms
/Chapter 2-Getting Started/Exercises/2.2/2.2-4.py
612
3.875
4
# Exercise 2.2-4: # See the pseudocode below. def job_not_done(): # For a given solvable problem, there should be a way to check if it's solved or not # Here is the part that verifies a solution. return check_result def work(input_data): # For a given solvable problem, it should be solved using finite amount of time and space # Here is the part that solves the problem. pass def fun(input_data): while job_not_done(): # We can stop the algorithm by checking if the work is already done. # The earlier we check, the shorter the best case running time can be. work(input_data) return output_data
d4952a7d52ffaba9ea1c3344891e3b75dae2be63
phyo17/GHI-lessons
/Python/Video lessons/9ForLoopWithExample.py
563
3.671875
4
#For loop # i=0 # for i in range(5): # print(i) # i=0 # z=range(5) # for i in z: # print(i) # l=[10,11,12,13,14,15] # print(l[0]) # for i in l: # print(i) # s='phyopyaesone' # for i in s: # print(i) s=('a','b','c',3,4,5) for i in s: print(i) floatnum=[1.2,1.3,1.4,1.5,1.6,10.5] print('The numbers first select is ',floatnum[0:3]) print('The numbers second select is ',floatnum[2:-1]) print('All float number in list is ',floatnum[:]) a=[1,2,3,4,5] b=[1,2,3,4,5] print('Address of list a is ',id(a)) print('Address of list b is ',id(b))
84cd25f426e351f6f9f4451978f7987666dcb512
guhaigg/python
/month01/day19/review01.py
1,599
4.28125
4
""" 补充 一.Python内存管理机制 1. 引用计数:每个数据都存储着被变量绑定的次数 当为0时被销毁. 当遇到循环引用时,会导致内存泄露. a = 10 b = a 此时数据10的引用计数为2 del a b = 20 此时数据10的引用计数为0 因为循环引用,导致内存泄露的代码: list01 = [] list02 = [] list01.append(list02) list02.append(list01) 此时列表的引用计数为2 del list01,list02 此时列表的引用计数为1 应该销毁但是不能销毁 2. 标记清除 全盘扫描内存空间,检查数据是否可用. 如果不可用则做出清除的标记. 缺点:全盘扫描过慢 3. 分代回收 运行程序时,将内存分为小中大三代. 创建新数据时,在小代分配空间. 在内存告急时,触发"标记清除". 将有用的数据升代,没用的数据释放 优化内存: 尽少产生垃圾,对象池,配置垃圾回收器 """ # 对象池 # 每次创建数据时,都先判断池中是否有相同成员 # 如果有直接返回数据地址,没有再开辟空间存储. data01 = "10.6546351456" data02 = "10.6546351456" print(id(data01)) print(id(data02))
caec85c6969821bbdbfcae55cc864f975f445617
gselva28/100_days_of_code
/DAY 01/print things.py
450
4.15625
4
#print stuffs print("hello world!!") print("Prints the things which is inside the comment") #String manipulation print("hello world!!\n Prints the thing which is inside the comment") #string concatenation print("Hello" + " " + "Selva") print('String Concatenation is done with the "+" sign') #input management input("Enter your name: ") print("Hello " + input("What is your name?")+"!") #input length finder print(len(input("Enter your name")))
6b9ef764a90227a22c99d0c9d1529c6aed09a9f5
charles-debug/learning_record
/76-公共操作之运算符乘号.py
213
3.6875
4
str1 = 'a' list1 = ['hello'] t1 = ('world',) # *:复制 print(str1 *5) # aaaaa print(list1 *5) #['hello', 'hello', 'hello', 'hello', 'hello'] print(t1*5) # ('world', 'world', 'world', 'world', 'world')
94707923ad8945e4675d9bcb0033aa73f7902cb4
andutzu7/Lucrare-Licenta-MusicRecognizer
/NN/NNModule/Metrics/ActivationSoftmaxCategoricalCrossentropy.py
661
3.546875
4
import numpy as np # Softmax classifier - combined Softmax activation # and cross-entropy loss for faster backward step class Activation_Softmax_Loss_CategoricalCrossentropy(): # Backward pass def backward(self, derivated_values, y_true): # Number of samples samples = len(derivated_values) # If labels are one-hot encoded, # turn them into discrete values if len(y_true.shape) == 2: y_true = np.argmax(y_true, axis=1) # Copy so we can safely modify self.derivated_inputs = derivated_values.copy() # Calculate gradient self.derivated_inputs[range(samples), y_true] -= 1
1761a497785e9bac3a1ba032c4c5d14bd4224c41
Xevion/exercism
/python/house/house.py
1,089
3.5
4
# Constants for building the rhyme secondaries = ['sowing his corn', 'that crowed in the morn', 'all shaven and shorn', 'all tattered and torn', 'all forlorn', 'with the crumpled horn'] verbs = ['belonged to', 'kept', 'woke', 'married', 'kissed', 'milked', 'tossed', 'worried', 'killed', 'ate',] nouns = ['farmer', 'rooster', 'priest', 'man', 'maiden', 'cow', 'dog', 'cat', 'rat', 'malt',] intial = 'This is the house that Jack built.' first = 'This is the horse and the hound and the horn' last = 'that lay in the house that Jack built.' # Build the array of verses lines = (["that {} the {}{}".format(verbs[i], nouns[i], '' if i > 5 else ' ' + secondaries[i]) for i in range(10)])[::-1] # Build a specific verse def verse(n): if n == 1: return [intial] if n == 12: return [first] + [lines[-1]] + verse(11)[1:] return ["This is the {}{}".format( nouns[len(nouns) - n + 1], '' if n < 6 else f' {secondaries[-n + 5 ]}')] + [lines[i - 3] for i in range(n, 2, -1)] + [last] recite = lambda start, end : [' '.join(verse(x)) for x in range(start, end + 1)]
6fd8ae928777131af68160c3f2d7477fba2483bf
JackJuno/Tic-Tac-Toe
/tictactoe.py
2,043
4
4
import math board = [[' ' for i in range(0, 3)] for j in range(0, 9, 3)] print('---------') for i in board: print('| {} |'.format(' '.join(i))) print('---------') step_turn_sign = 'X' step_count = 0 while True: x, y = input('Enter the coordinates: ').split() # check if user input is numbers if x.isnumeric() and y.isnumeric(): x = int(x) y = int(y) else: print('You should enter numbers!') continue # check if coordinates in the field if x not in range(1, 4) or y not in range(1, 4): print('Coordinates should be from 1 to 3!') continue # check if cell is empty column = x - 1 row = 3 - y if board[row][column] == ' ': board[row][column] = step_turn_sign print('---------') for i in board: print('| {} |'.format(' '.join(i))) print('---------') step_count += 1 else: print('This cell is occupied! Choose another one!') continue match = [] # check for lines for i in range(3): if board[i][0] == board[i][1] == board[i][2] != ' ': match.append(step_turn_sign) # check for columns for j in range(3): if board[0][j] == board[1][j] == board[2][j] != ' ': match.append(step_turn_sign) # check for diagonals if board[0][0] == board[1][1] == board[2][2] != ' ': match.append(step_turn_sign) elif board[0][2] == board[1][1] == board[2][0] != ' ': match.append(step_turn_sign) # result printing if len(match) > 1 or math.fabs(board.count('X') - board.count('O')) > 1: print('Impossible') continue elif len(match) == 0 and ' ' in board: print('Game not finished') continue elif len(match) == 0 and ' ' not in board and step_count == 9: print('Draw') break elif len(match) == 1: print('{} wins'.format(match[0])) break if step_turn_sign == 'X': step_turn_sign = 'O' else: step_turn_sign = 'X'
c8af2f4b7a34a652b3e70beec36d346ba82c19d3
amit-gupta-16/git-in-one-video
/Ex-5 Health managment sys.py
4,781
4.03125
4
# # Health Managment system # # Manage 3 clients data - Amit, Ankit, mohit # make 6 files - 3 for diet and 3 for exercises record # how program will works: # asks for client name - 3 options to choose # asks for log data or retrieve data - two options # ask about diet or exercise # # How data will store: [display time] exercise name or diet name and display client name at above '''=============FIRST ATTEMPT===========''' # print(":: Health Managment System ::\n\n") # # FOR LOGGING THE DATA # def log_data(): # client_name = int(input("Press 1 for Amit\nPress 2 for Ankit\nPress 3 for Mohit\n")) # if client_name == 1: # d_or_e = int(input("What you want to log - \nPress 1 for diet\nPress 2 for exercise\n")) # if d_or_e == 1: # with open("amit_diet.txt","a") as f: # diet_log = input("Enter what you eat today - \n") # f.write(diet_log) # else: # with open("amit_exercise.txt", "a") as f: # exe_log = input("Enter which exercise you do todya - \n") # f.write(exe_log) # elif client_name == 2: # d_or_e = int(input("What you want to log - \nPress 1 for diet\nPress 2 for exercise\n")) # if d_or_e == 1: # with open("ankit_diet.txt", "a") as f: # diet_log = input("Enter what you eat today - \n") # f.write(diet_log) # else: # with open("ankit_exercise.txt", "a") as f: # exe_log = input("Enter which exercise you do today - \n") # f.write(exe_log) # elif client_name == 3: # d_or_e = int(input("What you want to log - \nPress 1 for diet\nPress 2 for exercise\n")) # if d_or_e == 1: # with open("mohit_diet.txt", "a") as f: # diet_log = input("Enter what you eat today - \n") # f.write(diet_log) # else: # with open("mohit_exercise.txt", "a") as f: # exe_log = input("Enter which exercise you do today - \n") # f.write(exe_log) # # FOR RETRIEVING THE DATA # def retrieve_data(): # client_name = int(input("Press 1 for Amit\nPress 2 for Ankit\nPress 3 for Mohit\n")) # if client_name == 1: # d_or_e = int(input("What you want to retrieve - \nPress 1 for diet\nPress 2 for exercise\n")) # if d_or_e == 1: # with open("amit_diet.txt") as f: # print(f.read()) # else: # with open("amit_exercise.txt") as f: # print(f.read()) # elif client_name == 2: # d_or_e = int(input("What you want to retrieve - \nPress 1 for diet\nPress 2 for exercise\n")) # if d_or_e == 1: # with open("ankit_diet.txt") as f: # print(f.read()) # else: # with open("ankit_exercise.txt") as f: # print(f.read()) # elif client_name == 3: # d_or_e = int(input("What you want to retrieve - \nPress 1 for diet\nPress 2 for exercise\n")) # if d_or_e == 1: # with open("mohit_diet.txt") as f: # print(f.read()) # else: # with open("mohit_exercise.txt") as f: # print(f.read()) # log_or_retrieve = int(input("Press 1 for log data\nPress 2 for retrieve data\n")) # if log_or_retrieve == 1: # log_data() # elif log_or_retrieve == 2: # retrieve_data() '''===================SECOND ATTEMPT=====================''' # Amit's Solution = Ex-5 Health Managment system def gettime(): import datetime return datetime.datetime.now() def log_data(): name = input("Enter your name: ") d_or_e = int(input("Press 1 for Diet\nPress 2 for Exercise")) if d_or_e == 1: with open(name + "_diet.txt", "a") as f: diet = input("Enter what you eat today: ") f.write(str([str(gettime())]) + "\t" + diet + "\n") elif d_or_e == 2: with open(name + "_exercise.txt", "a") as f: exercise = input("Enter which exercise you perform today: ") f.write(str([str(gettime())]) + "\t" + exercise + "\n") def retrieve_data(): name = input("Enter your name: ") d_or_e = int(input("Press 1 for Diet\nPress 2 for Exercise")) if d_or_e == 1: with open(name + "_diet.txt") as f: print(f"{name.title()} ,you eat:\n" + f.read()) elif d_or_e == 2: with open(name + "_exercise.txt") as f: print(f"\n{name.title()} ,you perform following exercises:\n" + f.read()) print("\t\t\t::Health Managment System:: \n\n") inp = int(input("What you want to do-\nPress 1 for log data\nPress 2 for retrieve data")) if inp == 1: log_data() elif inp == 2: retrieve_data()
fb81295bc005d6d55dacf8969b876bd7ec254d28
sjzyjc/lintcode
/845/845.py
382
3.65625
4
class Solution: """ @param a: the given number @param b: another number @return: the greatest common divisor of two numbers """ def gcd(self, a, b): # write your code here big = max(a, b) small = min(a, b) if small == 0: return big return self.gcd(small, big % small) sl = Solution() print(sl.gcd(10,15))
a7674151f7fee59df4383fbfd7e1a81a9dcff765
MrReKT/Work1.0
/lesson-1/Programm.py
331
3.828125
4
__author__ = "Барыбин Вячеслав Русланович" name = input("Введите Имя") age = input("Введите Возраст") diff = int(age) - 18 if diff == 0: print(name, "равен", age) elif diff < 0: print(name, "Младше на", abs(diff), 'года(лет)') else: print(name, "Старше на", diff, 'Года(нет)')
34251d42e78634c01551e700ec645653ae748712
ishikashendge/python
/28 - AddTuple.py
115
3.796875
4
t = ('a','b','c','d') print(t) l=list(t) l.append(input("Enter element to be added - ")) t=tuple(l) print(t)
acee69089976da8444645899f935ff6de1520140
lalbricenov/quartaLiceo202021
/Web/Clase9/basico.py
1,576
4.25
4
# Variables x = 2 y = 4.5 nombre = "Quarta" # f strings:formatted strings como en C print(f"El tipo de variable de x es {type(x)} y su valor es {x}") print(f"El tipo de variable de y es {type(y)} y su valor es {y}") print(f"El tipo de variable de nombre es {type(nombre)} y su valor es {nombre}") notas = [3, 5.4, 6.9, 9.3, 9.4, 9.6] print(f"El tipo de variable de notas es {type(notas)} y su valor es {notas}") print(f"El tipo de variable la primera nota es {type(notas[0])} y su valor es {notas[0]}") print(f"El tipo de variable la segunda nota es {type(notas[1])} y su valor es {notas[1]}") # Diccionario en python estudiante = {"nombre":"Juan", "apellido":"Rodriguez", "edad":59, "notas":[6.7, 9.4, 7.5, 6.3 ]} # El apellido de Juan es Rodriguez, su edad es 59 y el promedio de sus notas es print(f"El apellido de {estudiante['nombre']} es {estudiante['apellido']} y su edad es {estudiante['edad']} y el promedio de sus notas es {sum(estudiante['notas'])/len(estudiante['notas']):.2f}") # OPERADORES # aritmeticos x=3 y=4.5 z=17 print(f"Division: {z/x}") print(f"Modulo (residuo): {z % x}") # logicos a = True b = False # tabla de verdad del and print("TABLA DE VERDAD DEL AND") print(f"T and T: {True and True}") print(f"T and F: {True and False}") print(f"F and T: {False and True}") print(f"F and F: {False and False}") # tabla de verdad del or print("TABLA DE VERDAD DEL OR") print(f"T or T: {True or True}") print(f"T or F: {True or False}") print(f"F or T: {False or True}") print(f"F or F: {False or False}") #print(f"And: {a and b}") #print(f"Or: {a or b}")
faa092daa29ddcfc2a2c05e5d5c7217eedeb120d
cmellojr/python
/employee_of_the_month.py
437
3.953125
4
#!/usr/bin/python3 work_hours = [('Abby',100), ('Billy', 4000), ('Cassie',800)] def employee_check(work_hours): current_max = 0 employee_of_month = '' for employee,hours in work_hours: if hours > current_max: current_max = hours employee_of_month = employee else: pass return (employee_of_month,current_max) x = employee_check(work_hours) print(x)
5b1246c4718bcd36d152cddd9111be40f31e8ad9
justinuzoije/List_exercises
/positive_numbers2.py
275
4.03125
4
numberList = [] posNumbers = [] howMany = int(raw_input("How many numbers?: ")) for i in range(howMany): number = int(raw_input("Please enter a number: ")) numberList.append(number) for i in numberList: if i > 0: posNumbers.append(i) print posNumbers
dc4487232935751d3d9919c3fe842294748507d7
OgnyanPenkov/Programming0-1
/week1/5-Saturday-Tasks/solutions/print_digits.py
496
3.75
4
# Тук ползваме следната идея # Ако имаме едно число n # n % 10 ни дава последната цифра на това число # n // 10 ни дава числото без последната цифра # Ако n е само 1 цифра, n // 10 ще даде 0. Това е и условието за край на цикъла n = input("Enter number: ") n = int(n) while n != 0: digit = n % 10 print(digit) n = n // 10
1daa78aac4a8b0180573e88266011f65f77861a5
algorithm006-class01/algorithm006-class01
/Week_01/G20200343030585/LeetCode_66_585.py
983
3.71875
4
# -*- coding:utf-8 -*- # 解题思路 # 1.输入是非负整数组成的数组,每个元素为一个数字 # 2.要求在这个数字上+1,然后再按大小输出到数组,保证在数组里面的顺序是从大到小 # 3.由于只是加一,只需要考虑最后一位+1的情况 # 1. 最后一位非9,+1后直接写入最后一位的值就行 # 2. 最后一位为9,+1后结果为0,需要判断然后进一位+1,这个步骤可以循环 # 3.最后排除数字全是9的情况 class Solution(object): def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ length = len(digits) for i in range(length - 1, -1, -1): digits[i] += 1 digits[i] = digits[i] % 10 if digits[i] != 0: return digits digits.insert(0, 1) return digits if __name__ == "__main__": obj = Solution() print(obj.plusOne([9,9,9]))
fa0e7b896199178be5191965154253a327de8990
gbramley/Python36-Drill
/Python36drill.py
2,189
4.0625
4
#Assign an integer to a variable x = 15 y = 5 z=0 #Assign a string to a variable name = "Gavin" print name.upper() #Assign a float to a variable y= float(15)/float(3) print y #Use the print function and .format() notation to print out the variable you assigned s = "Hello, Gavin" str(s) print('Today is {}'.format(s)) #Use each of the operators +,-,*,/,+=,=,% print (x+y) print (x-y) print (x*y) print (x/y) z += x print "Value of z is ", z z = x + y print "Value of z is", z print "Hello it is %d oclock and I am %d yrs old" % (2, 33) #Use of logial operators: and, or, not if (x >= 15) and (y > 4): print "True" w = 15 if not (w < 1) or (w > 35): print "false" #Use of conditonal statments: if, elif, else x = 14 if x ==15: print 'x = 15' elif x == 9: print 'x = 9' else: print 'x does not equal 9 or 15' #use of a while loop counter = 10 while counter < 15: print counter counter = counter + 1 #use of a for loop for counter in range (10,15): print counter #create a list and iterate through that list #to print each item out on new line name_of_friends = ['Liese Chapman', 'Matt Huiskamp', 'Walter Colt',] print "My great friends are: " + name_of_friends[0] print "My great friends are: " + name_of_friends[1] print "My great friends are: " + name_of_friends[2] for friend in name_of_friends: print "My great friends are: " + friend #Create a tuple and iterate through it using a for loop to #print each item out on new line for z in (1,2,3): print z #Define a function that returns a string variable x=15 y=5 def subtraction(x): subtract = x - y return subtract toSubtraction = (20) subtractResult = subtraction(toSubtraction) print "The result of " + str(toSubtraction) + " subtract " +str(y) + " is " +str(x) x = 10 y = 100 def square(x): y = x * x return y toSquare = 10 squareResult = square(toSquare) print "The result of " +str(toSquare) + " squared is " +str(squareResult) #Call the function you defined above and print the result to the shell import SubtractionInfo print SubtractionInfo.subtraction(x)
c1a9bea79509113a716e42a56a06cbd5e60b26b3
LouiseDagher/hackinscience
/exercises/019/solution.py
240
3.703125
4
import sys import operator a = len(sys.argv) if a == 3: sys.argv[1] = int(sys.argv[1]) sys.argv[2] = int(sys.argv[2]) d = operator.add(sys.argv[1], sys.argv[2]) print(d) else: print("usage: python3 solution.py OP1 OP2")
f75ae606d522b9e83d2068c5482e2941a29c82aa
howardgood88/Computer_Network
/HW2/SMTP.py
3,351
3.515625
4
from socket import * import base64 import ssl import getpass msg = "\r\n I love computer networks!" endmsg = "\r\n.\r\n" # Choose a mail server (e.g. Google mail server) and call it mailserver mailserver = 'smtp.cc.ncu.edu.tw' #'smtp.gmail.com' 'smtp.cc.ncu.edu.tw'#Fill in start #Fill in end # Create socket called clientSocket and establish a TCP connection with mailserver clientSocket = socket(AF_INET, SOCK_STREAM) clientSocket.connect((mailserver, 587)) recv = clientSocket.recv(1024).decode() print(recv) if recv[:3] != '220': print('220 reply not received from server.') # Send HELO command and print server response. heloCommand = 'EHLO Alice\r\n' clientSocket.send(heloCommand.encode()) recv1 = clientSocket.recv(1024).decode() print(recv1) if recv1[:3] != '250': print('250 reply not received from server.') # TLS加密 clientSocket.send('starttls\r\n'.encode()) recv_tls = clientSocket.recv(1024) print(recv_tls.decode()) clientSocket = ssl.wrap_socket(clientSocket, ssl_version = ssl.PROTOCOL_TLS) #Info for username and password print('Auth login...') username = '105503008@cc.ncu.edu.tw' #"howardgood88@gmail.com" username = base64.b64encode(username.encode()) password = getpass.getpass('Enter password') password = base64.b64encode(password.encode()) authMsg = "AUTH LOGIN\r\n" clientSocket.send(authMsg.encode()) recv_auth = clientSocket.recv(1024) print(recv_auth.decode()) clientSocket.send(username + b'\r\n') #clientSocket.send("\r\n".encode()) recv_user = clientSocket.recv(1024) print("Response after sending username: "+recv_user.decode()) end = b'\r\n' #end = base64.b64encode(end.encode()) clientSocket.send(password + end) #clientSocket.send("\r\n".encode()) recv_pass = clientSocket.recv(1024) print("Response after sending password: "+recv_pass.decode()) # Send MAIL FROM command and print server response. print('Send MAIL FROM command') clientSocket.send('MAIL FROM:<mailer-daemon@ee.ncu.edu.tw>\r\n'.encode()) recv2 = clientSocket.recv(1024).decode() print(recv2) if recv2[:3] != '250': print('250 reply not received from server.') # Send RCPT TO command and print server response. print('Send RCPT TO command') clientSocket.send('RCPT TO:<howardgood188@ee.ncu.edu.tw>\r\n'.encode()) recv2 = clientSocket.recv(1024).decode() print(recv2) if recv2[:3] != '250': print('250 reply not received from server.') # Send DATA command and print server response. print('Send DATA command') clientSocket.send('DATA\r\n'.encode()) recv2 = clientSocket.recv(1024).decode() print(recv2) if recv2[:3] != '354': print('354 reply not received from server.') # Send message data. print('Send message data') msg = 'SUBJECT: SMTP Mail Client Test\nSMTP Mail Client Test\n' clientSocket.send(msg.encode()) ''' with open('C:/Users/hpward/Desktop/python.jpg', 'rb') as f: data = MIMEImage(f.read(1024)) #data.add_header("Content-ID", "") #data.add_header("Content-Disposition", "inline", filename="python.jpg") #msg.attach(data) clientSocket.send(data.encode()) ''' clientSocket.send(b'\r\n.\r\n') recv2 = clientSocket.recv(1024).decode() print(recv2) if recv2[:3] != '250': print('250 reply not received from server.') # Send QUIT command and get server response. print('Send QUIT command') clientSocket.send('QUIT\r\n'.encode()) recv2 = clientSocket.recv(1024).decode() print(recv2) if recv2[:3] != '221': print('221 reply not received from server.') print('Finished Mail')
1f1cde72d581a8c1b12db63435970409158eca1b
AntoniyaV/SoftUni-Exercises
/Basics/01-First-Steps/02-radians-to-degrees.py
99
3.71875
4
from math import pi from math import floor rad = float(input()) deg = rad*180/pi print(floor(deg))
552921ed3e4121c30547428a503cd1e0214ffc04
dlesignac/cg
/puzzle/bender_1/python3/main.py
3,276
3.59375
4
import sys import math class Bender: def __init__(self, x, y, d): self.x = x self.y = y self.d = d self.b = False self.i = False class Board: SOUTH = 0 EAST = 1 NORTH = 2 WEST = 3 def __init__(self): self.h, self.w = [int(i) for i in input().split()] self.m = [] for i in range(self.h): line = list(input()) self.m += line def entry(self): z = self.m.index("@") return (z % self.w, z // self.w) def teleport(self, x, y): for i in range(self.w * self.h): x_ = i % self.w y_ = i // self.w if self.m[i] == "T" and (x_ != x or y_ != y): return (x_, y_) def exit(self): z = self.m.index("$") return (z % self.w, z // self.w) def at(self, x, y): return self.m[x + self.w * y] def neigh(self, x, y, d): if d == Board.SOUTH: return (x, y+1) elif d == Board.EAST: return (x+1, y) elif d == Board.NORTH: return (x, y-1) elif d == Board.WEST: return (x-1, y) def destroy(self, x, y): self.m[x + self.w * y] = " " s = "" B = Board() x, y = B.entry() b = Bender(x, y, 0) loop = False track = [] while (b.x, b.y) != B.exit() and not loop: x, y = B.neigh(b.x, b.y, b.d) dd = B.at(x, y) if dd == "#" or (dd == "X" and not b.b): x0, y0 = B.neigh(b.x, b.y, 0) x1, y1 = B.neigh(b.x, b.y, 1) x2, y2 = B.neigh(b.x, b.y, 2) x3, y3 = B.neigh(b.x, b.y, 3) d0 = B.at(x0, y0) d1 = B.at(x1, y1) d2 = B.at(x2, y2) d3 = B.at(x3, y3) if not b.i: if d0 != "#" and (d0 != "X" or b.b): b.d = 0 elif d1 != "#" and (d1 != "X" or b.b): b.d = 1 elif d2 != "#" and (d2 != "X" or b.b): b.d = 2 else: b.d = 3 else: if d3 != "#" and (d3 != "X" or b.b): b.d = 3 elif d2 != "#" and (d2 != "X" or b.b): b.d = 2 elif d1 != "#" and (d1 != "X" or b.b): b.d = 1 else: b.d = 0 else: x, y = B.neigh(b.x, b.y, b.d) if dd == "X": B.destroy(x, y) track = [] b.x = x b.y = y if b.d == 0: s += "SOUTH\n" elif b.d == 1: s += "EAST\n" elif b.d == 2: s += "NORTH\n" elif b.d == 3: s += "WEST\n" c = B.at(b.x, b.y) if c == "S": b.d = Board.SOUTH elif c == "E": b.d = Board.EAST elif c == "N": b.d = Board.NORTH elif c == "W": b.d = Board.WEST elif c == "I": b.i = not b.i elif c == "B": b.b = not b.b elif c == "T": b.x, b.y = B.teleport(b.x, b.y) if (b.x, b.y, b.d, b.b, b.i) in track: s = "LOOP" loop = True else: track.append((b.x, b.y, b.d, b.b, b.i)) print(s)
1dd559aa4fdbfa354d0ad8249ea1a603c8d0f197
isaaczinda/goai
/board.py
10,021
3.765625
4
# TODO: # - whether the game is over # - when does AI pass (no more legal moves) # def StartOfGameBoard() # [[EMPTY for w in range(width)] for h in range(height)] import copy # values for empty, black, white BLACK = 0 WHITE = 1 EMPTY = 2 def read_drawing(str): """ We want to be able to take in a grid, where . represents empty, X represents black, and O represents white, and convert it into an array of BLACK, WHITE, EMPTY """ grid = [[]] if str.startswith('\n'): str = str[1:] for letter in str: if letter == '\n': grid.append([]) elif letter == 'X': grid[-1].append(BLACK) elif letter == 'O': grid[-1].append(WHITE) elif letter == '.': grid[-1].append(EMPTY) return transpose(grid) def generate_empty_board(width, height): return [[EMPTY for i in range(height)] for s in range(width)] def transpose(grid): new_grid = [[0 for i in range(len(grid))] for j in range(len(grid[0]))] for i in range(len(grid)): for j in range(len(grid[0])): new_grid[j][i] = grid[i][j] return new_grid class BoardState: def __init__(self, board, turn, prevBoardState=None): # board[width][height] self.board = board self.height = len(board[0]) self.width = len(board) # turn = 1 if it's black turn, 2 if it's white's turn self.turn = turn self.prevBoardState = prevBoardState def __repr__(self): str = "" for h in range(self.height): for w in range(self.width): if self.board[w][h] == EMPTY: str += "." elif self.board[w][h] == BLACK: str += "X" elif self.board[w][h] == WHITE: str += "O" str += "\n" if self.turn == BLACK: str += "Black's turn\n\n" else: str += "White's turn\n\n" return str def __eq__(self, other): if not isinstance(other, BoardState): return False return self.turn == other.turn and self.board == other.board def _removeTakenPieces(self, color): ''' returns number pieces removed ''' numRemoved = 0 for w in range(self.width): for h in range(self.height): # If this square is the provided color and part of a # suffocated block, remove the whole block. if self.board[w][h] == color and self._blockSuffocated(w, h): for pos in self._getBlock(w, h): self.board[pos[0]][pos[1]] = EMPTY numRemoved += 1 return numRemoved def _checkMoveLegal(self, widthPos, heightPos): # Not legal if there's something there if self.board[widthPos][heightPos] != EMPTY: return False # Ko -- can't return board to two states ago newState = self._placeUnverified(widthPos, heightPos) if newState == self.prevBoardState: return False # _placeUnverified has already removed all of the opponent's taken # pieces. If after that the board ends in a position where our pieces # are taken, this means we committed suicide (placed in a place # that gets taken). if newState._removeTakenPieces(self.turn) > 0: return False # Otherwise legal return True def _getBlock(self, widthPos, heightPos): """ returns None if this is an empty square """ color = self.board[widthPos][heightPos] if color == EMPTY: return None searched = [] # assume everything in here hasn't already been searched toSearch = [(widthPos, heightPos)] while len(toSearch) > 0: elem = toSearch.pop() neighbors = self._getNeighborsSameColor(elem[0], elem[1], exclude=searched) toSearch += neighbors searched.append(elem) # don't search this again return searched def _blockSuffocated(self, widthPos, heightPos): color = self.board[widthPos][heightPos] otherColor = not color if color == EMPTY: return None # First, we get the block that this piece is located in block = self._getBlock(widthPos, heightPos) # check if its suffocated, if its not we're good! for blockWidthPos, blockHeightPos in block: # If a SINGLE one of the neighbors is not suffocated in a # single direction, the block is not suffocated if not all([ self._suffocatedLeft(otherColor, blockWidthPos, blockHeightPos), self._suffocatedRight(otherColor, blockWidthPos, blockHeightPos), self._suffocatedBelow(otherColor, blockWidthPos, blockHeightPos), self._suffocatedAbove(otherColor, blockWidthPos, blockHeightPos), ]): return False return True def _getNeighborsOfColor(self, color, widthPos, heightPos, exclude=[]): neighbors = [] # left if widthPos != 0 and self.board[widthPos-1][heightPos] == color: neighbors.append((widthPos-1, heightPos)) # right if widthPos != self.width - 1 and self.board[widthPos+1][heightPos] == color: neighbors.append((widthPos+1, heightPos)) # up if heightPos != 0 and self.board[widthPos][heightPos-1] == color: neighbors.append((widthPos, heightPos-1)) # down if heightPos != self.height-1 and self.board[widthPos][heightPos+1] == color: neighbors.append((widthPos, heightPos+1)) # remove excluded ones return [t for t in neighbors if t not in exclude] def _getNeighborsSameColor(self, widthPos, heightPos, exclude=[]): color = self.board[widthPos][heightPos] return self._getNeighborsOfColor(color, widthPos, heightPos, exclude=exclude) def _suffocatedLeft(self, otherColor, widthPos, heightPos): # Returns True if we hit the left wall of the board if widthPos == -1: return True # If we hit our own color, keep going if self.board[widthPos][heightPos] == (not otherColor): return self._suffocatedLeft(otherColor, widthPos-1, heightPos) # If we hit the other color, it is suffocated if self.board[widthPos][heightPos] == otherColor: return True # Otherwise it's empty so we return False return False def _suffocatedRight(self, otherColor, widthPos, heightPos): # Returns True if we hit the left wall of the board if widthPos == self.width: return True # If we hit our own color, keep going if self.board[widthPos][heightPos] == (not otherColor): return self._suffocatedRight(otherColor, widthPos+1, heightPos) # If we hit the other color, it is suffocated if self.board[widthPos][heightPos] == otherColor: return True # Otherwise it's empty so we return False return False def _suffocatedAbove(self, otherColor, widthPos, heightPos): # Returns True if we hit the left wall of the board if heightPos == -1: return True # If we hit our own color, keep going if self.board[widthPos][heightPos] == (not otherColor): return self._suffocatedAbove(otherColor, widthPos, heightPos-1) # If we hit the other color, it is suffocated if self.board[widthPos][heightPos] == otherColor: return True # Otherwise it's empty so we return False return False def _suffocatedBelow(self, otherColor, widthPos, heightPos): # Returns True if we hit the left wall of the board if heightPos == self.height: return True # If we hit our own color, keep going if self.board[widthPos][heightPos] == (not otherColor): return self._suffocatedBelow(otherColor, widthPos, heightPos+1) # If we hit the other color, it is suffocated if self.board[widthPos][heightPos] == otherColor: return True # Otherwise it's empty so we return False return False def _placeUnverified(self, widthPos, heightPos): newBoard = copy.deepcopy(self.board) newBoard[widthPos][heightPos] = self.turn newState = BoardState(newBoard, not self.turn, prevBoardState=self) # Now "take" the pieces # We pass in the other color, because only their pieces are taken. newState._removeTakenPieces(not self.turn) return newState def place(self, widthPos, heightPos): """ Returns new board state. If move was not legal, returns None. """ if not self._checkMoveLegal(widthPos, heightPos): return None return self._placeUnverified(widthPos, heightPos) def score(self, color): # count up my own stones numStones = sum([sum([elem == color for elem in row]) for row in self.board]) territoryOwned = 0 # count empty terratory that we occupy for w in range(self.width): for h in range(self.height): # only counts as territory if its empty if self.board[w][h] != EMPTY: continue theirColor = len(self._getNeighborsOfColor(not color, w, h)) ourColor = len(self._getNeighborsOfColor(color, w, h)) if theirColor == 0 and ourColor > 0: territoryOwned += 1 return numStones + territoryOwned def checkWinner(self): whiteScore = self.score(WHITE) + .5 blackScore = self.score(BLACK) if whiteScore > blackScore: return WHITE return BLACK if __name__ == '__main__': test()
d7521bc098c0548dfe1194ee35a927b9c055d139
KIMSUBIN17/Code-Up-Algorithm
/Python/1088 [기초-종합] 3의 배수는 통과_1.py
86
3.671875
4
a = int(input()) n = 1 while(n < a+1): if n%3 !=0: print(n) n+=1
c4cfea03f5144f63d7f5e11cc3386b14d26f9e4e
ncrebelo/IPS-Engenharia-Informatica
/PYTHON/tp2/server.py
6,278
3.609375
4
""" Simple multi-threaded socket server """ import socket import threading class Server: """The chat server.""" def __init__(self, host, port): self.host = host self.port = port self.sock = None self.commandlist = { "/username": (1, "Register Username: /username [USER]"), "/room": (2, "List current room: /room"), "/create": (3, "Create room: /create #[ROOM]"), "/rooms": (4, "List rooms: /rooms"), "/join": (5, "Enter room: /join #[ROOM]"), "/users": (6, "List users in current room: /users"), "/msgs": (7, "Send message to room: /msgs [MESSAGE]"), "/exit": (8, "User quits: /exit"), "/pmsgs": (9, "User send a private msg to another user: /pmsgs [USER] [MESSAGE]"), "/allusers": (11, "List all online users: /allusers"), "/help": (10, "Help menu: /help") } self.users = [] self.rooms = {"#welcome": []} def validateCommand(self, msg): command = msg.strip().split() # Check if it's a command if command[0] not in self.commandlist.keys(): res = "Unknown command." return res if command[0] == "/username": res = self.authUser(command[1]) self.users.append(command[1]) return res elif command[0] == "/room": res = self.isInRoom() return res elif command[0] == "/create": res = self.createRoom(command[1]) return res elif command[0] == "/rooms": res = self.getRooms() return res elif command[0] == "/join": res = self.joinRoom(command[1]) return res elif command[0] == "/users": res = self.getUsers() return res elif command[0] == "/msgs": res = self.sendRoomMessage(command[1], command[2]) return res elif command[0] == "/pmsgs": res = self.sendPrivateMessage(command[1], command[2]) return res elif command[0] == "/allusers": res = self.getAllValues() return res elif command[0] == "/exit": res = self.exit() return res elif command[0] == "/help": res = self.help() return res def start(self): """Starts the server.""" self.sock = socket.socket() self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind((self.host, self.port)) self.sock.listen(1) print('Listening on port %s ...' % self.port) try: while True: # Accept client connections conn, _ = self.sock.accept() # Starts client thread thread = threading.Thread(target=self.handle_client, args=(conn,)) thread.start() except ConnectionAbortedError: pass except OSError: pass def stop(self): """Stops the server.""" self.sock.close() def authUser(self, username): msg = "" if not username: msg += "/username required" elif username in self.users: msg += "/username taken" else: msg += "/username ok" self.rooms['#welcome'] += [username] return msg def joinRoom(self, roomName): msg = "" if roomName in self.rooms.keys(): for user in self.rooms.values(): self.rooms[roomName] += [user] msg += "/join ok" else: msg += "/join no_room" return msg def createRoom(self, roomName): msg = "" if roomName in self.rooms.keys(): msg += "/create room_exists" else: self.rooms.update({roomName: []}) msg += "/create ok" return msg def isInRoom(self): tempList = [] msg = "/room " for key, values in self.rooms.items(): if values in self.rooms.values(): tempList.append(key) for i in tempList: msg += "".join(i) else: msg += "Not in room" return msg def getRooms(self): roomList = "/rooms" for key in self.getAllKeys(): roomList += " " + key return roomList def getUsers(self): tempList = [] msg = "/users " for key, values in self.rooms.items(): if key in self.rooms.keys(): tempList.append(values) for i in tempList: msg += " ".join(i) return msg def sendPrivateMessage(self, receiver, usermsg): msg = "" if receiver in self.rooms.values(): msg += "(" + receiver + " @private)" + usermsg return msg def sendRoomMessage(self, sender, usermsg): msg = "" if sender in self.rooms.values(): msg += "(" + sender + self.isInRoom() + ")" + usermsg return msg def getAllValues(self): return self.rooms.values() def getAllKeys(self): return self.rooms.keys() def help(self): cmdlist = "Available Commands:" for k, v in self.commandlist.values(): cmdlist += "\n" + v return cmdlist def exit(self): return "/exit ok" def handle_client(self, conn): """Handles the client connection.""" while True: # Receive message msg = conn.recv(1024).decode() res = self.validateCommand(msg) print(res) # Send response conn.sendall(res.encode()) if msg == '/exit': break # Close client connection print('Client disconnected...') conn.close() if __name__ == "__main__": # Starts the server server = Server('0.0.0.0', 8000) server.start()
e39af27ac64bae696b64dfa0ca82644f8632aab9
Aasthaengg/IBMdataset
/Python_codes/p03469/s237759829.py
90
3.859375
4
n = input().split("/") if n[0] == "2017": n[0] = "2018" print(n[0]+"/"+n[1]+"/"+n[2])
cd9e20bb8e21e2e4509f38beb1d7351184610d93
heenach12/pythonpractice
/Linked_List/reverse_linked_list.py
1,840
4.03125
4
"""Given a linked list of N nodes. The task is to reverse this list. Example 1: Input: LinkedList: 1->2->3->4->5->6 Output: 6 5 4 3 2 1 Explanation: After reversing the list, elements are 6->5->4->3->2->1. Example 2: Input: LinkedList: 2->7->8->9->10 Output: 10 9 8 7 2 Explanation: After reversing the list, elements are 10->9->8->7->2.""" class Solution: def reverseList(self, head): """Below is the stack approach""" stack = [] temp = head while(temp): stack.append(temp) temp = temp.next head = temp = stack.pop() elem = None while(len(stack)> 0): elem = stack.pop() temp.next = elem temp = elem elem.next = None return head """Below is Iterative approach""" # next = None # prev = None # curr = head # # while(curr is not None): # next = curr.next # curr.next = prev # prev = curr # curr = next # head = prev # # return head class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None self.tail = None def insert(self, val): if self.head == None: self.head = Node(val) self.tail = self.head else: self.tail.next = Node(val) self.tail = self.tail.next def printList(n): while(n): print(n.data, end = " ") n = n.next print(" ") t = int(input()) for i in range(t): n = int(input()) arr = list(map(int, input().strip().split())) lis = LinkedList() for i in arr: lis.insert(i) newhead = Solution().reverseList(lis.head) printList(newhead)
553d722489136eab0c4560c6ca4f69fe93a754a3
RahulTechTutorials/PythonPrograms
/strings/reversestring5.py
468
4.40625
4
def revstring(string): orgstring = string for ch in string: string = ch + string if string == (orgstring * 2) : return orgstring else: return string.replace(orgstring,'') def main(): '''This is a program to reverse the string entered by user''' string = input('Please enter the string to reverse: ') rstring = revstring(string) print('The reverse string is : ', rstring) if __name__ == '__main__': main()
3a3e95e1fe840546416079b32f627b3e48e7ac1c
yosoydead/exercises
/equations calculator/16.py
231
3.625
4
def prime(n): for i in range(2, n): if n % i == 0: return False return True def show(start,finish): for i in range(start, finish+1): if prime(i) == True: print(i) show(2, 100)
6e3d92232a3459bfb511563fc9afc526813f2ce8
qinchenguang/my-daily-life
/python_study/first.py
6,054
3.96875
4
# if statement # a = 100; # if a > 0: # print a # else: # print -a # print like typeing input # name = raw_input('what is ur name: ') # print 'hello', name # print "i'm fine" # print 'i\'m fine' # x = 10 # x = x + 2 # print x # a = 'ABC' # b = a # a = 'XYZ' # print b # print a # classmates = ['Michael', 'Bob', 'Tracy'] # print classmates # print len(classmates) # print classmates[3] # test = (1, 2) # print test # print test[1] # age = 3 # if age >= 18: # print 'your age is', age # print 'adult' # else: # print 'tingger' # names = ['Michael', 'Bob', 'Tracy'] # for name in names: # print name # sum = 0 # aTmp = [0,1,2,3] # for i in aTmp: # sum += i # #print i # print sum # aTmp = range(2, 10) # print aTmp # sum = 0 # n = 99 # while n > 0: # sum = sum + n # n = n - 2 # print sum # d = {'Michael': 95, 'Bob': 75, 'Tracy': 85} # d['lizi'] = 12 # print d # print d.get('Michael') # print abs(-200) # print cmp(1,2) # print int('123') # print float('1.2323') # print str(123) # print bool(1) # def my_abs(x): # if not isinstance(x, (int, float)): # raise TypeError('bad operand type') # if x >= 0: # return x # else: # return -x # # print my_abs(-100) # # print my_abs('-100') # import math # def move(x, y, step, angle=0): # nx = x + step * math.cos(angle) # ny = y - step * math.sin(angle) # return nx, ny # # print move(100, 100, 60, math.pi / 6) # def power(x, n=2): # s = 1 # while n > 0: # n = n - 1 # s = s * x # return s # # print power(2, 3) # l = ['l', 'y', 'z', 'x'] # for i, value in enumerate(l): # print i, value # dict # d = {'a': 1, 'b': 2, 'c': 3} # for i, value in d.iteritems(): # print i, value # def f(x): # return x * x # print map(f, [1,2,3,4,5]) # print map(map, [1,2,3,4,5]) # def f(x, y): # return x + y # # print reduce(f, [1,2,3,4,5]) # print sum([1,2,3,4,5]) # def f(x, y): # print x,y # return x * 10 + y # # print reduce(f, [1,2,3]) # def is_odd(n): # return n % 2 == 1 # # print filter(is_odd, [1,2,3,4]) # def notEmpty(s): # return s and s.strip() # # print filter(notEmpty, ['A', '', 'B', None, 'C', ' ']) # print sorted([36, 5, 12, 9, 21, '12']) # def revertCmp(x, y): # if x < y: # return 1 # elif x > y: # return -1 # else: # return 0 # # # print sorted([36, 5, 12, 9, 21], revertCmp) # def now(): # print '123' # f = now # f() # print now.__name__ # print f.__name__ # decorator # def log(fnc): # def wrapper(*args, **kw): # print 'call %s():' % fnc.__name__ # return fnc(*args, **kw) # return wrapper # # @log # def now(): # print '123' # # now() # import time # print time.time() # def log(txt): # def decorator(fnc): # def wrapper(*args, **kw): # print '%s %s():' % (txt, fnc.__name__) # return fnc(*args, **kw) # return wrapper # return decorator # # @log('execute') # def now(): # print '2013-12-25' # # now() # !/usr/bin/env python # -*- coding: utf-8 -*- ' a test module ' # __author__ = 'Michael Liao' # # import sys # # def test(): # args = sys.argv # if len(args)==1: # print 'Hello, world!' # elif len(args)==2: # print 'Hello, %s!' % args[1] # else: # print 'Too many arguments!' # # if __name__=='__main__': # test() # # class Student(object): # pass # # bart = Student() # # print bart # print Student # class Student(object): # def __init__(self, name, score): # self.name = name # self.score = score # # def printScore(std): # print '%s: %s' % (std.name, std.score) # # bart = Student('Bart Simpson', 59) # # printScore(bart) # bart = Student('Bart Simpson', 59) # print bart.name # print bart.score # # class Student(object): # def __init__(self, name, score): # self.name = name # self.score = score # # def print_score(self): # print '%s: %s' % (self.name, self.score) # # bart = Student('Bart Simpson', 60) # bart.print_score() # from multiprocessing import Process # import os # # def run_proc(name): # print 'Run child process %s (%s)...' % (name, os.getpid()) # # if __name__=='__main__': # print 'parent is %s: ' % os.getpid() # p = Process(target=run_proc, args=('test',)) # print 'start...' # p.start() # p.join() # print 'end...' # from multiprocessing import Pool # import os, time, random # # def long_time_task(name): # print 'run task %s (%s)...' % (name, os.getpid()) # start = time.time() # time.sleep(random.random() * 3) # end = time.time() # print 'task %s runs %0.2f seconds.' % (name, (end - start)) # # if __name__=='__main__': # print 'parent process %s.' % os.getpid() # p = Pool() # for i in range(9): # p.apply_async(long_time_task, args=(i,)) # print 'Waiting for all subprocesses done...' # p.close() # p.join() # print 'All subprocesses done.' # import time, threading # # print time.time() # # def loop(): # print 'thread %s is running...' % threading.current_thread().name # n = 0 # while n < 4: # n = n + 1 # print 'thread %s >>> %s' % (threading.current_thread().name, n) # time.sleep(1) # print 'thread %s ended.' % threading.current_thread().name # # print 'thread %s is running...' % threading.current_thread().name # t = threading.Thread(target=loop, name='LoopThread') # t.start() # t.join() # print 'thread %s ended.' % threading.current_thread().name # # import time, threading # # balance = 0 # # def chang_it(n): # global balance # balance = balance + n # balance = balance - n # # def run_thread(n): # for i in range(10000): # chang_it(n) # # t1 = threading.Thread(target=run_thread, args=(5,)) # t2 = threading.Thread(target=run_thread, args=(8,)) # # t1.start() # t2.start() # t1.join() # t2.join() # print balance # import hashlib # # md5 = hashlib.md5() # md5.update('how to use md5 in ') # #md5.update('python hashlib?') # l = md5.hexdigest() # print l # # import itertools # natuals = itertools.count(1) # # print natuals # # for n in natuals: # print n # tcp/ip
ec6d34f04df528f13415dd9d83fbca0286129743
imaaduddin/Everything-Python
/format_method.py
447
4.0625
4
# str.format() = optional method that gives users more control when displaying output character = "Zabuza" weapon = "execution blade" print("{} weilds the {}".format(character, weapon)) print("{0} weilds the {1}".format(character, weapon)) # print("{} weilds the {}".format(character = "Naruto", weapon = "kunai")) text = "The {} jumped over the {}" text.format(character, weapon) numbers = 1000 print("The number PI is {}".format(numbers))
0a4acff21f20d215485385c5d6d15e4749e37c64
srimuthurajesh/Python-Examples
/basic_tries/gui.py
189
3.640625
4
from tkinter import * root=Tk() def leftclick(event): print("left is clicked") frame=Frame(root, width=200,height=200) frame.bind("<Button-1>",leftclick) frame.pack() root.mainloop()
a088c8262a255b05f23015a212721f2ed736b46a
DroneGoHome/Beacon
/BeaconPrototypeV1/src/ThreadingTest.py
356
3.859375
4
import threading,time def lower(): count=0 while count<5: print(count) time.sleep(2.5) count+=1 def upper(): count=10 while count>5: print(count) time.sleep(1) count-=1 #threading._MainThread() threading.Thread(target=upper).start() threading.Thread(target=lower).start() print("main thread")
b1d35e60cde58a408da33a1ebacf480879a63812
MishaResh/lesson1
/HWL1_6.py
1,217
4.03125
4
# Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. # Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить # номер дня, на который результат спортсмена составит не менее b километров. Программа должна # принимать значения параметров a и b и выводить одно натуральное число — номер дня. # Например: a = 2, b = 3. # Результат: # 1-й день: 2 # 2-й день: 2,2 # 3-й день: 2,42 # 4-й день: 2,66 # 5-й день: 2,93 # 6-й день: 3,22 var_day = int(input("Введите план на 1-ый день >>> ")) var_max = int(input("Введите max план на день >>> ")) var_i = 1 print(str(var_i) + "-й день: " + str(var_day)) while var_day < var_max: var_i += 1 var_day *= 1.1 print(str(var_i) + "-й день: " + str(round(var_day, 2)).replace('.', ','))
c9f08ea31defd3b84f1fa3bda2f498b3d846b2d9
xiaolcqbug/aiai
/Garfield/two.py
397
3.609375
4
# 线程的两种写法 from threading import Thread # 第一种 def task1(): print('线程开启') if __name__ == '__main__': p1 = Thread(target=task1) p1.start() # 第二种 class MyThread(Thread): def __init__(self): super(MyThread, self).__init__() def run(self): print('线程开启') if __name__ == '__main__': p1 = MyThread() p1.start()
ef8754d1a347c8f0cec54f65bbbd82c625c18c62
DaudAhmad0303/AI-Lab-3
/Queue_Implementation.py
1,078
4.28125
4
class my_queue: ''' This class works same as the Queue Data Structure does. ''' def __init__(self): self.__lst = [] def is_empty(self): if len(self.__lst) == 0: return True def size_of_queue(self): return len(self.__lst) def enqueue(self, val): self.__lst.append(val) def dequeue(self): if self.size_of_queue() != 0: val = self.__lst[0] self.__lst.pop(0) return val else: return None def print_queue(self): print(self.__lst) #--------------------Driver Program------------------------- q1 = my_queue() print('Current size of Queue: ',q1.size_of_queue()) q1.enqueue('Aqib') q1.enqueue('Zain') q1.enqueue('Ali') q1.print_queue() print('Current size of Queue: ',q1.size_of_queue()) print('De-Queued: ', q1.dequeue()) print('De-Queued: ', q1.dequeue()) print('Current size of Queue: ',q1.size_of_queue()) print('De-Queued: ', q1.dequeue()) print('Current size of Queue: ',q1.size_of_queue()) print(q1.__lst)
fdfe662d5f8c72fe9b001fb0caea4894895b281a
sohumd96/CTCI
/Chapter2/Problem5/sum_lists.py
562
3.75
4
from Chapter2.linked_list import * def sum_lists(head1, head2): total = 0 sentinel = LinkedList(0) linked_sum = sentinel while head1 is not None or head2 is not None: if head1 is not None: total += head1.data head1 = head1.next if head2 is not None: total += head2.data head2 = head2.next linked_sum.next = LinkedList(total % 10) linked_sum = linked_sum.next total //= 10 if total > 0: linked_sum.next = LinkedList(1) return sentinel.next
7fa40595cce930ab75f17e27b3275ad9d0dddc13
sashakrasnov/datacamp
/20-unsupervised-learning-in-python/3-decorrelating-your-data-and-dimension-reduction/07-clustering-wikipedia-part-1.py
1,450
3.625
4
''' Clustering Wikipedia part I You saw in the video that TruncatedSVD is able to perform PCA on sparse arrays in csr_matrix format, such as word-frequency arrays. Combine your knowledge of TruncatedSVD and k-means to cluster some popular pages from Wikipedia. In this exercise, build the pipeline. In the next exercise, you'll apply it to the word-frequency array of some Wikipedia articles. Create a Pipeline object consisting of a TruncatedSVD followed by KMeans. (This time, we've precomputed the word-frequency matrix for you, so there's no need for a TfidfVectorizer). The Wikipedia dataset you will be working with was obtained from here (https://blog.lateral.io/2015/06/the-unknown-perils-of-mining-wikipedia/) INSTRUCTIONS * Import: * TruncatedSVD from sklearn.decomposition. * KMeans from sklearn.cluster. * make_pipeline from sklearn.pipeline. * Create a TruncatedSVD instance called svd with n_components=50. * Create a KMeans instance called kmeans with n_clusters=6. * Create a pipeline called pipeline consisting of svd and kmeans. ''' # Perform the necessary imports from sklearn.decomposition import TruncatedSVD from sklearn.cluster import KMeans from sklearn.pipeline import make_pipeline # Create a TruncatedSVD instance: svd svd = TruncatedSVD(n_components=50) # Create a KMeans instance: kmeans kmeans = KMeans(n_clusters=6) # Create a pipeline: pipeline pipeline = make_pipeline(svd, kmeans)
b118360ef067e1ec9f19baa75d3306c04ee5e9eb
Light-Y007/MachineLearning
/2. Regression/3. Polynomial Regression/polynomial_regression.py
2,508
3.5
4
#Polynomial Regression #importing Libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #IMPORTING THE DATASET dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:, 1:2].values y = dataset.iloc[:, 2].values '''#Taking care of missing data #from sklearn.impute import SimpleImputer #from sklearn.preprocessing import OneHotEncoder , LabelEncoder #imputer = SimpleImputer(missing_values=np.nan, strategy='mean') #imputer = imputer.fit(X[:, 1:3]) #X[:,1:3] = imputer.transform(X[:,1:3]) #Encoding categorical data #from sklearn.compose import ColumnTransformer #ct = ColumnTransformer([("Country", OneHotEncoder(), [0])], remainder = 'passthrough') #X = ct.fit_transform(X) #labelencoder_y = LabelEncoder() #y = labelencoder_y.fit_transform(y) #Splitting the data into training set and test set no need for spliting because only 10 records are there from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) #feature Scaling from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test)''' #Fitting the Linear Regression to the dataset from sklearn.linear_model import LinearRegression lin_reg = LinearRegression() lin_reg.fit(X,y) #Fitting the Polynomial Regression to the dataset from sklearn.preprocessing import PolynomialFeatures poly_reg = PolynomialFeatures(degree = 4) X_poly = poly_reg.fit_transform(X) lin_reg2 = LinearRegression() lin_reg2.fit(X_poly,y) #Visualising the Linear Regression plt.scatter(X, y, color = 'red') plt.plot(X, lin_reg.predict(X), color = 'blue') plt.title('Truth or Bluff (Linear Regression)') plt.xlabel('Position Level') plt.ylabel('Salary') plt.show() #Visualising the Polynomial Regression X_grid = np.arange(min(X), max(X), 0.1) X_grid = X_grid.reshape(len(X_grid),1) plt.scatter(X, y, color = 'red') plt.plot(X_grid, lin_reg2.predict(poly_reg.fit_transform(X_grid)), color = 'blue') plt.title('Truth or Bluff (Polynomial Regression 4th Degree more smooth using X_grid)') plt.xlabel('Position Level') plt.ylabel('Salary') plt.show() # Predicting a new result with Linear Regression lin_reg.predict([[6.5]]) # Predicting a new result with Polynomial Regression lin_reg2.predict(poly_reg.fit_transform([[6.5]]))
2aa117aec651f92baafb7c54cef1df93a3395cdb
RahulRanjan-Dev/pythoncode
/Python_code/List_demo.py
311
3.640625
4
def check_sum_property(lst): running_sum = 0 for i in range(len(lst)): running_sum += lst[i] print(running_sum) if running_sum != i + 1: return False return True # Test cases input1 = [1,1,1,1] output1 = check_sum_property(input1) print(output1) # False
3fb64af3af21196b1669862dfc6f93cda6129a81
carloswagner1/ProgramasPython
/secao06/Exercicio04.py
355
3.6875
4
#entradas Altura = float(input("Informe a sua altura: ")) sexo = input("Informe o sexo (m/f): ") #processamento if sexo.lower() == 'm': PesoIdeal = (72.7 * Altura) -58 elif sexo.lower() == 'f': PesoIdeal = (62.1 * Altura) - 44.7 else: PesoIdeal = 0 print("Sexo não reconhecido.") print("O peso ideal é {0:.2f} Kg".format(PesoIdeal))
782f577f1d5655d4903d685d10cfde9cc39a2011
Quinton-H/Calculator
/calculator.py
1,806
4.21875
4
calculator = True while calculator: start = input("Hello! I'm your calculator would you like to use me (y/n)?: ").strip().lower() if start == "y" or "yes": calculate = input("Would you like to Multiply(m)/Divide(d)/Add(a)/Subtract(s)/Power(p)? :").strip().lower() if calculate == "add" or "a": num1 = input("To add please enter a number: ").strip() num2 = input("Please enter another number: ").strip() add = int(num1) + int(num2) print("{} + {} is {}!".format(num1, num2, add)) elif calculate == "subtract" or "s": num1 = input("To subtract a number please enter a number: ").strip() num2 = input("Please enter another number: ").strip() subtract = int(num1) - int(num2) print("{} - {} is {}!".format(num1, num2, subtract)) elif calculate == "multiply" or "m": num1 = input("To multiply a number please enter a number: ").strip() num2 = input("Please enter another number: ").strip() multiply = int(num1) * int(num2) print("{} x {} is {}!".format(num1, num2, multiply)) elif calculate == "divide" or "m": num1 = input("To divide a number please enter a number: ").strip() num2 = input("Please enter another number: ").strip() divide = int(num1) / int(num2) print("{} / {} is {}!".format(num1, num2, divide)) elif calculate == "power" or "p": num1 = input("Please enter a number: ").strip() num2 = input("Please enter another number for the power of: ").strip() power = int(num1) ** int(num2) print("{} to the power of {} is: {}!".format(num1, num2, power)) else: print("Okay! Another time then!")
c9195fab307d8291d6ea8b9e7d7109d91d59d6e3
jeantorresa190899/TrabajoFinal
/Desarrollo.py
8,779
3.890625
4
import os, sys os.system("cls") import random # Inicio de la Aplicación print("********* Hola, bienvenido a esta nueva plataforma de aprendizaje.***********") nombre = str(input("¿Cuál es tu nombre? -----------> ")) print("Hola", nombre) print("Este programa consiste en responder 20 preguntas de cultura" + " general, \nlas cuales te ayudarán a expandir tus conocimientos.") print("\n") print("----------------------------------------------------------------") print("| ¡COMENZEMOS! |") print("----------------------------------------------------------------") class Question: def __init__(self, prompt, answer): self.prompt = prompt self.answer = answer question_prompts = [ "¿Cuál es un tipo de sabor primario?\na)Quemado\nb)Rostizado\nc)Umami\nd)Sabroso\n\n", "¿Cuál es el lugar más frío de la tierra??\na)Antartida\nb)Suecia\nc)Groenlandia\nd)Islandia\n\n", "¿Quién escribió La Odisea?\na)Sócrates\nb)Pitágoras\nc)Homero\nd)Aristóteles\n\n", "¿Cuántos Estados tiene integrados Estados Unidos? \na)32\nb)49\nc)50\nd)55\n\n", "¿En qué continente está San Marino?\na)América del Norte\nb)América del Sur\nc)Europa\nd)Asia\n\n", "¿Quién inventó el primer avión?\na)Los hermanos Wright\nb)Los hermanos Warner\nc)Los hermanos Wachowski\nd)Los hermanos Lumiére\n\n", "¿Quién escribió Cien años de soledad?\na)Gabriel García Márquez\nb)Alfredo Bryce Echenique\nc)Cesar Vallejo\nd)Ricardo Úceda\n\n", "¿En qué deporte destacaba Toni Elías?\na)Motociclismo\nb)Fútbol\nc)Formula 1\nd)Voley\n\n", "¿Qué deporte practicaba Michael Jordan?\na)Baseball\nb)Football\nc)Basketball\nd)Golf\n\n", "¿Dónde se inventó el ping-pong?\na)Estados Unidos de América\nb)Inglaterra\nc)Canadá\nd)Irlanda\n\n", "¿De qué estilo arquitectónico es la Catedral de Notre Dame en París?\na)Rómanico\nb)Barroco\nc)Neoclásico\nd)Gótico\n\n", "¿Quién va a la cárcel?\na)Imputado\nb)Acusado\nc)Condenado\nd)Testigo\n\n", "¿A qué país pertenece la ciudad de Varsovia?\na)Polonia\nb)Austria\nc)Rusia\nd)Bielorusia\n\n", "¿Cuál es el metal más caro del mundo?\na)Oro\nb)Plata\nc)Rodio\nd)Aluminio\n\n", "¿Cuál es la nacionalidad de Pablo Neruda?\na)Chilena\nb)Boliviana\nc)Argentina\nd)Uruguaya\n\n", "¿Cuál es el país más poblado del mundo?\na)Rusia\nb)China\nc)EE.UU\nd)Canadá\n\n", "¿Quién fue el líder de los nazis durante la Segunda Guerra Mundial? \na)Mussolini \nb)Stalin \nc)Hitler \nd)F.Roosevelt\n\n", "¿En qué país se encuentra la torre de Pisa? \na)Italia \nb)Francia \nc)España \nd)Alemania \n\n", "¿Cuantos huesos tiene el cuerpo humano? \na)214 \nb)206 \nc)216 \nd)202 \n\n", "¿Cual de los siguientes animales es un marsupial? \na)Gato \nb)Koala \nc)Chimpancé \nd)Conejo\n\n", "Si una década tiene 10 años.¿Cuantos años tiene un lustro? \na)20 \nb)10 \nc)5 \nd)15\n\n", "¿En qué año llegó el primer hombre a la Luna?\na)1969 \nb)1979 \nc)1980 \nd)1976\n\n", "¿En que continente se encuentra Haití?\na)Africa \nb)Europa \nc)America \nd)Oceania\n\n", "¿Quién pintó “la última cena”?\na)Raffaello Sanzio de Urbino \nb)Miguel Angel \nc)Alessandro di Mariano \nd)Leonardo D'Vinci\n\n", "¿Cómo se llama el himno nacional de Francia?\na)Das Lied der Deutschen \nb)The Star-Spangled Banner\nc)Marsellesa \nd)Il Canto degli Italiani\n\n", "¿Qué año llegó Cristóbal Colón a América?\na)1512 \nb)1498 \nc)1492 \nd)1495\n\n", "¿Cuál es el río más largo del mundo?\na)Yangtsé \nb)Nilo \nc)Amazonas \nd)Misisipi\n\n", "¿Cuantos corazones tienen los pulpos?\na)2 \nb)1 \nc)3 \nd)5\n\n", "¿Cuál es el libro sagrado del Islam?\na)Biblia \nb)Coran \nc)Credo\nd)Documento de Damasco\n\n", "¿En qué país se ubica la Casa Rosada?\na)EE.UU \nb)Uruguay \nc)Argentina \nd)Chile\n\n", "¿Cuantas fueron las principales cruzadas(1095 - 1291)?\na)3 \nb)6 \nc)8 \nd)5\n\n", "¿Quién fue el primer presidente del Perú?\na)Don José de San Martín \nb)José Mariano de la Riva Agüero y Sánchez Boquete \nc)José Bernardo de Torre Tagle \nd)José de la Mar\n\n", "¿Cómo se la nombró a la primera computadora programable ?\na)Maquina de turing \nb)Z1 \nc)Eniac \nd)Osborne\n\n", "¿Cuál ha sido la guerra más sangrienta de la historia?\na)1ra guerra mundial \nb)2da guerra mubdial \nc)Guerra de vietnam \nd)Guerra civil española\n\n", "¿Cuántas patas tiene una abeja?\na)6 \nb)10 \nc)4 \nd)8\n\n", "¿Cuantos años tiene un lustro ?\na)5 \nb)10 \nc)25 \nd)50\n\n", "¿Con qué otro nombre se denomina al hexaedro?\na)cono \nb)piramide \nc)esfera \nd)cubo\n\n", "La capital de Irlanda es:\na)Budapest \nb)Berlín \nc)Atenas \nd)Dúblin\n\n", "Si el radio de un círculo mide 5 centímetros, ¿cuánto mide el diámetro?\na)5 centímetros \nb)20 centímetros \nc)10 centímetros \nd)2 centímetros\n\n", "¿Cuál es el planeta de mayor tamaño del Sistema Solar?\na)Mercurio \nb)Marte \nc)Júpiter \nd)Tierra\n\n", "Una carga positiva y otra negativa:\na)No pasa nada \nb)Se atraen \nc)Intercambian sus polos \nd)Se repelen\n\n", "Colón se embarcó en su viaje a América en tres embarcaciones, ¿Cuál no fue una de ellas?\na)Pinta \nb)Santa María \nc)La Niña \nd)Santa Cristina\n\n", "La unidad de volumen en el Sistema Internacional es:\na)Amperio por metro \nb)Amperio por metro cuadrado \nc)Metro cuadrado \nd)Metro cúbico\n\n", "La temperatura a la cual la materia pasa de estado líquido a estado gaseoso se denomina:\na)Ecuación de estado \nb)Punto de ebullición \nc)Transición de fase \nd)Punto de fusión\n\n", "¿Cuántas vueltas da el segundero en una vuelta completa en un reloj de doce horas?\na)720 \nb)800 \nc)420 \nd)360\n\n", ] questions = [ Question(question_prompts[0], "c"), Question(question_prompts[1], "a"), Question(question_prompts[2], "c"), Question(question_prompts[3], "c"), Question(question_prompts[4], "c"), Question(question_prompts[5], "a"), Question(question_prompts[6], "a"), Question(question_prompts[7], "a"), Question(question_prompts[8], "c"), Question(question_prompts[9], "b"), Question(question_prompts[10], "d"), Question(question_prompts[11], "c"), Question(question_prompts[12], "a"), Question(question_prompts[13], "c"), Question(question_prompts[14], "a"), Question(question_prompts[15], "b"), Question(question_prompts[16], "c"), Question(question_prompts[17], "a"), Question(question_prompts[18], "b"), Question(question_prompts[19], "b"), Question(question_prompts[20], "c"), Question(question_prompts[21], "b"), Question(question_prompts[22], "c"), Question(question_prompts[23], "d"), Question(question_prompts[24], "c"), Question(question_prompts[25], "c"), Question(question_prompts[26], "c"), Question(question_prompts[27], "c"), Question(question_prompts[28], "b"), Question(question_prompts[29], "c"), Question(question_prompts[30], "c"), Question(question_prompts[31], "b"), Question(question_prompts[32], "b"), Question(question_prompts[33], "b"), Question(question_prompts[34], "a"), Question(question_prompts[35], "a"), Question(question_prompts[36], "d"), Question(question_prompts[37], "d"), Question(question_prompts[38], "c"), Question(question_prompts[39], "c"), Question(question_prompts[40], "b"), Question(question_prompts[41], "d"), Question(question_prompts[42], "d"), Question(question_prompts[43], "b"), Question(question_prompts[44], "a") ] #Proceso def run_quiz(questions): score = 0 i = 0 random.shuffle(questions) questions = random.sample(questions, k=20) for question in questions: print("................") print("Pregunta:", i+1) print(question.prompt) from itertools import chain, repeat answer = {'a', 'b', 'c', 'd'} prompts = chain(["Ingrese una letra del listado: "], repeat("Ingresa una letra del listado: ")) replies = map(input, prompts) valid_response = next(filter(answer.__contains__, replies)) print(valid_response) i +=1 if valid_response == question.answer: score += 1 print("Tienes", score, "de", len(questions)) if score <= 5: mensaje = "- Vuelve a intentar" elif score <=10: mensaje = "- Not bad!" elif score <=15: mensaje = "- Buen intento!" else: mensaje = "- Buen trabajo!" print(mensaje) run_quiz(questions)
fffeab5772e84756addfc85aef598fbcd114512e
jamiejamiebobamie/pythonPlayground
/DS2.1_popquiz.py
1,005
3.546875
4
# def myPoorlyNamedFunction(matrix): #this is obviously incorrect, i computed the minimum for each row: # minimum = float("inf") # for index, i in enumerate(matrix): # for j in i: # minimum = min(j, minimum) # # matrix[index].append(minimum) #i realized my error here and thought I might get some brownie points if I tried to subtract the minimum from each interior array item # for _ in range(0,len(matrix)-2): # for j, columns in enumerate() # -matrix[_][j]-=matrix[_][-1] # # return matrix # print(myPoorlyNamedFunction(matrix)) A = [[1,2,3], # A = [[1,2,3], [1,2,3], # [2,4,6], [1,2,3]] # [3,6,9]] def computeColumn(matrix): i = j = 0 while i < len(matrix): if i != 0 and j < len(matrix[0]): matrix[i][j] += matrix[i-1][j] j += 1 if j == len(matrix[0]): j = 0 i += 1 return matrix print(computeColumn(A))
cbfa7b64b9c2de0d8558988012a5edf91fd2072a
sgrade/pytest
/codeforces/994A.py
289
3.5
4
# A. Fingerprints from collections import OrderedDict n, m = map(int, input().split()) x = list(input().split()) y = list(input().split()) ans = OrderedDict() for key in y: if key in x: ans[x.index(key)] = key print(' '.join([value for key, value in sorted(ans.items())]))
daa4393da3191f7de7fac6621b45078db8c3d56f
pavradev/algorithms
/structures/t0896_bribes/bribes.py
3,502
4
4
#!/usr/bin/python import sys import os from collections import deque from functools import total_ordering @total_ordering class Path: """Path in a tree""" def __init__(self, cost, nodes): self.cost = cost self.nodes = nodes def __add__(self, other): cost = self.cost + other.cost nodes = self.nodes + other.nodes return Path(cost, nodes) def __hash__(self): return hash(self.cost) def __eq__(self, other): return self.cost == other.cost def __lt__(self, other): return self.cost < other.cost def __repr__(self): return '%s\n%s' % (self.cost, ' '.join([repr(n) for n in self.nodes])) class Tree: """Simple tree implementation""" def __init__(self, idx, bribe): self.idx = idx self.bribe = bribe self.children = [] def find_child(self, idx): # TODO: add lambda test if self.idx == idx: return self for child in self.children: found_child = child.find_child(idx) if found_child: return found_child return def add_child(self, child): self.children.append(child) def print_children(self): print ('%s (%s):' % (self.idx, self.bribe)) + ', '.join([str(c.idx) for c in self.children]) for child in self.children: child.print_children() def get_min_cost_path(self): paths = [c.get_min_cost_path() for c in self.children] if paths: return Path(self.bribe, [self.idx]) + min(paths) else: return Path(self.bribe, [self.idx]) def build_tree(filename): f = open(filename, 'rU') n = int(f.readline()) nodes = {1: Tree(1, 0)} for i in range(n): data = deque([int(n) for n in f.readline().split()]) node = nodes[data.popleft()] for j in range(data.popleft()): idx = data.popleft() bribe = data.popleft() child = Tree(idx, bribe) node.add_child(child) nodes[idx] = child return nodes[1] # Util function to check if got equals to expected def test(got, expected): if got == expected: prefix = ' OK ' else: prefix = ' X ' print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected)) def file_as_str(filename): f = open(filename, 'rU') return f.read() def in_match_out(infilename, outfilename): (infile, inext) = os.path.splitext(infilename) (outfile, outext) = os.path.splitext(outfilename) return outfile == infile.replace('in', 'out', 1) # If input file specified then it prints the result of the algorithm # Otherwise it tests all input/output files in ./tests folder def main(): if len(sys.argv) >= 2: filename = sys.argv[1] tree = build_tree(filename) print tree.get_min_cost_path() else: filenames = os.listdir('tests') infiles = [f for f in filenames if f.startswith('in')] outfiles = [f for f in filenames if f.startswith('out')] files = [(os.path.join('tests', infile), os.path.join('tests', outfile)) for infile in infiles for outfile in outfiles if in_match_out(infile, outfile)] for infile, outfile in files: print infile, outfile tree = build_tree(infile) min_path = tree.get_min_cost_path() test(repr(min_path), file_as_str(outfile)) if __name__ == '__main__': main()
9598105cbb767848e242d08886520f99d6ddeda5
goodboyhu/pythonrep
/01_Python基础/加等于.py
548
4.28125
4
# 在 python 中,列表变量调用 += 本质上是在执行列表变量的 extend 方法,不会修改变量的引用 def demo(num, num_list): print("函数内部代码") # num = num + num num += num # num_list.extend(num_list) 由于是调用方法,所以不会修改变量的引用 # 函数执行结束后,外部数据同样会发生变化 num_list += num_list print(num) print(num_list) print("函数代码完成") gl_num = 9 gl_list = [1, 2, 3] demo(gl_num, gl_list) print(gl_num) print(gl_list)
ae9e91363f0d350422d3ccff01996d57c0776a88
LeahSchwartz/CS101
/APTProblemSets/Set2/Pancakes.py
639
3.671875
4
''' Created on Sep 12, 2017 @author: leahschwartz ''' def minutesNeeded (numCakes, capacity): if numCakes == 0: return 0 if numCakes <= capacity: return 10 if numCakes % capacity == 0: return numCakes / capacity * 10 #if remandier is half or less can do trick if numCakes % capacity <= capacity: if numCakes % capacity <= (capacity/2): return numCakes / capacity * 10 + 5 else: return numCakes / capacity * 10 + 10 if numCakes % capacity >= capacity: return numCakes / capacity * 10 return 10 if __name__ == '__main__': pass
7b98e5ccdcd1a93100a2aed52307eadff08b7276
asg0416/BJ_Algorithm
/05_quiz.py
451
3.84375
4
def avg(list): list_sum = 0 for num in range(1,len(list)): list_sum += list[num] avg = list_sum / list[0] return avg def find(list): count = 0 for ind in range(1, len(list)): if list[ind] > avg(list): count += 1 result = round(count / list[0] * 100, 3) x = '{result:.3f}%' return x n = int(input()) for i in range(n): a = list(map(int,input().split())) print(find(a))
5e1cd1a11e38a41eee412dc80f8090f5cfd0c92f
Chilip-Noguez/Curso-em-video-Python
/exercicios/aulas/aula_07_alinhamento.py
579
4.25
4
nome = str(input('Digite seu nome: ')) print('É um prazer te conhecer, {:20}!'.format(nome)) #impressão com 20 caracteres print('É um prazer te conhecer, {:>20}!'.format(nome)) #impressão de alinhamento à direita com 20 caracteres print('É um prazer te conhecer, {:<20}!'.format(nome))#impressão de alinhamento à esquerda com 20 caracteres print('É um prazer te conhecer, {:^20}!'.format(nome))#impressão de alinhamento centralizado com 20 caracteres print('É um prazer te conhecer, {:=^20}!'.format(nome))#impressão de alinhamento centralizado com 20 caracteres
e52f13173464391d80e4403da1028da80bbc865b
soarflighting/LeetCode_Notes
/searchAlgorith/BackTracking/letterCombination_17.py
1,090
3.859375
4
# 17.电话号码的字母组合(Medium) # 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。 # 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。 # 回溯法 class Solution(object): ###利用递归进行回溯迭代 def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ phone = {2:"abc",3:"def",4:"ghi",5:"jkl",6:"mno",7:"pqrs",8:"tuv",9:"wxyz"} output = [] def backtrack(combination,next_digits): if len(next_digits) == 0: print(combination) output.append(combination) else: print(combination) for letter in phone[int(next_digits[0])]: backtrack(combination+letter,next_digits[1:]) if digits: backtrack("",digits) return output if __name__ == '__main__': s = Solution() d = "234" res = s.letterCombinations(d) print(res)
df5f93831ddbf501bf32770aae5723cfafdbe620
dhelly/Python
/cifradecesar.py
1,026
3.921875
4
#!/usr/bin/python #Exemplo encrypt e decrypt - Cifra de Cesar import sys def encrypt(mensagem): cifra = '' mensagem = mensagem.lower() for letras in mensagem: if letras in alfabeto: x = alfabeto.find(letras) + chave if x >= total: x -= total cifra += alfabeto[x] return cifra def decrypt(mensagem): cifra = '' mensagem = mensagem.lower() for letras in mensagem: if letras in alfabeto: x = alfabeto.find(letras) - chave cifra += alfabeto[x] return cifra if(len(sys.argv) < 4): print "[+] Modo de uso: ./cifra.py <chave> <mensagem> <--encrypt>" print "[+] Exemplo: ./cifra.py 3 aka --encrypt" else: alfabeto = 'abcdefghijklmnopqrstuvwxyz' total = 26 chave = int(sys.argv[1]) msg = str(sys.argv[2]) if "--encrypt" in sys.argv[3]: print "[+] Mensagem: " + encrypt(msg) elif "--decrypt" in sys.argv[3]: print "[+] Mensagem: " + decrypt(msg)
ffbe50433b5f9875b55550dc4c7cddf2c74bc5e0
bjwu/option_pricing
/Application.py
35,253
3.625
4
""" A graphical user interface for users to easily price various options with multiple pricer. """ from tkinter import * from tkinter import ttk from tkinter import scrolledtext import tkinter.font as tkFont from BSEuroOption import BSEuroOption from ImpliedVolatility import ImpliedVolatility from CFGeoAsianOption import GeoAsianOption from CFGeoBasketOption import CFGeoBasketOption import math from MCArithAsianOption import MCArithAsianOption from MCArithBasketOption import MCArithBasketOption from BiTreeAmericanOption import BiTreeAmericanOption class Application: def __init__(self): self.window = Tk() self.window.title("Mini Option Pricer") self.window.geometry('%dx%d' % (700, 400)) self.menubar = Menu(self.window) self.__createPage() self.__HomePage() self.__createMenu() self.window.config(menu=self.menubar) self.__forgetFrame() self.frameHomePage.pack() # Place frameHomePage into the window # design the homepage ft = tkFont.Font(size = 23, weight = tkFont.BOLD) Label(self.frameHomePage, text = "Mini Option Pricer", font = ft, fg = "grey", height = 11).pack() Label(self.frameHomePage, text = "Authors: Wu Bijia, Zhang Weibin, Xue Botu").pack() self.window.mainloop() def __createPage(self): self.frame1 = Frame(self.window) self.frame2 = Frame(self.window) self.frame3 = Frame(self.window) self.frame4 = Frame(self.window) self.frame5 = Frame(self.window) self.frame6 = Frame(self.window) self.frame7 = Frame(self.window) self.frameHomePage = Frame(self.window) def __HomePage(self): homepage = Menu(self.menubar, tearoff=0) homepage.add_command(label = "Homepage", command=self.run_homepage) homepage.add_command(label = "Quit", command = self.Quit) self.menubar.add_cascade(label = 'Homepage', menu = homepage) def __createMenu(self): filemenu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label='Select Pricer Model', menu=filemenu) filemenu.add_command(label = "Pricer 1: European Options - Black-Scholes Formulas", command=self.task1) filemenu.add_command(label = "Pricer 2: Implied Volatility - European Options", command=self.task2) filemenu.add_command(label = "Pricer 3: Geometric Asian Options - Closed-Form Formula", command=self.task3) filemenu.add_command(label = "Pricer 4: Geometric Basket Options - Closed-Form Formula", command=self.task4) filemenu.add_command(label = "Pricer 5: Arithmetic Asian Options - Monte Carlo Method", command=self.task5) filemenu.add_command(label = "Pricer 6: Arithmetic Mean Basket Options - Monte Carlo Method", command=self.task6) filemenu.add_command(label = "Pricer 7: American Options - Binomial Tree Method", command=self.task7) # For switching page, forget the current page and jump to another page def __forgetFrame(self): self.frame1.pack_forget() self.frame2.pack_forget() self.frame3.pack_forget() self.frame4.pack_forget() self.frame5.pack_forget() self.frame6.pack_forget() self.frame7.pack_forget() self.frameHomePage.pack_forget() # Implement Black-Scholes Formulas for European call/put option. def task1(self): self.__forgetFrame() frame = self.frame1 frame.pack() # Place frame1 into the window # define labels label_title = Label(frame, text = "Implement Black-Scholes Formulas for European Call/Put Options.", fg = "red", justify = "right").grid(row = 1, column = 1,sticky = W) label_s0 = Label(frame, text = "Spot Price of Asset:").grid(row = 2, column = 1, sticky = W) label_sigma = Label(frame, text = "Volatility:").grid(row = 3, column = 1, sticky = W) label_r = Label(frame, text = "Risk-free Interest Rate:").grid(row = 4, column = 1, sticky = W) label_repo = Label(frame, text = "Repo Rate:").grid(row = 5, column = 1, sticky = W) label_T = Label(frame, text = "Time to Maturity (in years):").grid(row = 6, column = 1, sticky = W) label_K = Label(frame, text = "Strike:").grid(row = 7, column = 1, sticky = W) label_OptionType = Label(frame, text = "Option Type:").grid(row = 8, column = 1, sticky = W) self.s0 = DoubleVar() self.sigma = DoubleVar() self.r = DoubleVar() self.repo = DoubleVar() self.T = DoubleVar() self.K = DoubleVar() self.option_type = StringVar() # define input boxes for input variables entry_s0 = Entry(frame, textvariable = self.s0).grid(row = 2, column = 2, sticky = W) entry_sigma = Entry(frame, textvariable = self.sigma).grid(row = 3, column = 2, sticky = W) entry_r = Entry(frame, textvariable = self.r).grid(row = 4, column = 2, sticky = W) entry_repo = Entry(frame, textvariable = self.repo).grid(row = 5, column = 2, sticky = W) entry_T = Entry(frame, textvariable = self.T).grid(row = 6, column = 2, sticky = W) entry_K = Entry(frame, textvariable = self.K).grid(row = 7, column = 2, sticky = W) # define the list for user to select option type self.comboboxlist_task1 = ttk.Combobox(frame, width = 17, values = ("Select Option Type", "Call Option", "Put Option"), textvariable = self.option_type, postcommand = self.run_task1) self.comboboxlist_task1.current(0) # set the default selection self.comboboxlist_task1.grid(row = 8, column = 2, sticky = W) # Reset input and log btReset = Button(frame, width = 10, text = "Reset", command = self.ResetTask1).grid(row = 10, column = 2, columnspan = 1, sticky = E) # define run button to run the pricer btRun = Button(frame, width = 10, text = "Run", command = self.run_task1).grid(row = 10, column = 2, columnspan = 1, sticky = W) # define a window to display result self.logs = scrolledtext.ScrolledText(frame, width = 74, height = 12) self.logs.grid(row = 11, column = 1, rowspan = 4, columnspan = 2, sticky = W) # Implied volatility calculations. def task2(self): self.__forgetFrame() frame = self.frame2 frame.pack() # Place frame2 into the window # define labels label_title = Label(frame, text = "Implied Volatility Calculator for European Options", fg = "red", justify = "right").grid(row = 1, column = 1,sticky = W) label_s0 = Label(frame, text = "Spot Price of Asset:").grid(row = 2, column = 1, sticky = W) label_r = Label(frame, text = "Risk-free Interest Rate:").grid(row = 3, column = 1, sticky = W) label_q = Label(frame, text = "Repo Rate:").grid(row = 4, column = 1, sticky = W) label_T = Label(frame, text = "Time to Maturity (in years):").grid(row = 5, column = 1, sticky = W) label_K = Label(frame, text = "Strike:").grid(row = 6, column = 1, sticky = W) label_V = Label(frame, text = "Option Premium:").grid(row = 7, column = 1, sticky = W) label_OptionType = Label(frame, text = "Option Type:").grid(row = 8, column = 1, sticky = W) self.s0 = DoubleVar() self.r = DoubleVar() self.q = DoubleVar() self.T = DoubleVar() self.K = DoubleVar() self.V = DoubleVar() self.option_type = StringVar() # define input boxes for input variables entry_s0 = Entry(frame, textvariable = self.s0).grid(row = 2, column = 2, sticky = E) entry_r = Entry(frame, textvariable = self.r).grid(row = 3, column = 2, sticky = E) entry_q = Entry(frame, textvariable = self.q).grid(row = 4, column = 2, sticky = E) entry_T = Entry(frame, textvariable = self.T).grid(row = 5, column = 2, sticky = E) entry_K = Entry(frame, textvariable = self.K).grid(row = 6, column = 2, sticky = E) entry_V = Entry(frame, textvariable = self.V).grid(row = 7, column = 2, sticky = E) # define the list for user to select option type self.comboboxlist_task2 = ttk.Combobox(frame, width = 17, values = ("Select Option Type", "Call Option", "Put Option"), textvariable = self.option_type, postcommand = self.run_task2) self.comboboxlist_task2.current(0) # set the default Option Type self.comboboxlist_task2.grid(row = 8, column = 2, sticky = E) # Reset input and log btReset = Button(frame, width = 23, text = "Reset", command = self.ResetTask2).grid(row = 9, column = 1, columnspan = 1, sticky = E) # define run button to run the pricer btRun = Button(frame, width = 23, text = "Run", command = self.run_task2).grid(row = 9, column = 1, columnspan = 1, sticky = W) # define a window to display result self.logs = scrolledtext.ScrolledText(frame, width = 74, height = 12) self.logs.grid(row = 10, column = 1, rowspan = 4, columnspan = 2, sticky = W) # Implement closed-form formulas for geometric Asian call/put option. def task3(self): self.__forgetFrame() frame = self.frame3 frame.pack() # Place frame3 into the window # define labels label_title = Label(frame, text = "Implement Closed-form Formulas for Geometric Asian Call/Put Options", fg = "red", justify = "right").grid(row = 1, column = 1,sticky = W) label_s0 = Label(frame, text = "Spot Price of Asset:").grid(row = 2, column = 1, sticky = W) label_sigma = Label(frame, text = "Implied Volatility:").grid(row = 3, column = 1, sticky = W) label_r = Label(frame, text = "Risk-free Interest Rate:").grid(row = 4, column = 1, sticky = W) label_T = Label(frame, text = "Time to Maturity (in years):").grid(row = 5, column = 1, sticky = W) label_K = Label(frame, text = "Strike:").grid(row = 6, column = 1, sticky = W) label_n = Label(frame, text = "Observation Times for the Geometric Average:").grid(row = 7, column = 1, sticky = W) label_OptionType = Label(frame, text = "Option Type:").grid(row = 8, column = 1, sticky = W) self.s0 = DoubleVar() self.sigma = DoubleVar() self.r = DoubleVar() self.q = DoubleVar() self.T = DoubleVar() self.K = DoubleVar() self.n = IntVar() self.option_type = StringVar() # define input boxes for input variables entry_s0 = Entry(frame, textvariable = self.s0).grid(row = 2, column = 2, sticky = E) entry_sigma = Entry(frame, textvariable = self.sigma).grid(row = 3, column = 2, sticky = E) entry_r = Entry(frame, textvariable = self.r).grid(row = 4, column = 2, sticky = E) entry_T = Entry(frame, textvariable = self.T).grid(row = 5, column = 2, sticky = E) entry_K = Entry(frame, textvariable = self.K).grid(row = 6, column = 2, sticky = E) entry_n = Entry(frame, textvariable = self.n).grid(row = 7, column = 2, sticky = E) # define the list for user to select option type self.comboboxlist_task3 = ttk.Combobox(frame, width = 17, values = ("Select Option Type", "Call Option", "Put Option"), textvariable = self.option_type, postcommand = self.run_task3) self.comboboxlist_task3.current(0) # set the default Option Type self.comboboxlist_task3.grid(row = 8, column = 2, sticky = E) # Reset input and log btReset = Button(frame, width = 29, text = "Reset", command = self.ResetTask3).grid(row = 9, column = 1, columnspan = 1, sticky = E) # define run button to run the pricer btRun = Button(frame, width = 29, text = "Run", command = self.run_task3).grid(row = 9, column = 1, columnspan = 1, sticky = W) # define a window to display result self.logs = scrolledtext.ScrolledText(frame, width = 74, height = 12) self.logs.grid(row = 10, column = 1, rowspan = 4, columnspan = 2, sticky = W) # Implement closed-form formulas for geometric basket call/put options. def task4(self): self.__forgetFrame() frame = self.frame4 frame.pack() # Place frame4 into the window # define labels label_title = Label(frame, text = "Implement Closed-form Formulas for Geometric Basket Call/Put Options", fg = "red", justify = "right").grid(row = 1, column = 1,sticky = W) label_s0_1 = Label(frame, text = "Spot Price of Asset 1:").grid(row = 2, column = 1, sticky = W) label_s0_2 = Label(frame, text = "Spot Price of Asset 2:").grid(row = 3, column = 1, sticky = W) label_sigma_1 = Label(frame, text = "Volatility of Asset 1:").grid(row = 4, column = 1, sticky = W) label_sigma_2 = Label(frame, text = "Volatility of Asset 2:").grid(row = 5, column = 1, sticky = W) label_r = Label(frame, text = "Risk-free Interest Rate:").grid(row = 6, column = 1, sticky = W) label_T = Label(frame, text = "Time to Maturity (in year):").grid(row = 7, column = 1, sticky = W) label_K = Label(frame, text = "Strike:").grid(row = 8, column = 1, sticky = W) label_rho = Label(frame, text = "Correlation:").grid(row = 9, column = 1, sticky = W) label_OptionType = Label(frame, text = "Option Type:").grid(row = 10, column = 1, sticky = W) self.s0_1 = DoubleVar() self.s0_2 = DoubleVar() self.sigma_1 = DoubleVar() self.sigma_2 = DoubleVar() self.r = DoubleVar() self.T = DoubleVar() self.K = DoubleVar() self.rho = DoubleVar() self.option_type = StringVar() # define input boxes for input variables entry_s0_1 = Entry(frame, textvariable = self.s0_1).grid(row = 2, column = 2, sticky = E) entry_s0_2 = Entry(frame, textvariable = self.s0_2).grid(row = 3, column = 2, sticky = E) entry_sigma_1 = Entry(frame, textvariable = self.sigma_1).grid(row = 4, column = 2, sticky = E) entry_sigma_2 = Entry(frame, textvariable = self.sigma_2).grid(row = 5, column = 2, sticky = E) entry_r = Entry(frame, textvariable = self.r).grid(row = 6, column = 2, sticky = E) entry_T = Entry(frame, textvariable = self.T).grid(row = 7, column = 2, sticky = E) entry_K = Entry(frame, textvariable = self.K).grid(row = 8, column = 2, sticky = E) entry_rho = Entry(frame, textvariable = self.rho).grid(row = 9, column = 2, sticky = E) # define the list for user to select option type self.comboboxlist_task4 = ttk.Combobox(frame, width = 17, values = ("Select Option Type", "Call Option", "Put Option"), textvariable = self.option_type, postcommand = self.run_task4) self.comboboxlist_task4.current(0) # set the default Option Type self.comboboxlist_task4.grid(row = 10, column = 2, sticky = E) # Reset input and log btReset = Button(frame, width = 29, text = "Reset", command = self.ResetTask4).grid(row = 11, column = 1, columnspan = 1, sticky = E) # define run button to run the pricer btRun = Button(frame, width = 29, text = "Run", command = self.run_task4).grid(row = 11, column = 1, columnspan = 1, sticky = W) # define a window to display result self.logs = scrolledtext.ScrolledText(frame, width = 74, height = 9) self.logs.grid(row = 12, column = 1, rowspan = 4, columnspan = 2, sticky = W) # Implement the Monte Carlo method with control variate technique for Arithmetic Asian call/put options. def task5(self): frame = self.frame5 self.__forgetFrame() frame.pack() # Place frame5 into within the window label_title = Label(frame, text = "Arithmetic Asian Option from MC", fg = "red", justify = "right").grid(row = 1, column = 1,sticky = W) label_s0 = Label(frame, text="S0").grid(row=2, column=1, sticky=E) label_sigma = Label(frame, text="sigma").grid(row=2, column=3, sticky=E) label_r = Label(frame, text="r").grid(row=3, column=1, sticky=E) label_T = Label(frame, text="T").grid(row=3, column=3, sticky=E) label_n = Label(frame, text="n").grid(row=4, column=1, sticky=E) label_K = Label(frame, text="K").grid(row=4, column=3, sticky=E) label_m = Label(frame, text="m").grid(row=5, column=1, sticky=E) self.s0 = DoubleVar() self.sigma = DoubleVar() self.r = DoubleVar() self.T = DoubleVar() self.n = IntVar() self.K = DoubleVar() self.option_type = StringVar() self.m = IntVar() self.ctrl_var = BooleanVar() entry_s0 = Entry(frame, width=15, textvariable=self.s0).grid(row=2, column=2, sticky=E) entry_sigma = Entry(frame, textvariable=self.sigma).grid(row=2, column=4, sticky=E) entry_r = Entry(frame, width=15,textvariable=self.r).grid(row=3, column=2, sticky=E) entry_T = Entry(frame, textvariable=self.T).grid(row=3, column=4, sticky=E) entry_n = Entry(frame, width=15, textvariable=self.n).grid(row=4, column=2, sticky=E) entry_K = Entry(frame, textvariable=self.K).grid(row=4, column=4, sticky=E) entry_m = Entry(frame, width=15, textvariable=self.m).grid(row=5, column=2, sticky=E) cbtCV = Checkbutton(frame, text="Control Variate?", variable=self.ctrl_var).grid(row=6, column=1, sticky=W) rbPut = Radiobutton(frame, width=6, text="Put", bg="red", variable=self.option_type, value='put').grid(row=6, column=2, sticky=E) rbCall = Radiobutton(frame, width=6, text="Call", bg="yellow", variable=self.option_type, value='call').grid(row=6, column=3, sticky=W) btRun = Button(frame, width=10, text="Run", command=self.run_task5).grid(row=7, column=1, columnspan=4) self.logs = scrolledtext.ScrolledText(frame, width = 74, height = 16) self.logs.grid(row=8, column=1, columnspan=4) # Implement the Monte Carlo method with control variate technique for Arithmetric Mean Basket call/put options. (for the case a basket with two assets) def task6(self): frame = self.frame6 self.__forgetFrame() frame.pack() label_title = Label(frame, text = "Arithmetic Mean Bakset Option from MC", fg = "red", justify = "right").grid(row = 1, column = 1,sticky = W) label_s0_1 = Label(frame, text="S0_1").grid(row=2, column=1, sticky=E) label_s0_2 = Label(frame, text="S0_2").grid(row=2, column=3, sticky=E) label_sigma_1 = Label(frame, text="sigma_1").grid(row=3, column=1, sticky=E) label_sigma_2 = Label(frame, text="sigma_2").grid(row=3, column=3, sticky=E) label_r = Label(frame, text="r").grid(row=4, column=1, sticky=E) label_T = Label(frame, text="T").grid(row=4, column=3, sticky=E) label_K = Label(frame, text="K").grid(row=5, column=1, sticky=E) label_rho = Label(frame, text="rho").grid(row=5, column=3, sticky=E) label_m = Label(frame, text="m").grid(row=6, column=1, sticky=E) self.s0_1 = DoubleVar() self.s0_2 = DoubleVar() self.sigma_1 = DoubleVar() self.sigma_2 = DoubleVar() self.r = DoubleVar() self.T = DoubleVar() self.K = DoubleVar() self.rho = DoubleVar() self.option_type = StringVar() self.m = IntVar() self.ctrl_var = BooleanVar() entry_s0_1 = Entry(frame, width=16, textvariable=self.s0_1).grid(row=2, column=2, sticky=E) entry_s0_2 = Entry(frame, width=20, textvariable=self.s0_2).grid(row=2, column=4, sticky=E) entry_sigma_1 = Entry(frame, width=16, textvariable=self.sigma_1).grid(row=3, column=2, sticky=E) entry_sigma_2 = Entry(frame, width=20, textvariable=self.sigma_2).grid(row=3, column=4, sticky=E) entry_r = Entry(frame, width=16, textvariable=self.r).grid(row=4, column=2, sticky=E) entry_T = Entry(frame, width=20, textvariable=self.T).grid(row=4, column=4, sticky=E) entry_K = Entry(frame, width=16, textvariable=self.K).grid(row=5, column=2, sticky=E) entry_rho = Entry(frame, width=20, textvariable=self.rho).grid(row=5, column=4, sticky=E) entry_m = Entry(frame, width=16, textvariable=self.m).grid(row=6, column=2, sticky=E) cbtCV = Checkbutton(frame, text="Control Variate?", variable=self.ctrl_var).grid(row=7, column=1) rbPut = Radiobutton(frame, text="Put", bg="red", variable=self.option_type, value='put').grid(row=7, column=2) rbCall = Radiobutton(frame, text="Call", bg="yellow", variable=self.option_type, value='call').grid(row=7, column=3) btRun = Button(frame, width=10, text="Run", command=self.run_task6).grid(row=8, column=1, columnspan=4) self.logs = scrolledtext.ScrolledText(frame, height=14) self.logs.grid(row=9, column=1, columnspan=4) # The Binomial Tree method for American call/put options. def task7(self): frame = self.frame7 self.__forgetFrame() frame.pack() # define labels label_title = Label(frame, text = "Implement the Binomial Tree Method for American Call/Put Options", fg = "red", justify = "right").grid(row = 1, column = 1,sticky = W) label_s0 = Label(frame, text = "Spot Price of Asset:").grid(row = 2, column = 1, sticky = W) label_sigma = Label(frame, text = "Volatility:").grid(row = 3, column = 1, sticky = W) label_r = Label(frame, text = "Risk-free Interest Rate:").grid(row = 4, column = 1, sticky = W) label_T = Label(frame, text = "Time to Maturity (in years):").grid(row = 5, column = 1, sticky = W) label_K = Label(frame, text = "Strike:").grid(row = 6, column = 1, sticky = W) label_N = Label(frame, text = "Number of Steps:").grid(row = 7, column = 1, sticky = W) label_OptionType = Label(frame, text = "Option Type:").grid(row = 8, column = 1, sticky = W) self.s0 = DoubleVar() self.sigma = DoubleVar() self.r = DoubleVar() self.T = DoubleVar() self.K = DoubleVar() self.N = IntVar() self.option_type = StringVar() # define input boxes for input variables entry_s0 = Entry(frame, textvariable = self.s0).grid(row = 2, column = 2, sticky = W) entry_sigma = Entry(frame, textvariable = self.sigma).grid(row = 3, column = 2, sticky = W) entry_r = Entry(frame, textvariable = self.r).grid(row = 4, column = 2, sticky = W) entry_T = Entry(frame, textvariable = self.T).grid(row = 5, column = 2, sticky = W) entry_K = Entry(frame, textvariable = self.K).grid(row = 6, column = 2, sticky = W) entry_N = Entry(frame, textvariable = self.N).grid(row = 7, column = 2, sticky = W) # define the list for user to select option type self.comboboxlist_task7 = ttk.Combobox(frame, width = 17, values = ("Select Option Type", "Call Option", "Put Option"), textvariable = self.option_type, postcommand = self.run_task7) self.comboboxlist_task7.current(0) # set the default selection self.comboboxlist_task7.grid(row = 8, column = 2, sticky = W) # Reset input and log btReset = Button(frame, width = 10, text = "Reset", command = self.ResetTask7).grid(row = 9, column = 2, columnspan = 1, sticky = E) # define run button to run the pricer btRun = Button(frame, width = 10, text = "Run", command = self.run_task7).grid(row = 9, column = 2, columnspan = 1, sticky = W) # define a window to display result self.logs = scrolledtext.ScrolledText(frame, width = 74, height = 12) self.logs.grid(row = 10, column = 1, rowspan = 4, columnspan = 2, sticky = W) def run_homepage(self): self.__forgetFrame() self.frameHomePage.pack() def run_task1(self): OptionType = self.option_type.get() if OptionType == "Call Option": try: option = BSEuroOption() result = option.CallOption(S = self.s0.get(), sigma = self.sigma.get(), r = self.r.get(), q = self.repo.get(), T = self.T.get(), K = self.K.get()) self.logs.insert(END, "The Call Option Premium is: {}\n".format(result)) except ZeroDivisionError: self.logs.insert(END, "Input Parameter Error! Please input the correct parameters!\n") elif OptionType == "Put Option": try: option = BSEuroOption() result = option.PutOption(S = self.s0.get(), sigma = self.sigma.get(), r = self.r.get(), q = self.repo.get(), T = self.T.get(), K = self.K.get()) self.logs.insert(END, "The Put Option Premium is: {}\n".format(result)) except ZeroDivisionError: self.logs.insert(END, "Input Parameter Error! Please input the correct parameters!\n") else: pass self.comboboxlist_task1.current(0) def ResetTask1(self): self.s0 = 0 self.sigma = 0 self.r = 0 self.repo = 0 self.T = 0 self.K = 0 self.task1() def run_task2(self): OptionType = self.option_type.get() if OptionType == "Call Option": try: instance = ImpliedVolatility(S = self.s0.get(), r = self.r.get(), q = self.q.get(), T = self.T.get(), K = self.K.get(), V = self.V.get()) result = instance.CallVolatility() if math.isnan(result) or math.isinf(result): self.logs.insert(END, "Input Parameter Error! Please input the correct parameters!\n") else: self.logs.insert(END, "The Implied Volatility for Call Option is: {}\n".format(result)) except ZeroDivisionError: self.logs.insert(END, "Input Parameter Error! Please input the correct parameters!\n") if OptionType == "Put Option": try: instance = ImpliedVolatility(S = self.s0.get(), r = self.r.get(), q = self.q.get(), T = self.T.get(), K = self.K.get(), V = self.V.get()) result = instance.PutVolatility() if math.isnan(result) or math.isinf(result): self.logs.insert(END, "Input Parameter Error! Please input the correct parameters!\n") else: self.logs.insert(END, "The Implied Volatility for Put Option is: {}\n".format(result)) except ZeroDivisionError: self.logs.insert(END, "Input Parameter Error! Please input the correct parameters!\n") self.comboboxlist_task2.current(0) def ResetTask2(self): self.s0 = 0 self.sigma = 0 self.r = 0 self.T = 0 self.K = 0 self.N = 0 self.task2() def run_task3(self): OptionType = self.option_type.get() if OptionType == "Call Option": try: instance = GeoAsianOption(S = self.s0.get(), sigma = self.sigma.get(), r = self.r.get(), T = self.T.get(), K = self.K.get(), n = self.n.get()) result = instance.CallGeoAsian() if math.isnan(result) or math.isinf(result): self.logs.insert(END, "Input Parameter Error! Please input the correct parameters!\n") else: self.logs.insert(END, "The Call Option Premium is: {}\n".format(result)) except ZeroDivisionError: self.logs.insert(END, "Input Parameter Error! Please input the correct parameters!\n") if OptionType == "Put Option": try: instance = GeoAsianOption(S = self.s0.get(), sigma = self.sigma.get(), r = self.r.get(), T = self.T.get(), K = self.K.get(), n = self.n.get()) result = instance.PutGeoAsian() if math.isnan(result) or math.isinf(result): self.logs.insert(END, "Input Parameter Error! Please input the correct parameters!\n") else: self.logs.insert(END, "The Put Option Premium is: {}\n".format(result)) except ZeroDivisionError: self.logs.insert(END, "Input Parameter Error! Please input the correct parameters!\n") self.comboboxlist_task3.current(0) def ResetTask3(self): self.s0 = 0 self.sigma = 0 self.r = 0 self.T = 0 self.K = 0 self.n = 0 self.task3() def run_task4(self): OptionType = self.option_type.get() if OptionType == "Call Option": try: instance = CFGeoBasketOption(s0_1 = self.s0_1.get(), s0_2 = self.s0_2.get(), sigma_1 = self.sigma_1.get(), sigma_2 = self.sigma_2.get(), r = self.r.get(), T = self.T.get(), K = self.K.get(), rho = self.rho.get()) result = instance.CallGeoBasket() if math.isnan(result) or math.isinf(result): self.logs.insert(END, "Input Parameter Error! Please input the correct parameters!\n") else: self.logs.insert(END, "The Call Option Premium is: {}\n".format(result)) except ZeroDivisionError: self.logs.insert(END, "Input Parameter Error! Please input the correct parameters!\n") if OptionType == "Put Option": try: instance = CFGeoBasketOption(s0_1 = self.s0_1.get(), s0_2 = self.s0_2.get(), sigma_1 = self.sigma_1.get(), sigma_2 = self.sigma_2.get(), r = self.r.get(), T = self.T.get(), K = self.K.get(), rho = self.rho.get()) result = instance.PutGeoBasket() if math.isnan(result) or math.isinf(result): self.logs.insert(END, "Input Parameter Error! Please input the correct parameters!\n") else: self.logs.insert(END, "The Put Option Premium is: {}\n".format(result)) except ZeroDivisionError: self.logs.insert(END, "Input Parameter Error! Please input the correct parameters!\n") self.comboboxlist_task4.current(0) def ResetTask4(self): self.s0_1 = 0 self.s0_2 = 0 self.sigma_1 = 0 self.sigma_2 = 0 self.r = 0 self.T = 0 self.K = 0 self.rho = 0 self.task4() def run_task5(self): self.logs.insert(END, "waiting.... [It may take you several minutes]\n") option = MCArithAsianOption(s0=self.s0.get(), sigma=self.sigma.get(), r=self.r.get(), T=self.T.get(), K=self.K.get(), n=self.n.get(), m=self.m.get(), option_type=self.option_type.get(), ctrl_var=self.ctrl_var.get()) result, interval = option.pricing() self.logs.insert(END, "The option premium is: {}\n".format(result)) # output the 95% confidence interval self.logs.insert(END, "The 95% confidence interval is: {}\n\n".format(interval)) def run_task6(self): self.logs.insert(END, "waiting.... [It may take you several minutes]\n\n") option = MCArithBasketOption(s0_1=self.s0_1.get() ,s0_2=self.s0_2.get(), sigma_1=self.sigma_1.get(), sigma_2=self.sigma_2.get(), r=self.r.get(), T=self.T.get(), K=self.K.get(), rho=self.rho.get(),option_type=self.option_type.get(), ctrl_var=self.ctrl_var.get()) result, interval = option.pricing(num_randoms=self.m.get()) self.logs.insert(END, "The put option premium is: {}\n".format(result)) self.logs.insert(END, "The confidence interval is: {}\n".format(interval)) def run_task7(self): OptionType = self.option_type.get() if OptionType == "Call Option": try: option = BiTreeAmericanOption() result = option.BiTreeAmericanOption(S0 = self.s0.get(), sigma = self.sigma.get(), r = self.r.get(), T = self.T.get(), K = self.K.get(), N = self.N.get(), option = 'call') self.logs.insert(END, "The Call Option Premium is: {}\n".format(result)) except ZeroDivisionError: self.logs.insert(END, "Input Parameter Error! Please input the correct parameters!\n") elif OptionType == "Put Option": try: option = BiTreeAmericanOption() result = option.BiTreeAmericanOption(S0 = self.s0.get(), sigma = self.sigma.get(), r = self.r.get(), T = self.T.get(), K = self.K.get(), N = self.N.get(), option = 'put') self.logs.insert(END, "The Put Option Premium is: {}\n".format(result)) except ZeroDivisionError: self.logs.insert(END, "Input Parameter Error! Please input the correct parameters!\n") else: pass self.comboboxlist_task7.current(0) def ResetTask7(self): self.s0 = 0 self.sigma = 0 self.r = 0 self.T = 0 self.K = 0 self.N = 0 self.task7() def Quit(self): self.window.destroy() if __name__ == '__main__': Application()
d8bf5792e8a3b650de055d3691fcb0f7ca7109ea
LogiCule/DataCamp
/Python_Track/Intermediate Python/03_Logic_Control_Flow_and_Filtering.py
810
3.625
4
#Equality True==False -5*15!=75 'pyscript'=='PyScript' True==1 #Greater and less than print(x>=-10) print('test'<=y) print(True>False) #Compare arrays print(my_house>=18) print(my_house<your_house) #and, or, not (1) print(my_kitchen>10 and my_kitchen<18) print(my_kitchen<14 or my_kitchen>17) print(2*my_kitchen<3*your_kitchen) #Boolean operators with Numpy print(np.logical_or(my_house>18.5, my_house<10)) print(np.logical_and(my_house<11,your_house<11)) #skipped the if else part #Driving right (1) dr = cars['drives_right'] sel= cars[dr] print(sel) #Driving right (2) sel = cars[cars['drives_right']] #Cars per capita (1) car_maniac = cars[cars['cars_per_cap']>500] print(car_maniac) #Cars per capita (2) between = np.logical_and(cpc > 100,cpc < 500) medium= cars[between] print(medium)
37e49c6a4c50daad65957559e7c9b2e39f1d313d
PhongNH90/NguyenHaiPhong-Fundamental-C4E25
/session3/4.guessnumber.py
247
3.890625
4
from random import randint x = randint(1,100) print(x) n = int(input("Random Number is: ")) while n != x: if n > x: print("Too high") elif n < x: print("Too low") n = int(input("Random Number is: ")) print("Bingo")
9b55fc1f3ea4959be35b29606417a1bbfe38d621
Sasmita-cloud/Hacktoberfest2021_PatternMaking
/Python/Hut-Pattern.py
366
4
4
def printHutStar(n): for i in range(n): for j in range(i + 1, n): print(' ', end = '') for j in range(0, 2 * i + 1): print('*', end = '') print() for i in range(3): for j in range(3): print('*', end = '') for j in range(2 * n - 7): print(' ', end = '') for j in range(3): print('*', end = '') print() n = 7 printHutStar(n)
7242a77367af1db7ee56ef3d6c7ed7738fa474b8
Zoz24/sudoku_solver
/sudoku_solver/sudoku.py
2,647
4.09375
4
# This function checks for an empty spot in the grid that hasn't been filled up yet def search_empty(grid): for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == -1: return i, j return None# Return none if all spots have been filled up # This function print out the sudoku grid def print_grid(grid): for i in range(len(grid)): if i != 0 and i % 3 == 0: # Seperate each vertical stack print('--------------------') for j in range(len(grid[0])): if j != 0 and j % 3 == 0: # Seperate each block print('|', end='') print(grid[i][j], end = ' ') print() def validation(num, row, col, grid): # Check if the input number contracdicts with any number in the row if num in grid[row]: return False # Check if the input number contradicts with any number in the column for i in range(len(grid)): if num == grid[i][col]: return False # Check if the input number contracts with any number within its block start_row = row // 3 * 3 start_col = col // 3 * 3 for i in range(start_row, start_row + 3): for j in range(start_col, start_col + 3): if grid[i][j] == num: return False # Return True if no contradiction was found return True # Uses recursion and backtracking to solve the Sudoku grid def solver(grid): # Base case: if search_empty(grid) == None: return True else: row, col = search_empty(grid) for i in range(1, 10): if validation(i, row, col, grid): grid[row][col] = i if solver(grid): return True grid[row][col] = -1 return False def main(): # Creating a grid for testing purpose, can change into different grid if necessary test_grid = [ [4, -1, -1, -1, -1, -1, 9, -1, -1], [-1, -1, -1, -1, 3, -1, -1, -1, -1], [-1, 1, -1, -1, 6, 5, -1, 4, -1], [-1, -1, -1, 3, -1, -1, -1, 5, -1], [-1, -1, 6, -1, 5, 2, 7, -1, -1], [-1, 2, -1, 9, -1, -1, -1, -1, -1], [-1, -1, -1, 2, -1, -1, -1, -1, -1], [-1, 6, -1, -1, 4, 1, -1, 9, -1], [-1, -1, 7, -1, -1, -1, -1, -1, 8] ] if (solver(test_grid)): print("The solution is found and is shown below:") print_grid(test_grid) else: print("The Sudoku grid is not solvable, check for errors") if __name__ == '__main__': main()
9db59750eff5f00d458052079ca1c0050165cefe
maheshde791/python_samples
/pythonsamples/class_public.py
379
3.625
4
#!/usr/bin/python class Cup: def __init__(self): self.color = None self.content = None def fill(self, beverage): self.content = beverage print "in fill method" def empty(self): self.content = None print "in empty method" redCup = Cup() redCup.color = "red" redCup.content = "tea" redCup.empty() redCup.fill("coffee")
6aa856cead4879eb9e6b42253b244a9c679221ab
TalatWaheed/100-days-code
/code/python/Day-86/replace.py
101
3.859375
4
string=input("Enter string:") string=string.replace(' ','-') print("Modified string:") print(string)
81c2656aeeb771de7611cc59502a154729c402e2
LeafmanZ/CS180E
/[Chapter 07] Strings and Lists/Checker for integer string.py
137
3.890625
4
user_string = input() user_string.split() ''' Type your code here. ''' if user_string.isdigit(): print('yes') else: print('no')
d09474903829567ab953e48f32a344476ef5fe89
Sandy4321/Data_Science_Scratch
/Ch22_Recommender_Systems/recommender.py
11,585
4.5
4
""" In this module we examine how to make recommendations to users based on a listing of each user's interest. We will do this in three ways. The first way will simply recommend to the user what is popular across all users. The second (more sophisticated) method will use cosine similarity between users to recommend what other "similar users" interest are. This approach is called 'User-based collaborative filtering'. The third approach will be to look at the similarity in interest and generating suggestions based on the aggregated interest. This is called item-based collaborative filtering. """ from collections import Counter, defaultdict from DS_Scratch.Ch4_Linear_Algebra import dot_product, magnitude from operator import itemgetter # Load Users Interests # ######################## from DS_Scratch.Ch22_Recommender_Systems.user_data import users_interests # Popularity Recommendation # ############################# # The easiest approach is simply to recommend what is popular def count_interests(users_data): """ returns a list of tuples (interest, counts) from user_data. Assumes user_data is a list of list """ return Counter(interest for user_interests in users_data for interest in user_interests).most_common() # We can suggest to a user popular interest that he/she is not already # interested in def most_popular_new_interests(user_interest, users_data, max_results=5): """ returns unique recommendations based on most popular interests in user_data """ # get the popularity of each interests popular_interests = count_interests(users_data) # get the recommendations recommendations = [(interest,count) for interest, count in popular_interests if interest not in user_interest] # return only upto max_results return recommendations[:max_results] # User-based Collaborative Filtering # ###################################### # We will use cosine similarity to measure how similar our user is to # other users and then use these similar users interest to make # recommendations to our user def cosine_similarity(v,w): """ computes the normalized projection of v onto w """ return dot_product(v,w)/float(magnitude(v)*magnitude(w)) # In order to compute the cosine similarity we will need to assign indices # to each interest so we have user_interest_vectors to compare # get the unique interest using set comprehension. These will be in # alphabetical order since sort is called def get_unique_interest(users_data): """ gets a sorted list of unique interest in users_data """ return sorted(list({interest for user_interests in users_data for interest in user_interests})) # Now we want to produce an interest vector for each user. It will be binary # a 0 for no interest and 1 for true interest at the index corresponding to # that particular interest def make_user_interest_vector(user_interests, users_data): """ makes a binary vector of interest for user """ # get the unique interests unique_interests = get_unique_interest(users_data) return [1 if interest in user_interests else 0 for interest in unique_interests] def make_user_interest_matrix(users_data): """ returns a matrix of all user_interest vectors """ user_interest_matrix =[] for user in users_data: # For each user make the vector of interest user_interest_vector = make_user_interest_vector(user, users_data) # append the vector to the matrix user_interest_matrix.append(user_interest_vector) return user_interest_matrix def user_cosine_similarities(users_data): """ Computes cosine simiilarity of all users in user interest matrix """ # get the user interest matrix user_interest_matrix = make_user_interest_matrix(users_data) # compute the cosine similarity between all rows return [[cosine_similarity(interest_vector_i, interest_vector_j) for interest_vector_j in user_interest_matrix] for interest_vector_i in user_interest_matrix] def most_similar_users_to(user_id): """ sorts the users based on cosine similarity to the user with user_id """ # get all possible pair partners to user_id. exclude those with 0 # similarity # first get the cosine similarities between all users similarities = user_cosine_similarities(users_interests) # now get all possible non-zero pairs pairs = [(other_user_id, similarity) for other_user_id, similarity in enumerate(similarities[user_id]) if user_id != other_user_id and similarity > 0] # tuple sorting is by first el first which is other_user_id so we must # sort by 2nd el of tuple return sorted(pairs, key=itemgetter(1), reverse=True) def user_based_suggestions(user_id, include_current_interests=False): """ makes suggestions to user with id user_id based on their cosine similarity with other users """ suggestions = defaultdict(float) # go through the tuple list of user_ids and similarity of most_similar # users_to and pool the interest of each other_user_id into a defdict for other_user_id, similarity in most_similar_users_to(user_id): for interest in users_interests[other_user_id]: suggestions[interest] += similarity # convert the interest into a sorted list sorting by the number of times # that suggestion occurs suggestions = sorted(suggestions.items(), key=itemgetter(1), reverse=True) # possibly exclude from suggestions interest that already belong to # user_ids interest list if include_current_interests: return suggestions else: return [(suggestion, weight) for suggestion, weight in suggestions if suggestion not in users_interests[user_id]] # Item-Based Collaborative Filtering # ###################################### # As the number of possible interest increases (i.e. the num dimensions of # our vector increases) it becomes less and less likely that any two vectors # will be very similar. In high D spaces vectors tend to be very far apart # (see curse of dimensionality sec). So another method for making # suggestions to users is to do item-based collaborative filtering. In this # approach we compute the similarity between interests rather than users and # make recommendations from a pool of similar interest. # first we will transpose the user_interests_matrix so that rows correspond # to interests and cols correspond to users def transpose_user_interests(): # make the user_interests matrix user_interests_matrix = make_user_interest_matrix(users_interests) # get the unique interests unique_interests = get_unique_interest(users_interests) # perform the transpose so that now we have a matrix where each row is # an interest and the cols are a 0 or 1 for each users index interest_user_matrix = [[user_interest_vector[j] for user_interest_vector in user_interests_matrix] for j,_ in enumerate(unique_interests)] return interest_user_matrix # now we compute the similarities between the interest def interests_similarity(): """ computes the similarity between interests """ # first get the interest user matrix interests_user_matrix = transpose_user_interests() # compute the cosine similarities between the interest vectors interest_similarities = [ [cosine_similarity(user_vector_i, user_vector_j) for user_vector_j in interests_user_matrix] for user_vector_i in interests_user_matrix] return interest_similarities # now we can find the most similar interest to each interest with def most_similar_interest_to(interest_id): """ orders the interest in terms of cosine similarity to interest of interest_id """ # Get the interest similarities and pull ot the list for the interest we # want (interest_id) interest_similarities = interests_similarity() similarities = interest_similarities[interest_id] # get the unique interests unique_interests = get_unique_interest(users_interests) # get the pairs of unique interest and similarity pairs = [(unique_interests[other_interest_id], similarity) for other_interest_id, similarity in enumerate(similarities) if interest_id != other_interest_id and similarity > 0] # return the sorted tuples from largest to smallest similarity return sorted(pairs,key=itemgetter(1), reverse=True) # Now that we have a list and rank of interest similar to a given interest # we can make recommendations to the user def item_based_recommendations(user_id, include_current_interest=False): """ uses the users interest to determine similar interest to make recommendation """ suggestions = defaultdict(float) # get the user_interest_matrix user_interest_matrix = make_user_interest_matrix(users_interests) # get the user interest vector from the matrix user_interest_vector = user_interest_matrix[user_id] # now loop throught their interest and find similar interest for interest_id, is_interested in enumerate(user_interest_vector): if is_interested: similar_interest = most_similar_interest_to(interest_id) for interest, similarity in similar_interest: suggestions[interest] += similarity # sort the suggestions by weight (combined similarity) suggestions = sorted(suggestions.items(), key=itemgetter(1), reverse=True) # determine if we should include their already stated current interest # in suggestions if include_current_interest: return suggestions else: return [(suggestion, weight) for suggestion, weight in suggestions if suggestion not in users_interests[user_id]] if __name__ == "__main__": # Popularity Recommendation # ############################# print "Popularity Based Recommendations-------------------------------" # get the interest ordered by popularity popular_interests = count_interests(users_interests) # Interest by popularity print popular_interests print "\n" # print out user1 recommendations print "To user #1 we recommend..." print most_popular_new_interests(users_interests[1], users_interests) print "\n" # User-Based Collaborative Filtering # ###################################### print "User-Based Similarity Recommendations--------------------------" # print user similarity for two sample users user_similarities = user_cosine_similarities(users_interests) print "User #1 to User #8 similarity is..." print user_similarities[0][8] # print the most similar users to user 0 print "Ordered User-Similarity to User 0..." print most_similar_users_to(0) print "\n" # print the user suggestions for user_id[0] print "We recommend to user 0 the following..." print user_based_suggestions(0) print "\n" # Item-Based Collaborative Filtering # ###################################### print "Item-Based Similarity Recommendations-------------------------" print "The most similar interest to Big Data are..." print most_similar_interest_to(0) print "\n" print "We recommend to user 0 the following..." print item_based_recommendations(0)
084a3f7bd3108eb2934fb5b58d118c8df3c81d26
codename-water/WiproPJP
/Data Structures/Dictionary/h3.py
365
3.921875
4
thisDic={} n=int(input("Enter the number of entries you want in the dictionary.")) i=0 while i<n: a=input("Key") b=input("Value") thisDic[a]=b i+=1 print("Dictionary...",thisDic) x=input("Enter the key you want to search.") if x in thisDic: print(x,"is present in the Dictionary.") else: print(x,"is not present in the Dictionary.")
8600fb86f5a79ab01a40a6670ccfa3400747d198
ankitwayne/Python-Practice
/t13.py
546
4.0625
4
def add(x,y): return x+y def sub(x,y): return x-y def mul(x,y): return x*y def div(x,y): return x/y print "Enter operation : " print "1.Addition : " print "2.Substraction : " print "3.Multiplication : " print "4.Division : " choice=input("Enter your choice(1/2/3/4): ", ) n1=input("Enter first number : ") n2=input("Enter second number : ") if choice=='1': print add(n1,n2) elif choice=='2': print sub(n1,n2) elif choice=='3': print mul(n1,n2) elif choice=='4': print div(n1,n2) else: print "invalid input"
b5dc8fc3bf4bd8aedbb7a6ea4b714d01fe14baef
IainGillon/rockpaperscissors
/tests/game_test.py
864
3.609375
4
import unittest from models.game import Game from models.player import Player from controllers import controller class TestGame(unittest.TestCase): # from models.game import Game def setUp(self): self.game1 = Game("Iain", "Iain2", "rock", "paper" ) # self.game2 = Game("Matt Hardy", "scissors") # # def test_game_has_player(self): # # self.assertEqual("Jeff Hardy", self.game1.player) # # def test_game_has_player_choice(self): # # self.assertEqual("rock", self.game1.player_choice) # # def test_game_has_winner(self): # # self.assertEqual("YOU WIN!", Game.play_game(self)) # def test_game_is_draw(self): # self.assertEqual("IT'S A TIE", Game.play_game(self)) def test_play_game(self): self.assertEqual('The winner is player 1', Game.player1_name, Game.play_game(self))
830a982ef48fe8967f8f118b0180da2367c4bbcf
Zahidsqldba07/codefights-2
/core/labOfTransformations/newNumeralSystem.py
1,433
4.53125
5
""" Your Informatics teacher at school likes coming up with new ways to help you understand the material. When you started studying numeral systems, he introduced his own numeral system, which he's convinced will help clarify things. His numeral system has base 26, and its digits are represented by English capital letters - A for 0, B for 1, and so on. The teacher assigned you the following numeral system exercise: given a one-digit number, you should find all unordered pairs of one-digit numbers whose values add up to the number. Example For number = 'G', the output should be newNumeralSystem(number) = ["A + G", "B + F", "C + E", "D + D"]. Translating this into the decimal numeral system we get: number = 6, so it is ["0 + 6", "1 + 5", "2 + 4", "3 + 3"]. """ def newNumeralSystem(number): num_to_char = {0:'A',1:'B',2:'C',3:'D',4:'E',5:'F',6:'G',7:'H',8:'I',9:'J',10:'K',11:'L',12:'M',13:'N',14:'O',15:'P',16:'Q',17:'R',18:'S',19:'T',20:'U',21:'V',22:'W',23:'X',24:'Y',25:'Z'} char_to_num = {} for key in num_to_char: char_to_num[num_to_char[key]] = key print(char_to_num) first = "A" second = number ans = [] while char_to_num[first] <= char_to_num[second]: ans.append(first + " + " + second) try: first = num_to_char[char_to_num[first] + 1] second = num_to_char[char_to_num[second]-1] except: break return ans1
924461cdc0ea8d917670aafa6bf605daaacca3a8
GabrielaVilaro/Ejercicios_Programacion
/td46.py
1,928
3.875
4
#coding=UTF-8 ''' Ejercicio: 46, Tema: Toma de desiciones Enunciado --> (46.) Un artículo se vende en distintos supermercados a diferentes precios, estos son: P1 en el supermercado A, P2 en el supermercado B, y P3 en el supermercado C. Informar: 46.1. ¿Cuál es el precio promedio del artículo? 46.2. ¿Qué supermercado vende más barato? 46.3. ¿En qué porcentaje resulta más caro el artículo respecto de los otros dos supermercados? Nombre del archivo 'td46.py' Desarrollo del algoritmo en código Python ''' super_a = raw_input("\nIngrese el precio del producto del supermercado A: ") super_a = float(super_a) super_b = raw_input("\nIngrese el precio del producto del supermercado B: ") super_b = float(super_b) super_c = raw_input("\nIngrese el precio del producto del supermercado C: ") super_c = float(super_c) total = super_a + super_b + super_c def porcentaje(parte, todo): return parte / todo * 100 print "\nEl promedio del valor del producto es de: ", total / 3 if super_a < super_b and super_a < super_c: menor = super_a print "\nEl supermercado que tiene el menor precio es el: A" print "\nEs un %", porcentaje(super_b, total), "Más barato que el B." print "\nEs un %", porcentaje(super_c, total),"Más barato que el C." else: if super_b < super_a and super_b < super_c: menor = super_b print "\nEl supermercado que tiene el menor precio es el: B" print "\nEs un %", porcentaje(super_a, total), "Más barato que el B." print "\nEs un %", porcentaje(super_c, total),"Más barato que el C." else: if super_c < super_a and super_c < super_b: menor = super_c print "\nEl supermercado que tiene el menor precio es el: C" print "\nEs un %", porcentaje(super_a, total), "Más barato que el B." print "\nEs un %", porcentaje(super_b, total),"Más barato que el C." raw_input("\nOprima la tecla ENTER para finalizar.")
91a8bf4c4a45357250dbba6152adacfeec27b2f1
Conanap/University-Year1
/Intro comp sci I/ex/ex8.py
6,192
3.875
4
# Albion Fung # V 0.0.0 # Nov 16, 2015 class LightSwitch(): '''creates a light switch that can be turned on or off.''' def __init__(self, status): '''(self, str) -> NoneType initializing method Given status, this will create a light switch with the specified status REQ: status is a string, either 'on' or 'off'. No uppercase. Otherwise default to 'off'. >>>a = LightSwitch('on') print(a) I am on >>>a = LightSwitch('off') print(a) I am off >>>a = LightSwitch('BLAH') print(a) I am off >>>a = LightSwitch('ON') I am off ''' # if status says on if(status == 'on'): # make status on self._status = True else: # otherwise it's false self._status = False def __str__(self): '''(self) -> str Returns a string indicating if the switch is on or off when the object is printed. >>>a = LightSwitch('on') >>>print(a) I am on >>>a = LightSwitch('off') >>>print(a) I am off ''' # if it's on if(self._status): # return it's on return "I am on" else: # otherwise return off return "I am off" def turn_on(self): '''(self) -> NoneType Turns the switch off regardless of previous status >>>a = LightSwitch('on') >>>a.turn_on() >>>print(a) I am on >>>a = LightSwitch('off') >>>a.turn_on() >>>print(a) I am on ''' # turns it on self._status = True def turn_off(self): '''(self) -> NoneType Turns the switch off regardless of previous status >>>a = LightSwitch('on') >>>a.turn_off() >>>print(a) I am off >>>a = LightSwitch('off') >>>a.turn_off() >>>print(a) I am off ''' # turns it off self._status = False def flip(self): '''(self) -> NoneType Flips the switch, making it the opposite status. >>>a = LightSwitch('on') >>>a.flip() >>>print(a) I am off >>>a = LightSwitch('off') >>>a.flip() >>>print(a) I am on ''' # flip it self._status = not self._status def get_status(self): '''(self) -> NoneType returns the status of the switch. Not meant for external use >>>a = LightSwitch('on') >>>a.get_status() True >>>a.flip() >>>a.get_status() False ''' # return status return self._status class SwitchBoard(): '''Creates a switch board with a specific amount of light switches. Switches are off by default.''' def __init__(self, switch_num): '''(self, int) -> NoneType Initializing method. Ceates the number of switches specified, and makes them off. ''' # initialize a list of switches self._switches = [] # loop until number of switches are created for i in range(switch_num): # make a new switch that's off _new_switch = LightSwitch('off') # add the switch to the list self._switches.append(_new_switch) def __str__(self): '''(self) -> NoneType Returns a string when the object is being print. It returns 'The following switches are on: ", followed by the switch numbers that are on. >>>a = SwitchBoard(2) >>>print(a) The following switches are on: >>>a.flip(1) >>>print(a) The following switches are on: 1 ''' # create initial string we print anyways _out = "The following switches are on:" # for each switch for i in range(len(self._switches)): # check if it's on if(self._switches[i].get_status()): # if it is, add it to the string with a space in front status = str(i) _out += (" " + status) # return the string return _out def which_switch(self): '''(self) -> list of int Returns a list of switches that are on. >>>a = SwitchBoard(2) >>>a.which_switch() [] >>>a.flip(1) >>a.which_switch() [1] ''' # creates initial list _out = [] # check if each switch is on for i in range(len(self._switches)): if(self._switches[i].get_status()): # if it is, add it to the list status = [i] _out += status # return the list return _out def flip(self, switch_num): '''(self, int) -> NoneType flips the switch at the specified index. If it's out of range, nonthing wil be done. REQ: switch_num < amount of switches >>>a = SwitchBoard(2) >>>print(a) The following switches are on: >>>a.flip(1) print(a) The following witches are on: 1 ''' # if the switch exists if(switch_num < len(self._switches)): # flip it self._switches[switch_num].flip() def flip_every(self, step): '''(self, int) -> Nonetype Flips every step amount of switches. REQ: step > 0 >>>a = SwitchBoard(4) >>>a.flip_every(2) >>>print(a) The following switches are on: 0 2 4 ''' # flip each switch every certain amount of step for i in range(0, len(self._switches), step): self.flip(i) def reset(self): '''(self) -> Nonetype Makes all the switches in the switchboard off again >>>a = SwichBoard(3) >>>a.flip(1) a.which_switch() [1] >>>a.reset() >>>a.which_switch() [] ''' # turn each switch off for i in range(len(self._switches)): self._switches[i].turn_off()
c871318e878fbefaeac201c56e93fe4814e634af
ligj1706/learn-python-hard
/ex20.py
1,368
4.09375
4
# _*_ coding: utf-8 _*_ # 调用一个打开文件的包 from sys import argv script, input_file = argv # 定义读文件函数 def print_all(f): print f.read() # 定义寻找函数 def rewind(f): f.seek(0) # 定义两个变量 def print_a_line(line_count, f): print line_count, f.readline() current_file = open(input_file) print "First let's print the whole file:\n" # 打开文件,第一个定义的函数 print_all(current_file) # 打开第二个定义的函数,打开三行文件 print "Now let's rewind, kind of like a tape." rewind(current_file) print "Let's print three lines." # 打开第一行 current_line = 1 print_a_line(current_line, current_file) # 打开文件第二行 current_line = current_line + 1 print_a_line(current_line, current_file) # 打开文件第三行 current_line = current_line + 1 print_a_line(current_line, current_file) # 加分题 += 相当于w = w + 1 # 再打开一遍 print "Now let's rewind, kind of like a tape." rewind(current_file) print "Let's print three lines." # 打开第一行 current_line = 1 print_a_line(current_line, current_file) # 打开文件第二行 current_line += current_line print_a_line(current_line, current_file) # 打开文件第三行 current_line += current_line print_a_line(current_line, current_file)
3a7a7c6f5de5c5bfe2fc72aeaaeb430e6fce6448
jeisenma/ProgrammingConcepts
/10-dataviz/smoothBars.pyde
3,574
3.5
4
def setup(): global bg size(400,400) # create some labels someLabels = [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" ] # create some random numbers between 0 and 1000 someNumbers = [] for i in range(10): someNumbers.append( random(0,1000) ) # create a bar graph object with those labels and numbers bg = BarGraph(someLabels, someNumbers) def draw(): background(150) bg.update() bg.display() def mousePressed(): # generate random data between [0,1000] for the graph -- this could # be replaced with code that switches between different datasets someNumbers = [] for i in range(10): someNumbers.append( random(0,1000) ) bg.changeData(someNumbers) class BarGraph: def __init__( self, L, D ): self.labels = [] # labels for the bars self.data = [] # data displayed at the current frame self.oldData = [] # where we came from - used for interpolation self.newData = [] # where we're going - used for interpolation self.margin = 30 # margin around the edges of the sketch self.spacing = 5 # space between bars self.timer = 0.0 # time used for interpolation self.duration = 1.0 # how long the interpolation should take self.labels = [] # make space for our arrays # copy the parameter values to our arrays for i in range(len(L)): self.labels.append( L[i] ) self.data.append( D[i] ) self.oldData.append( D[i] ) def changeData( self, newNumbers ): """ change the data set this bar graph displays """ # copy the current data over to the oldData so we know where we're coming from for i,d in enumerate(self.data): self.oldData[i] = d # put the data into the newData array for interpolating to self.newData = [] for i in range(len(self.data)): self.newData.append( newNumbers[i] ) # start the interpolation timer (counting down) self.timer = self.duration def update( self ): if(self.timer > 0.0): # if timer is still going for i in range(len(self.data)): # interpolate between old and data # linear interpolation -- gradual, but not smooth #data[i] = lerp(oldData[i], newData[i], map(timer, duration, 0, 0, 1)) # cubic interpolation -- smooth and sexy self.data[i] = cubicEase( self.duration-self.timer, self.oldData[i], self.newData[i], self.duration) self.timer = self.timer - 1.0/frameRate # timer counting down def display( self ): w = (width-2*self.margin)/len(self.data) # figure out how wide each bar should be w -= self.spacing # add space between each bar for i,d in enumerate(self.data): x = self.margin + (w + self.spacing)*i y = height-self.margin # negative height draws rectangles up from the bottom left corner (instead of down from top right corner) h = -map( d, 0, 1000, 0, height-2*self.margin ) rect( x, y, w, h ) text( self.labels[i], x+w/2, y+20 ) # utility function def cubicEase( time, startingPoint, stoppingPoint, dur ): """ smooth interpolation between (startingPoint) and (stoppingPoint) parameters are: time, startingPoint, stoppingPoint, duration """ distance = stoppingPoint - startingPoint time = time / dur-1 return distance * ( time**3 + 1) + startingPoint
131fe4954c3d7794df1f25687b4860d12077039f
CodeThales/atividade-terminal-git
/Ex03.py
1,370
4.09375
4
#Utilizando estruturas de repetição com teste lógico, #faça um programa que peça uma senha para iniciar seu #processamento, só deixe o usuário continuar se a senha #estiver correta, após entrar dê boas vindas a seu usuário #e apresente a ele o jogo da advinhação, onde o computador #vai “pensar” em um número entre 0 e 10. O jogador vai tentar #adivinhar qual número foi escolhido até acertar, #a cada palpite do usuário diga a ele se o número escolhido #pelo computador é maior ou menor ao que ele palpitou, #no final mostre quantos palpites foram necessários para vencer. from random import randint token = 666 validacao = False while not validacao: senha = int(input('Digite sua senha para iniciar o jogo: ')) if senha == token: validacao = True pc = randint(0, 10) print('''Olá, meu nome é Stark. Sou uma inteligência artificial. Seja bem vind@. Eu acabei de pensar em um número entre 0 e 10. Consegue adivinhar qual foi? ''') acertou = False palpites = 0 while not acertou: jogador = int(input('Qual o seu palpite: ')) palpites += 1 if jogador == pc: acertou = True else: if jogador < pc: print('Foi mais... Tente novamente:') elif jogador > pc: print('Foi menos... Tente novamente: ') print(f'Você acertou com {palpites} tentativas. Parabéns!')
17199f1b883fb039d959f52f30ba88238f483a16
GOWRI181109/gow
/66.py
114
3.59375
4
rgv=int(input()) for v in range(2,rgv): if rgv%v==0: print("no") break else: print("yes")
7e40e581df6c74f5d6ae0d4cd220a70367c6f005
Ruban-chris/Interview-Prep-in-Python
/cracking_the_coding_interview/4/4-12.py
1,796
4
4
# You are given a binary tree in which each node contains an integer value # (which might be positive or negative). Design an alogorithm to count the number # of paths that sum to a given value. THe path does not need to start or end at # the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes). class BinaryTreeNode: def __init__(self, obj): self.data = obj self.right = None self.left = None def setData(self, obj): self.data = obj def setRight(self, node): self.right = node def setLeft(self, node): self.left = node node3 = BinaryTreeNode(3) node4 = BinaryTreeNode(5) node5 = BinaryTreeNode(5) node6 = BinaryTreeNode(5) node7 = BinaryTreeNode(5) node8 = BinaryTreeNode(5) node9 = BinaryTreeNode(0) nodeMinus10 = BinaryTreeNode(-10) node10 = BinaryTreeNode(10) node6, node4 node6, node8 node6, node8, node6.setLeft(node4) node6.setRight(node8) node4.setLeft(node3) node4.setRight(node5) node8.setLeft(node7) node8.setRight(node9) node9.setRight(nodeMinus10) nodeMinus10.setRight(node10) def numOfSummationPaths(node, total): if node is None: return 0 return numOfSummationPathsHelper(node, total, 0) + numOfSummationPaths(node.left, total) + numOfSummationPaths(node.right, total) def numOfSummationPathsHelper(node, total, runningTotal): if node is None: return False runningTotal += node.data if runningTotal is total: return 1 + numOfSummationPathsHelper(node.left, total, runningTotal) + numOfSummationPathsHelper(node.right, total, runningTotal) else: return numOfSummationPathsHelper(node.left, total, runningTotal) + numOfSummationPathsHelper(node.right, total, runningTotal) print(numOfSummationPaths(node6, 10))
6bd4ef3e8451617f464b78171dd87eae5590836c
bjung400/study
/Python/Quiz/Q10.py
97
3.5
4
a = {'A':90, 'B':80, 'C':70} print(a.pop('B')) i = 0 while i <= 100: print(i) i = i + 1
368af1f577739b98582c810e443604a4e6e12ce9
Wictor-dev/ifpi-ads-algoritmos2020
/iteração/12_media_dos_valores.py
277
4.03125
4
def main(): n = int(input('Digite a quantidade de números: ')) media = 0 count = 1 while(count <= n): print(f'N{count}:', end=' ') valor = int(input()) media += valor / n count += 1 print(media) main()
e68bb3393f2a4ffe01537ddc043293de7c79ff60
K-ennethA/LifeLog
/connect.py
1,140
3.84375
4
import sqlite3 from sqlite3 import Error def create_connection(db_file): conn = None try: conn = sqlite3.connect(db_file) return conn except Error as e: print(e) # finally: # if conn: # conn.close() return conn def create_table(conn, create_table_sql): try: c = conn.cursor() c.execute(create_table_sql) except Error as e: print(e) def main(): database = r"db/pythonsqlite.db" sql_create_projects_table = """CREATE TABLE IF NOT EXISTS users( id SERIAL, username VARCHAR NOT NULL, pass VARCHAR NOT NULL, UNIQUE(username) ); """ #create a database connection conn = create_connection(database) #create table(s) if conn is not None: create_table(conn, sql_create_projects_table) conn.commit() else: print("Error! cannot create the database connection.") conn.close() if __name__ == '__main__': main()
a23b069981fc9ec9f1ed327f680e654e5ccf0929
hemantkumbhar10/Practice_codes_python
/royal_orchid.py
1,881
3.703125
4
class Flower: flower_names = {'orchid':15, 'rose':25, 'jasmin':40} def __init__(self): self.__flower_name = None self.__price_per_kg = None self.__stock_available = None self.__required_quanitiy = None def set_flower_name(self, flower_name): self.__flower_name = flower_name def set_price_per_kg(self, price_per_kg): self.__price_per_kg = price_per_kg def set_stock_available(self, stock_available): self.__stock_available = stock_available def set_required_quantity(self,required_quantity): self.__required_quanitiy = required_quantity def get_flower_name(self): return self.__flower_name def get_price_per_kg(self): return self.__price_per_kg def get_stock_available(self): return self.__stock_available def get_required_quantity(self): return self.__required_quanitiy def validate_flower(self): return any(self.__flower_name in key for key in Flower.flower_names) def validate_stock(self): return self.__stock_available >= self.__required_quanitiy def sell_flower(self): if self.validate_flower() and self.validate_stock(): self.__stock_available -= self.__required_quanitiy return self.__stock_available else: return 'Invalid data' def check_level(self): for key,value in Flower.flower_names.items(): if self.validate_flower(): if value >= self.sell_flower(): return True else: return False f1 = Flower() f1.set_flower_name('orchid') f1.set_stock_available(25) f1.set_required_quantity(50) print(f1.validate_flower()) print(f1.validate_stock()) print(f1.sell_flower()) print(f1.check_level())