blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
18563b04d6ab9fe6175f4406a23c9c785d4b27e4
40309/variables
/spot check 2.py
560
3.796875
4
#Tony K. #23/09/2014 #Spot check whole_number= int(input("Please enter your integer of grams: ")) hundred = whole_number // 100 remainder1 = whole_number % 100 fifty = remainder1 // 50 remainder2 = remainder1 % 50 ten = remainder2 // 10 remainder3 = remainder2 % 10 five = remainder3 // 5 remainder4 = remainder3 % 5 two = remainder4 // 2 remainder5 = remainder4 % 2 one = remainder5 / 1 print("{0} grams goes into {1}x100g, {2}x50g, {3}x10g, {4}x5g, {5}x2g and {6}x1g".format(whole_number,hundred, fifty, ten, five, two, one))
13379372df1dd1a01be9881f4eaefc1666bd3fee
sungminoh/algorithms
/leetcode/solved/662_Maximum_Width_of_Binary_Tree/solution.py
3,736
4.0625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2020 sungminoh <smoh2044@gmail.com> # # Distributed under terms of the MIT license. """ Given the root of a binary tree, return the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels. The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes are also counted into the length calculation. It is guaranteed that the answer will in the range of 32-bit signed integer. Example 1: Input: root = [1,3,2,5,3,null,9] Output: 4 Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9). Example 2: Input: root = [1,3,null,5,3] Output: 2 Explanation: The maximum width existing in the third level with the length 2 (5,3). Example 3: Input: root = [1,3,2,5] Output: 2 Explanation: The maximum width existing in the second level with the length 2 (3,2). Constraints: The number of nodes in the tree is in the range [1, 3000]. -100 <= Node.val <= 100 """ from collections import defaultdict from collections import deque from typing import Optional import pytest import sys sys.path.append('../') from exercise.tree import TreeNode, build_tree # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def widthOfBinaryTree(self, root: TreeNode) -> int: """08/11/2020 22:36""" minmax = defaultdict(lambda: [float('inf'), -float('inf')]) def traverse(node, depth, pos): if node is None: return minmax[depth][0] = min(minmax[depth][0], pos) minmax[depth][1] = max(minmax[depth][1], pos) traverse(node.left, depth+1, pos*2 - 1) traverse(node.right, depth+1, pos*2) traverse(root, 0, 1) return max(m - n + 1 for n, m in minmax.values()) def widthOfBinaryTree(self, root: TreeNode) -> int: """08/11/2020 22:36""" q = deque([(root, 0, 1)]) d = 0 n, m = 1, 1 ret = 1 while q: node, depth, pos = q.popleft() if depth != d: ret = max(ret, m-n+1) n = m = pos d = depth else: n = min(n, pos) m = max(m, pos) if node.left: q.append((node.left, depth+1, pos*2-1)) if node.right: q.append((node.right, depth+1, pos*2)) ret = max(ret, m-n+1) return ret def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int: """03/11/2022 16:55""" ret = 0 queue = deque() if root: queue.append((0, root)) while queue: size = len(queue) mn = float('inf') mx = -float('inf') for _ in range(size): idx, node = queue.popleft() mn = min(mn, idx) mx = max(mx, idx) if node.left: queue.append((idx<<1, node.left)) if node.right: queue.append(((idx<<1) + 1, node.right)) ret = max(ret, mx-mn+1) return ret @pytest.mark.parametrize('values, expected', [ ([1,3,2,5,3,None,9], 4), ([1,3,None,5,3], 2), ([1,3,2,5], 2), ([1,3,2,5,None,None,9,6,None,None,7], 8), ]) def test(values, expected): assert expected == Solution().widthOfBinaryTree(build_tree(values)) if __name__ == '__main__': sys.exit(pytest.main(["-s", "-v"] + sys.argv))
6a1505bdc83fd6a62e8cf342309665a1728e649a
kyleecodes/Python-Advent-Calendar
/dec15.py
321
3.8125
4
# Write a function called where_is_2(series) that returns the position (integer) of the number 2. import pandas as pd def where_is_2(series): where_is_two = series.get_loc(2) return where_is_two if __name__ == '__main__': my_list = [1, 6, 4, 9, 3, 0, 2] data = pd.Index(my_list) where_is_2(data)
7cd95a2bfe2161389153693bd8b2f212cf5b4de8
smaecrof/Python-Playground
/pyDictionaries.py
850
3.828125
4
# Author: Spencer Mae-Croft # Date: 08/31/2020 dean = { 'first_name': "Dean", 'last_name': "Colvin", 'age': '69', 'hometown': "Plyouth", 'state':"Indiana", 'occupation':"Judge", } for key, value in dean.items(): print("\nKey: " + key + " ------> " + value) spencer = { 'first_name': 'Spencer', 'last_name': 'Mae-Croft', 'age': '22', 'hometown':'Plymouth', 'state':'Indiana', 'occupation': 'Programmer' } elise = { 'first_name':'Elise', 'last_name':'Patrick', 'age':'22', 'hometown':'Plymouth', 'state':'Indiana', 'Occupation':'Medical School Student' } people = [dean, spencer, elise] for person in people: print("\n") for key,value in person.items(): print(key + " ---> " + value)
2f76af470e5d7110407e619952ffa1464d104b0d
FaezehAHassani/python_exercises
/syntax_list.py
1,007
3.84375
4
# doing things to list ten_things = "Apples Oranges Crows Telephone Light Sugar" print("Wait there are not 10 things in that list. Let's fix that.") stuff = ten_things.split(' ') # if I put '' it give an error print(stuff) more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] print(more_stuff) while len(stuff) != 10: next_one = more_stuff.pop() # remove the last index from more_stuff and store it in next_one print("Adding: ", next_one) stuff.append(next_one) # adds next_one list to the end of stuff list print(f"There are {len(stuff)} items now.") print("There we go: ", stuff) print("Let's do some things with stuff.") print(stuff[1]) print(stuff[-1]) print(stuff.pop()) # typing print(pop(more_stuff)) gives error print(' '.join(stuff)) # reomoves ' ' from stuff list and print all indexes one after another with a space in between, if I put '' they will be printed without space print(stuff) print('#'.join(stuff[3:5])) # returns Telephone#Light
6bc76baaf14c6605e16add5f1fd994459f739f5b
gup-abhi/comp_image
/compressor.py
333
3.53125
4
# import PIL module import PIL # importing image from PIL module from PIL import Image # opening image from the current working directory img = Image.open("margot.jpg") # resizing the image to specific dimensions img = img.resize((500, 500), PIL.Image.ANTIALIAS) # saving the resize image to the directory img.save("margot2.jpg")
22007182db9256d478d3e063bd526b0222329bf9
DaphneKeys/Python-Projects-
/guessthenumtrynexcept.py
1,166
3.96875
4
import random print('What is your name?') name = input() while True: #infinite loop answer = random.randint(1,20) tries = 5 #added tries variable to count down works properly print('Hello! ' + name + ' We are going to play a guess game. Choose a number between 1 to 20\nTotal : 5 tries\n') while tries != 0: while True: guess = input('Take a guess: ') try: guess = int(guess) break except ValueError: print('Enter a number!') if guess > answer: tries -=1 print('That is too high! Tries left :' +str(tries)) elif guess < answer: tries -=1 print('That is too low. Tries left : '+str(tries)) else: break if guess == answer: print('Yes, that is correct, It was ' + str(answer) +'! Tries left:' + str(tries) ) break else: print('Oh no... You have 0 tries left, the correct answer was ' + str(answer)) break #Try and except works #Everything works!
f187e276afc96d69056eee0639c583ca14a33904
Ricardo301/CursoPython
/Desafios/Desafio036.py
701
3.734375
4
import colorama colorama.init() ValorCasa = float(input('Qual é o valor da casa R$ ')) salario = float(input('Qual é o seu salário? ')) ano = int(input('Em qunatos anos será percelada ?')) presmensal = ValorCasa / (ano*12) percentualSal = salario * 0.3 if presmensal > percentualSal: print('Para pagar uma casa de R${:.2f} em {} anos a prestação serpa de R${:.2f} você ganha R${:.2f} é muito pouco'.format( ValorCasa, ano, presmensal, salario)) print('Emprestimo Negado') else: print('Para pagar uma casa de R${:.2f} em {} anos a prestação serpa de R${:.2f} você ganha R${:.2f} '.format( ValorCasa, ano, presmensal, salario)) print('Emprestimo concedido')
94e77c1f12be2d0e6c92d6bb8cefbc74caddc49a
ChaitanyaPuritipati/CSPP1
/CSPP1-Practice/cspp1-assignments/m10/how many_20186018/how_many.py
786
4.15625
4
''' Author: Puritipati Chaitanya Prasad Reddy Date: 9-8-2018 ''' #Exercise : how many def how_many(a_dict1): ''' #aDict: A dictionary, where all the values are lists. #returns: int, how many values are in the dictionary. ''' counter_values = 0 for i in a_dict1: counter_values = counter_values + len(a_dict1[i]) return counter_values def main(): ''' Main Function starts here ''' input_num = int(input()) a_dict = {} i_num = 0 while i_num < input_num: s_str = input() l_list = s_str.split() if l_list[0][0] not in a_dict: a_dict[l_list[0][0]] = [l_list[1]] else: a_dict[l_list[0][0]].append(l_list[1]) i_num = i_num+1 print(how_many(a_dict)) if __name__ == "__main__": main()
26d5a199376a5d5da3b8916ee096c81d021668d1
SafeeSaif/Personal-Code
/PE9 guessing game.py
661
3.828125
4
import random ans = random.randint(1,100) counter = 0 def GG(): global counter guess = int(input("Guess a number between 1 and 100, including 1 and 100!")) if (guess < 1) or (guess > 100): print("Invalid Input. Please guess between 1 and 9!") GG() elif guess == ans: print("Correct! You guessed", ans,"!") print("You guessed",counter,"times before winning!") elif guess > ans: print("Too High!") counter += 1 GG() elif guess < ans: print("Too Low!") counter += 1 GG() elif guess == "exit": return GG()
ecc5ae4c24b61bcc5084932639b6ca6129e3559d
dlwnstjd/python
/pythonex/0811/conprehensionex1.py
859
4
4
''' Created on 2020. 8. 11. @author: GDJ24 컴프리헨션 예제 패턴이 있는 list, dictionary, set을 간편하게 작성할 수 있는 기능 ''' numbers = [] for n in range(1,11): numbers.append(n) print(numbers) #컴프리헨션 표현 print([x for x in range(1,11)]) clist = [x for x in range(1,11)] print(clist) #1~10까지의 짝수 리스트 생성 evenlist = [] for n in range(1,11): if n % 2 == 0: evenlist.append(n) print(evenlist) #컴프리헨션 표현 evenlist = [x for x in range(1,11) if x % 2 == 0] print(evenlist) #2의 배수이고, 3의 배수인 값만 리스트에 추가하기 evenlist = [x for x in range(1,11) if x % 2 == 0 if x % 3 == 0] print(evenlist) #중첩사용 컴프리 헨션 사용하기 matrix = [[1,2,3],[4,5,6],[7,8,9]] print(matrix) list1 = [x for row in matrix for x in row] print(list1)
ddb92903626d550e904edae91d9d3049801e1856
JoshPennPierson/HackerRank
/Algorithms/Implementation/Birthday Chocolate.py
520
3.53125
4
#https://www.hackerrank.com/challenges/the-birthday-bar #!/bin/python3 import sys def getWays(squares, d, m): ways_to_break = 0 n = len(squares) for i in range(n-(m)+1): this_sum = 0 for j in range(m): this_sum += squares[i+j] if this_sum == d: ways_to_break += 1 return(ways_to_break) n = int(input().strip()) s = list(map(int, input().strip().split(' '))) d,m = input().strip().split(' ') d,m = [int(d),int(m)] result = getWays(s, d, m) print(result)
4207dd1925f6d2779660dd54937602c4aebb095e
rybodiddly/Archaeology-Grid-Layout-Tools
/hypotenuse.py
174
4
4
from math import sqrt print('Input sides A & B of triange:') a = float(input('a: ')) b = float(input('b: ')) c = sqrt(a**2 + b**2) print('Length of side C (hypotenuse):', c)
75bc634d23e6e4f3a7ce7912ad7a3730843cb198
tylerhuntington222/Rosalind
/transcribe.py
221
3.59375
4
def main(): with open('data', 'r') as f: data = f.readline() t = "" for i in data: if i == "T": t += "U" else: t += i t = t.strip() print (t) main()
bcd21fe69099f75fd17b95b1c151e4b8f1a7a1dc
MedvedMichael/PrepareSession
/Convertions/venv/convertions.py
1,797
3.796875
4
import math def convert16to10(num16=""): num10 = 0 alphabet = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"] for i in range(len(arr16)): num10 += (16 ** (len(num16) - i - 1)) * alphabet.index(num16[i]) print(num10) return num10 def convert10to16(num10=0): arr = [] alphabet = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"] while num10 >= 16: arr.insert(0, alphabet[num10 % 16]) num10 //= 16 if num10 != 0: arr.insert(0, alphabet[num10]) text = "" for element in arr: text += str(element) print(text) return text def convert10to2(num10=0): arr = [] while num10 >= 2: arr.insert(0, num10 % 2) num10 //= 2 if num10 == 1: arr.insert(0, 1) text = "" for element in arr: text += str(element) return text def convert2to10(num2=""): num10 = 0 for i in range(len(num2)): num10 += 2 ** (len(num2) - i - 1) * int(num2[i]) return num10 def convert16to2(num16=""): alphabet = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"] num2 = "" for i in range(len(num16)): element = alphabet.index(num16[i]) deltaNum = convert10to2(element) while len(deltaNum) < 4: deltaNum = "0" + deltaNum num2 += str(int(deltaNum)) print(num2) return num2 def convert2to16(num2=""): alphabet = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"] num16 = "" while len(num2) % 4 != 0: num2 = "0" + num2 for i in range(0, len(num2), 4): deltaNum = alphabet[convert2to10(num2[i:i + 4])] num16 += deltaNum print(num16)
8db319648fd17606fa301af4964677201bcf8f29
liorch1/learning-python
/list_overlap.py
389
3.796875
4
#!/usr/bin/env python36 import random a_list = [] b_list = [] c_list = [] #list after filtering list_element = int(input("please enter a number: ")) for i in range(list_element+1): a_list.append(random.randrange(1,100,1)) for j in range(11): b_list.append(random.randrange(1,100,1)) for num in a_list: if num in b _list and num not in c_list: c_list.append(num) print(c_list)
5539fd21c34ef951c8065a14bd15eca7a053bf22
chris-miklas/Python
/lab04/pcalc.py
452
3.84375
4
#!/usr/bin/env python3 """ Polish notation calculator. """ import sys stack = [] for i in sys.argv[1:]: if i.isnumeric(): stack.append(i) else: a, b = int(stack.pop()), int(stack.pop()) if i == '+': stack.append(a + b) elif i == '-': stack.append(a - b) elif i == '*': stack.append(a * b) elif i == '/': stack.append(a / b) print(stack.pop())
06db574b027c177f1468c9cf46aa9466450b1621
AnmolKhawas/PythonAssignment
/Assignment5/8.py
122
3.765625
4
#Take the input from the console and create a 2D List. m=[] for i in range(2): m.append(input().split(" ")) print(m)
e05f12b0c40cc88a422990b6af0fd1507b36d3ff
Zanzan666/2017A2CS
/Ch23/binary_tree.py
1,847
3.546875
4
#Jenny Zhan Opt3 np=-1 class BTNode: def __init__(self): self.value='' self.lp=np self.rp=np class BT: def __init__(self,length): self.fp=0 self.records=[] self.rootp=np for i in range(length): newNode=BTNode() newNode.lp=i+1 self.records.append(newNode) self.records[-1].lp=np def insert(self,Item): if self.fp != np: self.newnp=self.fp self.fp=self.records[self.fp].lp self.records[self.newnp].value=Item self.records[self.newnp].lp=np self.records[self.newnp].rp=np if self.rootp==np: self.rootp=self.newnp else: tempP=self.rootp while tempP != np: prevP=tempP if self.records[tempP].value>Item: self.TurnLeft=True tempP=self.records[tempP].lp elif self.records[tempP].value==Item: print("error") return None else: self.TurnLeft=False tempP=self.records[tempP].rp if self.TurnLeft: self.records[prevP].lp=self.newnp else: self.records[prevP].rp=self.newnp def find(self,Item): tempP=self.rootp while tempP !=np and self.records[tempP].value != Item: if self.records[tempP].value > Item: tempP=self.records[tempP].lp else: tempP=self.records[tempP].rp return tempP a=BT(10) a.insert(1) a.insert(3) a.insert(5) a.insert(2) a.insert(6) a.insert(4) print(a.find(3))
3c24e47b9739fd16748d8b6d00d262cf37e3a820
karlalopez/hackbright
/ready-set-code/bartender-solution-with-prints.py
1,546
3.84375
4
import random questions = { "strong": "Do ye like yer drinks strong?", "salty": "Do ye like it with a salty tang?", "bitter": "Are ye a lubber who likes it bitter?", "sweet": "Would ye like a bit of sweetness with yer poison?", "fruity": "Are ye one for a fruity finish?" } ingredients = { "strong": ["glug of rum", "slug of whisky", "splash of gin"], "salty": ["olive on a stick", "salt-dusted rim", "rasher of bacon"], "bitter": ["shake of bitters", "splash of tonic", "twist of lemon peel"], "sweet": ["sugar cube", "spoonful of honey", "spash of cola"], "fruity": ["slice of orange", "dash of cassis", "cherry on top"] } def find_preferences(): preferences = {} for type, question in questions.iteritems(): print type print question preferences[type] = raw_input().lower() in ["y", "yes"] print preferences[type] print "" print preferences return preferences def make_drink(preferences): drink = [] for ingredient_type, liked in preferences.iteritems(): print ingredient_type, liked if not liked: continue drink.append(random.choice(ingredients[ingredient_type])) print drink print drink return drink def main(): preferences = find_preferences() drink = make_drink(preferences) print "One drink coming up." print "It's full of good stuff. The recipe is:" for ingredient in drink: print "A {}".format(ingredient) if __name__ == "__main__": main()
f3b16e58273d44d8ddd5723944d9d09b9fe91932
RRCHcc/python_base
/python_base/day05/exercise02.py
1,160
4.1875
4
""" 练习3 在控制台中输入一个月份 返回该月份的天数 1 3 5 7 8 10 12(31天) 4 6 9 11(30天) 2 (当28天 使用元组 """ month = int(input("请输入月份:")) day_of_month = (31, 28, 31,30, 31, 30, 31, 31, 30, 31, 30, 31) if month > 12 or month < 1: print("输入错误") else: print(day_of_month[month-1]) month =int(input("请输入月份:")) if month<1 or month>12: print("输入错误") else: day_of_month = (31,28,31,30,31,30,31,31,30,31,30,31) print(day_of_month[month-1]) int_month = int(input("输入一个月份")) if int_month<1 or int_month>12: print("输入有误") else: #将每月的天数,存入元组 day_of_month = (31,28,31,30,31,30,31,30,31,30,31) print(day_of_month[int_month-1]) # #利用元组 # int_month = int(input("输入一个月份")) # if int_month<1 or int_month>12: # print("输入有误") # elif int_month == 2: # print("该月份有28天") # #elif int_month == 4 or int_month == 6 or int_month == 9 or int_month == 11: # elif int_month in (4,6,9,11): # print("该月份有30天") # else: # print("该月份有31天")
46a51a3dc2c738701422a9352fa9488d13e7616a
envisioncheng/python
/pyworkshop/2_intermediate_python/chapter4/exercise_part5_try_except.py
274
4.1875
4
try: my_dict = {"hello": "world"} print(my_dict["foo"]) except KeyError: print("Oh no! That key doesn't exist") try: my_dict = {"hello": "world"} print(my_dict["foo"]) except KeyError as key_error: print(f"Oh no! The key {key_error} doesn't exist!")
0d1e569eb57b766cdf3e1cee3d21e93e0204bbb3
Aasthaengg/IBMdataset
/Python_codes/p03197/s189769078.py
124
3.65625
4
N = int(input()) ret = "second" for _ in range(N): a = int(input()) if a % 2 != 0: ret = "first" print(ret)
9905d616ba947f617a1159fc4a5954c91aca9d5d
danielballan/scikit-image
/doc/examples/plot_windowed_histogram.py
5,113
3.546875
4
from __future__ import division """ ======================== Sliding window histogram ======================== Histogram matching can be used for object detection in images [1]_. This example extracts a single coin from the `skimage.data.coins` image and uses histogram matching to attempt to locate it within the original image. First, a box-shaped region of the image containing the target coin is extracted and a histogram of its greyscale values is computed. Next, for each pixel in the test image, a histogram of the greyscale values in a region of the image surrounding the pixel is computed. `skimage.filters.rank.windowed_histogram` is used for this task, as it employs an efficient sliding window based algorithm that is able to compute these histograms quickly [2]_. The local histogram for the region surrounding each pixel in the image is compared to that of the single coin, with a similarity measure being computed and displayed. The histogram of the single coin is computed using `numpy.histogram` on a box shaped region surrounding the coin, while the sliding window histograms are computed using a disc shaped structural element of a slightly different size. This is done in aid of demonstrating that the technique still finds similarity in spite of these differences. To demonstrate the rotational invariance of the technique, the same test is performed on a version of the coins image rotated by 45 degrees. References ---------- .. [1] Porikli, F. "Integral Histogram: A Fast Way to Extract Histograms in Cartesian Spaces" CVPR, 2005. Vol. 1. IEEE, 2005 .. [2] S.Perreault and P.Hebert. Median filtering in constant time. Trans. Image Processing, 16(9):2389-2394, 2007. """ import numpy as np import matplotlib import matplotlib.pyplot as plt from skimage import data, transform from skimage.util import img_as_ubyte from skimage.morphology import disk from skimage.filters import rank matplotlib.rcParams['font.size'] = 9 def windowed_histogram_similarity(image, selem, reference_hist, n_bins): # Compute normalized windowed histogram feature vector for each pixel px_histograms = rank.windowed_histogram(image, selem, n_bins=n_bins) # Reshape coin histogram to (1,1,N) for broadcast when we want to use it in # arithmetic operations with the windowed histograms from the image reference_hist = reference_hist.reshape((1, 1) + reference_hist.shape) # Compute Chi squared distance metric: sum((X-Y)^2 / (X+Y)); # a measure of distance between histograms X = px_histograms Y = reference_hist num = (X - Y) ** 2 denom = X + Y frac = num / denom frac[denom == 0] = 0 chi_sqr = 0.5 * np.sum(frac, axis=2) # Generate a similarity measure. It needs to be low when distance is high # and high when distance is low; taking the reciprocal will do this. # Chi squared will always be >= 0, add small value to prevent divide by 0. similarity = 1 / (chi_sqr + 1.0e-4) return similarity # Load the `skimage.data.coins` image img = img_as_ubyte(data.coins()) # Quantize to 16 levels of greyscale; this way the output image will have a # 16-dimensional feature vector per pixel quantized_img = img // 16 # Select the coin from the 4th column, second row. # Co-ordinate ordering: [x1,y1,x2,y2] coin_coords = [184, 100, 228, 148] # 44 x 44 region coin = quantized_img[coin_coords[1]:coin_coords[3], coin_coords[0]:coin_coords[2]] # Compute coin histogram and normalize coin_hist, _ = np.histogram(coin.flatten(), bins=16, range=(0, 16)) coin_hist = coin_hist.astype(float) / np.sum(coin_hist) # Compute a disk shaped mask that will define the shape of our sliding window # Example coin is ~44px across, so make a disk 61px wide (2 * rad + 1) to be # big enough for other coins too. selem = disk(30) # Compute the similarity across the complete image similarity = windowed_histogram_similarity(quantized_img, selem, coin_hist, coin_hist.shape[0]) # Now try a rotated image rotated_img = img_as_ubyte(transform.rotate(img, 45.0, resize=True)) # Quantize to 16 levels as before quantized_rotated_image = rotated_img // 16 # Similarity on rotated image rotated_similarity = windowed_histogram_similarity(quantized_rotated_image, selem, coin_hist, coin_hist.shape[0]) fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 10)) axes[0, 0].imshow(quantized_img, cmap='gray') axes[0, 0].set_title('Quantized image') axes[0, 0].axis('off') axes[0, 1].imshow(coin, cmap='gray') axes[0, 1].set_title('Coin from 2nd row, 4th column') axes[0, 1].axis('off') axes[1, 0].imshow(img, cmap='gray') axes[1, 0].imshow(similarity, cmap='hot', alpha=0.5) axes[1, 0].set_title('Original image with overlaid similarity') axes[1, 0].axis('off') axes[1, 1].imshow(rotated_img, cmap='gray') axes[1, 1].imshow(rotated_similarity, cmap='hot', alpha=0.5) axes[1, 1].set_title('Rotated image with overlaid similarity') axes[1, 1].axis('off') plt.show()
c21ca4ee01b74868728316a94fada3419eb9bdf6
wodndb/PythonWithKoreatech
/hw03/hw03_05_01.py
382
4.03125
4
#!usr/local/bin/python # coding: utf-8 def addall(L): "Return SUM of element in List that is parameter of this function by for~in literal" result = 0 for k in range(len(L)): if(type(L[k]) == int): result += L[k] return result print ">>> addall([1])" print addall([1]) print print ">>> addall([1, 2, 3, 4, 5, 6, 7, 8, 9])" print addall([1, 2, 3, 4, 5, 6, 7, 8, 9]) print
e24151d2dcee730e42356a25a6eb000862b8e2c3
sk12bansal/python_prg
/cycle.py
177
3.828125
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 9 15:34:57 2017 @author: surakum2 """ from itertools import cycle a=[10,20,30,40] b=[50,60,70,80] for v in cycle(a,b): print(v)
007c0a11798300eae4d1b912ce409a71af3c1294
hzfmax/path_planning
/utils/distance.py
725
3.5
4
import math CHV = 1. CD = math.sqrt(2) def manhattanDistance( i1: int, j1: int, i2: int, j2: int ) -> float: dx, dy = abs(i1 - i2), abs(j1 - j2) return CHV*(dx + dy) def diagonalDistance( i1: int, j1: int, i2: int, j2: int ) -> float: dx, dy = abs(i1 - i2), abs(j1 - j2) return CHV*abs(dx - dy) + CD*min(dx, dy) def chebyshevDistance( i1: int, j1: int, i2: int, j2: int ) -> float: dx, dy = abs(i1 - i2), abs(j1 - j2) return CHV*max(dx, dy) def euclidDistance( i1: int, j1: int, i2: int, j2: int ) -> float: dx, dy = abs(i1 - i2), abs(j1 - j2) return CHV*math.sqrt(dx*dx + dy*dy)
e7f9020bd287389c07b1e332a937c963fd862186
seoseokbeom/leetcode
/142LInkLIstCycle2.py
410
3.5
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def detectCycle(self, head): slow= head fast= head while slow.next!=None and fast.next!=None and fast.next.next!=None: slow=slow.next fast=fast.next.next if(slow==fast):
59e2b59557d9c919da8c6e209788f4cac2524846
henrikhellstrom/chess
/piece/pawn.py
3,111
3.5
4
from piece import Piece import pygame import constants class Pawn(Piece): #white is a boolean #pos is a list [x, y], holding square index def __init__(self, white, pos): self.white = white if white == True: self.image = pygame.image.load(constants.image_dir + "/white_pawn.png") else: self.image = pygame.image.load(constants.image_dir + "/black_pawn.png") self.pos = pos self.type = "pawn" #Returns which moves would be possible on an empty board def get_all_moves(self): ret = [] if self.white == True: if self.pos[1]-1 >= 0: ret.append([self.pos[0], self.pos[1]-1]) ret.append([self.pos[0]-1, self.pos[1]-1]) ret.append([self.pos[0]+1, self.pos[1]-1]) if self.pos[1] == 6: ret.append([self.pos[0], self.pos[1]-2]) if self.white == False: if self.pos[1]+1 <= 7: ret.append([self.pos[0], self.pos[1]+1]) ret.append([self.pos[0]-1, self.pos[1]+1]) ret.append([self.pos[0]+1, self.pos[1]+1]) if self.pos[1] == 1: ret.append([self.pos[0], self.pos[1]+2]) return ret # Remove all moves blocked by movement and return the remaining moves def remove_blocked_moves(self, pieces): moves_containing_piece = self.get_moves_containing_piece(pieces) moves_without_piece = self.get_moves_not_containing_piece(pieces) possible_moves = [] for move in moves_containing_piece: if move[0] == self.pos[0]: pass else: #Allow captures for piece in pieces: if piece.pos[0] == move[0] and piece.pos[1] == move[1]: if piece.white != self.white: possible_moves.append(move) for move in moves_without_piece: if move[0] == self.pos[0]: #Allow moving straight possible_moves.append(move) else: pass #Prevent pawns from being able to jump over pieces if len(possible_moves) == 1: if abs(possible_moves[0][1] - self.pos[1]) == 2: return [] return possible_moves def get_moves_containing_piece(self, pieces): moves = self.get_all_moves() moves_containing_piece = [] if pieces != None: for move in moves: for piece in pieces: if piece.pos[0] == move[0] and piece.pos[1] == move[1]: moves_containing_piece.append(move) return moves_containing_piece def get_moves_not_containing_piece(self, pieces): moves = self.get_all_moves() moves_not_containing_piece = moves[:] for piece in pieces: for move in moves: if piece.pos[0] == move[0] and piece.pos[1] == move[1]: moves_not_containing_piece.remove(move) return moves_not_containing_piece
9b3b3fe46d3f9bfa165d1d54c1c45c11ad9a00dd
Sonatrix/Sample-python-programs
/fibonacci_series.py
138
3.75
4
num = int(input()) def fibo(n): a,b = 0,1 for i in range(n): yield a a,b = b,a+b for i in fibo(num): print(i)
7e748bef5e0b8ccfc8e667a18a2d9dcf2462ea91
hiteshishah/BDA
/HW_KNN_Hiteshi_Shah.py
16,378
3.53125
4
""" hw_knn_hiteshi_shah.py author: Hiteshi Shah date: 11/9/2017 description: To write a program to remove outliers from the training data using KNN """ import numpy as np import math class TreeNode: """ A tree node contains: :slot attr: The attribute that the node belongs to :slot val: The threshold value for splitting the node into left & right :slot left: The left child of the node :slot right: The right child of the node :slot child: This property indicates whether the child is a "Left" child or a "Right" child """ __slots__ = 'attr', 'val', 'left', 'right', 'child' def __init__(self, attr, val, left=None, right=None, child=None): """ function to initialize a node. :param attr: The attribute that the node belongs to :param val: The threshold value for splitting the node into left & right :param val: The threshold value for splitting the node into left & right :param left: The left child of the node :param right: The right child of the node :param child: This property indicates whether the child is a "Left" child or a "Right" child """ self.attr = attr self.val = val self.left = left self.right = right self.child = child def main(): # getting the training data from the CSV file data = np.genfromtxt("HW_05C_DecTree_TRAINING__v540.csv", delimiter=",", dtype="unicode") # separating the attributes from the rest of the data attributes = data[0] attributes = attributes[:len(attributes) - 1] # separating the training data from the target variable and converting the training data to float training_data = data[1:].T target_variable = training_data[len(training_data) - 1] training_data = training_data[:len(training_data) - 1].astype(np.float) # cleant he data before building the decision tree training_data, target_variable = knn_cleaning(training_data.T, target_variable, 9) training_data = training_data.T # running the decision tree on the training data root = decision_tree(training_data, attributes, target_variable) # setting the child labels in the decision tree setChild(root) # writing the classification program with open('HW_KNN_Hiteshi_Shah_Classifier.py', 'a') as file: # some boiler plate code at the start of the program that loads the test data into the classifier file.write('import numpy as np\n\n' 'data = np.genfromtxt("HW_05C_DecTree_TESTING__FOR_STUDENTS__v540.csv", delimiter=",", dtype="unicode")\n' 'attributes = data[0]\n' 'data = data[1:].astype(np.float)\n' 'classes = []\n' 'for line in data:\n') # recursive function that writes the if-else statements of the decision tree in the program preorder(root, file, 0, attributes) # code to save the results of the classifier program to a CSV file file.write('\nnp.savetxt("HW_KNN_Hiteshi_Shah_MyClassifications.csv", classes, fmt="%s", delimiter=",", ' 'header="Class", comments="")') def knn_cleaning(training_data, target_variable, k): ''' function to perform KNN cleaning in the training data, given the value of k :param training_data: the training data to be cleaned :param target_variable: the target variable of the training data :param k: the number of nearest neighbors :return: the cleaned training data and its corresponding target variable ''' n = len(training_data) outlier_scores = {} # dictionary to keep track of indices of outliers and their outlier scores # for every point in the training data, compute the distance from the point to every other point in the dataset # sort the distances in ascending order to get the k nearest neighbors of the current data point # and store the average of these distances as the outlier score of the current data point for i in range(0, n): distances = [] for j in range(0, n): if i == j: continue else: distances.append(compute_distance(training_data[i], training_data[j])) distances = sorted(distances)[:k] outlier_scores[i] = sum(distances) / k # sort the data points in descending ourder of their outlier scores sorted_scores = sorted(outlier_scores.items(), key=lambda value: value[1], reverse=True) # here, we want to remove 5% of the data, so we remove 5% of the data points with the highest outlier scores number_of_points_to_remove = int(0.05 * n) for i in range(0, number_of_points_to_remove + 1): index = sorted_scores[i][0] training_data[index] = -100000 target_variable[index] = "X" training_data = np.array([point for point in training_data if len(set(point)) != 1]) target_variable = np.array([point for point in target_variable if point != "X"]) return training_data, target_variable def compute_distance(point1, point2): ''' function to compute the euclidean distance between point1 and point2 :param point1: the first end point :param point2: the second end point :return: the distance between point1 and point2 ''' sum = 0 for i in range(0, len(point1)): sum += math.pow(point1[i] - point2[i], 2) return math.sqrt(sum) def decision_tree(training_data, attributes, target_variable): ''' function that recursively builds the decision tree for the given training data :param training_data: the data on which the decision tree is built :param attributes: the attributes in the training data :param target_variable: list of values of the target variable for the classification, corresponding to the training data :return: returns the final decision tree ''' # if the training data or the list of attributes is empty, # returns the majority of the target variable classes as the leaf node if (len(training_data) == 0) or (len(attributes) == 0): return TreeNode(find_majority(target_variable)[0], find_majority(target_variable)[0]) # if all the target variable classes are the same, # returns the target variable class as the leaf node elif len(set(target_variable)) == 1: return TreeNode(target_variable[0], target_variable[0]) # if there are less than or equal to 20 instances in target variable # returns the majority of the target variable classes as the leaf node elif len(target_variable) <= 20: return TreeNode(find_majority(target_variable)[0], find_majority(target_variable)[0]) # recursively builds the decision tree else: # chooses the best attribute with the lowest gini index as the current root best_attribute, best_value = choose_attribute(attributes, training_data, target_variable) root = TreeNode(best_attribute, best_value) attribute_index = np.where(attributes == best_attribute)[0][0] # removes the chosen best attribute from the list of attributes attributes = np.delete(attributes, attribute_index) # transposing the training data to divide into left and right branches, # where values <= best value go to the left and values > best value go to the right training_data = training_data.T left_training_data = [] right_training_data = [] left_target_variable = [] right_target_variable = [] for index in range(0, len(training_data)): if training_data[index][attribute_index] <= best_value: left_training_data.append(training_data[index]) left_target_variable.append(target_variable[index]) else: right_training_data.append(training_data[index]) right_target_variable.append(target_variable[index]) left_training_data = np.array(left_training_data).T right_training_data = np.array(right_training_data).T # recursively calling the decision tree function on the left and right children left_child = decision_tree(left_training_data, attributes, left_target_variable) right_child = decision_tree(right_training_data, attributes, right_target_variable) # setting the left and right branches of the current root to the respective children and returning the resulting root root.left = left_child root.right = right_child return root def find_majority(target_variable): ''' function to find the majority of the classes in the given list of the target variable :param target_variable: list of classes of the target variable :return: the class with the maximum occurrence in the given list ''' maxMap = {} # dictionary for mapping the class with the maximum occurrence maximum = ('', 0) # initializing the tuple for maximum(occurring element, no. of occurrences) # mapping all the classes in the list with their occurrences to the dictionary for value in target_variable: if value in maxMap: maxMap[value] += 1 else: maxMap[value] = 1 # keeping track of the maximum on the go if maxMap[value] > maximum[1]: maximum = (value, maxMap[value]) return maximum def choose_attribute(attributes, training_data, target_variable): ''' function to choose the attribute with the lowest gini index :param attributes: list of attributes in the training data :param training_data: the training data :param target_variable: list of classes in the target variable, corresponding to the training data :return: the attribute (and its value) with the lowest gini index ''' best_gini_index = math.inf # initializing the best (lowest) gini index # for each attribute, splitting the training data into left & right at each value of the attribute # and computing the gini index at that value of the attribute for index in range(0, len(attributes)): for value in training_data[index]: left, right, sorted_target_variable = split(training_data[index], value, target_variable) gini_index = compute_gini_index(left, right, sorted_target_variable) # storing the lowest gini index, along with the attribute and its value if gini_index < best_gini_index: best_gini_index = gini_index best_attribute = attributes[index] best_value = value return best_attribute, best_value def split(training_data, value, target_variable): ''' function to split the given data, at the given value. Also to rearrange the classes in the list of the target variable :param training_data: the data to be split into left & right :param value: the value at which the split will occur :param target_variable: the list of classes of the target variable :return: left & right lists of the given data after the split, and the rearranged list of the target variable ''' # rearranging the target variable in ascending order of the values in the given data sorted_target_variable = [x for _, x in sorted(zip(training_data, target_variable))] # sorting the given data in ascending order training_data = sorted(training_data) # initialzing the left and right lists for the split left = [] right = [] # for each value in the data, if value <= the given splitting value, we append that value to the left list # if value > the given splitting value, we append that value to the right list for data in training_data: if data <= value: left.append(data) else: right.append(data) return left, right, sorted_target_variable def compute_gini_index(left, right, target_variable): ''' function to compute the gini index, given the left and right splits and the target variable :param left: the left list after the split :param right: the right list after the split :param target_variable: the list of classes of the target variable :return: the computed gini index ''' num_left = len(left) # no. of values in the left list num_right = len(right) # no. of values in the right list # initializing the counts for the classes of the target variable in both (left & right) lists left_greyhound_count = 0 left_whippet_count = 0 right_greyhound_count = 0 right_whippet_count = 0 # counting the occurrences of each class of the target variable in both (left & right) lists for index in range(0, num_left): if target_variable[index] == "Greyhound": left_greyhound_count += 1 else: left_whippet_count += 1 for index in range(0, num_right): if target_variable[index] == "Greyhound": right_greyhound_count += 1 else: right_whippet_count += 1 # computing the respective gini indexes of the left and right lists if left_greyhound_count + left_whippet_count == 0: left_gini_index = 0 else: left_gini_index = 1 - math.pow(left_greyhound_count / (left_greyhound_count + left_whippet_count), 2)\ - math.pow(left_whippet_count / (left_greyhound_count + left_whippet_count), 2) if right_greyhound_count + right_whippet_count == 0: right_gini_index = 0 else: right_gini_index = 1 - math.pow(right_greyhound_count / (right_greyhound_count + right_whippet_count), 2) \ - math.pow(right_whippet_count / (right_greyhound_count + right_whippet_count), 2) # computing the combined gini index gini_index = (num_left / (num_left + num_right)) * left_gini_index + (num_right / (num_left + num_right)) * right_gini_index return gini_index def setChild(root, child=None): ''' function to set "Left" and "Right" labels to child nodes :param root: the root of the decision tree :param child: the label indicating if the current node is a "Left" child or a "Right" child ''' if root: root.child = child setChild(root.left, "Left") setChild(root.right, "Right") def preorder(node, file, tabs, attributes): ''' function to recursively write if-else statements of the decision tree, in pre-order style :param node: the current node in the decision tree :param file: the file to write the if-else statements into :param tabs: the current number of tabs (indentation) :param attributes: the list of attributes in the training data ''' # returns if there is no node if not node: return # if the node is a leaf node, it writes code to append the class to the final list if node.attr == "Whippet" or node.attr == "Greyhound": if node.child == "Right": file.write("\t" * tabs) file.write("else:\n") file.write("\t" * (tabs + 1)) file.write("classes.append('" + node.attr +"')\n") else: # if the node is a "Left" child, it writes the if statement if node.child != "Right": tabs += 1 file.write("\t" * tabs) attr_index = np.where(attributes == node.attr)[0][0] file.write("if line[" + str(attr_index) + "] <= " + str(node.val) +":\n") # if the node is a "Right" child, it writes the else statement else: file.write("\t" * tabs) file.write("else:\n") if node.left: tabs += 1 file.write("\t" * tabs) attr_index = np.where(attributes == node.attr)[0][0] file.write("if line[" + str(attr_index) + "] <= " + str(node.val) + ":\n") # recursively calling this function on the left and right branches of the current node preorder(node.left, file, tabs, attributes) preorder(node.right, file, tabs, attributes) main()
3c09cdbde93e56c0c4d3b49ba34ab548236696d8
mradu97/python-programmes
/matrix_practice.py
376
3.78125
4
i=0 while(i <= 10): j=5 while(j>(i/2)): print(" ",end="") j=j-1 j=0 while(j<i+1): print("*",end="") j=j+1 print("") i=i+2 i=12 while(i >= 0): j=6 while(j> (i/2)): print(" ",end="") j=j-1 j=0 while(j<i-1): print("*",end="") j=j+1 print("") i=i-2
20c68827ab499f77cfacd859d56b8c0815603728
stacyzhao/Monty-Hall-Dilemma
/monty-hall.py
2,540
3.78125
4
import random def player_select_door(doors): return random.randint(0,len(doors)-1) def setup_game(number_of_doors): # doors = ["Car"] + ['Goat' for x in range(0, number_of_doors - 1)] doors = ["Car"] + ['Goat' + str(x) for x in range(0, number_of_doors - 1)] random.shuffle(doors) return doors def available_doors(doors, player_door): # remaining_doors = doors[:player_door] + doors[player_door+1:] remaining_doors = list(range(0, len(doors))) remaining_doors.remove(player_door) eligible_doors = [] for door in remaining_doors: if doors[door] != "Car": eligible_doors.append(door) return eligible_doors def get_open_door(available_doors): return random.choice(available_doors) def remaining_doors(player_door, opened_door, doors): remaining_door = list(range(0, len(doors))) remaining_door.remove(player_door) remaining_door.remove(opened_door) return remaining_door[0] def stay_or_switch_decision(): decision = random.randint(0,1) if decision == 1: print ("Stay") #stay return True else: print("Switch") #switch return False def play_game(number_of_doors, stay, doors, player_door, remaining_door): if stay: if doors[player_door] == "Car": print ("winner!") return True else: print ("loser!") return False else: if doors[remaining_door] == "Car": print ("winner!") return True else: print ("loser!") return False def play_game_stay(doors, player_door): if doors[player_door] == "Car": # print ("winner!") return True else: # print ("loser!") return False def play_game_switch(doors, remaining_door): if doors[remaining_door] == "Car": return True else: return False # return t/f if they win or not def main(): stay_counter = 0 switch_counter = 0 for _ in range(1000): doors = setup_game(3) player_door = player_select_door(doors) available_door = available_doors(doors, player_door) opened_door = get_open_door(available_door) if play_game_switch(doors, remaining_doors(player_door, opened_door, doors)): switch_counter += 1 if play_game_stay(doors, player_door): stay_counter += 1 print ("Stay: ", stay_counter) print ("Switch: ", switch_counter) if __name__ == '__main__': main()
3835ec856d25c12b67531ab4ed9503571821077d
kevinconway/chattools
/tests/test_mention.py
3,169
3.625
4
"""Test suites for @mention tools.""" from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from chattools import mention def test_mentions_are_empty_if_not_present(): """Ensure there are no mentions generated if not exist in the text. Example: mary, you there? Result: () """ results = tuple(mention.mentions('mary, you there?')) assert not results def test_mention_detects_at_text_start(): """Ensure mentions at the beginning of a line of text are found. Example: @mary, you there?. Result: ('mary',) """ results = tuple(mention.mentions('@mary, you there?')) assert 'mary' in results assert len(results) == 1 def test_mention_detects_mid_stream(): """Ensure mentions within the body of the text are found. Example: Has anyone seen @mary today? I need her help. Result: ('mary',) """ results = tuple( mention.mentions('Has anyone seen @mary today? I need her help.') ) assert 'mary' in results assert len(results) == 1 def test_mention_detects_end_of_text(): """Ensure mentions at the end of a line are also detected. Example: When you get a chance, I really need your help with this @mary! Results: ('mary',) """ results = tuple( mention.mentions( 'When you get a chance, I really need your help with this @mary!', ) ) assert 'mary' in results assert len(results) == 1 def test_mention_detects_multiple_mentions(): """Ensure multiple mentions are detected if given. Example: Hey, @mary & @geetha, thanks for knocking out that bug! Results: (mary, geetha) """ results = tuple( mention.mentions( 'Hey, @mary & @geetha, thanks for knocking out that bug!', ) ) assert 'mary' in results assert 'geetha' in results assert len(results) == 2 def test_mention_detects_multiline(): """Ensure the mentions are detected even if the text more than one line. Example: @everyone, three cheers for our team's MVPs of the day! @mary, @geetha resolved a major customer issue! Drinks on @themanager tonight! Results: ('everyone', 'mary', 'geetha', 'themanager') """ results = tuple( mention.mentions( """@everyone, three cheers for our team's MVPs of the day! @mary, @geetha resolved a major customer issue! Drinks on @themanager tonight!""", ) ) assert 'everyone' in results assert 'mary' in results assert 'geetha' in results assert 'themanager' in results assert len(results) == 4 def test_mention_skips_emails(): """Ensure email addresses are not mistaken for mentions. Example: @riddhi, try emailing the new team @ devtools@ourcorp.com. Results: ('riddhi',) """ results = tuple( mention.mentions( '@riddhi, try emailing the new team @ devtools@ourcorp.com.', ) ) assert 'riddhi' in results assert 'ourcorp' not in results assert 'ourcorp.com' not in results assert len(results) == 1
edd7ba01dc19e8ca95ccd195dc2d581d0a030db3
elzbyfar/tkh-phase-1
/week-007-solutions/song_script.py
917
3.6875
4
class Song: def __init__(self, title, artist, genre): self.title = title self.artist = artist self.genre = genre self.price = 0.99 self.purchases = 0 self.total_sales = 0.00 def display_info(self): return f"{self.title} by {self.artist}" def buy(self): self.purchases += 1 self.total_sales += self.price return f"Thank you for your purchase of {self.display_info()}." def more_info(self): return f"'{self.title}' is a {self.genre} song. It has been purchased {self.purchases} times. The song has grossed ${'{0:.2f}'.format(self.total_sales)} to date." def __add__(self, other_song): return self.price + other_song.price if __name__ == '__main__': import sys song_info = sys.argv song = Song(*song_info[1:]) print(song.display_info())
955e9e3012e65c505411c40a6944e4859b3c276f
jpragasa/Learn_Python
/Basics/19e_Dictionaries_Challenge.py
1,332
4.0625
4
locations = {0: "You are sitting in front of a computer learning Python", 1: "You are standing at the end of a road before a small brick building", 2: "Random text 1", 3: "Random text 2, aaa", 4: "Random text 3", 5: "Random text 5"} exits = {0: {"Q": 0}, 1: {"Q": 0, "W": 2, "E": 3, "N": 5, "S": 4}, 2: {"Q": 0, "N": 5}, 3: {"Q": 0, "W": 1}, 4: {"Q": 0, "N": 1, "W": 2}, 5: {"Q": 0, "W": 2}, "S": 1} vocabulary = {"QUIT": "Q", "NORTH": "N", "SOUTH": "S", "EAST": "E", "WEST": "W"} # print(locations[0].split()) # print(locations[3].split(", ")) # print(' '.join(locations[0].split())) loc = 1 while True: available_exits = ", ".join(exits[loc].keys()) print(locations[loc]) if loc == 0: break direction = input("Available exits are " + available_exits).upper() print() if len(direction) > 1: words = direction.split() for word in words: if word in vocabulary: direction = vocabulary[word] break if direction in exits[loc]: loc = exits[loc][direction] else: print("You cannot go in that direction")
018127f1a505764b72523f1c9028f1c47e352d2a
Hallldor/school_projects
/hlutaprof1/q4test2.py
220
4.0625
4
string1 = "" for number in range(1, 11): print("{:5}{:5}{:5}{:5}{:5}{:5}{:5}{:5}{:5}{:5}".format(number * 1, number * 2, number * 3, number * 4, number* 5, number * 6, number * 7, number * 8, number * 9, number* 10))
0d40b810e38ce707fd470d6339ef5281a10bf415
mmatvienko/aes
/main.py
2,070
3.875
4
from aes import * import argparse parser = argparse.ArgumentParser(description='Use AES with ECB.') parser.add_argument('--keysize', type=int, default=128, help="""Define key size. Pick between 128-bit or 256-bit.""") parser.add_argument('--keyfile', type=str, help="""Location of the file that contains your key.""") parser.add_argument('--inputfile', type=str, help="""Location of what you want to encrypt. """) parser.add_argument('--outputfile', type=str, help="""Path of your output""") parser.add_argument('--mode', type=str, help="""Do you want to encrypt or decrypt""") args = parser.parse_args() KEY_SIZE = args.keysize KEY_FILE = args.keyfile INPUT_FILE = args.inputfile OUTPUT_FILE = args.outputfile MODE = args.mode # define basic params to be passed into cipher # bock width doesn't change Nb = 4 # aes 128 if KEY_SIZE == 128: Nk = 4 Nr = 10 elif KEY_SIZE == 256: # aes 256 Nk = 8 Nr = 14 else: exit("Key Size has to be 128 or 256 bits") inp = None with open(INPUT_FILE, 'rb') as f: inp = f.read() if MODE == 'encrypt': # do some padding # thx for the code michael <3 length = 16 - (len(inp) % 16) inp += bytes([length])*length key = None with open(KEY_FILE, 'rb') as f: key = f.read() # perform key expansion w = [int(x) for x in KeyExpansion(key, Nk, Nb, Nr)] final = [] if MODE == 'encrypt': for c in range(len(inp)//16): for x in Cipher(inp[16*c:16*(c+1)],w,Nb,Nr): final.append(x) elif MODE == 'decrypt': # do decrypt stuff for c in range(len(inp)//16): for x in InvCipher(inp[16*c:16*(c+1)],w,Nb,Nr): final.append(x) else: exit("modes can either be encrypt of decrypt only") # just making sure everything is padded if len(final) % 16 != 0: print("length is not a multiple of 16... it should be") with open(OUTPUT_FILE, "wb") as f: f.write(bytes(final))
70223e604759aedf6744a49058c2ec6a23852501
friedlich/python
/19年8月/8.09/np.argmax.py
428
3.890625
4
# np.argmax:返回沿轴最大值的索引值 import numpy as np # 一维数组 A = np.arange(6).reshape(2,3) print(A) # 返回一维数组中最大值的索引值: B = np.argmax(A) print(B) C = np.argmax(A, 1) print(C) B = np.argmax(A, 0) print(B) # 二维数组 # 要索引的数组: E = np.array([[4,2,3],[2,3,4],[3,2,2]]) print(E) print(E.shape) F = np.argmax(E, axis=0) print(F) G = np.argmax(E, axis=1) print(G)
56e6a2a3207025573241af5c717f44f46c9a4b8d
yuuee-www/Python-Learning
/Pygame/Heads or Tails Game/check.py
889
3.828125
4
from pythonds.basic.queue import Queue def check(): # Code for checking the results ans_check = input('Do you want to print the result in dorder they were played or sorted? \n \ [Enter "o" for in order and "s" for sorted]\n') if ans_check == 'o': f = open('result.txt','r') # Another way to operate file I/O result = Queue() for line in open('result.txt'): line = line.strip() # To make the output more clear result.enqueue(line) while result.size()>1: print(result.dequeue()) f.close() if ans_check == 's': f = open('result.txt','r') result = [] # Read lines and store it as a list for line in open('result.txt'): line = line.strip() result.append(line) result.sort() # Sorted for item in result: print(item) f.close() check()
3e2cbeb8177a4d636310543237df358405faaf78
njaneto/dev-python
/scripts_py/Cap_5/exec_1.py
397
3.875
4
def main(): dia, mes, ano = eval(input("Digite o dia, mes e ano")) data = "{0}/{1}/{2}".format(dia,mes, ano) meses = ["Janeiro", "Fevereiro", "Marco", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro","Dezembro"] mesStr = meses[mes - 1] data2 = "{0} {1}, {2}".format(mesStr, dia, ano) print("A data eh {0} ou {1}".format(data, data2)) main()
c2d5b9cdea7719e3ff7bac82f760b8a1311f6efd
Luciano-A-Vilete/Python_Codes
/BYU_codes/Vilete_004.py
948
3.890625
4
#Python Code 004 #Library import import random #Words lists adjectives = ['attractive', 'brainy', 'brave', 'charming', 'smart'] animals = ['zebra', 'elephant', 'lion', 'dog', 'cat', 'bat'] verbs1 = ['run', 'scream', 'fly', 'walk', 'think'] exclamations = ['wow!', 'amazing!', 'great!!!', 'Wonderful!', 'Awesome!'] verbs2 = ['fight', 'clean', 'say', 'have', 'know'] verbs3 = ['make', 'take', 'use', 'work', 'feel'] #Just Trying to create a list of lists verbs_total = [verbs1, verbs2, verbs3] #Story story = (f'The other day, I was really in trouble. It all started when I saw a very {random.choice(adjectives)} {random.choice(animals)} {random.choice(verbs1)} down the hallway. "{random.choice(exclamations)}" I yelled. But all I could think to do was to {random.choice(verbs2)} over and over. Miraculously, that caused it to stop, but not before it tried to {random.choice(verbs3)} right in front of my family.') print(story)
68bb58f6bda7d537d6f103431c8d0cc5df415660
eencdl/leetcode
/python/countAndSay.py
946
3.921875
4
__author__ = 'don' """ The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ... 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth sequence. Note: The sequence of integers will be represented as a string. """ class Solution: # @param {integer} n # @return {string} def countAndSay(self, n): return self.helper(n,'1') def helper(self, n, seq): if n == 1: return seq newSeq = '' base = seq[0] cnt = 1 for i in range(1, len(seq)): if base == seq[i]: cnt += 1 else: newSeq += str(cnt) + base cnt = 1 base = seq[i] newSeq += str(cnt) + base return self.helper(n-1, newSeq)
9439135f5c06e6dee6d7a2d0c06a7d4ff6728dc6
romanannaev/python
/lessons stormnet/2019-10-24/dict.py
1,323
3.640625
4
# dictionary = {'andrey':27, 'alex':57, 'eugen':47, 'anfisa':37, 'nik':17,} # dictionary2 = {} # age = 20 # for i in range(16): # dictionary2["name" + str(i)] = age + i # # print(dictionary2) # dictionary = dict(minsk=1000, gomel= 500, gomel= 600) # # print(dictionary) # a = [['minsk', 1000], ['gomel', 500]] # f = dict(a) # # print(f) # b = dict.fromkeys(['d', 'h', 'g', 't'], 100) # # print(b) # # print(dictionary['minsk']) # dictionary['ecaterina'] = 'second' # del dictionary['minsk'] # dictionary.setdefault('luda') # print(dictionary) # # print(dictionary.pop('luda')) # print(dictionary.keys()) # print(dictionary.items()) # print(dictionary.pop() # count_alpha = {} # st = input('enter string :') # for i in st: # if i in count_alpha:# if i.isalpha(): # count_alpha[i] += 1 #d[i] = d.get(i, 0) + 1 # else: # count_alpha[i] = 1 # print(count_alpha) # for i in sorted(count_alpha): # print(i, count_alpha[i]) words = {} while True: s = input('enter string:') if s in words: print('Word', s, 'translated like: ', words[s]) else: print('Enter translated word', s) words[s] = input('enter:') # def flatten(lst): # return [y for x in lst for y in x] # Пример: # lst = [[1, 2, 3], [4, 5, 6]] # print(flatten(lst)) # [1, 2, 3, 4, 5, 6]
dc4c3f9f928bc6dfd3ddf582f3b066cd9caf000a
saurav912/Codeforces-Problemset-Solutions
/CDFPangram.py
124
3.6875
4
x = int(input()) y = input() y = y.upper() y = list(y) if len(set(y)) == 26: print('YES') else: print('NO')
860a2c9d21dfa690cb15d59bb7df3b8fe8ebb380
DrewRitos/projects
/AssignXIII("IXL").py
7,956
4.1875
4
import random #I import random to generate all of the numbers within each problem print("Welcome to IXL") #Asks the user what they want to practice for the first time op = input("What skill would you like to practice today?") #Starts a loop that allows the user to take multiple tests multiple times while True: #The points are generated per user input, and num is equal to the question number the user is on points = 0 num = 0 #Determines which operator the user wants and randomly generates problems and asks the user them #If they reach 10 points, they win #If they get to -5 points, they lose #If they get a question right, they get 3 points #When they get it wrong, they lose 5 points if op == "+": while True: num += 1 integer1 = random.randint(1,100) integer2 = random.randint(1,100) answer = integer1 + integer2 q = float(input("\n"+str(num)+". "+str(integer1)+" + "+str(integer2)+" =")) if q == answer: print("Correct!") points += 3 print("Points:",points) else: print("Incorrect. Try again") points -= 5 print("Points:",points) while True: q = float(input("\n"+str(num)+". "+str(integer1)+" + "+str(integer2)+" =")) if q == answer: print("Correct!") points += 3 print("Points:",points) break else: print("Incorrect. Try again") points -= 1 print("Points:",points) if points >= 10: print("\nYou have mastered the skill of addition!") print("It took you",num,"questions to master this skill.") break elif points <= -5: print("Sorry, you dropped below the lowest possible score.\nYou may need some addition practice.\nGoodbye.") break elif op == "-": while True: num += 1 integer1 = random.randint(51,100) integer2 = random.randint(1,50) answer = integer1 - integer2 q = float(input("\n"+str(num)+". "+str(integer1)+" - "+str(integer2)+" =")) if q == answer: print("Correct!") points += 3 print("Points:",points) else: print("Incorrect. Try again") points -= 5 print("Points:",points) while True: q = float(input("\n"+str(num)+". "+str(integer1)+" - "+str(integer2)+" =")) if q == answer: print("Correct!") points += 3 print("Points:",points) break else: print("Incorrect. Try again") points -= 1 print("Points:",points) if points >= 10: print("\nYou have mastered the skill of subtraction!") print("It took you",num,"questions to master this skill.") break elif points <= -5: print("Sorry, you dropped below the lowest possible score.\nYou may need some addition practice.\nGoodbye.") break elif op == "//": while True: num += 1 integer1 = random.randint(1,100) integer2 = random.randint(1,10) answer = integer1 // integer2 q = float(input("\n"+str(num)+". "+str(integer1)+" // "+str(integer2)+" =")) if q == answer: print("Correct!") points += 3 print("Points:",points) else: print("Incorrect. Try again") points -= 5 print("Points:",points) while True: q = float(input("\n"+str(num)+". "+str(integer1)+" // "+str(integer2)+" =")) if q == answer: print("Correct!") points += 3 print("Points:",points) break else: print("Incorrect. Try again") points -= 1 print("Points:",points) if points >= 10: print("\nYou have mastered the skill of integer division!") print("It took you",num,"questions to master this skill.") break elif points <= -5: print("Sorry, you dropped below the lowest possible score.\nYou may need some addition practice.\nGoodbye.") break elif op == "*": while True: num += 1 integer1 = random.randint(1,20) integer2 = random.randint(1,20) answer = integer1 * integer2 q = float(input("\n"+str(num)+". "+str(integer1)+" * "+str(integer2)+" =")) if q == answer: print("Correct!") points += 3 print("Points:",points) else: print("Incorrect. Try again") points -= 5 print("Points:",points) while True: q = float(input("\n"+str(num)+". "+str(integer1)+" * "+str(integer2)+" =")) if q == answer: print("Correct!") points += 3 print("Points:",points) break else: print("Incorrect. Try again") points -= 1 print("Points:",points) if points >= 10: print("\nYou have mastered the skill of multiplication!!") print("It took you",num,"questions to master this skill.") break elif points <= -5: print("Sorry, you dropped below the lowest possible score.\nYou may need some addition practice.\nGoodbye.") break elif op == "random": p = random.randint(1,4) if p == 1: op = "+" elif p == 2: op = "-" elif p == 3: op = "//" elif p == 4: op = "*" if op == "+": num += 1 integer1 = random.randint(1,100) integer2 = random.randint(1,100) answer = integer1 + integer2 q = float(input("\n"+str(num)+". "+str(integer1)+" + "+str(integer2)+" =")) if q == answer: print("Correct!") points += 3 print("Points:",points) else: print("Incorrect. Try again") points -= 5 print("Points:",points) while True: q = float(input("\n"+str(num)+". "+str(integer1)+" + "+str(integer2)+" =")) if q == answer: print("Correct!") points += 3 print("Points:",points) break else: print("Incorrect. Try again") points -= 1 print("Points:",points) elif op == "-": num += 1 integer1 = random.randint(51,100) integer2 = random.randint(1,50) answer = integer1 - integer2 q = float(input("\n"+str(num)+". "+str(integer1)+" - "+str(integer2)+" =")) if q == answer: print("Correct!") points += 3 print("Points:",points) else: print("Incorrect. Try again") points -= 5 print("Points:",points) while True: q = float(input("\n"+str(num)+". "+str(integer1)+" - "+str(integer2)+" =")) if q == answer: print("Correct!") points += 3 print("Points:",points) break else: print("Incorrect. Try again") points -= 1 print("Points:",points) elif op == "//": num += 1 integer1 = random.randint(1,100) integer2 = random.randint(1,10) answer = integer1 // integer2 q = float(input("\n"+str(num)+". "+str(integer1)+" // "+str(integer2)+" =")) if q == answer: print("Correct!") points += 3 print("Points:",points) else: print("Incorrect. Try again") points -= 5 print("Points:",points) while True: q = float(input("\n"+str(num)+". "+str(integer1)+" // "+str(integer2)+" =")) if q == answer: print("Correct!") points += 3 print("Points:",points) break else: print("Incorrect. Try again") points -= 1 print("Points:",points) elif op == "*": num += 1 integer1 = random.randint(1,20) integer2 = random.randint(1,20) answer = integer1 * integer2 q = float(input("\n"+str(num)+". "+str(integer1)+" * "+str(integer2)+" =")) if q == answer: print("Correct!") points += 3 print("Points:",points) else: print("Incorrect. Try again") points -= 5 print("Points:",points) while True: q = float(input("\n"+str(num)+". "+str(integer1)+" * "+str(integer2)+" =")) if q == answer: print("Correct!") points += 3 print("Points:",points) break else: print("Incorrect. Try again") points -= 1 print("Points:",points) if points >= 10: print("\nWow, you are a master of mathematics! Congratulations on your achievement.") print("It took you",num,"questions to master this skill.") break elif points <= -5: print("Sorry, you dropped below the lowest possible score.\nYou may need some addition practice.\nGoodbye.") break op = input("\nWould you like to try another skill?") if op == "no": break
ca353ca9c936ea6dabcbb8a968ab5bb27d363228
jhkang1517/python_basic
/python_basic_grammar/python기초_class예시.py
273
4.03125
4
# Why use __init__ function? class A(object): def a(self, bag): self.bag = bag return print(bag) class B(object): def __init__(self, bag): self.bag = bag return print(bag) CLSA = A() CLSA.a("JH's bag") CLSB = B("JH's bag")
f00fa6b718d5052a17abfb958ed57820fc2d0029
GreatBahram/exercism-python
/space-age/space_age.py
902
3.921875
4
from typing import Callable, Optional SECONDS_IN_EARTH_YEAR = 31557600 ORBITAL_PERIODS = { 'earth': 1, 'mercury': 0.2408467, 'venus': 0.61519726, 'mars': 1.8808158, 'jupiter': 11.862615, 'saturn': 29.447498, 'uranus': 84.016846, 'neptune': 164.79132, } def age_on_planet(seconds_alive: float, planet: str) -> float: """Return age on a given planet.""" annual_seconds = SECONDS_IN_EARTH_YEAR * ORBITAL_PERIODS[planet] return round(seconds_alive / annual_seconds, 2) class SpaceAge: """ This class doesn't need to exist. https://www.youtube.com/watch?v=o9pEzgHorH0 """ def __init__(self, seconds: float) -> None: self.seconds = seconds def __getattr__(self, planet: str) -> Optional[Callable]: if planet.startswith('on_'): return lambda: age_on_planet(self.seconds, planet[3:]) return None
cdd7e7e9057f08c66230dca49fb5403401e36e9f
housseinihadia/HackerRank-Solutions
/Regex/06 - Assertions/03 - Positive Lookbehind.py
800
3.734375
4
# ======================== # Information # ======================== # Direct Link: https://www.hackerrank.com/challenges/positive-lookbehind/problem # Difficulty: Easy # Max Score: 20 # Language: Python # ======================== # Solution # ======================== import re regex_pattern = r'(?<=[13579])\d' # Regex Pattern: # . # ├── (?<=[13579]) # │ ├── ?<= - Denotes a positive lookbehind # │ ├── [13579] - Denotes any single character included in the list '13579' # │ └── Matches \d, but only if there’s [13579] before it # └── \d # └── Denotes a digit (equal to [0-9]) # Example: 123Go! # Example: 11111 Test_String = input() match = re.findall(regex_pattern, Test_String) print("Number of matches :", len(match))
93ba8c4d2e4433ff5f68d58660f75123a28cf0f7
csalgar81/practice05
/ocurrences_of_words.py
451
3.921875
4
"""Program description""" text = "this is a collection of words of nice words this is a fun thing it is" dict1 ={} words = text.split() words_sorted = [] for element in words: dict1[element] = 0 for element in words: if element in dict1: dict1[element] += 1 # print (dict1) for key in dict1: words_sorted.append(key) words_sorted.sort() print(words_sorted) for element in words_sorted: print(element,":",dict1[element])
0b2a1af42020bc02e0f0c5e62133d5a74b0b936f
Tanner-York-Make-School/SPD-2.31-Testing-and-Architecture
/lab/refactoring/consolidate_duplicate_conditional_fragments.py
701
3.703125
4
""" By Kami Bigdely Consolidate duplicate conditional fragments """ def add(mix, something): mix.append(something) return mix def mix_ice_with_cream(): print('mixed ice with cream.') return ['ice', 'cream'] def is_coffee(drink): return 'coffe' in drink def is_strawberry_milkshake(drink): return 'strawberry milkshake' in drink def make_drink(drink, addons): mix = [] if is_coffee(drink): mix = add(mix, 'coffee') elif is_strawberry_milkshake(drink): mix = mix_ice_with_cream() mix = add(mix, 'strawberry') mix = add(mix, addons) return mix final_drink = make_drink('strawberry milkshake', ['milk','sugar']) print(final_drink)
a910e89a06e7d6771e5a7d92d2dfa82d3af12bf9
joolink96/Python
/Quiz-표준체중.py
943
3.65625
4
#QUiz-표준체중 # 표준 체중을 구하는 프로그램을 작성하시오 # *표준 체중 : 각 개인의 키에 적당한 체중 # (성별에 따른 공식) # 남자: 키(m) x키(m) x 22 # 여자: 키(m) x키(m) x 21 # 조건1 : 표준 체중은 별도의 함수 내에서 계산 # *함수명 : std_weight # *전달값 : 키(height),성별(gender) # 조건2 : 표준 체중은 소수점 둘째자리까지 표시 # (출력 예제) # 키 175cm 남자의 표준 체중은 67.38kg 입니다. def std_weight(height,gender): #키 m단위 if gender=="man" : return height*height*22 elif gender=="woman": return height*height*21 height=175 #cm 단위 gender="man" weight=round(std_weight(height/100,gender),2) # 반환된 weight값을 소수점 둘째 자리까지만 출력 print("키 {0}cm {1}의 표준 체중은 {2}kg 입니다" .format(height,gender,weight))
698bcbed9ba4a2fec1ab8395801405761e08322a
DowlutZuhayr/hello-world
/Homework3.py
1,215
3.984375
4
def main(): num1 = input("Enter a number: ") if num1.isdigit(): print("Continue") else: num1 = input("Enter a valid number: ") num2 = input("Enter another number: ") if num2.isdigit(): print("Continue") else: num2 = input("Enter a valid number") operator_sign = input("Enter an operator sign") if operator_sign == '*': def mul(a, b): ans = int(a) * int(b) return ans result = mul(num1, num2) print(result) if operator_sign == '+': def add(c, d): ans1 = int(c) + int(d) return ans1 result2 = add(num1, num2) print(result2) if operator_sign == '-': def sub(e, f): ans2 = int(e) - int(f) return ans2 result3 = sub(num1, num2) print(result3) if operator_sign == '/': def div(g, h): ans3 = int(g) / int(h) return ans3 result4 = div(num1, num2) print(result4) restart = input("Do you wish to restart?").lower() if restart == "yes": main() else: exit() main()
ccb566e7a407e5ae523e7215d10a8f5132444ca0
anilkumarreddyn/PythonProgramming
/Practicals/Practical1/MaxOutOf3.py
264
4.25
4
# 2 Write a program to get the maximum number out of three numbers a, b, c = input("Enter Three Numbers: ").split() a, b, c = int(a), int(b), int(c) if a > b and a > c: print("A is Max") elif b > a and b > c: print("B is Max") else: print("C is Max")
0aeab3c581a23559e4122b58d6d746cf6af7b02c
elisgitpage/ConwaysGameOfLife
/MainGame.py
1,211
3.6875
4
""" Matplotlib Animation Example author: Jake Vanderplas email: vanderplas@astro.washington.edu website: http://jakevdp.github.com license: BSD """ import numpy as np from matplotlib import pyplot as plt from matplotlib import animation # set up figure, axis, plot element fig = plt.figure() ax = plt.axes(xlim=(0,2), ylim=(-2,2)) line, = ax.plot([], [], lw=2) # initialization function: plot background of each frame def init(): line.set_data([], []) return line, # animation function. called sequentially def animate(i): x = np.linspace(0, 2, 1000) y = np.sin(2 * np.pi * (x - 0.01 * i)) line.set_data(x, y) return line, # call the animator. blit = True means only re-draw the # parts that have changed anim = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True) # save the animation as an mp4. This requires ffmpeg or mencoder to be # installed. The extra_args ensure that the x264 codec is used, so that # the video can be embedded in html5. You may need to adjust this for # your system: for more information, see # http://matplotlib.sourceforge.net/api/animation_api.html anim.save('basic_animation.htm', fps=30) #, extra_args=['-vcodec', 'libx264']) plt.show()
ff8d7708f2311a7c4b57bcca37d7d8c6c3ca0152
sergeymong/Python
/Python Data Science/Data Science from Scratch/linear_algebra.py
1,777
3.703125
4
from functools import reduce import cProfile from functools import partial def vector_add(v, w): return [v_i + w_i for v_i, w_i in zip(v, w)] def vector_subtract(v, w): return [v_i + w_i for v_i, w_i in zip(v, w)] # its the same that reduce # def vector_sum(*vectors): # resul# t = vectors[0] # # for vector in vectors[1:]: # result = vector_add(result, vector) # # return result def vector_sum(*vectors): return reduce(vector_add, vectors) def scalar_multiply(c, v): return [c * v_i for v_i in v] def vector_mean(*vectors): n = len(vectors) return scalar_multiply(1 / n, vector_sum(vectors)) # scalar multiply def dot(v, w): """v1 * w1 + v2 * w2 ... + vn * wn""" return sum(v_i * w_i for v_i, w_i in zip(v, w)) def sum_of_squares(v): """v1 * v1 + ... vn * vn""" return dot(v, v) def magnitude(v): from math import sqrt return sqrt(sum_of_squares(v)) def squared_distance(v, w): """"(v1 - w2) ** 2 + ... + (vn - wn) ** 2""" return sum_of_squares(vector_subtract(v, w)) # distance between two vectors def distance(v, w): return magnitude(vector_subtract(v, w)) ################## # matrix functions ################## def shape(A): num_rows = len(A) num_cols = len(A[0]) if A else 0 return num_rows, num_cols def get_row(A, i): return A[i] def get_columns(A, j): return [A_i[j] for A_i in A] def make_matrix(num_rows, num_cols, entry_fn): return [[entry_fn(i, j) for j in range(num_cols)] for i in range(num_rows)] def is_diagonal(i, j): return 1 if i == j else 0 identity_matrix = make_matrix(5, 5, is_diagonal) print(identity_matrix) # x = range(10000) # y = range(50000, 60000) # # print(distance(x, y))
4cf2ca1d92b0352f084c2ad65f96d032cae77b3f
Ayush-1211/Python
/Python Decorators/1. Higher Order Functions.py
273
3.65625
4
''' A function is called Higher Order Function if it contains other functions as a parameter or returns a function as an output ''' def create_adder(x): def adder(y): return x + y return adder add_15 = create_adder(15) print(add_15(10))
68e7b718a037df9de07e7976178042dc55083045
tugsbayasgalan/6.857-PSET-1
/code/2a.py
2,001
3.515625
4
from nltk.corpus import words def xor(input1, input2): assert len(input1) == len(input2) result = "" for index in range(len(input1)): if input1[index] == input2[index]: result += "0" else: result += "1" return result def convert_binary_to_word(binary_string): result = "" for i in range(len(binary_string)//8): character = chr(int(binary_string[i*8: i*8 + 8], 2)) result += character return result def convert_word_to_binary(word): hex_result = "" for letter in word: hex_letter = format(ord(letter), "x") assert len(hex_letter) == 2 hex_result += hex_letter return convert_hex_to_binary(hex_result) def convert_hex_to_binary(hex_word): hex_to_binary = { "0":"0000", "1": "0001", "2": "0010", "3": "0011", "4":"0100", "5":"0101", "6":"0110", "7":"0111", "8": "1000", "9": "1001", "a":"1010", "b":"1011", "c":"1100", "d": "1101", "e":"1110", "f":"1111"} hex_word_without_space = hex_word.replace(" ", "") result = "" for letter in hex_word_without_space: result += hex_to_binary[letter] return result if __name__ == '__main__': c1 = "a6 a5 6d f4 8c a0 fc 86 d6 1f 2f e9" c2 = "ac b9 60 e1 94 a3 f2 93 d2 01 24 f5" possible_words = set() for word in words.words(): if len(word) == 12: possible_words.add(word) c1_binary = convert_hex_to_binary(c1) c2_binary = convert_hex_to_binary(c2) c_xor = xor(c1_binary, c2_binary) for word in possible_words: binary_word = convert_word_to_binary(word) second_binary_word = xor(binary_word, c_xor) second_possible_word = convert_binary_to_word(second_binary_word) if second_possible_word in possible_words: print("This is the first word: {}".format(word)) print("This is the second word: {}".format(second_possible_word)) break
2ee0f61cbd96521fbd0aa71f12e54243b4b1a54e
rajatsharma98/CS677
/HW/lyndon97_3_3_7.py
2,670
3.59375
4
'''7. what are the top 5 most popular items for each day of the week? does this list stays the same from day to day?''' import os import pandas as pd wd = os.getcwd() input_dir = wd file = os.path.join(input_dir, 'BreadBasket_DMS_output.csv') df = pd.read_csv(file) # out_file = os.path.join(input_dir, 'res_1.csv') # grouped = df.groupby(['Weekday','Item']).count() # print(grouped['Year']) item_count = df.groupby(['Weekday','Item'],sort=True).agg(count = ('Item','count')) # item_count.to_csv(os.path.join(input_dir, 'res_2.csv')) res = item_count.sort_values(['Weekday','count'], ascending=False).groupby('Weekday').head(5) print("The top 5 most popular items for each day of the week is listed below:") print(res) print("Based on the result, Tuesday and Thursday are the same, plus Sunday and Wednesday are the same.") print('Coffee, bread, tea are top three every day of the week.') # s=df['Weekday'].groupby(df['Item']).value_counts() # # dfs = pd.read_csv(out_file) # wd = ["Sunday","Saturday","Friday","Thursday","Tuesday","Wednesday","Monday"] # data_mon = dfs[dfs['Weekday'] == 'Monday'] # data_tue = dfs[dfs['Weekday'] == 'Tuesday'] # data_wed = dfs[dfs['Weekday'] == 'Wednesday'] # data_thr = dfs[dfs['Weekday'] == 'Thursday'] # data_fri = dfs[dfs['Weekday'] == 'Friday'] # data_sat = dfs[dfs['Weekday'] == 'Saturday'] # data_sun = dfs[dfs['Weekday'] == 'Sunday'] # # # print(len(data_mon)+len(data_tue)+len(data_wed)+len(data_thr)+len(data_fri)+len(data_sat)+len(data_sun)) # # print("Mon",data_mon.sort_values('count', ascending=False)[:5]["Item"].tolist()) # print('Tue',data_tue.sort_values('count', ascending=False)[:5]["Item"].tolist()) # print('Wed',data_wed.sort_values('count', ascending=False)[:5]["Item"].tolist()) # print('Thu',data_thr.sort_values('count', ascending=False)[:5]["Item"].tolist()) # print('Fri',data_fri.sort_values('count', ascending=False)[:5]["Item"].tolist()) # print('Sat',data_sat.sort_values('count', ascending=False)[:5]["Item"].tolist()) # print('Sun',data_sun.sort_values('count', ascending=False)[:5]["Item"].tolist()) # # # print("Mon",data_mon.sort_values('count', ascending=False)[-5:]["Item"].tolist()) # print('Tue',data_tue.sort_values('count', ascending=False)[-5:]["Item"].tolist()) # print('Wed',data_wed.sort_values('count', ascending=False)[-5:]["Item"].tolist()) # print('Thu',data_thr.sort_values('count', ascending=False)[-5:]["Item"].tolist()) # print('Fri',data_fri.sort_values('count', ascending=False)[-5:]["Item"].tolist()) # print('Sat',data_sat.sort_values('count', ascending=False)[-5:]["Item"].tolist()) # print('Sun',data_sun.sort_values('count', ascending=False)[-5:]["Item"].tolist()) #
a48d9c88b2b624cd3e014fe17cc02a464eda4977
jon-moreno/learn-python
/ex18sd.py
652
3.984375
4
# this one is like your scripts with argv def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2) def print_any(*args): x = 1 for y in args: print "argument", x, y x += 1 # ok, that *args is actually pointless, we can just do this def print_two_again(arg1, arg2): print "arg1: %r, arg2: %r" % (arg1, arg2) # this one just takes one argument def print_one(arg1): print "arg1: %r" % arg1 # this one takes no arguments def print_none(): print "I got nothing'." print_any("Zed", "Shaw", "Wammy", "O\'Hare") #print_two("Zed", "Shaw") #print_two_again("Zed", "Shaw") #print_one("First!") #print_none()
68d5a6f6bccc26636eeb6dcbf68289493b776af9
mat10tng/doctorEulerPython
/Euler37.py
384
3.78125
4
from doctorPrime import * sm = 0 count = 0 number = 5 while count != 11: prime = str(findPrime(number)) isTrucatable = True for i in range(len(prime)): if (not isPrime(int(prime[i::])) ) or ( not isPrime(int(prime[:len(prime)-i:])) ): isTrucatable = False print(prime) number+= 1 if isTrucatable: sm+= int(prime) count+= 1 print(count) print(sm)
b3530616126a70c407f8fb45f2ac2a1c8970d133
MyeongJaeKim/deeplearning
/exercise/linear_regression/linear_regression_bias.py
1,021
3.65625
4
import tensorflow as tf # 테스트 데이터 x = [1, 2, 3] y = [1, 2, 3] # 변수 선언 a = tf.Variable(tf.random_uniform([1], -10.0, 10.0)) X = tf.placeholder(tf.float32, name="X") Y = tf.placeholder(tf.float32, name="Y") b = tf.Variable(tf.random_uniform([1], -10.0, 10.0)) # Y = aX + b hypothesis = tf.add(tf.multiply(a, X), b) # Error (=loss) (=cost) 함수 error = tf.reduce_mean(tf.square(hypothesis - Y)) # Tensorflow Train 변수 선언 optimizer = tf.train.GradientDescentOptimizer(0.1) train = optimizer.minimize(error) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # 실제 Train for step in range(1000): _, error_val = sess.run([train, error], feed_dict={X: x, Y: y}) print("Step {} Error {}".format(step, error_val)) print("Train was finished. a is {} and b is {}".format(sess.run(a), sess.run(b))) print("Let's test real value") print("X: 4.87, Y:", sess.run(hypothesis, feed_dict={X: 4.87}))
0424ae97e61552837e1ca47af433f4588939bf8b
itroulli/HackerRank
/Python/Collections/002-defaultdict_tutorial.py
363
3.671875
4
# Name: DefaultDict Tutorial # Problem: https://www.hackerrank.com/challenges/defaultdict-tutorial/problem # Score: 20 from collections import defaultdict d = defaultdict(list) n, m = map(int, input().split()) for i in range(1, n+1): d[input()].append(i) for _ in range(m): b = input() if b in d: print(*d[b]) else: print(-1)
66293a7abf3d36dc53d384df2fa86c56bf7ca251
sreeaurovindh/code_sprint
/recursion/fmax.py
210
3.53125
4
def fmax(arr,mVal,n): if n == len(arr): return mVal else: if mVal <arr[n]: mVal = arr[n] return fmax(arr,mVal,n+1) a = [3,4,1,55,66,2] print(fmax(a,a[0],0))
d3f3ac2c017d34a0c093ea810abe7b991fc0a596
JingruWu10/thinkful
/linear_regression.py
2,800
3.65625
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as sm loansData = pd.read_csv('https://github.com/Thinkful-Ed/curric-data-001-data-sets/raw/master/loans/loansData.csv') ## cleaning the file loansData['Interest.Rate'] = loansData['Interest.Rate'].str.rstrip('%').astype(float).round(2) / 100.0 loanlength = loansData['Loan.Length'].str.strip('months')#.astype(int) --> loanlength not used below loansData['FICO.Score'] = loansData['FICO.Range'].str.split('-', expand=True)[0].astype(int) #add interest rate less than column and populate ## we only care about interest rates less than 12% loansData['IR_TF'] = loansData['Interest.Rate'] < 0.12 #create intercept column loansData['Intercept'] = 1.0 # create list of ind var col names ind_vars = ['FICO.Score', 'Amount.Requested', 'Intercept'] #define logistic regression logit = sm.Logit(loansData['IR_TF'], loansData[ind_vars]) #fit the model result = logit.fit() #get fitted coef coeff = result.params #print coeff print result.summary() #result has more information print coeff def logistic_function(fico_score, loan_amount, coefficients): b, a1, a2 = coefficients x = b + a1*fico_score + a2*loan_amount p = 1./(1.+np.exp(-x)) return p p1 = logistic_function(720, 10000, coeff) print p1 print p1>0.70 def prep(fico_score, loan_amount, coefficients): return logistic_function(fico_score, loan_amount, coefficients) > 0.70 print prep(400, 100000, coeff) from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') colors = ["r" if bool(ib12) else "b" for ib12 in loansData['IR_TF'] ] ax.scatter(loansData['FICO.Score'], loansData['Amount.Requested'], loansData['IR_TF'], c=colors) ax.set_xlabel('FICO SCORE') ax.set_ylabel('Amount Requested') ax.set_zlabel('Interest Below 0.12?') plt.show() #plot your data and surface# xmin = loansData['FICO.Score'].min() xmax = loansData['FICO.Score'].max() ymin = loansData['Amount.Requested'].min() ymax = loansData['Amount.Requested'].max() N = 10 x = np.linspace(xmin, xmax, 20) y = np.linspace(ymin, ymax, 20) X, Y = np.meshgrid(x,y) Z = logistic_function(X,Y,coeff) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') colors = ["r" if bool(ib12) else "b" for ib12 in loansData['IR_TF'] ] ax.scatter(loansData['FICO.Score'], loansData['Amount.Requested'], loansData['IR_TF'], c=colors) preds = result.predict(loansData[ind_vars]) ax.scatter(loansData['FICO.Score'], loansData['Amount.Requested'], preds, c="y") ax.plot_wireframe(X,Y,Z,alpha=0.5) ax.set_xlabel('FICO SCORE') ax.set_ylabel('Amount Requested') ax.set_zlabel('Interest Below 0.12?') plt.show()
c11ec7fa0262ba1bee19b19d5454a1519799a98a
rodgers2000/Projects
/udacity/data-structures-and-algorithms/notes/basic-algorithms/knapsack.py
483
3.875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 1 14:34:01 2019 @author: mrodgers """ def max_value(knapsack_max_weight, items): lookup_table = [0] * (knapsack_max_weight + 1) for item in items: for capacity in reversed(range(knapsack_max_weight + 1)): if item.weight <= capacity: lookup_table[capacity] = max(lookup_table[capacity], lookup_table[capacity - item.weight] + item.value) return lookup_table[-1]
404ef32c163524500dfdac707af3e8abedabc641
shyfeel/myTestCode
/Python/python编程从入门到实践/helloworld.py
94
3.625
4
#-*- coding: UTF-8 -*- char = ["a","b","c","d"] #a = char.pop(0) char.remove("b") print char
aa243adf437344f246ff3acbba31fcaafcc727f6
apolloLemon/CalculPython_S4
/lambda.py
120
3.578125
4
def polynome(a,b,c): return lambda x : a*x**2 + b*x + c f = polynome(1,1,1) g = polynome(2,0,-3) print f(3) print g(3)
ca69381a8623f148bc036407276f5e076fd51e56
AnshVaid4/Python
/Login password cracking/For Windows/exe file codes/CODE CryptHashes EXE.py
2,200
3.78125
4
import bcrypt import time print(" // // ") print(" // // ") print(" // // ") print(" //======// _____ ") print(" // // //| // \ // // ") print(" // // // | ||_____ //===// ") print(" // // //==| \ // // ") print(" // // // | \____// // // ") print("_____________________________________ ") print("------By: Ansh Vaid----v1.0---------- ") print("\n\n") string=input("Enter the string you want to get bcrypt hashed: ") ask=input("Do you want to enter BCRYPT salt? Y/N ") if (ask=="Y"): salta=input("Enter a valid BCRYPT salt ") if "$2b$12$" in salta: salta=bytes(salta,'utf-8') print("Creating hash with "+str(salta.decode())) print("\nBCRYPT salt used in hashing is: " + str(salta.decode())) ######################################################## print("---------------------------------------------------------------------------------------------") hasha=bcrypt.hashpw(bytes(string,'utf-8'),salta) print("BCRYPT hash with salt is: " + str(hasha.decode())) time.sleep(15) exit(1) else: print("Invalid BCRYPT salt entered. Come again later!") time.sleep(10) exit(0) if (ask=="N"): salta=bcrypt.gensalt() else: exit(0) print("\nBCRYPT salt used in hashing is: " + str(salta.decode())) ######################################################## print("---------------------------------------------------------------------------------------------") hasha=bcrypt.hashpw(bytes(string,'utf-8'),salta) print("BCRYPT hash with salt is: " + str(hasha.decode())) time.sleep(15)
c5284dbcfbd1c74f4d00b3392e3b3e564fa9b287
yintrigue/awesome-baby-names
/src/abn/utils/performance.py
1,053
3.734375
4
"""The performance modules includes tools to manage algorthm performance. """ import time from typing import Callable class Timer: """Timer class provides tools to time code performance. """ def __init__(self) -> None: __start = 0 __end = 0 def start(self) -> None: """Start the timer. """ self.__start = time.time() def end(self, m: str = "") -> None: """End the timer. Args: m (str): Message to be prefixed to the time. """ self.__end = time.time() print("{:s}{:f}".format(m, self.__end - self.__start)) def time_it(func: Callable) -> Callable: """Decorator function to time the performance of the function. Result in seconds will be printed. Returns: Callable: A new function with timer added. """ def new_function(*args: list, **kwargs: dict) -> object: t = Timer() t.start() result = func(*args, **kwargs) t.end("Time:") return result return new_function
74a8bc289eb1f48fe80a28eadff2d9816983f823
begsener/PythonCourse
/ex5.py
1,514
4.125
4
<<<<<<< HEAD #exercise 5 # " double quote means that it is a string my_name = 'Zed A. Shaw' my_age = 35 my_weight = 180 #lbs my_height = 74 my_eyes = 'blue' my_teeth = 'white' my_hair = 'brown' print ("Let's talk about %s." % my_name) #%s means it is a string print ("He's %d inches tall." % my_height) #%d means it is a number print ("He's %d pounds heavy." % my_weight) print ("Actually he is not too heavy.") print ("He's got %s eyes and %s hair." % (my_eyes, my_hair)) print ("His teeth are usually %s depending on the coffee." % my_teeth) print ("If I add %d, %d and %d, I get %d. " %(my_age, my_height, my_weight, my_age + my_height + my_weight)) #%r means print this no matter what. #rounding #my_number=1.2344 #round(my_number) ======= #exercise 5 # " double quote means that it is a string my_name = 'Zed A. Shaw' my_age = 35 my_weight = 180 #lbs my_height = 74 my_eyes = 'blue' my_teeth = 'white' my_hair = 'brown' print ("Let's talk about %s." % my_name) #%s means it is a string print ("He's %d inches tall." % my_height) #%d means it is a number print ("He's %d pounds heavy." % my_weight) print ("Actually he is not too heavy.") print ("He's got %s eyes and %s hair." % (my_eyes, my_hair)) print ("His teeth are usually %s depending on the coffee." % my_teeth) print ("If I add %d, %d and %d, I get %d. " %(my_age, my_height, my_weight, my_age + my_height + my_weight)) #%r means print this no matter what. #rounding #my_number=1.2344 #round(my_number) >>>>>>> c8bb34737bc484eb9350bc0efd6f8f17c3d673bd
c646fb8626cdfa8ea6d4d52f178ec2845096b617
ebookleader/Programmers
/Level1/makePrimeNumber.py
946
3.625
4
from math import sqrt from itertools import combinations def solution(nums): sum_list = [] answer = 0 # 3중 for문 사용하는 방법 for i in range(len(nums)): for j in range(i+1, len(nums)): for k in range(j+1, len(nums)): sum_list.append(nums[i]+nums[j]+nums[k]) for s in sum_list: if checkPrime(s): answer += 1 # itertools 사용하는 방법 for c in combinations(nums, 3): # 3개 선택 threeSum = sum(c) if checkPrime(threeSum): answer += 1 return answer def checkPrime(num) -> bool: result = True for i in range(2, int(sqrt(num))+1): if (num % i) == 0: result = False break return result print(solution([1,2,7,6,4])) # 소수 판별 알고리즘 # 1번 def checkPrime1(n): for i in range(2, n): if (n % i) == 0: return False return True
12268451d5a76026b9bff7ff8ea370daaf7dff73
niranjan09/DataStructures_Algorithms
/DP/maxSumContiguousArray.py
650
3.53125
4
# Kadane's algorithm def getMaxSumContiguousArray(arr): start_max, end_max, max_sum= 0, 0, float('-inf') start_current, end_current, current_sum = 0, 0, float('-inf') for numi, num in enumerate(arr): if(num > current_sum + num): start_current = end_current = numi current_sum = num else: current_sum = current_sum + num end_current = numi if(current_sum > max_sum): start_max, end_max = start_current, end_current max_sum = current_sum return max_sum, start_max, end_max print(getMaxSumContiguousArray([-2, -3, -5, 0, -1, -2, -3, -4]))
9f406f26c666cbf63fb3bf502c9a5bcdbe041bb6
z502185331/leetcode-python
/150-Evaluate-Reverse-Polish-Notation/solution.py
800
3.671875
4
class Solution(object): def evalRPN(self, tokens): """ :type tokens: List[str] :rtype: int """ if not tokens: return 0 stack = [] operators = ['+', '-', '*', '/'] for token in tokens: if token not in operators: stack.append(int(token)) else: num2 = stack.pop() num1 = stack.pop() stack.append(self.eval(token, num1, num2)) return stack.pop() def eval(self, oper, num1, num2): if oper == '+': return num1 + num2 elif oper == '-': return num1 - num2 elif oper == '*': return num1 * num2 else: return int(num1 / float(num2))
34b97f78e3a3319dc5c6019228d59ebda2e877ab
fred-yu-2013/avatar
/pyexamples/tests/test_class.py
940
3.90625
4
# -*- coding: utf-8 -*- __author__ = 'Fred' class MyClass(): def __init__(self): self.counter = 100 obj = MyClass() print obj.counter # del后无法添加 # del obj.counter # AttributeError: MyClass instance has no attribute 'counter' # print obj.counter obj.name = 'John' obj.id = 5 print obj.id # 可以通过__dict__属性添加 obj.__dict__['name'] = 'Fred' print obj.name class Employee(): """ 此类可在外面增加成员变量 """ pass john = Employee() john.name = 'John Doe' # 删除后,仍然可以添加 del john.name john.name = 'John Doe' class B: pass class C(B): pass class D(C): pass for c in [B, C, D]: try: raise c() except D: print "D" except C: print "C" except B: print "B" for c in [B, C, D]: try: raise c() except B: print "B" except C: print "C" except D: print "D"
5fb64ed3ff919136f22a4637309a19d016d6ca07
gitrookie/codesnippets
/pycode/sortingalgos.py
230
3.640625
4
# sortingalgos.py def insertsort(l): length = len(l) - 1 for i in range(length): j = i + 1 num = l[j] while j > 0 and l[j-1] > num: l[j] = l[j-1] j -= 1 l[j] = num
1a635ba93d596e08f2954f3a53de5ddfc7be28f2
VinothRajasekar/practice
/graphs/knightsboard.py
1,041
3.640625
4
from collections import deque DIRECTIONS = [(2,1),(2,-1),(-2,1),(-2,-1),(1,2),(1,-2),(-1,2),(-1,-2)] def find_minimum_number_of_moves(rows, cols, start_row, start_col, end_row, end_col): def get_neighbors(lcoation): neighbors =[] for i, j in DIRECTIONS: new_r, new_c = location[0] + i , location[1] + j if 0 <= new_r < rows and 0 <= new_c < cols: neighbors.append((new_r, new_c)) return neighbors start_cell = start_row, start_col visited = {start_row, start_col} q = deque([((start_row,start_col), 0)]) while q: location, count = q.popleft() if location == (end_row,end_col): return count for n in get_neighbors(location): if n not in visited: visited.add(n) q.append((n, count + 1)) return -1 rows = 5 cols = 5 start_row = 0 start_col = 0 end_row = 4 end_col = 4 print(find_minimum_number_of_moves(rows, cols, start_row, start_col, end_row, end_col))
6bbcac2bbed36c4bb59e1055693bf31b120f014e
Firmino-Neto/Exercicios---Python--UFC-
/Função e vetores -py/38.py
526
3.9375
4
def Ordenada(): print ("Digite os elementos da lista: ") i = 0 c = [] while i < 10: n = int(input("Digite um numero: ")) if i == 0 or n > c[-1]: c.append(n) i = i + 1 else: j = 0 while j < len(c): if n <= c[j]: c.insert(j,n) break j = j + 1 i = i + 1 i = 0 while i < len(c): print(c[i]) i = i + 1 print(Ordenada())
ceae6bb3ad7b07e8fbd5a40fc9d41448a47a94f3
srangar03/InteractiveProgramming
/test.py
6,001
3.75
4
import pygame # Define some colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) def draw_stick_figure(screen, x, y): # Head pygame.draw.ellipse(screen, BLACK, [1 + x, y, 10, 10], 0) # Legs pygame.draw.line(screen, BLACK, [5 + x, 17 + y], [10 + x, 27 + y], 2) pygame.draw.line(screen, BLACK, [5 + x, 17 + y], [x, 27 + y], 2) # Body pygame.draw.line(screen, RED, [5 + x, 17 + y], [5 + x, 7 + y], 2) # Arms pygame.draw.line(screen, RED, [5 + x, 7 + y], [9 + x, 17 + y], 2) pygame.draw.line(screen, RED, [5 + x, 7 + y], [1 + x, 17 + y], 2) # Setup pygame.init() # Set the width and height of the screen [width,height] size = [700, 500] screen = pygame.display.set_mode(size) pygame.display.set_caption("My Game") # Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() # Hide the mouse cursor pygame.mouse.set_visible(0) # Speed in pixels per frame x_speed = 0 y_speed = 0 # Current position x_coord = 10 y_coord = 10 # -------- Main Program Loop ----------- while not done: # --- Event Processing for event in pygame.event.get(): if event.type == pygame.QUIT: done = True # User pressed down on a key elif event.type == pygame.KEYDOWN: # Figure out if it was an arrow key. If so # adjust speed. if event.key == pygame.K_LEFT: x_speed = -3 elif event.key == pygame.K_RIGHT: x_speed = 3 elif event.key == pygame.K_UP: y_speed = -3 elif event.key == pygame.K_DOWN: y_speed = 3 # User let up on a key elif event.type == pygame.KEYUP: # If it is an arrow key, reset vector back to zero if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: x_speed = 0 elif event.key == pygame.K_UP or event.key == pygame.K_DOWN: y_speed = 0 # --- Game Logic # Move the object according to the speed vector. x_coord = x_coord + x_speed y_coord = y_coord + y_speed # --- Drawing Code # First, clear the screen to WHITE. Don't put other drawing commands # above this, or they will be erased with this command. screen.fill(WHITE) draw_stick_figure(screen, x_coord, y_coord) # Go ahead and update the screen with what we've drawn. pygame.display.flip() # Limit frames per second clock.tick(60) # Close the window and quit. pygame.quit() # Create an 800x600 sized screen # screen = pygame.display.set_mode([800, 600]) # # This sets the name of the window # pygame.display.set_caption('CMSC 150 is cool') # # clock = pygame.time.Clock() # Set positions of graphics # background_position = [0, 0] # # Load and set up graphics. # background_image = pygame.image.load("apocalypse red sky.jpg").convert() # # player_image = pygame.image.load("playerShip1_orange.png").convert() # player_image.set_colorkey(BLACK) # done = False # while not done: # # for event in pygame.event.get(): # # if event.type == pygame.QUIT: # # done = True # # elif event.type == pygame.MOUSEBUTTONDOWN: # # click_sound.play() # # Copy image to screen: # screen.blit(background_image, background_position) # # Get the current mouse position. This returns the position # # as a list of two numbers. # # player_position = pygame.mouse.get_pos() # x = player_position[0] # y = player_position[1] # # Copy image to screen: # screen.blit(player_image, [x, y]) # pygame.display.flip() # clock.tick(60) # # pygame.quit() # pygame.mouse.set_visible(0) # # background = pygame.Surface(screen.get_size()) # background = background.convert() # background.fill((250, 250, 250)) # # # Put Text On The Background, Centered # if pygame.font: # font = pygame.font.Font(None, 36) # text = font.render("Pummel The Chimp, And Win $$$", 1, (10, 10, 10)) # textpos = text.get_rect(centerx=background.get_width()/2) # background.blit(text, textpos) # # # Display The Background While Setup Finishes # screen.blit(background, (0, 0)) # pygame.display.flip() # # # prepare game objects # whiff_sound = load_sound('whiff.wav') # punch_sound = load_sound('punch.wav') # chimp = Chimp() # fist = Fist() # allsprites = pygame.sprite.RenderPlain((fist, chimp)) # clock = pygame.time.Clock() # # # Main loop # while 1: # clock.tick(60) # # # handle all input events # for event in pygame.event.get(): # if event.type == QUIT: # return # elif event.type == KEYDOWN and event.key == K_ESCAPE: # return # elif event.type == MOUSEBUTTONDOWN: # if fist.punch(chimp): # punch_sound.play() #punch # chimp.punched() # else: # whiff_sound.play() #miss # elif event.type == MOUSEBUTTONUP: # fist.unpunch() # # allsprites.update() # # # draw all objects # screen.blit(background, (0, 0)) # allsprites.draw(screen) # pygame.display.flip() def get_init(): """return true if the pygame module has been initialized.""" # return "sys" in sys.modules pass def load_image(name, colorkey=None): """Loading Resources""" # fullname = os.path.join('data', name) # try: # image = pygame.image.load(fullname) # except(pygame.error, message): # print('Cannot load image:', name) # raise(SystemExit, message) # image = image.convert() # if colorkey is not None: # if colorkey is -1: # colorkey = image.get_at((0,0)) # image.set_colorkey(colorkey, RLEACCEL) # return image, image.get_rect() pass
722df7e1799052de3ba62399b04c860bad8dfede
kzbigboss/scc-csc110
/module 3/KazzazMarkEXTR01SecHY1Ver02.py
1,306
4.3125
4
# Project: EXTR: 1 - Triangle (KazzazMarkEXTR01SecHYVer01.py) # Name: Mark Kazzaz # Date: 2017-07-12 # Description: This program will draw a triangle based on user input of height def main(): # greet user, share input requirement print('Welcome to the trianger printer!' ,'Please enter in whole numbers the height of your desired triangle.' ,sep = '\n' ) # if invalid input is detected, loop until valid input is accepted isValidInput = False while isValidInput == False: try: ### obtain input from user strTriangleHeightInput = str(input('Triangle height: ')) ### convert input to integer intTriangleHeight = int(strTriangleHeightInput) ### record valid input and move on isValidInput = True except: ### an invalid input was found. ask user to try again. print('Invalid input detected. Try again.') # prepare variable to help with printing triangle strTriangleCharacter = 'X' intLoopCount = 0 # loop through printing until loop interation exceeds user input while (intLoopCount < intTriangleHeight): intLoopCount = intLoopCount + 1 print(strTriangleCharacter * intLoopCount) main()
ffaba0f0e5ebeaa43601228c908422529f0771f9
nineninenine/space-invaders
/game_functions.py
10,758
3.640625
4
import sys import pygame import sys from time import sleep from bullet import Bullet from alien import Alien def check_keydown_events(event, ai_settings, screen, ship, bullets): """respond to key presses""" #if the event.key attribute is a right arrow key(pygame.K_RIGHT), move the ship right #by ticking moving_right flag to true. the ship moves right as long as #the right arrow key is held down. if event.key == pygame.K_RIGHT: ship.moving_right = True #same for the left button elif event.key == pygame.K_LEFT: ship.moving_left = True #create a new bullet and add it to the bullets group if its < the allowed number of bullets elif event.key == pygame.K_SPACE: fire_bullets(ai_settings, screen, ship, bullets) #quit if the user presses the q key elif event.key == pygame.K_q: sys.exit() def check_keyup_events(event, ship): """respond to key releases""" #when a key is released, check to see if its the right arrow key. #if it is, stop the ship moving right by ticking th moving_right #flag to false if event.key == pygame.K_RIGHT: ship.moving_right = False #same for the left button elif event.key == pygame.K_LEFT: ship.moving_left = False def check_events(ai_settings, screen, stats, play_button, ship, aliens, bullets): """respond to keypresses and mouuse events""" #watch for keyboard and mouse events. #this is an event loop for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() #if someone presses a key aka #if the event.type attribute is pygame.KEYDOWN that means someone pressed a button. elif event.type == pygame.KEYDOWN: check_keydown_events(event, ai_settings, screen, ship, bullets) #when someone releases a key aka #if the event.type attribute is pygame.KEYUP that means someone released a button. elif event.type == pygame.KEYUP: check_keyup_events(event, ship) elif event.type == pygame.MOUSEBUTTONDOWN: #get the x,y of hte mouse postion at click mouse_x, mouse_y = pygame.mouse.get_pos() #stats argument is passed so method can access game_active attrb check_play_button(ai_settings, screen, stats, play_button, ship, aliens, bullets, mouse_x, mouse_y) def check_play_button(ai_settings, screen, stats, play_button, ship, aliens, bullets, mouse_x, mouse_y): """start a new game when the player clicks the play button""" #rect collidepoint method used check if mouseclick overlaps with button rect button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y) if button_clicked and not stats.game_active: #reset difficulty when new player starts ai_settings.initialize_dynamic_settings() #hide teh mouse cursor dude pygame.mouse.set_visible(False) #reset stats and start game stats.reset_stats() stats.game_active = True #empty aliens and bullets group obj aliens.empty bullets.empty #create fresh alien fleet and center ship create_fleet(ai_settings, screen, ship, aliens) ship.center_ship() def fire_bullets(ai_settings, screen, ship, bullets): """fire a bullet if we havent reached max amt of bullets on screen""" if len(bullets) < ai_settings.bullets_allowed: #Bullet is the class we wrote new_bullet = Bullet(ai_settings, screen, ship) #bullets (note thhe plural) is a sprite group object from pygame # .add is a function from the sprite object and it adds our bullet # obj to the sprite group obj. bullets.add(new_bullet) def update_bullets(ai_settings, screen, ship, aliens, bullets): """"update positions of bullets and remove old bullets""" #update bullet positions #"bullets" is a sprite group obj. it automatically calls bullet.update() from the class we created #for each bullet we place in the group bullets bullets.update() #remove bullets taht have moved past the top of the screen. for bullet in bullets.copy(): if bullet.rect.bottom <= 0: bullets.remove(bullet) #print("bullets on screen: "+ str(len(bullets))) check_bullet_alien_collisions(ai_settings, screen, ship, aliens,bullets) def check_bullet_alien_collisions(ai_settings, screen, ship, aliens, bullets): """remove any bullets and aliens that have collided""" #check for any bullets that have hit aliens #if so, remove the bullet and alien. #the 2 True params remove the bullets and aliens # change the first to False so keep the bullet going collisions = pygame.sprite.groupcollide(bullets, aliens, True, True) #if each alien in the aliens (note plural) group are shotdown, make new alien fleet if len(aliens) == 0: #remove all bullets and make a new fleet, increase difficulty bullets.empty() ai_settings.increase_speed() create_fleet(ai_settings, screen, ship, aliens) def update_screen(ai_settings, screen, stats, ship, aliens, bullets, play_button): """update images on the screen and flip to the new screen""" #redraw the screen with each pass thru the loop screen.fill(ai_settings.bg_color) #redraw all bullets behind ship and aliens for bullet in bullets.sprites(): bullet.draw_bullet() #draw the ship on the screen ship.blitme() #aliens is a group obj that holds instances of our alien class. #the draw function draws each element in the group at the position defined in its rect aliens.draw(screen) #draw play button if the game is inactive if not stats.game_active: play_button.draw_button() #make the most recently drawn screen visible #erase the old screen so only the latest screen is visible #when we move around in the game or enemies move around #flip will update the screen to show new positions of elements #and hide old positions pygame.display.flip() def get_number_aliens_x(ai_settings, alien_width): """figure out the number of aliens that fit in a row""" #we want the aliens to be spaced out one alien wide. #we calculate 2x an alien for the alien and one alien-width spot to its right. available_space_x = ai_settings.screen_width - (2 * alien_width) #cast as int to get a whole number of aliens. int() truncates the decimal. number_aliens_x = int(available_space_x / (2 * alien_width)) return number_aliens_x def get_number_rows(ai_settings, ship_height, alien_height): """determine the nubmer of rows of aliens fit on the screen""" #to figure out the amount of vertical space we want to substract # the alien height from the top, the ship height from the bottom, # and 2x the alien height from the bottom available_space_y = ai_settings.screen_height - (3 * alien_height) - ship_height #we want one alien height space between rows, so 2x the height number_rows = int(available_space_y / (2 * alien_height)) return number_rows def create_alien(ai_settings, screen, aliens, alien_number, row_number): """create an alien and put it in a row""" #we create one alien and get its rect. alien = Alien(ai_settings, screen) alien_width = alien.rect.width #we want a margin around the screen thats one alien width on both sides. #calculate the x-coord of the aliens so they line up side by side. #this function is called in a loop and alien_number is the #iterator and is used to place the aliens out side by side. alien.x = alien_width + (2 * alien_width * alien_number) #assign the x-coord to the alien rect alien.rect.x = alien.x #similar as the x-coord, assign a y-coord alien.rect.y = alien.rect.height + (2 * alien.rect.height * row_number) #add the alien to the group obj aliens.add(alien) def create_fleet(ai_settings, screen, ship, aliens): """create a full fleet of aliens""" #we create one alien to get its rect for the number_aliens_x function. #we don actually use this alien in the fleet alien = Alien(ai_settings, screen) number_aliens_x = get_number_aliens_x(ai_settings, alien.rect.width) number_rows = get_number_rows(ai_settings, ship.rect.height, alien.rect.height) #create first row of aliens. for row_number in range(number_rows): for alien_number in range(number_aliens_x): #creat an alien and put it in the row create_alien(ai_settings, screen, aliens, alien_number, row_number) #def update_aliens(aliens): # """update the position of the alien fleet""" # #aliens (plural) is a group obj. not the alien (singular) class we made. # #aliens contains instances of the alien obj. # #aliens.update() calls the update() function in each instance of the alien class # aliens.update() def check_fleet_edges(ai_settings, aliens): """respond if any aliens reach the edge of the screen""" #move the aliens down one row and start moving the other way for alien in aliens.sprites(): if alien.check_edges(): change_fleet_direction(ai_settings, aliens) break def change_fleet_direction(ai_settings, aliens): """drop an entire fleet and change the fleets direction.""" for alien in aliens.sprites(): alien.rect.y += ai_settings.fleet_drop_speed #change the fleet direction by flpping from positive to neg or vice versa ai_settings.fleet_direction *= -1 def update_aliens(ai_settings, stats, screen, ship, aliens, bullets): """check if the fleet is at the edge of the screen and then update the postion of all aliens in the fleet""" check_fleet_edges(ai_settings, aliens) #aliens (plural) is a group obj. not the alien (singular) class we made. #aliens contains instances of the alien obj. #aliens.update() calls the update() function in each instance of the alien class aliens.update() #check for alien-ship collisions #takes 2 arguements, a sprite and a group if pygame.sprite.spritecollideany(ship, aliens): ship_hit(ai_settings, stats, screen, ship, aliens, bullets) #print("Ship was hit!!") #look for aliens getting to the bottom of the screen check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets) def ship_hit(ai_settings, stats, screen, ship, aliens, bullets): """respond when the ship is hit by an alien""" #one less ship if stats.ships_left > 0: stats.ships_left -= 1 #empty out current aliens and bullets group obj (note plurals) aliens.empty() bullets.empty() #create new fleet of aliens and new ship centered on the screen create_fleet(ai_settings, screen, ship, aliens) ship.center_ship() #pause so players have a moment before game restarts sleep(0.5) else: stats.game_active = False #bring teh mouse back when player runs out of lives and game is over pygame.mouse.set_visible(True) def check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets): """check to see if any aliens ahve reached teh bottom of the screen""" screen_rect = screen.get_rect() for alien in aliens.sprites(): if alien.rect.bottom >= screen_rect.bottom: #treat this alient the same as if it had hit a ship #ie reset fleet, bullets, recenter ship ship_hit(ai_settings, stats, screen, ship, aliens, bullets) break
4ed34673a26cef8aa90e13d95c8077d72e8aee40
dunn0052/Personal-projects
/dice_fctns.py
962
3.984375
4
#dice functions def factorial(n): if(n < 0): print("can't be negative") return elif(n%1 > 0): print("must be whole number") return if(n == 0): return 1 if (n > 1): n = factorial(n-1) * n return n #recursive iteration else: return n def choose(n, r): return factorial(n)//factorial(r)//factorial(n-r) #nCr def pick(n, r): return factorial(n)//factorial(n - r) #nPr def binomial_at_least(n,k,p): #n = number of tries #k = number of successes #p = probablity of success per try prob = 0 while(n>=k): prob = prob + choose(n,k)*(p)**k*(1-p)**(n-k) k = k + 1 return prob def WOD(n,k): #Chances of rolling k successes with n dice in WOD print("Rolling",n,"dice with",k,"successe(s)") print(round(binomial_at_least(n,k,0.3)*100), "%")
032b62b1801b589d655cf84e9b69485f086c2938
edobranchi/Hashing
/main.py
4,107
3.84375
4
import Linear_Hash import Chained_Hash import plot def print_menu(): ## Your menu design here print(30 * "-", "MENU", 30 * "-") print("1. Popolazione Hash Lineare") print("2. Popolazione Hash Concatenato") print("3. Grafici Hash Lineare") print("4. Grafici Hash Concatenato") print("5. Test Ricerca con successo concatenamento") print("6. Test Ricerca senza successo concatenamento") print("7. Test Ricerca con successo lineare") print("8. Test Ricerca senza successo lineare") print(67 * "-") def print_sub_menu(): print(30 * "-", "MENU", 30 * "-") print("1. Ricerca Valore:") print("2. Cancella valore:") print("3. Stampa la tabella") print("4. Uscita") print(67 * "-") loop = True while loop: ## While loop which will keep going until loop = False print_menu() ## Displays menu choice = int(input("Enter your choice [1-5]: ")) if choice == 1: print("Creazione Hash lineare") hash_dim = int(input("Dimensione tabella hash desiderata:")) num_ins = int(input("Numero di inserimenti: ")) success_bool = Linear_Hash.insert_generation(hash_dim,num_ins) if success_bool==True: annidated_loop = True else: annidated_loop= False while annidated_loop: print_sub_menu() choice_linear= int(input("Enter your choice [1-3]: ")) if choice_linear == 1: search_value = int(input("Inserire il valore da cercare:")) Linear_Hash.linear_search(search_value) elif choice_linear == 2: delete_value = int(input("Inserire il valore da eliminare:")) Linear_Hash.linear_delete(delete_value) elif choice_linear == 3: Linear_Hash.linear_display() elif choice_linear==4: print("Torno al menu precedente") annidated_loop=False else: print("Nessuna scelta corrispondente riprovare...") if choice == 2: print("Creazione Hash concatenato") hash_dim = int(input("Dimensione tabella hash desiderata:")) num_ins = int(input("Numero di inserimenti: ")) Chained_Hash.list_creation(hash_dim) Chained_Hash.insert(num_ins) annidated_loop=True while annidated_loop: print_sub_menu() choice_linear= int(input("Enter your choice [1-3]: ")) if choice_linear == 1: search_num = int(input("Inserisci il valore da cercare: ")) Chained_Hash.hash_search(search_num) elif choice_linear == 2: del_num = int(input("Inserisci il valore da eliminare: ")) Chained_Hash.hash_delete(del_num) elif choice_linear == 3: Chained_Hash.display_hash() elif choice_linear==4: print("Torno al menu precedente") annidated_loop=False else: input("Nessuna scelta corrispondente riprovare") if choice == 3: hash_dim = int(input("Inserisci la dimensione della tabella:")) num_ins = int(input("Inserisci il numero di inserimenti da creare:")) plot.linear_plot(hash_dim,num_ins) if choice == 4: hash_dim = int(input("Inserisci la dimensione della tabella:")) num_ins = int(input("Inserisci il numero di inserimenti da creare:")) plot.chained_plot(num_ins,hash_dim) elif choice==5: hash_dim = int(input("Inserisci la dimensione della tabella:")) plot.research_plot_chained_success(hash_dim) elif choice == 6: hash_dim = int(input("Inserisci la dimensione della tabella:")) plot.research_plot_chained_notsuccess(hash_dim) elif choice == 7: hash_dim = int(input("Inserisci la dimensione della tabella:")) plot.research_plot_linear_success(hash_dim) elif choice == 8: hash_dim = int(input("Inserisci la dimensione della tabella:")) plot.research_plot_linear_notsuccess(hash_dim)
e0a2e3d78eb4588b908e2f09968bfcd033255ce8
fabsta/url_downloader
/src/FileDownloader.py
4,950
3.515625
4
from urllib2 import urlopen, URLError, HTTPError from urlparse import urlparse import os.path import imghdr class FileDownloader: 'FileDownloader class that handles file downloads' def __init__(self): """ constructor method for FileDownloader. Initiates an empty array of urls Defines allowed image types """ self._urls = [] self._allowed_image_types = {'png': 1, 'jpg':1, 'gif':1, 'jpeg':1,'svg':1, 'img':1} @property def urls(self): """ gets the current urls @rtype: array @return: list of urls. """ return self._urls @urls.setter def urls(self,urls): """ sets the urls @type urls: array @param urls: list of urls """ self._urls = urls def add_url(self,url): """ adds a url to the list of urls @type url: string @param url: url of file to be downloaded """ self._urls.append(url) def read_file(self,file): """ Reads urls from a given file `file`. @type file: string @param file: file containing urls. @rtype: IOError @return: error message in case the file could not be opened. """ try: f = open(file) for line in iter(f): self.add_url(line.rstrip("\r\n")) f.close() except IOError: raise IOError('Cannot open file') def valid_url(self,source): """ Reads urls from a given file `file`. @type source: string @param source: url. @rtype: ValueError @return: error message in case the url has no scheme like 'http' or 'ftp'. """ o = urlparse(source) if(not o.scheme): raise ValueError('url has no schema') else: return 1 def download_image(self,source,destination): """ Downloads an image given by `source` and saves it into `destination`. @type source: string @param source: url. @type destination: string @param destination: download location. @rtype: IOError @return: error message in case the file could not be downloaded. """ if source == '': raise ValueError('no url provided') if destination == '': raise ValueError('not a valid destination') if self.has_valid_image_extension(source): if(self.download_file(source, destination)): return self else: raise IOError('could not download file') else: raise ValueError('not a valid image file extension') def save_file(self,f, destination): """ Downloads an file given by `source` and saves it into `destination`. @type f: opened url @param f: downloaded url content. @type destination: string @param destination: download location. @rtype: IOError @return: error message in case it could not be saved """ try: with open(destination, "wb") as local_file: local_file.write(f.read()) if(self.has_saved_file(destination)): return 1 else: raise IOError("could not save file") except IOError: raise IOError("could not save file") def download_file(self,source,destination): """ Downloads an file given by `source` and saves it into `destination`. @type source: string @param source: url. @type source: string @param source: download location. @rtype: TypeError @return: error message in case the url seems invalid. """ try: if self.valid_url(source): f = urlopen(source) if(self.save_file(f,destination)): return 1 else: return "error" else: raise TypeError('url has no schema') except HTTPError, e: return e.code except URLError, e: return e.args else: return 1 def has_valid_image_extension(self,source): """ Checks whether a provided url looks like a image file by checking it's file extension @type source: string @param source: url. @rtype: TypeError @return: error message in case the url does not have a valid image extension. """ file_name = source.split('/')[-1] extension = file_name.split('.')[-1] if not extension in self._allowed_image_types: raise TypeError('not a valid image file extension') else: return 1 def has_saved_file(self,destination): """ Checks whether a file was successfully saved @type destination: string @param destination: the file location. @rtype: IOError @return: error message in case the file was not saved. """ if(os.path.exists(destination)): if(os.stat(destination).st_size != 0): return 1 else: raise IOError ("file is empty") else: raise IOError ("file does not exist") def is_real_image(self, destination): """ Checks whether a downloaded file is a real image file @type destination: string @param destination: the file location. @rtype: ValueError @return: if it is not an image """ if(imghdr.what(destination) in self._allowed_image_types): return 1 else: raise ValueError("not an image format")
cf84c7a1f5f352a5f2748511aa8ca29f2ae1aaf5
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/sieve/e9021824770448cc9970aa356bcc1694.py
190
3.515625
4
def sieve(limit): primes = range(2, limit) for i in primes: not_primes = [x for x in primes if x % i == 0] primes = [x for x in primes if x not in not_primes or x == i] return primes
12bbbdf87dfa78ad6d51264d706393fddc20b14c
surbbahl/sdet
/Listchecker.py
147
3.609375
4
numlist=[10,20,40,50,40] firstelement=numlist[0] lastelement=numlist[-1] if firstelement==lastelement: print(True) else: print(False)
98d3ae2af10b2d67fc6b238421ec4f43831ee4d9
edt-yxz-zzd/python3_src
/script/try_python/try_func_keyword.py
566
3.921875
4
''' we can not: f(self, a, **kw) self.f(a, self=1) # Error ''' def f(a, **kw): return a+kw['a'] try: f(1, a=2) # TypeError: f() got multiple values for argument 'a' except TypeError:pass else: raise class C: def f(a, **kw): return a+kw['a'] def g(self, *a, **kw): print(a) print(kw) c = C() c.g(a=(2,), kw={}) # a=(), kw = {'a': (2,), 'kw': {}} try: c.f(a=(2,)) except TypeError:pass else: raise try: c.f(a=2) # TypeError: f() got multiple values for argument 'a' except TypeError:pass else: raise
91965c127a0cc4acb36c6eaded097a3f2e204682
FrozenLemonTee/DSAA
/algorithm/Bubble_sort.py
1,038
3.765625
4
from DSAA.data_structure.basic.init_structure import initializeLinkedList from DSAA.algorithm.Nodes_changing import exchangeNode import time def bubbleSort(my_linked_list): if my_linked_list.length() == 0 or my_linked_list.length() == 1: pass elif my_linked_list.length() == 2: if my_linked_list.head_node.getData() > my_linked_list.last_node.getData(): exchangeNode(my_linked_list, 0) else: for i in range(0, my_linked_list.length()): for j in range(0, my_linked_list.length() - 1 - i): if my_linked_list.getNode(j).getData() > my_linked_list.getNode(j + 1).getData(): exchangeNode(my_linked_list, j) if __name__ == "__main__": start = time.perf_counter() linked_list = initializeLinkedList(1000) print("冒泡排序前:") linked_list.printAll() bubbleSort(linked_list) print("冒泡排序后:") linked_list.printAll() end = time.perf_counter() print("用时{0}秒.".format(end - start)) pass
4e23b285ea4e1888bc398f736f62c42efbf52e94
jae-hun-e/python_practice_SourceCode
/뼈대코드/5/5-18.py
286
3.828125
4
def insert(x,ss): def loop(ss,left): if ss != []: if x <= ss[0]: pass # Write your code here. else: pass # Write your code here. else: left.append(x) return left return loop(ss,[])
47d3501563c96b471dad29117f192e60e673f144
GezhinOleg/Py_Dev_L4
/proba.py
599
3.6875
4
import json from pprint import pprint class CountryIterate: def __init__(self, start, end, interval_size = 2): self.start = start - interval_size self.end = end self.interval_size = interval_size def __iter__(self): return self def __next__(self): self.start += self.interval_size if self.start >= self.end: raise StopIteration return self.start def main(): my_range = CountryIterate(1, 10) for country in my_range: print(country) if __name__ == '__main__': main()
e4563c71f4493db051ce2fb24e905c8be30d5aaa
zhangxinzhou/PythonLearn
/helloworld/chapter05/demo01.07.py
268
4
4
str1 = '@明日科技 @扎克伯格 @abc' count = str1.count('@') print("字符串:", str1, "包含", count, "个@符号") print(str1.count('@')) print(str1.find('@')) print(str1.count('#')) print(str1.find('#')) # index与find类似,不过找不到时会抛异常
0d3ee274b09f506103419a3d5e2d443c0d38b8c0
snigdhasen/myrepo
/examples/ex11.py
1,084
3.890625
4
''' various file reading techniques ''' import json def read_file_1(filename): file = open(filename, 'rt') for line in file.readlines(): print(line, end='') file.close() def read_file_2(filename): file = open(filename, 'rt') # the 'file' object itself is iterable; no need to call .readlines() for line in file: print(line, end='') file.close() def read_file_3(filename): # when you exit the 'with' block, file.close() is called automatically with open(filename) as file: for line in file: print(line, end = '') def csv2json(filename): with open(filename) as file: headers = file.readline().strip().split(',') lines = file.readlines() data = [dict(zip(headers, line.strip().split(','))) for line in lines] out_filename = filename[:-4] + '.json' with open(out_filename, 'w') as outfile: json.dump(data, outfile, indent=3) def main(): filename = 'people.csv' # read_file_3(filename) csv2json(filename) if __name__=='__main__': main()
0000e64b5789f5ee9ed16b73462406bec84f9e1f
mandos1995/online_judge
/BOJ/단계별로 풀어보기/ch02_if문/1300_두 수 비교하기.py
235
3.8125
4
""" 문제 두 정수 A와 B가 주어졌을 때, A와 B를 비교하는 프로그램을 작성하시오. """ num1, num2 = map(int, input().split()) if num1 > num2: print('>') elif num1 == num2: print('==') else: print('<')
cec3bd9b6d105269e6be4613c5c078105b6a368d
shankar7791/MI-10-DevOps
/Personel/Siddhesh/Python/24Feb/Operator4.py
164
4.15625
4
# Logical Operators x = int(input("First number : ")) y = int(input("Second number : ")) if x is y : print("True") elif x is not y : print("False")
a06d251656d70de9cf2669ad98288f791db8af37
bunshue/vcs
/_4.python/__code/Python大數據特訓班(第二版)/ch03/ch03_all.py
10,663
3.796875
4
# filewrite1.py content='''Hello Python 中文字測試 Welcome''' f=open('file1.txt', 'w' ,encoding='utf-8', newline="") f.write(content) f.close() # filewrite2.py content='''Hello Python 中文字測試 Welcome''' with open('file1.txt', 'w' ,encoding='utf-8', newline="") as f: f.write(content) # fileread1.py with open('file1.txt', 'r', encoding='utf-8') as f: output_str=f.read(5) print(output_str) # Hello # fileread2.py with open('file1.txt', 'r', encoding ='UTF-8') as f: print(f.readline()) print(f.readline(3)) # fileread3.py with open('file1.txt', 'r', encoding='utf-8') as f: content=f.readlines() print(type(content)) print(content) # fileread4.py with open('file2.txt', 'r', encoding ='UTF-8') as f: print(f.readlines()) # csv_read.py import csv # 開啟 csv 檔案 with open('school.csv', newline='') as csvfile: # 讀取 csv 檔案內容 rows = csv.reader(csvfile) # 以迴圈顯示每一列 for row in rows: print(row) # csv_read_dict.py import csv # 開啟 csv 檔案 with open('school.csv', newline='') as csvfile: # 讀取 csv 檔內容,將每一列轉成 dictionary rows = csv.DictReader(csvfile) # 以迴圈顯示每一列 for row in rows: print(row['座號'],row['姓名'],row['國文'],row['英文'],row['數學']) # csv_write_list1.py import csv with open('test1.csv', 'w', newline='') as f: # 建立 csv 檔寫入物件 writer = csv.writer(f) # 寫入欄位及資料 writer.writerow(['座號', '姓名', '國文', '英文', '數學']) writer.writerow([1, '葉大雄', 65, 62, 40]) writer.writerow([2, '陳靜香', 85, 90, 87]) writer.writerow([3, '王聰明', 92, 90, 95]) # csv_write_list2.py import csv # 建立csv二維串列資料 csvtable = [ ['座號', '姓名', '國文', '英文', '數學'], [1, '葉大雄', 65, 62, 40], [2, '陳靜香', 85, 90, 87], [3, '王聰明', 92, 90, 95] ] # 寫入csv檔案 with open('test2.csv', 'w', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerows(csvtable) # csv_write_dict.py import csv with open('test3.csv', 'w', newline='') as csvfile: # 定義欄位 fieldnames = ['座號', '姓名', '國文', '英文', '數學'] # 將 dictionary 寫入 csv 檔 writer = csv.DictWriter(csvfile, fieldnames=fieldnames) # 寫入欄位名稱 writer.writeheader() # 寫入資料 writer.writerow({'座號': 1, '姓名': '葉大雄', '國文': 65, '英文': 62, '數學': 40}) writer.writerow({'座號': 2, '姓名': '陳靜香', '國文': 85, '英文': 90, '數學': 87}) writer.writerow({'座號': 3, '姓名': '王聰明', '國文': 92, '英文': 90, '數學': 95}) # jsonload1.py import json class_str = """ { "一年甲班": [ { "座號": 1, "姓名": "葉大雄", "國文": 65, "英文": 62, "數學": 40 }, { "座號": 2, "姓名": "陳靜香", "國文": 85, "英文": 90, "數學": 87 }, { "座號": 3, "姓名": "王聰明", "國文": 92, "英文": 90, "數學": 95 } ] } """ datas = json.loads(class_str) print(type(datas)) for data in datas["一年甲班"]: print(data, data['姓名']) # jsonload2.py import json with open('class_str.json', 'r', encoding='utf-8') as f: datas = json.load(f) print(type(datas)) for data in datas["一年甲班"]: print(data, data['姓名']) # jsondump1.py import json with open('class_str.json', 'r', encoding='utf-8') as f: datas = json.load(f) print(datas, type(datas)) dumpdata = json.dumps(datas, ensure_ascii=False) print(dumpdata, type(dumpdata)) # jsondump2.py import json with open('class_str.json', 'r', encoding='utf-8') as f: datas = json.load(f) with open('new_class_str.json', 'w', encoding='utf-8') as f: dumpdata = json.dump(datas, f, ensure_ascii=False) # xlsx_write.py import openpyxl # 建立一個工作簿 workbook=openpyxl.Workbook() # 取得第 1 個工作表 sheet = workbook.worksheets[0] # 以儲存格位置寫入資料 sheet['A1'] = '一年甲班' # 以串列寫入資料 listtitle=['座號', '姓名', '國文', '英文', '數學'] sheet.append(listtitle) listdatas=[[1, '葉大雄', 65, 62, 40], [2, '陳靜香', 85, 90, 87], [3, '王聰明', 92, 90, 95]] for listdata in listdatas: sheet.append(listdata) # 儲存檔案 workbook.save('test.xlsx') # xlsx_read.py import openpyxl # 讀取檔案 workbook = openpyxl.load_workbook('test.xlsx') # 取得第 1 個工作表 sheet = workbook.worksheets[0] # 取得指定儲存格 print(sheet['A1'], sheet['A1'].value) # 取得總行、列數 print(sheet.max_row, sheet.max_column) # 顯示 cell資料 for i in range(1, sheet.max_row+1): for j in range(1, sheet.max_column+1): print(sheet.cell(row=i, column=j).value,end=" ") print() sheet['A1'] = '二年甲班' workbook.save('test.xlsx') # sqlite_cursor.py import sqlite3 conn = sqlite3.connect('school.db') # 建立資料庫連線 cursor = conn.cursor() # 建立 cursor 物件 # 建立一個資料表 sqlstr='''CREATE TABLE IF NOT EXISTS scores \ ("id" INTEGER PRIMARY KEY NOT NULL, "name" TEXT NOT NULL, "chinese" INTEGER NOT NULL, "english" INTEGER NOT NULL, "math" INTEGER NOT NULL ) ''' cursor.execute(sqlstr) # 新增記錄 cursor.execute('insert into scores values(1, "葉大雄", 65, 62, 40)') cursor.execute('insert into scores values(2, "陳靜香", 85, 90, 87)') cursor.execute('insert into scores values(3, "王聰明", 92, 90, 95)') conn.commit() # 更新 conn.close() # 關閉資料庫連線 # sqlite_crud1.py import sqlite3 conn = sqlite3.connect('school.db') # 建立資料庫連線 # 建立一個資料表 sqlstr='''CREATE TABLE IF NOT EXISTS scores \ ("id" INTEGER PRIMARY KEY NOT NULL, "name" TEXT NOT NULL, "chinese" INTEGER NOT NULL, "english" INTEGER NOT NULL, "math" INTEGER NOT NULL ) ''' conn.execute(sqlstr) conn.commit() # 更新 conn.close() # 關閉資料庫連線 # sqlite_crud2.py import sqlite3 conn = sqlite3.connect('school.db') # 建立資料庫連線 # 定義資料串列 datas = [[1,'葉大雄',65,62,40], [2,'陳靜香',85,90,87], [3,'王聰明',92,90,95]] # 新增資料 for data in datas: conn.execute("INSERT INTO scores (id, name, chinese, english, math) VALUES \ ({}, '{}', {}, {}, {})".format(data[0], data[1], data[2], data[3], data[4])) conn.commit() # 更新 conn.close() # 關閉資料庫連線 # sqlite_crud3.py import sqlite3 conn = sqlite3.connect('school.db') # 建立資料庫連線 # 更新資料 conn.execute("UPDATE scores SET name='{}' WHERE id={}".format('林胖虎', 1)) conn.commit() # 更新 conn.close() # 關閉資料庫連線 # sqlite_crud4.py import sqlite3 conn = sqlite3.connect('school.db') # 建立資料庫連線 # 刪除資料 conn.execute("DELETE FROM scores WHERE id={}".format(1)) conn.commit() # 更新 conn.close() # 關閉資料庫連線 # fetchall.py import sqlite3 conn = sqlite3.connect('school.db') # 建立資料庫連線 cursor = conn.execute('select * from scores') rows = cursor.fetchall() # 顯示原始資料 print(rows) # 逐筆顯示資料 for row in rows: print(row[0],row[1]) conn.close() # 關閉資料庫連線 # fetchone.py import sqlite3 conn = sqlite3.connect('school.db') # 建立資料庫連線 cursor = conn.execute('select * from scores') row = cursor.fetchone() print(row[0], row[1]) conn.close() # 關閉資料庫連線 # mysqltable.py import pymysql conn = pymysql.connect('localhost',port=3306,user='root',passwd='1234',charset='utf8', db='pythondb') #連結資料庫 with conn.cursor() as cursor: sql = """ CREATE TABLE IF NOT EXISTS Scores ( ID int NOT NULL AUTO_INCREMENT PRIMARY KEY, Name varchar(20), Chinese int(3), English int(3), Math int(3) ); """ cursor.execute(sql) #執行SQL指令 conn.commit() #提交資料庫 conn.close() # mysqlinsert.py import pymysql conn = pymysql.connect('localhost',port=3306,user='root',passwd='1234',charset='utf8', db='pythondb') #連結資料庫 with conn.cursor() as cursor: sql = """ insert into scores (Name, Chinese, English, Math) values ('葉大雄',65,62,40), ('陳靜香',85,90,87), ('王聰明',92,90,95) """ cursor.execute(sql) conn.commit() #提交資料庫 conn.close() # mysqlquery.py import pymysql conn = pymysql.connect('localhost',port=3306,user='root',passwd='1234',charset='utf8', db='pythondb') #連結資料庫 with conn.cursor() as cursor: sql = "select * from scores" cursor.execute(sql) datas = cursor.fetchall() # 取出所有資料 print(datas) print('-' * 30) # 畫分隔線 sql = "select * from scores" cursor.execute(sql) data = cursor.fetchone() # 取出第一筆資料 print(data) conn.close() # mysqlupdate.py import pymysql conn = pymysql.connect('localhost',port=3306,user='root',passwd='1234',charset='utf8', db='pythondb') #連結資料庫 with conn.cursor() as cursor: sql = "update scores set Chinese = 98 where ID = 3" cursor.execute(sql) conn.commit() sql = "select * from scores where ID = 3" cursor.execute(sql) data = cursor.fetchone() print(data) conn.close() # mysqldelete.py import pymysql conn = pymysql.connect('localhost',port=3306,user='root',passwd='1234',charset='utf8', db='pythondb') #連結資料庫 with conn.cursor() as cursor: sql = "delete from scores where ID = 3" cursor.execute(sql) conn.commit() sql = "select * from scores" cursor.execute(sql) data = cursor.fetchall() print(data) conn.close() # LinkGoogleSheet.py import gspread from oauth2client.service_account import ServiceAccountCredentials as sac # 設定金鑰檔路徑及驗證範圍 auth_json = 'PythonConnectGsheet1-6a6086d149c5.json' gs_scopes = ['https://spreadsheets.google.com/feeds'] # 連線資料表 cr = sac.from_json_keyfile_name(auth_json, gs_scopes) gc = gspread.authorize(cr) # 開啟資料表 spreadsheet_key = '1OihpM657yWo1lc3RjskRfZ8m75dCPwL1IPwoDXSvyzI' sheet = gc.open_by_key(spreadsheet_key) # 開啟工作簿 wks = sheet.sheet1 # 清除所有內容 wks.clear() # 新增列 listtitle=['座號', '姓名', '國文', '英文', '數學'] wks.append_row(listtitle) # 標題 listdatas=[[1, '葉大雄', 65, 62, 40], [2, '陳靜香', 85, 90, 87], [3, '王聰明', 92, 90, 95]] for listdata in listdatas: wks.append_row(listdata) # 資料內容
037e5af0c260d4f0ba1ab51341d8ecdcd58485be
busz/my_leetcode
/python/Pascals_Triangle.py
1,045
3.890625
4
''' Created on 2014-3-22 Leetcoder : Pascal's Triangle Problem : Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5, Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] @author: xqk ''' class Solution: # @return a list of lists of integers def generate(self, numRows): if numRows == 0: return [] if numRows == 1: return [ [1] ]; A = [ [1] , [1,1] ] if numRows ==2: return A l = 3 while l <= numRows: t = [] i = 0 while i < l: if i == 0: t.append(1) i = i + 1 continue if i == l -1: t.append(1) break t.append(A[len(A) - 1][i-1]+A[len(A) - 1][i]) i = i + 1 l = l + 1 A.append(t) return A test = Solution() print test.generate(5)
66f597aec9d1bad37c9688a6496bb01030718947
vanillasky/skogkatt
/commons/util/numeral.py
821
3.828125
4
from typing import Any def to_decimal(value: str) -> int or float: """ int 또는 float 으로 형변환 :param value: string value :return: int or float or None if cannot convert type """ result = value.lstrip('0') if result == '' or result == '00': return 0 try: result = int(value) except ValueError: try: result = float(value) except ValueError: return None return result def format_with(value: Any, separator=',') -> str: decimal_value = to_decimal(value) if isinstance(value, str) else value try: formatted = format(decimal_value, f"-{separator}") except ValueError: return value return formatted def value_of(obj: Any) -> str: return 'None' if obj is None else str(obj)
28a274c712fb074c6b8e71fc8ec1b37721de11d3
Diegotmi/Des_python
/Calculadora.py
184
4
4
primeiro_numero = int(input('Insira seu primeiro número:')) segundo_numero = int(input( 'Insira o segundo número:') ) print('Soma dos numeros é:', primeiro_numero + segundo_numero)
1c80635c0eb3227a9ffbc6d851fc1544739e0372
EmperoR1127/algorithms_and_data_structures
/Stacks and Queues/ArrayStack.py
959
3.84375
4
class ArrayStack: """LIFO Stack implementation using a Python list as underlying storage.""" def __init__(self): """A list used to store data""" self._data = [] def __len__(self): return len(self._data) def is_empty(self): return len(self._data) == 0 def push(self, value): """Push value to the top of the stack""" self._data.append(value) def pop(self): """Delete and return the value on top of the stack raise an exception when the stack is empty """ if self.is_empty(): raise ValueError("The stack is empty") return self._data.pop() def top(self): """Return the value on top of the stack raise an exception when the stack is empty """ if self.is_empty(): raise ValueError("The stack is empty") return self._data[-1] def __str__(self): return str(self._data)
81546e178116cd7f3d4a8da67d1b93e33f7e2e4f
Hoangxt/PythonK
/Tutorial/ExRandom Password Generator/Random_Password_Generator.py
777
4
4
''' Project: Random Password Generator Password: adbXYZ-69_96 ''' import string import random LETTERS = string.ascii_letters NUMBER = string.digits PUNCTUATION = string.punctuation def password_generator(length=8): printable = f'{LETTERS}{NUMBER}{PUNCTUATION}' printable = list(printable) random.shuffle(printable) random_password = random.choices(printable, k=length) # dang o dang list random_password = ''.join(random_password) return random_password def get_passwordlength(): password_length = input("How long do you want your password: ") return int(password_length) def main(): password_length = get_passwordlength() password = password_generator(password_length) print(password) if __name__ == "__main__": main()