blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
89c31e16dd5cc9762b731758cb5671ddca6cbeb4
vipulsingh24/DSA
/Sorting/bublle_sort.py
337
4.09375
4
# Bubble Sort Algorithm def bubble_sort(data): for i in range(len(data) - 1, 0, -1): for j in range(i): if data[j] > data[j + 1]: temp = data[j] data[j] = data[j + 1] data[j+1] = temp print("Current data state: ", data) return data
a7c0aae2914f7f0a426121af5bf628273d2c5102
github-hewei/Python3_study
/1/11.九九乘法表.py
239
3.8125
4
# -*- coding: utf-8 -*- def printMulTable( num=9 ): '''打印九九乘法表''' for i in range(1, num+1): for j in range(1, i+1): print("%dx%d=%d"%(j, i, j*i), end="\t") print(end="\n") printMulTable()
e21c72d1c2f408b629b3093153d2b2e72ee6f4f0
YunsongZhang/lintcode-python
/Amazon 2019秋招面试高频题/3 - Amazon 电面 Follow up/246. Binary Tree Path Sum II.py
857
3.6875
4
class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None class Solution: """ @param: root: the root of binary tree @param: target: An integer @return: all valid paths """ def binaryTreePathSum2(self, root, target): paths = [] if root is None: return paths self.dfs(root, 0, target, paths, []) return paths def dfs(self, root, end, target, paths, path): if root is None: return path.append(root.val) temp = target for i in range(end, -1, -1): temp = temp - path[i] if temp == 0: paths.append(path[i:]) self.dfs(root.left, end + 1, target, paths, path) self.dfs(root.right, end + 1, target, paths, path) path.pop()
a80699e2b122a93973f68edebc706bc50b5f8186
VakinduPhilliam/Python_Concurrent_Futures
/Python_Concurrent_Futures_Thread_Pool_Executor.py
1,362
3.953125
4
# Python Concurrent Futures # concurrent.futures Launching parallel tasks. # The concurrent.futures module provides a high-level interface for asynchronously executing callables. # The asynchronous execution can be performed with threads, using ThreadPoolExecutor, or separate processes, using ProcessPoolExecutor. # Both implement the same interface, which is defined by the abstract Executor class. # ThreadPoolExecutor. # ThreadPoolExecutor is an Executor subclass that uses a pool of threads to execute calls asynchronously. # Deadlocks can occur when the callable associated with a Future waits on the results of another Future. # # For example: # import time def wait_on_b(): time.sleep(5) print(b.result()) # b will never complete because it is waiting on a. return 5 def wait_on_a(): time.sleep(5) print(a.result()) # a will never complete because it is waiting on b. return 6 executor = ThreadPoolExecutor(max_workers=2) a = executor.submit(wait_on_b) b = executor.submit(wait_on_a) # # And: # def wait_on_future(): f = executor.submit(pow, 5, 2) # This will never complete because there is only one worker thread and # it is executing this function. print(f.result()) executor = ThreadPoolExecutor(max_workers=1) executor.submit(wait_on_future)
f802ea7f225aed1261d02d60eb47849252052cca
CianLR/judge-solutions
/kattis/bridgesandtunnels2.py
927
3.53125
4
from heapq import heappush, heappop def dijkstra(adj, start, end): seen = set() # Time outside, total time, vertex pq = [(0, 0, start)] while pq: to, tt, u = heappop(pq) if u == end: return "{} {}".format(to, tt) elif u in seen: continue seen.add(u) for v, t, o in adj[u]: if v in seen: continue heappush(pq, (to + (t if o else 0), tt + t, v)) return 'IMPOSSIBLE' def main(): N, M, P = [int(x) for x in input().split()] adj = [[] for _ in range(N)] for _ in range(M): u, v, t, io = input().split() u, v, t = int(u), int(v), int(t) adj[u].append((v, t, io == 'O')) adj[v].append((u, t, io == 'O')) for _ in range(P): start, end = [int(x) for x in input().split()] print(dijkstra(adj, start, end)) if __name__ == '__main__': main()
9a1d317238f7bb13fd4470f81b892d8b8363ded4
ChenhaoJiang/LeetCode-Solution
/51-100/53_maximum_subarray_v2.py
1,106
3.5625
4
def get(a,l,r): # 递归(分治法) if l==r: return {'isum':a[l],'lsum':a[l],'rsum':a[l],'msum':a[l]} m = int((l+r)/2) isum = get(a,l,m)['isum'] + get(a,m+1,r)['isum'] # isum为[l,r]的区间和 # lsum为[l,r]内以l为左端点的最大子段和 lsum = max(get(a,l,m)['lsum'] , get(a,l,m)['isum'] + get(a,m+1,r)['lsum']) # rsum为[l,r]内以r为右端点的最大子段和 rsum = max(get(a,m+1,r)['rsum'] , get(a,m+1,r)['isum'] + get(a,l,m)['rsum']) # msum为[l,r]内最大子段和 msum = max(get(a,l,m)['msum'],get(a,m+1,r)['msum'],get(a,l,m)['rsum']+get(a,m+1,r)['lsum']) return {'isum':isum,'lsum':lsum,'rsum':rsum,'msum':msum} class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ return get(nums,0,len(nums)-1)['msum'] """ 思路:分治法,维护四个量(见注释),区间长度为1时结束递归。但事实上DP时间复杂度为O(n),而分治法时间复杂度为O(nlogn)。精妙是精妙,但架不住代码长,复杂度高啊。 """
1462079fc423bdb05ad8d8bb4b8b10f58f79deab
arpit0891/Project-Euler
/p062.py
638
3.640625
4
import itertools def compute(): numdigits = 0 data = {} # str numclass -> (int lowest, int count) for i in itertools.count(): digits = [int(c) for c in str(i**3)] digits.sort() numclass = "".join(str(d) for d in digits) if len(numclass) > numdigits: # Process and flush data for smaller number of digits candidates = [lowest for (lowest, count) in data.values() if count == 5] if len(candidates) > 0: return str(min(candidates)**3) data = {} numdigits = len(numclass) lowest, count = data.get(numclass, (i, 0)) data[numclass] = (lowest, count + 1) if __name__ == "__main__": print(compute())
da886d6eb86d11d486c6b2a45a311ee21b07d5ba
cybelewang/leetcode-python
/code758BoldWordsInString.py
1,892
3.96875
4
""" 758 Bold Words in String Given a set of keywords words and a string S, make all appearances of all keywords in S bold. Any letters between <b> and </b> tags become bold. The returned string should use the least number of tags possible, and of course the tags should form a valid combination. For example, given that words = ["ab", "bc"] and S = "aabcd", we should return "a<b>abc</b>d". Note that returning "a<b>a<b>b</b>c</b>d" would use more tags, so it is incorrect. Note: words has length in range [0, 50]. words[i] has length in range [1, 10]. S has length in range [0, 500]. All characters in words[i] and S are lowercase letters. """ # similar problems: 45 Jump Game II class Solution: # help from http://www.cnblogs.com/grandyang/p/8531642.html # originally thought the method of extending the bold end, similar to problem 45 Jump Game II # originally I was thinking how to generate the "res" when iterating the S, but figured out it was hard to update the bold start index without the help of a bold array def boldWords(self, words, S): n = len(S) res, end = '', 0 # end is the current ending index to be bold bold = [False]*n # bold[i] indicates if S[i] is bold for i in range(n): for word in words: m = len(word) if i + m <=n and S[i:i+m] == word: end = max(end, i+m) bold[i] = end > i i = 0 while i < n: if not bold[i]: res += S[i] i += 1 continue res += "<b>" j = i while j < n and bold[j]: j += 1 res += S[i:j] + "</b>" i = j return res words = ["ab", "bc"] S = "aabcd" print(Solution().boldWords(words, S))
2050b4affc534cca22794ef4fd46f88329bf2420
kontai/python
/面向對象/運算符重載/type元類/自定制元类精简版.py
325
3.546875
4
class MyType(type): def __init__(self,a,b,c): print('元類的構造函數執行') def __call__(self, *args, **kwargs): obj=object.__new__(self) self.__init__(obj,*args,**kwargs) return obj class Foo(metaclass=MyType): def __init__(self,name): self.name=name f1=Foo('alex')
73e4dc80119ee187b8aa7af7c4d9d6edea15d494
Sunny61676/PythonPractice
/PythonPracticeSelf/str_ex.py
1,338
4.125
4
''' Hello = "Hello World" print(Hello) len(Hello) First5 = Hello[0:5] print(First5) HelloBig = (First5 + " Big " + Hello[6:len(Hello)] ) print(HelloBig) print(HelloBig.upper()) print(HelloBig.lower()) print(HelloBig.lower().title()) first = 'Lily' last = 'Wang' print("My first name is %s, my last name is %s." %(first, last) ) print( (first+" "+last).upper() ) print( (first+" "+last).lower() ) print( (first+" "+last).lower().title() ) print(len(first+" "+last)) print(first[0]+"."+last[0]+".") name = [] name.append(first) name.append(last) print(name) s = "_" s = s.join(name) print(s) print(s[:4] + s[5:]) ''' print("What are your name?") name = input() print("Hello, %s" %name) print("Please enter a lower number: ") lnumber = int(input()) print("Please enter a higher number: ") hnumber = int(input()) print(lnumber+hnumber) print("There are %d numbers between %d and %d." % (hnumber-lnumber, lnumber, hnumber)) i=0 m=9 number=[] squareNumber = [] while i <= m: if i>m: break number.append(i) squareNumber.append(i*i) i += 1 print(number) print(squareNumber) matrixList=[[4,6,7],[3,5,7],[2,5,4]] for ml in matrixList: print(ml) m =len(matrixList) print(m) for l in matrixList: i= 0 while i < m: print(l[i], end = ' ') i += 1 print("\n")
57672f5efc67fa17b9e18eed2f27c6bfb3ae3abb
danhnhan54/maidanhnhan-fundamentals-c4e22
/session3/fav.py
120
3.65625
4
favs = ["netflix","teaching","redbull"] print(favs) new_fav = input("Your new thing: ") favs.append(new_fav) print(favs)
c385722fa5416ecd4d477c2112d356f52904b566
kopchik/itasks
/hash.py
644
3.53125
4
#!/usr/bin/env python3 import math class Hash: def __init__(self, bits=3): self.bits = bits #if bits: # self.values = [Hash(bits=bits-1) for x in range(2**bits) if bit] self.values = [None for x in range(2**bits)] def set(self, key, val, h=None): if not h: h = self.hash(key) idx = self.idx(h) self.values[idx] = key def self.hash(self, key): return hash(key) def rm(self, key): pass def idx(self, h): mask = (1<<self.bits) - 1 return h & mask def lookup(self, key): pass if __name__ == '__main__': h = Hash(2) h.set(1,2) h.set(2,2) h.set(3,2) h.set(1024,2)
31686a79eb32de189aabb5d3b310cc50f288d86e
SIS101/id-maker
/render-id.py
149
3.640625
4
import csv students = list() with open("my.csv", "r") as f: reader = csv.reader(f) for row in list(reader)[1:]: students.append(row)
fdafa938618d6a8d3caabcc9b6e13b15ae25d950
shankar7791/MI-11-DevOps
/Personel/Rahul/Python/Assignment07/Bmi.py
425
4.28125
4
h = float(input("Enter height in cm : ")) w = float(input("Enter weight in kg : ")) def bmi(h,w): BMI = w / (h/100)**2 print(f"The BMI is - {BMI}") if BMI <= 18.4: print("You are underweight.") elif BMI <= 24.9: print("You are healthy.") elif BMI <= 29.9: print("You are over weight.") elif BMI <= 34.9: print("") elif BMI <= 39.9: print("You are obese.") else: print("") bmi(h,w)
7547287452d7473e72b6954fc953c736e8651918
OmishaPatel/Python
/daily-coding-problem/shortest_path.py
1,001
3.796875
4
from collections import deque def shortest_path(board, start, end): seen = set() queue = deque([(start,0)]) while queue: #enque coordinate,count = queue.popleft() if coordinate == end: return count seen.add(coordinate) neighbors = get_valid_neighbors(board, coordinate[0], coordinate[1]) queue.extend((neighbor, count+1)for neighbor in neighbors if neighbor not in seen) def get_valid_neighbors(board, row, col): return [(r,c) for r,c in [ #up (row - 1, col), #down (row + 1 , col), #left (row, col - 1), #right (row, col + 1) ] if is_valid(board, r,c)] def is_valid(board, row,col): return (row >= 0) and (row < len(board)) and (col >= 0) and (col < len(board[0])) mat = [ ['0', '1', '0', '1'], [ '1', '0', '1', '1'], [ '0', '1', '1', '1'], [ '1', '1', '1', '0']] print(shortest_path(mat,(0,3),(3,0)))
e022e8d6191e7d032425cef79c3a19d024f7fe57
Psingh12354/Python-practice
/HalfDiamond.py
282
3.9375
4
def halfDiamond(n): for i in range(n): for j in range(0,i+1): print('*',end="") print() for i in range(1,n): for j in range(i,n): print('*',end="") print() n=int(input("Enter the number : ")) halfDiamond(n)
c8c1befa3f7471367a44fd8ad08044fdd85b05f6
oshuakbaev/pp2
/lecture_5/task1/18.py
226
3.5
4
def count_words(filepath): with open(filepath) as f: data = f.read() data.replace(",", " ") return len(data.split(" ")) print(count_words("/Users/olzhas/Documents/GitHub/pp2/lecture_5/task1/w3res.txt"))
59906602361d1b6f4727d47e2c08a0c750b99143
pittzhou/DeepLearningCourseCodes-1
/01_TF_basics_and_linear_regression/tensorflow_basic.py
8,932
4.46875
4
# coding: utf-8 # # TensorFlow基础 # In this tutorial, we are going to learn some basics in TensorFlow. # ## Session # Session is a class for running TensorFlow operations. A Session object encapsulates the environment in which Operation objects are executed, and Tensor objects are evaluated. In this tutorial, we will use a session to print out the value of tensor. Session can be used as follows: # In[1]: import tensorflow as tf a = tf.constant(100) with tf.Session() as sess: print sess.run(a) #syntactic sugar print a.eval() # or sess = tf.Session() print sess.run(a) # print a.eval() # this will print out an error # ## Interactive session # Interactive session is a TensorFlow session for use in interactive contexts, such as a shell. The only difference with a regular Session is that an Interactive session installs itself as the default session on construction. The methods [Tensor.eval()](https://www.tensorflow.org/versions/r0.11/api_docs/python/framework.html#Tensor) and [Operation.run()](https://www.tensorflow.org/versions/r0.11/api_docs/python/framework.html#Operation) will use that session to run ops.This is convenient in interactive shells and IPython notebooks, as it avoids having to pass an explicit Session object to run ops. # In[2]: sess = tf.InteractiveSession() print a.eval() # simple usage # ## Constants # We can use the `help` function to get an annotation about any function. Just type `help(tf.consant)` on the below cell and run it. # It will print out `constant(value, dtype=None, shape=None, name='Const')` at the top. Value of tensor constant can be scalar, matrix or tensor (more than 2-dimensional matrix). Also, you can get a shape of tensor by running [tensor.get_shape()](https://www.tensorflow.org/versions/r0.11/api_docs/python/framework.html#Tensor)`.as_list()`. # # * tensor.get_shape() # * tensor.get_shape().as_list() # In[3]: a = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.float32, name='a') print a.eval() print "shape: ", a.get_shape(), ",type: ", type(a.get_shape()) print "shape: ", a.get_shape().as_list(), ",type: ", type(a.get_shape().as_list()) # this is more useful # ## Basic functions # There are some basic functions we need to know. Those functions will be used in next tutorial **3. feed_forward_neural_network**. # * tf.argmax # * tf.reduce_sum # * tf.equal # * tf.random_normal # #### tf.argmax # `tf.argmax(input, dimension, name=None)` returns the index with the largest value across dimensions of a tensor. # # In[4]: a = tf.constant([[1, 6, 5], [2, 3, 4]]) print a.eval() print "argmax over axis 0" print tf.argmax(a, 0).eval() print "argmax over axis 1" print tf.argmax(a, 1).eval() # #### tf.reduce_sum # `tf.reduce_sum(input_tensor, reduction_indices=None, keep_dims=False, name=None)` computes the sum of elements across dimensions of a tensor. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in reduction_indices. If `keep_dims` is true, the reduced dimensions are retained with length 1. If `reduction_indices` has no entries, all dimensions are reduced, and a tensor with a single element is returned # In[5]: a = tf.constant([[1, 1, 1], [2, 2, 2]]) print a.eval() print "reduce_sum over entire matrix" print tf.reduce_sum(a).eval() print "reduce_sum over axis 0" print tf.reduce_sum(a, 0).eval() print "reduce_sum over axis 0 + keep dimensions" print tf.reduce_sum(a, 0, keep_dims=True).eval() print "reduce_sum over axis 1" print tf.reduce_sum(a, 1).eval() print "reduce_sum over axis 1 + keep dimensions" print tf.reduce_sum(a, 1, keep_dims=True).eval() # #### tf.equal # `tf.equal(x, y, name=None)` returns the truth value of `(x == y)` element-wise. Note that `tf.equal` supports broadcasting. For more about broadcasting, please see [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html). # In[6]: a = tf.constant([[1, 0, 0], [0, 1, 1]]) print a.eval() print "Equal to 1?" print tf.equal(a, 1).eval() print "Not equal to 1?" print tf.not_equal(a, 1).eval() # #### tf.random_normal # `tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)` outputs random values from a normal distribution. # # In[7]: normal = tf.random_normal([3], stddev=0.1) print normal.eval() # ## Variables # When we train a model, we use variables to hold and update parameters. Variables are in-memory buffers containing tensors. They must be explicitly initialized and can be saved to disk during and after training. we can later restore saved values to exercise or analyze the model. # # * tf.Variable # * tf.Tensor.name # * tf.all_variables # # #### tf.Variable # `tf.Variable(initial_value=None, trainable=True, name=None, variable_def=None, dtype=None)` creates a new variable with value `initial_value`. # The new variable is added to the graph collections listed in collections, which defaults to `[GraphKeys.VARIABLES]`. If `trainable` is true, the variable is also added to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. # In[8]: # variable will be initialized with normal distribution var = tf.Variable(tf.random_normal([3], stddev=0.1), name='var') print var.name tf.initialize_all_variables().run() print var.eval() # #### tf.Tensor.name # We can call `tf.Variable` and give the same name `my_var` more than once as seen below. Note that `var3.name` prints out `my_var_1:0` instead of `my_var:0`. This is because TensorFlow doesn't allow user to create variables with the same name. In this case, TensorFlow adds `'_1'` to the original name instead of printing out an error message. Note that you should be careful not to call `tf.Variable` giving same name more than once, because it will cause a fatal problem when you save and restore the variables. # In[9]: var2 = tf.Variable(tf.random_normal([2, 3], stddev=0.1), name='my_var') var3 = tf.Variable(tf.random_normal([2, 3], stddev=0.1), name='my_var') print var2.name print var3.name # #### tf.all_variables # Using `tf.all_variables()`, we can get the names of all existing variables as follows: # In[10]: for var in tf.all_variables(): print var.name # ## Sharing variables # TensorFlow provides several classes and operations that you can use to create variables contingent on certain conditions. # * tf.get_variable # * tf.variable_scope # * reuse_variables # #### tf.get_variable # `tf.get_variable(name, shape=None, dtype=None, initializer=None, trainable=True)` is used to get or create a variable instead of a direct call to `tf.Variable`. It uses an initializer instead of passing the value directly, as in `tf.Variable`. An initializer is a function that takes the shape and provides a tensor with that shape. Here are some initializers available in TensorFlow: # # * `tf.constant_initializer(value)` initializes everything to the provided value, # * `tf.random_uniform_initializer(a, b)` initializes uniformly from [a, b], # * `tf.random_normal_initializer(mean, stddev)` initializes from the normal distribution with the given mean and standard deviation. # In[11]: my_initializer = tf.random_normal_initializer(mean=0, stddev=0.1) v = tf.get_variable('v', shape=[2, 3], initializer=my_initializer) tf.initialize_all_variables().run() print v.eval() # #### tf.variable_scope # `tf.variable_scope(scope_name)` manages namespaces for names passed to `tf.get_variable`. # In[12]: with tf.variable_scope('layer1'): w = tf.get_variable('v', shape=[2, 3], initializer=my_initializer) print w.name with tf.variable_scope('layer2'): w = tf.get_variable('v', shape=[2, 3], initializer=my_initializer) print w.name # #### reuse_variables # Note that you should run the cell above only once. If you run the code above more than once, an error message will be printed out: `"ValueError: Variable layer1/v already exists, disallowed."`. This is because we used `tf.get_variable` above, and this function doesn't allow creating variables with the existing names. We can solve this problem by using `scope.reuse_variables()` to get preivously created variables instead of creating new ones. # In[13]: with tf.variable_scope('layer1', reuse=True): w = tf.get_variable('v') # Unlike above, we don't need to specify shape and initializer print w.name # or with tf.variable_scope('layer1') as scope: scope.reuse_variables() w = tf.get_variable('v') print w.name # ## Place holder # TensorFlow provides a placeholder operation that must be fed with data on execution. If you want to get more details about placeholder, please see [here](https://www.tensorflow.org/versions/r0.11/api_docs/python/io_ops.html#placeholder). # In[14]: x = tf.placeholder(tf.int16) y = tf.placeholder(tf.int16) add = tf.add(x, y) mul = tf.mul(x, y) # Launch default graph. print "2 + 3 = %d" % sess.run(add, feed_dict={x: 2, y: 3}) print "3 x 4 = %d" % sess.run(mul, feed_dict={x: 3, y: 4})
7534f9f7e416d1f089a1a08f02fe2f07a4be4645
tlennen/hackerrank-practice
/Python Practice/set_mutations.py
832
3.703125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT # https://www.hackerrank.com/challenges/py-set-mutations/problem?h_r=next-challenge&h_v=zen n = int(input()); set_A = set(map(int,input().split())) queries = int(input()) for x in range(0,queries): command = list(input().split()) if command[0] == "intersection_update": set_B = set(map(int,input().split())) set_A.intersection_update(set_B) elif command[0]=="update": set_B = set(map(int,input().split())) set_A.update(set_B) elif command[0]=="difference_update": set_B = set(map(int,input().split())) set_A.difference_update(set_B) elif command[0]=="symmetric_difference_update": set_B = set(map(int,input().split())) set_A.symmetric_difference_update(set_B) print(sum(set_A))
b49ef2fc080b3aa2772a3dfb8a125c593769e789
ameseric/lang-reviews
/misc/python/arraypivot.py
1,440
4.0625
4
""" Write a function that pivots an array of size n by k places. Assuming a right pivot. E.g. 12345 pivot 2 -> 45123 """ ''' Naive implementation of array pivot. O(n). ''' def pivotArrayNaive( intArray ,pivotPos ): LENGTH = len( intArray) if pivotPos == 0: return intArray if pivotPos >= LENGTH or pivotPos < 0: return -1 pivotArray = [0] * LENGTH index = 0 for num in intArray: pivotArray[ -LENGTH + pivotPos + index] = num index = index + 1 return pivotArray ''' Different version, more concise, but only because of python. Mechanically is about the same, since Python should be copying values from the array into new arrays.''' def pivotArrayCons( intArray ,pivotPos): LENGTH = len( intArray) if pivotPos == 0: return intArray if pivotPos >= LENGTH or pivotPos < 0: return -1 return intArray[-pivotPos:] + intArray[:LENGTH-pivotPos] def printTest(): arr = [1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9] print( pivotArrayNaive( arr ,0) ,pivotArrayNaive( arr ,2) ,pivotArrayNaive( arr ,5) ,pivotArrayNaive( arr ,9) ,pivotArrayNaive( arr ,-4) ) print( pivotArrayCons( arr ,2) ) def sizeTest(): arr = [1 for i in range(1000000)] pivotArrayNaive( arr ,90) print( "Between") pivotArrayCons( arr ,90) printTest() sizeTest()
87fa240e4454b66c8972e423380c81ce2c3641cb
Arocha4/Projects
/python/webmap-folium/map1.py
2,356
3.671875
4
# this script when compiled will create an htmlfile named map1.html shown at the last line which has multiple layers # that color codes the map according to popularion along with location of cvolcanoes in north america. # the attached fiels volcanoes.txt and world.json are the refferenced files. Found them online import folium #import library folium folium is a library that creates leaflet Maps import pandas # install pandas linrary very powerful for data analysis used here to interprit the refferenced json and txt/csv files data = pandas.read_csv("volcanoes.txt") # load data into varible data for forloop to loop all the markers lat = list(data["LAT"]) lon = list(data["LON"]) elev = list(data["ELEV"]) def color_produced(elevation): # function that determins the color of the marker based on elevation of the volcano if elevation < 1000: return 'green' elif 1000 <elevation< 3000: return "orange" else: return "red" map = folium.Map(location= [32,-122], zoom_start=6, tiles = "Stamen Terrain") fgv = folium.FeatureGroup(name="Volcanoes") # feature group marker is a feature. can add multiple features per object. # use zip funtion to loop through iterables. for lt, ln, el in zip(lat, lon, elev): # loop for iterating throught the list since We dont want to add a marker for every location fgv.add_child(folium.CircleMarker(location=[lt,ln],radius=6,popup=str(el)+"m",fill_color=color_produced(el), fill=True, fill_opacity=0.7)) fgp = folium.FeatureGroup(name="Population") # feature group layer for population fgp.add_child(folium.GeoJson(data =open("world.json", 'r', encoding="utf-8-sig").read(), style_function=lambda x:{'fillColor':"green" if x['properties']['POP2005'] < 10000000 else 'orange' if 10000000 <=x['properties']["POP2005"] < 20000000 else 'red'} )) # if else function that determines the contries color based on population map.add_child(fgv) #make feature group for Volanoes map.add_child(fgp) #make feature group for population map.add_child(folium.LayerControl()) # layer control to turn feature groups on and off map.save("Map1.html") # save scrip as html file you can open once compiled
84042eef928ff03910d116ebd07f9581ad585d07
riyasaxena/python
/playingWithLoops.py
412
3.796875
4
startRange = int (input("Enter the number from which you want to start printing tables: ")) endRange = int (input("Enter the number till which you want to print tables: ")) # for anumber in range (startRange, endRange) : print print ("timestable of ", anumber ) print for loopdaloop in range (1, 11) : print (anumber, "*", loopdaloop, "=", anumber * loopdaloop)
c6fe7babab81645a5802d363f62d03ae3ee2e434
wuranxu/leetcode
/601to650/623. 在二叉树中增加一行.py
1,460
3.859375
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def addOneRow(self, root: TreeNode, v: int, d: int) -> TreeNode: # 如果d是1,则直接创立一个node,并把root赋予给node.left并返回node if d == 1: node = TreeNode(v) node.left = root return node # 当前深度为1 current = 1 queue = [root] # 否则开始正常的bfs while len(queue) > 0: size = len(queue) for i in range(size): node = queue.pop(0) left = node.left right = node.right # 因为要在深度的上一层进行修改,所以是d-1 if current == d - 1: node.left = TreeNode(v) node.right = TreeNode(v) node.left.left = left node.right.right = right # 添加完所有该层节点,可以直接return root了,这里用break一样 if i == size - 1: break # 否则开始正常的bfs if node.left is not None: queue.append(node.left) if node.right is not None: queue.append(node.right) current += 1 return root
f926c0a1635120ab9a37fc84e78800b7bbf90a56
shelbycobra/LeetcodeSolutions
/easy/IntersectionII.py
475
3.921875
4
class Solution: def intersect(self, nums1, nums2): nums1 = sorted(nums1); nums2 = sorted(nums2); result = [] while nums1 and nums2: if nums[0] == nums2[0]: result.append(nums1.pop(0)) nums2.pop(0) elif nums1[0] > nums2[0]: nums2.pop(0) else: nums1.pop(0) print(result) if __name__ == "__main__": intersect([1,2,2,1], [2,2])
ac40d612f1b9b6577156a9319f6d6ff1880c91a4
jeff-lund/CS199
/Python/Loops/bronk.py
262
3.78125
4
# Using Lord Brounkers continued fraction to estimate pi n = int(input("Enter a positive, odd number: ")) if n % 2 == 0: print("Nope") else: z = 1 while n > 1: z = 2 + n**2 / z n -= 2 z = 4 / (1 + 1 / z) print(z)
c22390bb91463fa2c680fd10cb1dc4ea68492dce
chendaofa123/Python
/3-5.py
176
4
4
names=['Tom','Jine','Collins','Red'] print(names[1]+'can not keep the appointment') names[1]='Grous' for name in names: print(name+',I hope to have dinner with you ')
875dc28ef62f5f8fef663ef9f6e77cf73896c964
onkursen/road-trip-recommendations
/dump_attributes.py
1,409
3.578125
4
# Get all restaurants from a desired city (in this case, Phoenix) # and save them to a file using Pickle, Python's persistence model. from util import * # Use logging file configuration logging.config.fileConfig('logging.conf') logger = logging.getLogger('dump_restaurants') BUSINESS_PATH = DATASET_PATH + 'yelp_academic_dataset_business.json' attributes = set() file_businesses = open(BUSINESS_PATH) for line in file_businesses: if line.strip() == '': continue # Python json module doesn't play nice with newlines # (which show up in addresses) line_with_newlines_removed = re.sub('\n', ', ', line) # Only select restaurants from the desired city business = json.loads(line) if business['city'] == DESIRED_CITY and \ 'Restaurants' in business['categories']: business_attributes = business['attributes'] if 'stars' not in business: logger.debug("Processing business: %s" % business['name']) print 'PROBLEM' for attr in business_attributes: if type(business_attributes[attr]) == bool: attributes.add(attr) file_businesses.close() attributes.add('Price Range') logger.debug('%d attributes in %s found' % (len(attributes), DESIRED_CITY)) for attr in attributes: print attr # Save restaurants to the output using Pickle, Python's # persistence model logger.debug('Saving restaurants to file: %s' % ATTRIBUTES_PATH) joblib.dump(attributes, ATTRIBUTES_PATH)
527969afa1d886ac4fb1bb215bde5be050523876
syurskyi/Python_Topics
/045_functions/004_closures/_exercises/_templates/001/002_Closures.py
942
3.78125
4
# -*- coding: utf-8 -*- # # Реализация с помощью именованных функций: # ___ make_adder x # ___ adder n # r_ x + n # захват переменной "x" из внешнего контекста # r_ ? # # # То же самое, но через безымянные функции: # make_adder _ l_ x |l... n x + ?) # # f _ ? 10 # print ? 5 # 15 # print ? -1 # 9 #print() # # ___ multiplier n # multiplier возвращает функцию умножения на n # ___ mul k # r_ n * k # r_ ? # # # mul3 _ ? 3 # mul3 - функция, умножающая на 3 # print ? 3 ? 5 # # n _ 3 # # ___ mult k mul_n # r_ m.. * k # # # n = 7 # print m.. 3 # n = 13 # print m.. 5 # # n = 10 # mult = l____ k mul_n m.. * k # print ? 3 # # # ___ outer_func x # ___ inner_func y # # inner_func замкнуло в себе х # r_ y + x # r_ ?
7f4f0d82ed7a00e69ff8e3268665219dcd08eb6b
harikrishna-vadlakonda/Patterns
/12.py
184
3.78125
4
n = int(input("enter the no of rows: ")) for i in range(n): print(" "*i+chr(65+i),end=' ') if i != n-1: print(" "*(2*n-2*i-3)+chr(65+i),end = '') print()
0e4938e4ce0f4dd4d8367932f8d48850cc958b4d
Turjo7/Python-Revision
/return.py
138
3.75
4
def square_number(num): return num*num #By deafult a python function returs None #result = square_number(3) print(square_number(3))
7714ba14ec9f3f47741a26005e277c7b7f3c97e9
USTBlzg10/-offer
/target/classes/nowcoder/S14_FindKthToTail14.py
852
3.5
4
class ListNode: def __init__(self, x): self.val = x self.next = None class FindKthToTail: def findKthToTail(self, head, k): tail = pre = head for _ in range(k): if not tail: return None tail = tail.next while tail: pre = pre.next tail = tail.next return pre def arrayToList(self, array, index): head = None if index < len(array): value = array[index] head = ListNode(value) head.next = self.arrayToList(array, index+1) return head if __name__ == '__main__': test = FindKthToTail() array = [1, 2, 3, 4, 5, 6, 7, 8, 9] head = test.arrayToList(array, 0) result = test.findKthToTail(head, 1) if result: print(result.val) else:print("null")
7ceeda6ce815711dc48b51bd2a8e44a10b44e035
aseksenali/webdev
/Third/I.py
153
3.625
4
a = int(input()) counter = 0 i = 2 while a != 1: if a % i == 0: counter += 1 a /= i continue i += 1 print(counter + 1)
77b495b6217fb32c63053693529e00e292f418b8
SjorsVanGelderen/Graduation
/python_3/data_structures/linked_list.py
1,309
3.9375
4
"""Linked list data structure Copyright 2016, Sjors van Gelderen """ # Empty list class Empty: def __init__(self): self.is_empty = True # List segment class Segment: def __init__(self, _value, _tail): self.value = _value self.tail = _tail self.is_empty = False # Full list functionality class List: def __init__(self): self.segment = Empty() def __str__(self): values = [] segment = self.segment while not segment.is_empty: values.append(str(segment.value)) segment = segment.tail return " ".join(values) def populate(self, *_values): for value in _values: self.segment = Segment(value, self.segment) def reverse(self): result = List() values = [] segment = self.segment while not segment.is_empty: values.append(segment.value) segment = segment.tail for value in values: result.segment = Segment(value, result.segment) self.segment = result.segment # Main program logic def program(): linked_list = List() linked_list.populate(1, 2, 3, 4) print(linked_list) linked_list.reverse() print(linked_list) program()
be6cd52867f82ab37a100a760f1d01d1a5e55ca7
Kai-Ch/py_01
/common_module/itertools_p/itertools_02.py
252
3.515625
4
#coding=utf-8 #description: _author_ = 'Kai,Chen' _time_ = '2018/4/25' import itertools #chain() ch = itertools.chain('ABC','XYZ') for n in ch: print(n) #groupby() for key,group in itertools.groupby('AAABBBCCDDD'): print(key, list(group))
672563e8c5dda9f9fdb5d45be6771583ba70fa18
soundaraj/python-practices1
/vowel.py
207
3.9375
4
def vowel(value): vow = ['a','e','i','o','u'] if value in vow: print 'This is vowel' else: print 'This is constant' value = raw_input("enter the values \t") vowel(value)
957506803683a0686d97ee28af05fbbff07f1dc0
yamileherrera/Ejercicios-Python-FP-1-Semestre
/prg_13_repaso Marzo 02.py
882
3.8125
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 2 19:30:12 2021 @author: yamile """ # Programa que lee N numeros enteros y calcula su promedio sale con # un numero menor a cero # Declarar variables num = 0 # Variable que almacena los numeros que digita el usuario suma = 0 # Variable que almacena la suma de los numeros positivos med = 0.0 # Variable que almacena la media canEle = 0 # Variable que almacena la cantidad de numeros digitados num = int(input("Número : ")) # Lectura del primer numero while (num > 0): # Inicio del ciclo suma = suma + num num =int(input(" Número : ")) # Lectura de los otros numeros canEle = canEle + 1 # Termina el ciclo if canEle != 0 : med = suma/canEle # Calcular la media print("la media es: ",med) # Imprimir la media else: print("No hay número para calcular la media")
a2b126ff2a3cf4a509fa6e210a3eb01bce55d24e
mridulrb/Basic-Python-Examples-for-Beginners
/Programs/MyPythonXII/Unit1/PyChap01/swap.py
322
4.15625
4
# File name: ...\\MyPythonXII\Unit1\PyChap01\swap.py # This program swaps two numbers without using third variable a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) a = a + b b = a - b a = a - b print("After swapping a is –> %d" %(a)) print("After swapping b is –> %d" %(b))
745d73657038dcb3e42936d43b28642c5811f18f
anand-mishra/geofence
/geofence.py
4,957
4.21875
4
# -*- coding: utf-8 -*- import math class Polygon(object): def __str__(self): return "%s: %s" % (self.__shape_type, self.__shape) def __init__(self): self.__shape = {} self.__shape_type = 'polygon' def set_shape(self, poly): """Creates a polygon. Keyword arguments: poly -- should be tuple of tuples contaning vertex in (x, y) form. e.g. ( (0,0), (0,1), (1,1), (1,0), ) """ assert type(()) == type(poly), "argument must be tuple of tuples." assert len(poly) > 1, "polygon must have more than one vertex." self.__shape['vertex_list'] = poly self.__shape['vertex_count'] = len(poly) def is_inside(self, point): """Returns True if the point lies inside the polygon, False otherwise. Works on Ray Casting Method (https://en.wikipedia.org/wiki/Point_in_polygon) Keyword arguments: point -- a tuple representing the coordinates of point to be tested in (x ,y) form. """ poly = self.__shape['vertex_list'] n = self.__shape['vertex_count'] x, y = point inside = False p1x,p1y = poly[0] for i in range(n+1): p2x,p2y = poly[i % n] if y > min(p1y,p2y): if y <= max(p1y,p2y): if x <= max(p1x,p2x): if p1y != p2y: xints = (y-p1y)*(p2x-p1x)/float(p2y-p1y)+p1x if p1x == p2x or x <= xints: inside = not inside p1x,p1y = p2x,p2y return inside class Circle(object): def __str__(self): return "%s: %s" % (self.__shape_type, self.__shape) def __init__(self): self.__shape = {} self.__shape_type = 'circle' def set_shape(self, args): """Creates a circle. Keyword arguments: args -- will we a tuple of center and radius center should be tuple of coordinates in (x, y) form; radius should be scalar value represnting radius of the circle. """ assert len(args) == 2, "there must be exactly two arguments." assert type(()) == type(args[0]), "first part of argument must be a tuple." assert args[1] > 0, "radius must be positive value." center = args[0] radius = args[1] self.__shape['center'] = center self.__shape['radius'] = radius def is_inside(self, point): """ algo: we will calculate the distance of the point from the center of the circle and if it is <= radius we can say that point is inside the circle """ x, y = point center_x, center_y = self.__shape['center'] radius = self.__shape['radius'] d = abs( math.sqrt( (center_x - x) ** 2 + (center_y + y) ** 2 ) ) return d <= radius class Geofence(object): def __str__(self): return str(self.__shape) def __init__(self, shape_type): shape_types = ['circle', 'polygon'] assert shape_type in shape_types, "available geofence shapes are circle|polygon" if shape_type == 'circle': self.__shape = Circle() elif shape_type == 'polygon': self.__shape = Polygon() def set_shape(self, *args): """Creates a Circle|Polygon depending on shape_type. Keyword arguments (in case of Circle): args -- will we a tuple of center and radius center should be tuple of coordinates in (x, y) form; radius should be scalar value represnting radius of the circle. Keyword arguments (in case of Polygon): poly -- should be tuple of tuples contaning vertex in (x, y) form. e.g. ( (0,0), (0,1), (1,1), (1,0), ) """ self.__shape.set_shape(args) def get_shape(self): """Return the shape object Geofence(will be instance of Circle|Polygon)""" return self.__shape def get_shape_type(self): """Returns the shape_type of the geofence will be circle|polygon""" return self.__shape_type def is_inside(self, point): """Returns True if the point lies inside the geofence region. Keyword arguments: point - a tuple of coordinates in (x, y) form. """ return self.__shape.is_inside(point) if __name__ == "__main__": gfs = [] g = Geofence('polygon') g.set_shape( ( 1, 1 ), ( 1, 2 ), ( 2, 2 ), ( 2, 1 ) ) gfs.append(g) g = Geofence('circle') g.set_shape( ( 1 , 1 ), 3) gfs.append(g) for gf in gfs: print gf.get_shape() print gf.is_inside( ( 1.5, 1.5 ) ) print gf.is_inside( ( 4.9, 1.2 ) ) print gf.is_inside( ( 1.8, 1.1 ) )
d68fc775b237dee93301d9ea3445850d35502a10
erardlucien/python_exercises
/fib.py
510
4.15625
4
# write Fibonacci series up to n. def fib(n): """Print a Fibonacci series up to n.""" a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a + b print() # fib(2000) # return Fibonacci series up to n def fib2(n): """Return a list containing the Fibonacci series up to n.""" result = [] a, b = 0, 1 while a < n: result.append(a) # see below a, b = b, a + b return result # fib100 = fib2(100) call it # print(fib100) # write the result
c3ab8410cd08b4b7f673e8717924a4a82cd08ba0
scobbyy2k3/python-challenge
/pyBank/main.py
2,292
3.734375
4
import os import csv #path for file filepath = os.path.join("C:\\Users\\HADEORLAH\\Desktop\\python-challenge\\pyBank\\Resources\\budget_data.csv") month_count = 0 total_revenue = 0 currentmonth_revenue = 0 previous_revenue = 0 revenue_change = 0 revenue_changes = [] months = [] # open csv file with open(filepath,'r', newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") next(csvreader) # gather monthly changes in revenue for row in csvreader: # number of months in dataset month_count = month_count + 1 #revenue change by month months.append(row[0]) currentmonth_revenue = int(row[1]) total_revenue = total_revenue + currentmonth_revenue if month_count > 1: revenue_change = currentmonth_revenue - previous_revenue revenue_changes.append(revenue_change) previous_revenue = currentmonth_revenue # month to month calcualtion of revenue change sum_rev_changes = sum(revenue_changes) average_change = sum_rev_changes / (month_count - 1) max_change = max(revenue_changes) min_change = min(revenue_changes) max_month_index = revenue_changes.index(max_change) min_month_index = revenue_changes.index(min_change) max_month = months[max_month_index] min_month = months[min_month_index] # print summary to user print("Financial Analysis") print("----------------------------------------") print(f"Total Months: {month_count}") print(f"Total Revenue: ${total_revenue}") print(f"Average Revenue Change: ${average_change}") print(f"Greatest Increase in Revenue: {max_month} (${max_change}) ") print(f"Greatest Decrease in Revenue: {min_month} (${min_change}) ") # Name white file output_file = filepath [0:-4] write_budget_dataCSV = f"{output_file}_pybank_results.txt" # Open write file text = open(write_budget_dataCSV, mode = 'w') text.write("Financial Analysis" + "\n") text.write("----------------------------------------" + "\n") text.write(f"Total Months: {month_count}" + "\n") text.write(f"Total Revenue: ${total_revenue}" + "\n") text.write(f"Average Revenue Change: ${average_change}" + "\n") text.write(f"Greatest Increase in Revenue: {max_month} (${max_change})" + "\n") text.write(f"Greatest Decrease in Revenue: {min_month} (${min_change})" + "\n")
74e772a2701ef51007a8791e606acf2795e49f5b
ch-canaza/holbertonschool-low_level_programming
/0x1C-makefiles/5-island_perimeter.py
591
3.8125
4
#!/usr/bin/python3 """ tecnical enterview preparation """ def island_perimeter(grid): """ function that returns perimeter of an island """ p = 0 for i in range(len(grid)): for j in range(len(grid[i])): if (grid[i][j]) == 1: if (p == 0): p = p + 3 else: p += 2 if (grid[i][j]) == 1: if ((grid[i][j - 1]) == 1 and (grid[i - 1][j]) == 1): if grid[i - 1][j - 1] == 1: p -= 2 p += 1 return (p)
75b19920e372f8c91cc3ec59f05a87975e4d9b24
h2sp/dev
/python/input.py
415
3.578125
4
#-- encoding:utf-8 --# name = input("お名前は? ") """ 直接文字列を入力すると以下のエラー ""で入力文字をくくるとエラーでない Traceback (most recent call last): File "input.py", line 3, in <module> name = input("お名前は? ") File "<string>", line 1, in <module> """ age = input("何歳ですか? ") print("こんにちは! %sさん (%s歳)" % (name, age))
241940fb42ea3367a197aca1d86ebdff24858571
katerinazuzana/sign-language-dictionary
/dictionary/scrolled_frame.py
4,774
3.84375
4
import tkinter as tk from tkinter import ttk from autoscrollbar import AutoScrollbar class ScrolledFrame(tk.Frame): """A frame that is either horizontally or vertically scrollable.""" def __init__(self, parent, width, height, orient, border=False, **options): """Create a frame with a scrolled canvas that has an inner frame. The canvas can be scrolled using a scrollbar or by a mouse wheel. Arguments: parent: a parent tkinter widget width (int): a width of the visible canvas area height (int): a height of the visible canvas area orient (str): takes either 'horizontal' or 'vertical' value to indicate the orientation of the scrollbar border (bool): says whether there is a border around ScrolledFrame """ super().__init__(parent, **options) if border: self.configure(borderwidth=2, relief='groove') bgcolor = options.get('bg', self['bg']) # make a canvas with vertical and horizontal scrollbars vsbar = AutoScrollbar(self, orient=tk.VERTICAL) hsbar = ttk.Scrollbar(self, orient=tk.HORIZONTAL) # AutoScrollbar doesn't work here - wouldn't appear # (horizontal ScrolledFrame is used with .grid_propagate(0)) canvas = tk.Canvas(self, # visible area size: width=width, height=height, bg=bgcolor) vsbar.config(command=canvas.yview) hsbar.config(command=canvas.xview) if orient == 'horizontal': self.rowconfigure(0, minsize=height) self.rowconfigure(1, minsize=40) # to fit a scrollbar canvas.config(xscrollcommand=hsbar.set) canvas.grid(column=0, row=0, sticky=tk.N+tk.S+tk.W, columnspan=3) else: # vertical: canvas.config(yscrollcommand=vsbar.set) canvas.grid(column=0, row=0, sticky=tk.N+tk.E+tk.S+tk.W) # enable scrolling the canvas with the mouse wheel self.bind('<Enter>', self.bindToWheelVertical) self.bind('<Leave>', self.unbindWheel) self.rowconfigure(0, weight=1) canvas.config(highlightthickness=0) self.canvas = canvas # make the inner frame interior = tk.Frame(canvas, bg=bgcolor, cursor='hand2') self.interior = interior self.canvas.create_window((0, 0), window=interior, anchor=tk.NW) def configureInterior(event): size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) # set the total canvas size canvas.config(scrollregion=(0, 0, size[0], size[1])) if orient == 'horizontal': # hide scrollbar when not needed if interior.winfo_reqwidth() <= canvas.winfo_width(): hsbar.grid_forget() # disable scrolling the canvas with the mouse wheel self.unbind('<Enter>') self.canvas.unbind('<Leave>') else: hsbar.grid(column=0, row=1, sticky=tk.N+tk.E+tk.W, columnspan=3) # enable scrolling the canvas with the mouse wheel self.bind('<Enter>', self.bindToWheelHorizontal) self.bind('<Leave>', self.unbindWheel) interior.bind('<Configure>', configureInterior) def bindToWheelVertical(self, event): """Bind vertical scrolling of the canvas to the mouse wheel.""" self.canvas.bind_all('<Button-5>', self.scrollDown) self.canvas.bind_all('<Button-4>', self.scrollUp) def bindToWheelHorizontal(self, event): """Bind horizontal scrolling of the canvas to the mouse wheel.""" self.canvas.bind_all('<Button-5>', self.scrollRight) self.canvas.bind_all('<Button-4>', self.scrollLeft) def unbindWheel(self, event): """Unbind the mouse wheel events.""" self.canvas.unbind_all('<Button-5>') self.canvas.unbind_all('<Button-4>') def scrollDown(self, event): """Scroll the canvas down.""" self.canvas.yview_scroll(1, 'units') def scrollUp(self, event): """Scroll the canvas up.""" self.canvas.yview_scroll(-1, 'units') def scrollRight(self, event): """Scroll the canvas to the right.""" self.canvas.xview_scroll(1, 'units') def scrollLeft(self, event): """Scroll the canvas to the left.""" self.canvas.xview_scroll(-1, 'units')
04481a452c5d49e33634aa235cc5dd5f00813d2d
rodrigoks/python
/desafios/mundo1/d031.py
524
3.921875
4
print('==' * 40) print('Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 parta viagens mais longas.') print('--' * 40) distancia = int(input('Qual a distancia da viagem? ')) valorProximo = 0.5 valorLonge = .45 print('PROCESSANDO...') if distancia > 200: preco = distancia * valorLonge else: preco = distancia * valorProximo print('O custo da viagem sera de R$ {:.2f}.'.format(preco)) print('==' * 40)
d3545f4edcaf8548f32d38343e27dd59c65c2b0c
k1xme/leetcode
/python/swapPairs.py
927
3.859375
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param {ListNode} head # @return {ListNode} def swapPairs(self, head): if not head: return None dummy = ListNode(0) dummy.next = head p = dummy while p.next.next: # it means there is a pair, so we can swap it. tmp = p.next.next.next # store the head of the next pair(if we have). first = p.next p.next = first.next first.next = tmp p.next.next = first # move on to the next one. p = p.next.next if not p.next: break return dummy.next head = ListNode(1) head.next = ListNode(2) head.next.next = ListNode(3) head.next.next.next = ListNode(4) s = Solution() print s.swapPairs(head)
74a4295a3eff0b256f0663601bcb17ba5b59e542
cbott/learnRGB
/colorlearn.py
5,632
3.75
4
#!/usr/bin/env python2 from Tkinter import * from colorlib import * import random import tkFont class Application(Frame): def __init__(self, master): #canvas / colored rectangle dimensions self.width = 800 self.height = 300 #answer rectangle dimenstions self.ans_width = 120 self.ans_height= 120 #Actual color of the displayed rectangle (r, g, b) self.current_color = (0, 0, 0) #just a big font so things are bigger self.big_font = tkFont.Font(root=master, family='Helvetica', size=20) Frame.__init__(self, master) self.grid(sticky=(E, W, S, N)) master.columnconfigure(0, weight=1) master.rowconfigure(0, weight=1) self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.mode = StringVar() #format for representing colors: INT/HEX self.generate() self.next_color() def next_color(self): """Change the color currently displayed""" self.current_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) self.color_canvas.config(bg=to_hex(self.current_color)) def submit(self): """Display the results: comparing user-entered values to actual color values""" if self.mode.get() == "INT": # string to int def convert(s): try: return float(s) except Exception: return 0 # int to string def fmt(color): return str(color) else: # "HEX" mode # convert a hex string to an integer ("a" -> 10) def convert(s): try: return int(s, 16) except Exception: return 0 # Format integers as hex strings (10 -> "0a") def fmt(color): return hex(color)[2:].zfill(2) # Read in user input, limit to within valid range of RGB (0-255) r = clamp_rgb(convert(self.r_in.get())) g = clamp_rgb(convert(self.g_in.get())) b = clamp_rgb(convert(self.b_in.get())) # Update input box with validated inputs to give user feedback # on which values were accepted self.r_in.delete(0,END) self.r_in.insert(0, fmt(r)) self.g_in.delete(0,END) self.g_in.insert(0, fmt(g)) self.b_in.delete(0,END) self.b_in.insert(0, fmt(b)) # Show results in output Text box self.out.delete(1.0, END) self.out.insert(END, "Actual Red : %s\n"%fmt(self.current_color[0])) self.out.insert(END, "Actual Green: %s\n"%fmt(self.current_color[1])) self.out.insert(END, "Actual Blue : %s\n"%fmt(self.current_color[2])) score = color_score(self.current_color, (r,g,b)) self.out.insert(END, "Your Score: %i"%score) #Show the user what their answer was self.answer_canvas.create_rectangle(1, 20, self.ans_width-1, self.ans_height-1, fill=to_hex((r, g, b))) def generate(self): """Draw fields on the window""" #Canvas used to display the color rectangle self.color_canvas = Canvas(self) self.color_canvas.grid(row=0, column=0, columnspan=3, sticky=(E, W, S, N)) self.content = Frame(self, pady=10) self.content.grid(sticky=N) Label(self.content, font=self.big_font, text="Red:").grid(row=1, column=0) self.r_in = Entry(self.content, font=self.big_font) self.r_in.grid(row=1, column=1) Label(self.content, font=self.big_font, text="Green:").grid(row=2, column=0) self.g_in = Entry(self.content, font=self.big_font) self.g_in.grid(row=2, column=1) Label(self.content, font=self.big_font, text="Blue:").grid(row=3, column=0) self.b_in = Entry(self.content, font=self.big_font) self.b_in.grid(row=3, column=1) Label(self.content,text="Representation:").grid(row=1, column=2, sticky=S) self.select_int = Radiobutton(self.content, text="Int", variable=self.mode, value="INT", takefocus=False) self.select_hex = Radiobutton(self.content, text="Hex", variable=self.mode, value="HEX", takefocus=False) self.select_int.select() self.select_int.grid(row=2, column=2, sticky=W) self.select_hex.grid(row=3, column=2, sticky=NW) self.btn_submit = Button(self.content, font=self.big_font, text="Submit!", command=self.submit) self.btn_submit.grid(row=4, column=1) self.btn_submit.bind('<Return>', lambda x:self.submit()) self.btn_color = Button(self.content, font=self.big_font, text="Next Color", command=self.next_color) self.btn_color.grid(row=4, column=0) #Automatically select the first color input if user hits enter while "next color" is active self.btn_color.bind('<Return>', lambda x:[self.next_color(), self.r_in.focus()]) #The text output section - display scores and results self.out = Text(self.content, width=40, height=4, font=self.big_font, takefocus=False) self.out.grid(row=5, column=0, columnspan=2) #Field to show the color that the user entered self.answer_canvas = Canvas(self.content, width=self.ans_width, height=self.ans_height) self.answer_canvas.create_rectangle(1, 1, self.ans_width, self.ans_height) self.answer_canvas.create_text(self.ans_width/2, 1, text="Your Answer:", anchor=N) self.answer_canvas.grid(row=5, column=2) root = Tk() root.title("Learn RGB") app = Application(root) root.mainloop()
55e5d5016d18f80351ccbaed5466578aecf0520f
yonggyulee/gitpython
/04/03.while.py
482
3.703125
4
# 1 ~ 10 합을 구하기 s = 0 # for n in range(1,11): # s += n # print(s) s, count = 0,1 while count < 10: print(count) s += count count+=1 print(s) #break #for n in range(10): # if n > 5 : # break # print(n, end=' ') i = 0 while i <10: if i>5: break print(i,end=' ') i+=1 print('\n===============================================') # 무한루프 i = 0 while True: print('infinite loop') if i >5: break i+=1
c665f25b7dbde922bfba18623ca107c60dce3181
noorah98/python1
/Session32B.py
3,955
3.921875
4
# Open Hashing with List # https://www.cs.usfca.edu/~galles/visualization/OpenHash.html class HashTable: def __init__(self, capacity=10): self.capacity = capacity self.size = 0 self.table = [] for i in range(capacity): self.table.append([]) def hashCode(self, data): idx = id(data) % self.capacity return idx def put(self, data): idx = self.hashCode(data) self.table[idx].append(data) print(">> Data {} Inserted at Index {}".format(data, idx)) self.size += 1 def find(self, data): pass def delete(self, data): pass def iterate(self): for i in range(self.capacity): if len(self.table[i]) != 0: print(">> Data in BUCKET", i) for data in self.table[i]: print(data) print("~~~~~~~~~~~~~~") """ # HashTable with Objects class HashTable: def __init__(self, capacity=10): self.capacity = capacity self.size = 0 self.table = [] # Assignment : Replace with Your LinkedList Implementation for i in range(capacity): self.table.append(None) def hashCode(self, data): idx = id(data) % self.capacity return idx def put(self, data): idx = self.hashCode(data) if self.table[idx] == None: self.size += 1 else: print(">> COLLISION DETECTED FOR", data) self.table[idx] = data print(">> Data {} Inserted at Index {}".format(data, idx)) def find(self, data): idx = self.hashCode(data) if self.table[idx] == data: return idx else: return -1 def delete(self, data): idx = self.hashCode(data) if self.table[idx] == data: self.table[idx] = None self.size -= 1 print("Data Deleted", data) else: print("Data Not Found", data) def iterate(self): for data in self.table: if data != None: print(data) """ """ # Basic HashTable class HashTable: def __init__(self, capacity=10): self.capacity = capacity self.size = 0 self.table = [] # Assignment : Replace with Your LinkedList Implementation for i in range(capacity): self.table.append(None) def hashCode(self, data): idx = data % self.capacity return idx def put(self, data): idx = self.hashCode(data) if self.table[idx] == None: self.size += 1 self.table[idx] = data print(">> Data {} Inserted at Index {}".format(data, idx)) def find(self, data): idx = self.hashCode(data) if self.table[idx] == data: return idx else: return -1 def delete(self, data): idx = self.hashCode(data) if self.table[idx] == data: self.table[idx] = None self.size -= 1 print("Data Deleted", data) else: print("Data Not Found", data) def iterate(self): # for i in range(self.capacity): # if self.table[i] != None: # print(self.table[i]) for data in self.table: if data != None: print(data) def main(): hTable1 = HashTable(12) # hTable2 = HashTable(20) hTable1.put(20) hTable1.put(12) hTable1.put(13) hTable1.put(14) hTable1.put(19) hTable1.put(24) # Collision hTable1.delete(13) hTable1.delete(300) print("~~~~~~~~~~~~") # print(hTable1.table) hTable1.iterate() # Data will be shown as UNORDERED Due to HASHING :) print("~~~~~~~~~~~~") print(hTable1.size) if __name__ == "__main__": main() """
5634469e7b6d9b39ff27c7c6d718ebd3971ab99a
JNAnnis/Reports337
/Report_01_Updated.py
3,363
4.125
4
# -*- coding: utf-8 -*- """ Report 1: Primitive Pythagorean Triples A pythagorean triple consists of a set of positive integers, (a, b, c) that satisfies the equation a^2 + b^ = c^2. """ import matplotlib.pyplot as plt import math def mygcd(a, b): """ Method to determine the greatest common denominator of two numbers. Parameters: a (int): first number, must be greater than 0 b (int): second number, must be greater than 0 Returns: a (int): greatest common denominator of parameters a and b """ while a != b: if a > b: a = a - b else: b = b - a return a def is_square(a, b): """ Method to determine whether two numbers make a perfect square. Parameters: a (int): first number, must be greater than 0 b (int): second number, must be greater than 0 Returns: bool: True if perfect square, False if not """ c = a**2 + b**2 x = math.sqrt(c) y = math.ceil(x) return x == y def ppt_generate(w, x, y, z, title): """ Generates a plot of points, (a, b), that make pythagorean triples, with duplicates removed via the condition a < b. Parameters: w (int): start value for the range of 'a' values to test, must be greater than 0 x (int): end value for the range of 'a' values to test, must be greater than 0 y (int): start value for the range of 'b' values to test, must be greater than 0 z (int): end value for the range of 'b' values to test, must be greater than 0 title (str): title for the graph Returns: None """ plt.figure(figsize = (10, 10)) plt.title(title, fontweight = 'bold', fontsize = 18, pad = 10) plt.xlabel('a', fontweight = 'bold', fontsize = 14, labelpad = 10) plt.ylabel('b', fontweight = 'bold', fontsize = 14, labelpad = 10) for a in range(w, x): for b in range(y, z): if mygcd(a, b) == 1 and is_square(a, b) == True and a < b: plt.plot(a, b, 'b.', markersize = 5) def ppt_print(e, f, g, h): """ Creates a table of pythagorean triples (a, b, c) that exist in a specified range of 'a' and 'b' values, with duplicates removed via the condition a < b. Parameters: e (int): start value for the range of 'a' values to test, must be greater than 0 f (int): end value for the range of 'a' values to test, must be greater than 0 g (int): start value for the range of 'b' values to test, must be greater than 0 h (int): end value for the range of 'b' values to test, must be greater than 0 Returns: None """ print("{}\t{}\t{}".format('a', 'b', 'c')) print('___________') for a in range(e, f): for b in range(g, h): if mygcd(a, b) == 1 and is_square(a, b) == True and a < b: cVal = math.sqrt(a**2 + b**2) c = int(cVal) print("{}\t{}\t{}".format(a, b, c))
698c218e58ac682132a5901eb0085bedba49f30f
vikas-t/practice-problems
/full-problems/fourElements.py
1,030
3.5
4
#!/usr/bin/python # https://practice.geeksforgeeks.org/problems/four-elements/0 def validPair(pair1, pair2): """ Validates that the sets have nothing in common or the pair is unique """ for p1 in pair1: for p2 in pair2: if not p1 & p2: return True return False def sol(arr, n, k): """ Create a hash of all possible two element sums. For every element (say p) in the hash check if k-p is in the hash and the elements are unique """ m = max(arr) c = [[] for i in range(2*m+1)] # Use list comprehension instead of saying [[]]*(2*m+1) for i in range(n-1): for j in range(i+1, n): s = arr[i]+arr[j] c[s].append({i,j}) # For every sum we store the set of all possible i and j in a set for p in range(len(c)): if not c[p]: continue q = k - p if q >= 0 and q < len(c) and c[q] and validPair(c[p], c[q]): return 1 return 0
88ffe6a17ff4b60cf4c20ffd4900cc2c1f64c594
petereast/cs-year01-archive
/ce151/ass1.py
6,462
4.21875
4
""" ass1.py CE151 assignment 1 template created by sands 30/10/10 modified by sands 28/10/11 - number of exercises changed modified by sands 28/10/6 - number of exercises changed, example added modified by pe16564 30/10/16 - Started assignments """ from math import sqrt import math def ex0(): """ example use 8 at exercise selection prompt in my code to select it """ i = int(input("Enter a non-negative integer: ")) if i<0: print("Negative numbers do not have real square roots") else: root = sqrt(i) print("The square root is", round(root, 2)) def ex1() : """ exercise 1 """ print("Exercise 1 - Triangle stuff") height = float(input("Enter the height: ")) width = float(input("Enter the width: ")) print("The length of the hypotenuse is {0}".format(sqrt(height**2 + width**2))) angle_in_degrees = math.degrees(math.atan(height/width)) print("The first of the two interior angles is {0:.1f}".format(angle_in_degrees)) print("The 2nd of the two interior angles is {0:.1f}".format(180-(90+angle_in_degrees))) def ex2() : """ exercise 2 """ print("Exercise 2 - Fibonacci") n = int(input("Enter the value for n: ")) seq = [0, 1] + [i for i in range(n)] for index, num in enumerate(range(n)): seq[index+2] = seq[index+1] + seq[index] print(seq[index+2], end=",") def ex3() : """ exercise 3 """ print("Exercise 3 - Binomial Coefficient") x = int(input("Please enter a positive integer value for x: ")) y = int(input("Please enter a positive integer value for y: ")) coef = None if x == y: coef = 1 elif y < x: seq = [x for x in range(x-(y+1), x)] mul = 1 for number in seq: mul *= number coef = mul // math.factorial(y) else: print("Invalid value for X or Y") print("The Coefficient is {0}".format(coef)) def ex4() : """ exercise 4 """ print("Exercise 4 - Sentence processing") print("Note: I did this exercise twice as my primary method of completing this task seemed too easy.") string = input("Enter some words: ") longest = 0 shortest = len(string) for word in string.split(): print(word) if len(word) > longest: longest = len(word) if len(word) < shortest: shortest = len(word) print("Longest word: {0}\nShortest word: {1}".format(longest, shortest)) # Because that's the easy way of doing it, I'll write a more longwinded solution here def ex4_extra(): """ Exercise 4 - Longwinded edition """ string = input("Enter some words: ") words = [] current_word = "" for char in string: if char not in [" ", "\n", "\t"]: current_word += char else: if current_word != "": words.append(current_word) current_word = "" for w in words: print(w) #ex4_extra() def ex5() : """ exercise 5 """ print("Exercise 5 - Vowels") vowels = {"a":0, "e":0, "i":0, "o":0, "u":0} vowels_list = list("aeiou") string = input("Please enter a string: ") for char in string: if char in vowels_list: vowels.update({char:vowels[char]+1}) lowest_v = '' lowest_c = len(string) for pair in vowels: if vowels[pair] < lowest_c: lowest_c = vowels[pair] lowest_v = pair elif vowels[pair] == lowest_c: lowest_v+=pair grammar = " is" if len(lowest_v) != 1: grammar = "s are" print("The least frequent vowel{2}: {0} ({1})".format(lowest_v, lowest_c, grammar)) def ex6() : """ exercise 6 """ print("Exercise 6 - Bubble Sort") print("Enter a sequence of positive integers, enter -1 to end") numbers = [] x = int(input(">>> ")) while x > 0: numbers.append(x) xa = input(">>> ") try: x = int(xa) except ValueError: print("Number list accepted") break print("before:", numbers) # TODO: Sort the numbers unchanged = False while not unchanged: unchanged = True for index, value in enumerate(numbers): if index != 0: if value > numbers[index-1]: numbers[index], numbers[index-1] = numbers[index-1], numbers[index] unchanged = False print(numbers) def ex7() : """ exercise 7 - Reverse Polish Notation """ print("Exercise 7 - RPN") VALID_OPERATORS = ["-", "+", "*"] ops = {"-":lambda x, y: x - y, "+":lambda x, y: x + y, "*":lambda x, y: x*y} s_expr = input("Enter an expression using RPN to be evaluated: ") # Remove spaces from expression, convert into list. expr = list("".join(s_expr.split())) values = [] for item in expr: print(values) try: values.append(int(item)) except ValueError: if item in VALID_OPERATORS and len(values) >= 2: # Valid state values.append(ops[item](values.pop(), values.pop())) print(values) elif item not in VALID_OPERATORS: print("Invalid Operation: invalid operator") if len(values) == 1: print("The value of this espression is: {0}".format(values[0])) else: print("Invalid Operation: operator-operand mismatch") # print(expr) # OPERATORS = {"-":0, "+":1,"*":2} # # expr.reverse() # # for index, item in enumerate(expr): # if item in OPERATORS: # expr[index] = ops[OPERATORS[item]](expr[index+1], index[expr+2]) # modify the following line so that your name is displayed instead of Lisa's print("CE151 assignment 1 - Peter East") # do not modify anything beneath this line exlist = [None, ex1, ex2, ex3, ex4, ex5, ex6, ex7, ex0] running = True while running : line = input("Select exercise (0 to quit): ") if line == "0" : running = False elif len(line)==1 and "1"<=line<="8": exlist[int(line)]() else : print("Invalid input - try again")
05b43d84f5799094000273c48cae0ad3f6afe869
lobodaalina/G11
/main.py
234
3.796875
4
import random def func(): n = int(input("Enter the number of elements:")) list = [random.randint(0, 1000) for i in range(n)] print(list) print("First number is", list[0]) print("Last number is", list[-1]) func()
f894cd53a371f3c8640ecdfde2505c2e45adae10
PNeekeetah/Leetcode_Problems
/Generate_Random_Point_In_A_Circle.py
2,747
3.78125
4
# -*- coding: utf-8 -*- """ Created on Mon Feb 22 17:40:21 2021 @author: Nikita # Credit to my friend EIS for the solution randPoint2 # Credit to my other friend RCM for the solution randPoint2 """ import matplotlib.pyplot as plt import random import numpy as np import math class Solution: def __init__(self, radius: float, x_center: float, y_center: float): self.radius = radius self.x_center = x_center self.y_center = y_center def randPoint(self) -> list: y = random.uniform(self.y_center - self.radius, self.y_center + self.radius ) term = ((self.radius - y + self.y_center)*(self.radius + y - self.y_center))**(1/2) x = random.uniform(self.x_center - term ,self.x_center + term ) return [x,y] def randPoint1(self) -> list: x= 2**31 y= 2**31 while ((x-self.x_center)**2+(y-self.y_center)**2 > self.radius**2): x = self.x_center - self.radius + self.radius*2*random.uniform(0,1) y = self.y_center - self.radius + self.radius*2*random.uniform(0,1) return [x,y] def randPoint2(self) -> list: alpha = random.uniform(0, 2*np.pi) s_rad = self.radius*math.sqrt(random.uniform(0,1)) x = s_rad*np.cos(alpha) + self.x_center y = s_rad*np.sin(alpha) + self.y_center return [x,y] # Initialize Solution with these points y_c = -73839.1 x_c = -3289891.3 r = 0.01 solution = Solution(r,x_c,y_c) # Draw circle y_1 = np.arange(y_c - r, y_c + r, r/10000) x_1 = [x_c + np.sqrt((r - i + y_c)*(r + i - y_c)) for i in y_1] x_2 = [x_c - np.sqrt((r - i + y_c)*(r + i - y_c)) for i in y_1] scatter = [solution.randPoint1() for i in range (1000)] points = np.array(scatter).transpose() # Plot plt.figure() plt.plot(x_1,y_1) plt.plot(x_2,y_1) plt.scatter(points[0],points[1],color = "red") plt.axes() plt.xlabel("X") plt.ylabel("Y") plt.title("Circle randPoint scatter") plt.show() """ My initial approach was rather mathematical (and inefficient). Vectors are easier than analysis, I should have learned this to this day. Nonetheless, implementation 2 is inspired by my friends' idea that had to do with sampling. Fully aware it's inefficient, but I wanted to do it that way too. I also appreciate the third idea that my other friend suggested, using a rotation vector and a tranlation vector to move it to the center of the circle. It's worth noting that none of these submissions actually worked. Mine and my friend's are too slow. For some reason, the accepted submissions included a math.sqrt(random.random()) function. I do not understand why, and it remains a mystery for me. This submission can be considered a failure as far as I'm concerned. """
a673eef7d991a119fd8e5ef5ba2e9c14cf657429
Laende/CRAP
/exceptions.py
2,701
3.75
4
from requests.exceptions import HTTPError class HTTP500(HTTPError): """ The Web server (running the Web Site) encountered an unexpected condition that prevented it from fulfilling the request by the client (e.g. your Web browser or our CheckUpDown robot) for access to the requested URL. """ def __str__(self): return repr('500 Internal server error') class HTTP400(HTTPError): """ Http400 Error Exception The server cannot or will not process the request due to an apparent client error e.g., malformed request syntax, invalid request message framing, or deceptive request routing). """ def __str__(self): return repr('400 Bad Request') class HTTP401(HTTPError): """ Http401 Error Exception Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource. """ def __str__(self): return repr('401 Unauthorized') class HTTP403(HTTPError): """ Http403 Error Exception The request was a valid request, but the server is refusing to respond to it. 403 error semantically means "unauthorized", i.e. the user does not have the necessary permissions for the resource. """ def __str__(self): return repr('403 Forbidden') class HTTP404(HTTPError): """ Http404 Error Exception The requested resource could not be found but may be available in the future. Subsequent response by the client are permissible. """ def __str__(self): return repr('404 not Found occurred') class HTTP405(HTTPError): """ Http405 Error Exception A request method is not supported for the requested resource; for example, a GET request on a form which requires data to be presented via POST, or a PUT request on a read-only resource. """ def __str__(self): return repr('405 Method Not Allowed') class HTTP415(HTTPError): def __str__(self): return repr('415 Wrong media type. application/json only.') class HTTP429(HTTPError): """ Http429 Error Exception The user has sent too many response in a given amount of time. Intended for use with rate limiting schemes. """ def __str__(self): return repr('429 Too Many Requests') class HTTP503(HTTPError): """ Http503 Error Exception The server is currently unavailable (because it is overloaded or down for maintenance). Generally, this is a temporary state. """ def __str__(self): return repr('503 Service Unavailable')
dcdc49a3cffc52a1f90c063d96c2a177dd63a80e
wmyles/Self_Taught_Programmer
/Self_Taught_Programmer/thatcher_hangman_test.py
2,694
4.125
4
#hangman game def hangman(word):# function accepts variable name word as param wrong=0 # amount of wrong characters thy guessed stages=["", # list filled with strings use to draw hanman, when we print this it will appear "________ ", "| ", "| | ", "| O ", "| /|\ ", "| / \ " ] rletters=list(word)# list containg each character in variable word that keeps track of letters to be guessed board=["_"]* len(word)# list of strings used to keep track of the hins you display to player two Win=False #^so an underscore for every letter print("Welcome to Hangman") while wrong < len(stages)-1 : #saying that hangman drawing is not made(remember that we subtract 1 because wrong starts counting from 1 but index starts from 0) #when wrong is more than STRINGS in hangman game is over we subtract one because of below/propertis of lists print("\n") #stage lists count from zero its a list so u have to compnesate while wrong starts from 0 msg="guess a letter"#above prints a blank space char=input(msg) if char in rletters:#if guess is charact we need to update list cind=rletters.index(char)# use index method to get first index of the letter player two guessed board[cind]=char# use the index returned by method above and set it equal to the guess to have the board be updated rletters[cind]='$' # index only returns the first index in which the letter occurs #thus if letter appears twice it wont work because itll stop at first # get around this by replacing that letter with a dollar sign so it wont be read/recongized print("rletters:{0}".format(rletters)) else: wrong+=1 print((" ".join(board))) #print the scoreboard counter=wrong + 1 print("\n".join(stages[0:counter])) #printing hangman is tricky "\n" is blank space, so joining stages pritns the entire hangman #however, we need to slice it to the point in which the game is now # we can use variable e that we set to wrong, wrong is where we are at in the game # we add one to wrong because the end slice does not get included in the result if "_" not in board: # if no underscores then the game is won! print("you win!") print(" ".join(board)) Win=True break if not Win: print("\n".join(stages[0: wrong])) #print the full hangman print("you lose! it was {}.".format(word)) #use format to input word that was not gessed hangman("caat")
1340c3e85a45be839e58d68c372a829d03b3f465
HieweiDu/Algorithms-
/bubbleSort.py
187
3.859375
4
def bubbleSort(arr): for i in range(1,len(arr)): for j in range(0,len(arr-1)): if arr(j)>arr(j-1): arr(j),arr(j-1)= arr(j-1),arr(j) return arR
18bc6d2e162a5a0b27f4010c08ea58e4015188ce
paulruvolo/SoftwareDesign
/inclass18/problem_1_tests.py
421
3.65625
4
# -*- coding: utf-8 -*- """ Created on Thu Apr 3 10:40:40 2014 @author: pruvolo """ import unittest def sum_squares_even(n): # TODO: need to write this code!!! return True class SumSquaresEvenTests(unittest.TestCase): def test_sum_squares_even_basic(self): self.assertEqual(sum_squares_even(10),220) self.assertEqual(sum_squares_even(5),20) if __name__ == '__main__': unittest.main()
43aa57d98a1a699a4c4aad96cea9adec209263af
Loweg/k-means-python
/k_means.py
3,763
3.640625
4
import random import numpy import operator import csv #import matplotlib.pyplot as plt #import matplotlib.cm as cm dataset = "wine.data" n_means = 3 #the amount of clusters means = [] #list containing n_means amount of Mean objects n_samples = 50 #amount of random test data points #no need to change this if you are using real data samples = [] #list of all samples data_dimensions = 14 #the amount of dimensions the data has #Change manually for now if you get an error, the message will tell you how many dim's the data is n_iters = 0 #Which iteration the program is on, for debugging purposes class Mean: """object to store one mean/centroid""" def __init__(self, pos): self.pos = pos self.points = [] self.prev_points = [] #to check if the algorithm has completed self.color = None def nearest_mean(x): """returns mean object closest to given point""" distances = {} #dict of mean to distance to point for mean in means: distances[mean] = numpy.linalg.norm(mean.pos - x) return min(distances.items(), key=operator.itemgetter(1))[0] def update_mean(): """assigns the means a new pos based on the centroid of its corresponding cluster""" for mean in means: mean.prev_points = mean.points for i in range(data_dimensions): try: mean.pos[i] = sum(map(lambda x: x[i], mean.points))/len(mean.points) except: print("Warning: mean has no points at itr ", n_iters) def main(): global n_iters for _ in range(n_means): m = [] #Randomly generates initial coordinates for Means for _ in range(data_dimensions): m.append(random.randint(1, 100)) means.append(Mean(numpy.array(m))) #color generation for two dimensional plotting #uncomment if plotting your two dimensional data, otherwise it will throw an error #colors = cm.rainbow(numpy.linspace(0, 1, len(means))) #for i, c in enumerate(means): # c.color: colors[i] #Samples data structure: #List containing n lists containing d integers, where n is the number of samples, and d is the number of dimensions in the data #samples = [[random.randint(1, 100), random.randint(1, 100), random.randint(1, 100)] for _ in range(n_samples)] #Randomly generate samples #Use csv to read each line of a csv file into samples[] samples = [] with open(dataset, 'rt') as f: reader = csv.reader(f) for row in reader: row = [float(i) for i in row] samples.append(row) print("Successfully generated sample list:") print(samples) fit = False while not fit: #Append each point to its closest mean for sample in samples: closest = nearest_mean(sample) closest.points.append(sample) #check to see if all the points lists have been the same for 1 itr if len([c for c in means if c.points == c.prev_points]) == n_means: fit = True update_mean() else: update_mean() n_iters += 1 for mean in means: print("mean generation finished:") print(mean.points) #plotting test for 2 dimensional data: """ for i, c in enumerate(means): plt.scatter(c.pos[0], c.pos[1], marker = 'o', color = c.color, s = 75) x_cors = [x[0] for x in c.points] y_cors = [y[1] for y in c.points] plt.scatter(x_cors, y_cors, marker = '.', color = c.color) plt.xlabel('x') plt.ylabel('y') title = 'K-means' plt.title(title) plt.savefig('{}.png'.format(title)) plt.show() """ if __name__ == "__main__": main()
c3d5027503ca832ea3e9a67c13c53776639c9e3f
KarinAlbiez0910/binomial_prob_distributions
/prob_bin_gauss_distributions-0.1/prob_bin_gauss_distributions/Binomialdistribution.py
4,844
4.3125
4
import math import matplotlib.pyplot as plt from .Generaldistribution import Distribution import math import numpy as np import pandas as pd import random class Binomial(Distribution): """ Binomial distribution class for calculating and visualizing a Binomial distribution. Attributes: mean (float) representing the mean value of the distribution stdev (float) representing the standard deviation of the distribution data_list (list of floats) a list of floats to be extracted from the data file p (float) representing the probability of an event occurring n (int) the total number of trial """ def __init__(self, prob=1, size=1): self.p = prob self.n = size self.data = [] def calculate_mean(self): """Function to calculate the mean from p and n Args: None Returns: float: mean of the data set """ mean = self.p * self.n self.mean = mean return self.mean def calculate_stdev(self): """Function to calculate the standard deviation from p and n. Args: None Returns: float: standard deviation of the data set """ stdev = math.sqrt(self.n * self.p * (1 - self.p)) self.stdev = stdev return self.stdev def replace_stats_with_data(self): """Function to calculate p and n from the data set Args: None Returns: float: the p value float: the n value """ self.read_data_file('numbers_binomial.txt') self.p = self.data.count(1)/len(self.data) self.n = len(self.data) self.mean = self.calculate_mean() self.stdev = self.calculate_stdev() return self.p, self.n def plot_bar(self): """Function to output a histogram of the instance variable data using matplotlib pyplot library. Args: None Returns: None """ data = pd.Series(self.data) counts = data.value_counts() plt.bar(x=counts.index, height=counts.values) plt.xticks(counts.index) plt.xlabel('Zero or One') plt.ylabel('Frequency') plt.title('Zero vs. One Frequency') plt.show() def pdf(self, k): """Probability density function calculator for the binomial distribution. Args: k (float): point for calculating the probability density function Returns: float: probability density function output """ return math.factorial(self.n)/(math.factorial(k)*math.factorial(self.n - k))*(self.p**k)*(1-self.p)**(self.n-k) def plot_bar_pdf(self): """Function to plot the pdf of the binomial distribution Args: None Returns: list: x values for the pdf plot list: y values for the pdf plot """ x_list = [] y_list = [] for k in range(0, n.self+1): x_list.append(k) y_list.append(self.pdf(k)) plt.bar(x=x_list, height=y_list) plt.xticks(x_list) plt.xlabel('Amount of matches') plt.ylabel('Probability for amount of matches') plt.title('Amount of matches and their probabilities') plt.show() return x_list, y_list def __add__(self, other): """Function to add together two Binomial distributions with equal p Args: other (Binomial): Binomial instance Returns: Binomial: Binomial distribution """ try: assert self.p == other.p, 'p values are not equal' binomial_result = Binomial() binomial_result.n = self.n + other.n binomial_result.p = other.p binomial_result.calculate_mean() binomial_result.calculate_stdev() except AssertionError as error: raise return binomial_result def __repr__(self): """Function to output the characteristics of the Binomial instance Args: None Returns: string: characteristics of the Gaussian """ return f'mean {self.mean}, standard deviation {self.stdev}, p {self.p}, n {self.n}'
565e5c703c02740032585fd3a07730fa665443d6
Anisha-Karmacharya/Movie-Management-System
/Codes/display_list.py
637
3.796875
4
#to display the list of movie available to customer def display_list(details): # creating function to display list print("------------------------------------------------------------------------------") print("Movie ID\tName of Movies\t\t\tPrice\t\t\tquantity") #Displays the given heading print("==============================================================================") for m in details: print(m[0],"\t\t",m[1],"\t\t\t",m[2],"\t\t\t",m[3]) #Displays the respective data from index print('\n') print("------------------------------------------------------------------------------")
c9b6a48d109543fa7955b60a4cb7004055977cb6
KjetilSekseKristiansen/Robotic-vision
/Assignment5/python/common1.py
1,559
3.515625
4
import numpy as np from scipy.ndimage import gaussian_filter import math from math import pi from math import exp import matplotlib.pyplot as plt # Task 1a def central_difference(I): """ Computes the gradient in the u and v direction using a central difference filter, and returns the resulting gradient images (Iu, Iv) and the gradient magnitude Im. """ k = np.array([0.5, 0, -0.5]) [x,y] = np.shape(I) Iu = np.zeros_like(I) Iv = np.zeros_like(I) for i in range(0,y): Iv[:,i] = np.convolve(k,I[:,i], 'same') for i in range(0, x): Iu[i,:] = np.convolve(k, I[i,:], 'same') Im = np.zeros_like(I) for i in range(0,x): for j in range(0,y): Im[i,j] = np.sqrt(Iv[i,j]**2+Iu[i,j]**2) print(np.shape(Iu)) return Iu, Iv, Im # Task 1b def blur(I, sigma): return gaussian_filter(I, sigma) def extract_edges(Iu, Iv, Im, threshold): """ Returns the u and v coordinates of pixels whose gradient magnitude is greater than the threshold. """ # This is an acceptable solution for the task (you don't # need to do anything here). However, it results in thick # edges. If you want better results you can try to replace # this with a thinning algorithm as described in the text. v,u = np.nonzero(Im > threshold) theta = np.arctan2(Iv[v,u], Iu[v,u]) return u, v, theta def rgb2gray(I): """ Converts a red-green-blue (RGB) image to grayscale brightness. """ return 0.2989*I[:,:,0] + 0.5870*I[:,:,1] + 0.1140*I[:,:,2]
0833bebf14d331684271e6cf81b8a10a75f3cdfc
s1effen/AdventOfCode
/Day19/day19.py
3,344
3.5625
4
import re grid = [] symbol = '#' with open("input.txt") as file: reader = file.readlines() for line in reader: row = [] for col in line.rstrip("\n"): row.append(col) grid.append(row) def printGrid(pointer): for i in range(len(grid)): row = "" for j in range(len(grid[i])): if(i == pointer[0] and j == pointer[1]): row += symbol else: row += grid[i][j] print(row) def getBounds(pointer,size,axis): if axis == 0: if(pointer[0] + size) > len(grid[0])-1: return (len(grid[0])-1-(size*2),len(grid[0])-1) elif(pointer[0] - size) < 0: return (0,(size*2)) else: return(pointer[0] - size,pointer[0] + size) else: if(pointer[1] + size) > len(grid)-1: return (len(grid)-1-size,len(grid)-1) elif(pointer[1] - size) < 0: return (0,size*2) else: return(pointer[1] - size,pointer[1] + size) def printdetailGrid(pointer,sizeHoriz,sizeVert): horBounds = getBounds(pointer,sizeHoriz,0) vertBounds = getBounds(pointer,sizeVert,1) for i in range(horBounds[0],horBounds[1]): row = "" for j in range(vertBounds[0],vertBounds[1]): if(i == pointer[0] and j == pointer[1]): row += symbol else: row += grid[i][j] print(row) def getStartCoord(): return (0,grid[0].index('|')) def getSymbol(coord): return grid[coord[0]][coord[1]] cursor = getStartCoord() direction = (1,0) #down def getNewDirection(coord,direction): directionA = (direction[1],direction[0]) checkA = (coord[0] + directionA[0], coord[1] + directionA[1]) directionB = (direction[1]*-1,direction[0]*-1) checkB = (coord[0] + directionB[0], coord[1] + directionB[1]) if getSymbol(checkA) != " ": return directionA elif getSymbol(checkB) != " ": return directionB else: return (0,0) def moveCursor(cursor,direction): cursor = (cursor[0] + direction[0],cursor[1] + direction[1]) symb = getSymbol(cursor) if symb == '+': #turn direction = getNewDirection(cursor,direction) return cursor, direction #print(cursor) #print(direction) #printGrid(cursor) #printdetailGrid(cursor,10,10) stepsToPrint = 0 letters = "" stepCount = 1 lastStepWithLetter = 0 while direction != (0,0): stepCount += 1 cursor,direction = moveCursor(cursor,direction) if(cursor[0] == 0 or cursor[1] == 0): print(letters) print(lastStepWithLetter) break if(getSymbol(cursor) == '+'): print("********************************** " + str(cursor) + ", " + str(stepCount) + " steps.") printdetailGrid(cursor,5,10) stepsToPrint = 3 else: if re.match(r"[A-Z]", getSymbol(cursor)): #Letter print("********************************** " + str(cursor) + ", " + str(stepCount) + " steps.") printdetailGrid(cursor,5,10) letters += getSymbol(cursor) lastStepWithLetter = stepCount if stepsToPrint > 0: print("********************************** " + str(cursor) + ", " + str(stepCount) + " steps.") printdetailGrid(cursor,5,10) stepsToPrint -= 1
836af4a11c5dcf800ff191ff98c0739dd14912a0
mnky9800n/data-analysis-tools
/plotting/correlation_matrix.py
891
3.8125
4
from matplotlib.pylab import pcolor def make_correlation_matrix(df, title): """ Creates a matplotlib plot of values (typically a correlation dataframe from Pandas). This plot has each value in a cell shaded on a color map for the entire matrix. The color map is by default reverse gray scale. requirements: matplotlib, pandas """ fig, ax = plt.subplots(figsize=(12,12)) pcolor(df, cmap='gray_r') plt.title(title) for n,mc in enumerate(df.values): for i,m in enumerate(mc): plt.text(n+0.35, i+0.35, str(round(m,2)), color='white', fontsize=24) plt.xticks(np.arange(0.5, 5.5, 1)) plt.yticks(np.arange(0.5, 5.5, 1)) labels = list(df.columns) # ['Video Access Fraction', 'Video Access Density', 'Course Grade', 'FMCE Pre', 'FMCE post'] ax.set_xticklabels(labels, rotation=90, fontsize=12) ax.set_yticklabels(labels, rotation=0, fontsize=12)
fabba1f6cbfcf51b26cdcc7e751a5ccde3517a2c
Heez27/AI_Edu
/Day11-class2/practice01.py
409
3.734375
4
#키보드로 정수 수치를 입력 받아 그것이 3의 배수인지 판단하세요 a = input('수를 입력하세요: ') for i in a: if i.isdigit()==0: print('정수가 아닙니다. ') break else: if int(a)%3 == 0: print('3의 배수입니다.') break else: print('3의 배수가 아닙니다. ') break
d1b403dd2f9f65329ad856140adcf69984741ac1
heronghua008/heronghuanotebook
/pythonNET/pythonNET06/day6/process2.py
534
3.640625
4
from multiprocessing import Process from time import sleep def worker(sec,name): for i in range(3): sleep(sec) print("I'm %s"%name) print("I'm working.....") #通过args给函数传参 #通过kwargs给函数传参 p = Process(name = "Worker",target = worker,args = (2,),\ kwargs = {'name':'Levi'}) p.start() #判断进程状态 print("is alive :",p.is_alive()) #进程名 print("process name:",p.name) #子进程PID print("process PID:",p.pid) p.join() print("=====Process over========")
9c1f6ace1e0c0727cc6c05c990c51fdb0326972b
yshshadow/Leetcode
/1-50/24.py
1,236
4.09375
4
# Given a linked list, swap every two adjacent nodes and return its head. # # Example: # # Given 1->2->3->4, you should return the list as 2->1->4->3. # Note: # # Your algorithm should use only constant extra space. # You may not modify the values in the list's nodes, only nodes itself may be changed. # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return None if not head.next: return head node, fast, slow = ListNode(-1), head.next, head node.next = slow res = node while slow and fast: # swap slow.next = fast.next fast.next = slow node.next = fast node = slow slow = slow.next if slow: fast = slow.next return res.next s = Solution() head = ListNode(1) head.next = ListNode(2) head.next.next = ListNode(3) head.next.next.next = ListNode(4) # head.next.next.next.next = ListNode(5) print(s.swapPairs(head).val)
b5c909b17afabb6bb933c50aa2b7104c70120b12
xErik444x/apuntesPython
/codes/Parte1/for/ForConElse.py
241
4.0625
4
#cuando el for llegue a 4, este va a ir al else for i in range(5): print(i) else: print("else:", i) #En este caso no va a pasar por el for y va directo al else i = 111 for i in range(2, 1): print(i) else: print("else:", i)
c8389e7fd94ca1697f8afdf022a024cc456d2550
syurskyi/Python_Topics
/045_functions/_exercises/templates/The_Modern_Python_3_Bootcamp/Coding Exercise 40 Yell Function Exercise.py
349
4.0625
4
# Using string concatenation: def yell(word): return word.upper() + "!" # Using the string format() method: def yell(word): return "{}!".format(word.upper()) # Using an f-string. My personal favorite, but only works in python 3.6 or later. # Udemy exercises don't support it currently :( def yell(word): return f"{word.upper()}!"
4205353427a2abc1b8b6caa7eab1041fc08e355b
arsezzy/python_base
/lesson7/lesson7_2.py
713
4
4
#!/usr/bin/python3 from abc import ABC, abstractmethod class Clother(ABC): @abstractmethod def get_consumption(self): pass class Coat(Clother): def __init__(self, param): self.size = param @property def get_consumption(self): return round(self.size / 6.5 + 0.5, 2) class Suit(Clother): def __init__(self, param): self.height = param @property def get_consumption(self): return 2 * self.height + 0.3 coat1 = Coat(13) print(f"coat1 size is {coat1.size}") print(f"consumtion for coat1 is {coat1.get_consumption}") suit1 = Suit(170) print(f"suit1 height is {suit1.height}") print(f"consumtions for suit1 is {suit1.get_consumption}")
ebf48ccde070e1e25a5ff9dfa817cda34cc6ac52
daniel-reich/turbo-robot
/nqNWZ7ayzZoRMZu8Z_13.py
614
4.15625
4
""" Create a function that takes a list of dictionary like `{ name: "John", notes: [3, 5, 4]}` and returns a list of dictionary like `{ name: "John", avgNote: 4 }`. If student has no notes (an empty array) then `avgNote` is zero. ### Examples [ { name: "John", notes: [3, 5, 4]} ] ➞ [ { name: "John", avgNote: 4 } ] ### Notes Round the `avgNote` to a whole number. """ def avg_note(stud): for x in stud: if x['notes']: x.update({'avgNote': round(sum(x['notes']) / len(x['notes']))}) else: x.update({'avgNote': 0}) [x.pop('notes') for x in stud] return stud
46a3f6676a443ba1f48c35aac4d7f12cfb52c69a
Filippos-Filippidis/Udacity_IntroToProgramming
/stage-3/media.py
1,005
3.53125
4
import webbrowser # webbrowser module provides a high-level # interface to allow displaying Web-based documents to users class Movie(): def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube, rating_image_url): """ Initialize the movie instance. Arguments: title: title of the movie storyline: story of the movie poster_image: movie poster trailer: movie trailer rating: movie rating ... Returns: None """ self.title = movie_title self.storyline = movie_storyline self.poster_image_url = poster_image self.trailer_youtube_url = trailer_youtube self.rating_image_url = rating_image_url def show_trailer(self): """ Function to play trailer in a web browser. Returns: None """ # Display url using the default browser webbrowser.open(self.trailer_youtube_url)
c2b98e19905a2b84e33b7ca344ef922415cfc80b
sens8tion/skaf-py-contrast
/hello.py
149
3.609375
4
import time from datetime import datetime while True: print("Hello why does this take so change 8") print(datetime.now()) time.sleep(1)
2fa98b5fa1e571062178c2976c3e2e98bfa80b07
sammysamsamsama/DATA1401-Spring-2020
/Labs/Lab-3/TicTacToe.py
2,819
3.875
4
# Write you solution here empty = 0 player_1 = 1 player_2 = 2 players = {0: " ", 1: "X", 2: "O"} def make_game_board(n=3): return [[empty] * n for i in range(n)] # return 1 if p1 wins # return 2 if p2 wins # return 0 if game not finished # return -1 if draw def check_game_finished(board): board_wins = [row for row in board] board_wins += [list(row) for row in zip(*board)] board_wins += [[board[i][i] for i in range(len(board))]] board_wins += [[board[len(board) - 1 - i][i] for i in range(len(board))]] if [1] * len(board) in board_wins: return 1 elif [2] * len(board) in board_wins: return 2 elif True in [board[i][j] == 0 for i in range(len(board)) for j in range(len(board))]: return 0 else: return -1 alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def draw_game_board(board): top = " " for col in range(1, len(board) + 1): top += " " + str(col) + " " print(top) r = 0 for row in board: line_1 = " " line_2 = alphabet[r] + " " r += 1 for col in row: line_1 += " ---" line_2 += "| " + players[col] + " " line_2 += "|" print(line_1) print(line_2) print(" " + " ---" * len(board)) def _move(board, player, coordinates): x, y = coordinates if board[x][y] == 0: board[x][y] = player return True else: return False def move(board, player, location): row = alphabet.find(location[0]) col = int(location[1:]) - 1 if board[row][col] == 0: _move(board, player, (row, col)) return True else: print("Cannot put " + players[player] + " at location " + location) return False def player_move(board, player): location = "A1" while True: draw_game_board(board) location = input("Place " + players[player] + " at: ").upper() if location[0] in alphabet and alphabet.find(location[0]) < len(board) and location[1:].isnumeric() and 0 < int( location[1:]) <= len(board) <= 26: break else: print("Invalid location. Try again.") if move(board, player, location): return True else: return player_move(board, player) def tic_tac_toe(): while True: board = make_game_board() current_player = True while check_game_finished(board) == 0: if current_player: player_move(board, 1) else: player_move(board, 2) current_player = not current_player result = check_game_finished(board) draw_game_board(board) print("It's a draw!" if result == -1 else ("Player 1 wins!" if result == 1 else "Player 2 wins!")) tic_tac_toe()
304090ff320636915ad091ab487c678d0571a5e0
tapanprakasht/Simple-Python-Programs
/pgm13.py
104
3.84375
4
n=int(input("Enter a number:") for i in range(n): for j in range(i): print(j)
5428cab7624f1872514a195c35e58589d97d6bf5
kartikeychoudhary/competitive_programming
/hackerrank/problem_solving/strings/caesar_cipher.py
884
3.5625
4
#!/bin/python3 import math import os import random import re import sys # Complete the caesarCipher function below. arr = list(map(chr, range(ord('A'), ord('Z')+1))) arr2 = list(map(chr, range(ord('a'), ord('z')+1))) def caesarCipher(s, k): s = list(s) for i in range(len(s)): if s[i] in arr: value = arr.index(s[i]) + k % 26 if value >= 26: value -= 26 s[i] = arr[value] elif s[i] in arr2: value = arr2.index(s[i]) + k % 26 if value >= 26: value -= 26 s[i] = arr2[value] temp = "" for i in s: temp+=i return temp if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) s = input() k = int(input()) result = caesarCipher(s, k) fptr.write(result + '\n') fptr.close()
726fb8172ba799874ee257a89e03744391ff9984
lorenzocastillo/Algos-and-DS
/SystemDesign/Sudoku.py
6,568
3.890625
4
""" Sudoku Solver based on Peter Norvig's implementation: http://norvig.com/sudoku.html """ from collections import namedtuple class Validator: """ Takes in a Sudoku Board object, and determines whether board has a valid Sudoku Solution """ def __init__(self, board): self.board = board.board self.ROWS = board.ROWS self.COLS = board.COLS self.subs = board.subs def is_row_valid(self, row): return len({num for num in self.board[row]}) == self.ROWS def is_col_valid(self, col): return len({row[col] for row in self.board}) == self.COLS def is_sub_matrix_valid(self, start, end): start_row, start_col = start end_row, end_col = end vals = set() for i in range(start_row, end_row): for j in range(start_col, end_col): val = self.board[i][j] if val in vals: return False vals.add(val) return True def is_valid(self): for i in range(self.ROWS): valid = self.is_row_valid(i) if not valid: return False for j in range(self.COLS): valid = self.is_col_valid(j) if not valid: return False for start,end in self.subs: valid = self.is_sub_matrix_valid(start, end) if not valid: return False return True class Board: Submatrix = namedtuple("Submatrix", 'start end') def __init__(self, input_board): self.board = list() self.ROWS = 9 self.COLS = 9 self.DIGITS = '123456789' def initialize_board(): cell = iter(input_board) for i in range(self.ROWS): self.board.append(list()) for j in range(self.COLS): self.board[i].append(next(cell)) initialize_board() def create_submatrices(): self.subs = list() for i in range(0, self.ROWS, 3): for j in range(0, self.COLS, 3): self.subs.append(self.Submatrix(start=(i, j), end=(i + 2, j + 2))) create_submatrices() def make_unit_list(): """ Determines which squares belong to the same units (i.e same cols, same rows and same submatrices :return: """ same_rows = list() for r in range(self.ROWS): row = list() for c in range(self.COLS): row.append((r,c)) same_rows.append(row) same_cols = list() for c in range(self.COLS): col = list() for r in range(self.ROWS): col.append((r, c)) same_cols.append(col) same_subs = list() for sub in self.subs: subs = list() for r in range(sub.start[0], sub.end[0] + 1): for c in range(sub.start[1], sub.end[1] + 1): subs.append((r,c)) same_subs.append(subs) return same_rows + same_cols + same_subs unit_list = make_unit_list() self.squares = [(r, c) for r in range(self.ROWS) for c in range(self.COLS)] # creates map from square to a list of its units self.units = {s: [u for u in unit_list if s in u] for s in self.squares} # removes duplicate units and itself from its peers list # first it flattens the list, then makes it into a set to remove duplicates, and then it removes itself self.peers = {s: set(sum(self.units[s], list())) - set([s]) for s in self.squares} def search(self, values): if values is False: return False elif all(len(values[s]) == 1 for s in self.squares): return values else: n, s = min((len(values[s]), s) for s in self.squares if len(values[s]) > 1) return self.some(self.search(self.assign(values.copy(), s, d)) for d in values[s]) def some(self, seq): for e in seq: if e: return e return False def solve(self): squares = self.squares values = {s: self.DIGITS for s in squares} for s in squares: d = self.board[s[0]][s[1]] if d in self.DIGITS and not self.assign(values, s, d): return False return self.search(values) def assign(self, values, square, digit): others = values[square].replace(digit, '') if all(self.eliminate(values, square, d2) for d2 in others): return values else: return False def eliminate(self, values, square, digit): if digit not in values[square]: return values values[square] = values[square].replace(digit, '') if len(values[square]) == 0: return False elif len(values[square]) == 1: d2 = values[square] self.board[square[0]][square[1]] = d2 if not all(self.eliminate(values, peer, d2) for peer in self.peers[square]): return False for unit in self.units[square]: dplaces = [s for s in unit if digit in values[s]] if len(dplaces) == 0: return False elif len(dplaces) == 1: if not self.assign(values, dplaces[0], digit): return False return values def __repr__(self): result = list() result.append('\n') for i, row in enumerate(self.board, 1): for j, num in enumerate(row, 1): result.append(str(num)) if j % 3 == 0 and j != len(self.board): result.append("|") result.append("\n") if i % 3 == 0 and i != len(self.board): result.append("-"*22) result.append("\n") return " ".join(result) def test(): # Easy Board board = Board("""4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......""") board.solve() validator = Validator(board) assert validator.is_valid() # Hard board board = Board("""003020600900305001001806400008102900700000008006708200002609500800203009005010300""".replace('0','.')) board.solve() validator = Validator(board) assert validator.is_valid() print("Success") if __name__ == '__main__': test()
067cd50838dfc3eb1ab35635be181a2930bf4aec
sarzz2/codewars-kata
/Sum of mixed array.py
277
3.859375
4
def sum_mix(arr): print(arr) ans = 0 for i in range(0, len(arr)): arr[i] = int(arr[i]) # changing all elements in a list to an integer ans = ans + arr[i] return ans sum_mix([1,"1","2"]) # passing numbers in the function
7ef910140a9d2f63ef34668f89c8462a3792b35d
Joecth/leetcode_3rd_vscode
/528.random-pick-with-weight.py
4,170
3.765625
4
# # @lc app=leetcode id=528 lang=python3 # # [528] Random Pick with Weight # # https://leetcode.com/problems/random-pick-with-weight/description/ # # algorithms # Medium (43.85%) # Likes: 789 # Dislikes: 2254 # Total Accepted: 109.2K # Total Submissions: 248.7K # Testcase Example: '["Solution","pickIndex"]\r\n[[[1]],[]]\r' # # Given an array w of positive integers, where w[i] describes the weight of # index i(0-indexed), write a function pickIndex which randomly picks an index # in proportion to its weight. # # For example, given an input list of values w = [2, 8], when we pick up a # number out of it, the chance is that 8 times out of 10 we should pick the # number 1 as the answer since it's the second element of the array (w[1] = # 8). # # # Example 1: # # # Input # ["Solution","pickIndex"] # [[[1]],[]] # Output # [null,0] # # Explanation # Solution solution = new Solution([1]); # solution.pickIndex(); // return 0. Since there is only one single element on # the array the only option is to return the first element. # # # Example 2: # # # Input # ["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"] # [[[1,3]],[],[],[],[],[]] # Output # [null,1,1,1,1,0] # # Explanation # Solution solution = new Solution([1, 3]); # solution.pickIndex(); // return 1. It's returning the second element (index = # 1) that has probability of 3/4. # solution.pickIndex(); // return 1 # solution.pickIndex(); // return 1 # solution.pickIndex(); // return 1 # solution.pickIndex(); // return 0. It's returning the first element (index = # 0) that has probability of 1/4. # # Since this is a randomization problem, multiple answers are allowed so the # following outputs can be considered correct : # [null,1,1,1,1,0] # [null,1,1,1,1,1] # [null,1,1,1,0,0] # [null,1,1,1,0,1] # [null,1,0,1,0,0] # ...... # and so on. # # # # Constraints: # # # 1 <= w.length <= 10000 # 1 <= w[i] <= 10^5 # pickIndex will be called at most 10000 times. # # # # @lc code=start from bisect import bisect_right from random import random, randint class Solution: def __init__(self, w: List[int]): """ :type w: List[int] """ self.prefix_sums = [] prefix_sum = 0 for weight in w: prefix_sum += weight self.prefix_sums.append(prefix_sum) self.total_sum = prefix_sum def pickIndex(self) -> int: """ :rtype: int """ target = self.total_sum * random() # run a binary search to find the target zone low, high = 0, len(self.prefix_sums) while low < high: mid = low + (high - low) // 2 if target > self.prefix_sums[mid]: low = mid + 1 else: high = mid return low class Solution_failedSomeHow: def __init__(self, w: List[int]): if not w: assert(0) self.pre_sum = [0] * len(w) self.pre_sum[0] = w[0] cur_sum = 0 for i in range(1, len(w)): self.pre_sum[i] = self.pre_sum[i-1] + w[i] self.total_sum = self.pre_sum[-1] print(self.pre_sum) # print(self.pre_sum) """ 3 4 1 7 3 7 8 15 """ def pickIndex(self) -> int: # target = self.total_sum * random() # target = randint(self.pre_sum[0], self.total_sum) target = randint(1, self.total_sum) start, end = 0, len(self.pre_sum)-1 while start + 1 < end: mid = start + (end - start)//2 if self.pre_sum[mid] < target: start = mid else: end = mid if self.pre_sum[start] == target: print(target, start, end, 'return start: {}'.format(start)) return start print(target, start, end, 'return end: {}'.format(end)) return end # Your Solution object will be instantiated and called as such: # obj = Solution(w) # param_1 = obj.pickIndex() # Your Solution object will be instantiated and called as such: # obj = Solution(w) # param_1 = obj.pickIndex() # @lc code=end
54a8dd162335c39c1ddf7f726bd59b2a802f7072
horlathunbhosun/algorithms
/add-two-numbers/index.py
835
3.65625
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: remainder = 0 v1 = l1 v2 = l2 result = ListNode(0) current = result while v1 or v2: v1Val = 0 v2Val = 0 if v1: v1Val = v1.val v1 = v1.next if v2: v2Val = v2.val v2 = v2.next intSum = v1Val + v2Val + remainder remainder = intSum // 10 current.next = ListNode(intSum % 10) current = current.next if remainder > 0: current.next = ListNode(remainder) return result.next
54606d34f486593a41079c24a6e52c5b396f7bd6
clayll/zhizuobiao_python
/练习/day08/1.numpy的矢量.py
902
3.703125
4
#numpy的矢量 #矢量是指一堆数组成的集合 #标量是指单独一个数。 #多维数组也叫矢量化计算 #numpy和python执行计算的效率比较 import datetime as dt import numpy as np n = 100000 start = dt.datetime.now() #记录当前时间 A, B = [], [] for i in range(n): A.append(i**2) B.append(i**3) C = [] for a, b in zip(A,B): C.append(a + b) print(type(C)) print('python执行',(dt.datetime.now() - start).microseconds) #numpy来写 start = dt.datetime.now() C = np.arange(n)** 2 + np.arange(n)**3 print(type(C)) print('numpy执行',(dt.datetime.now() - start).microseconds) ''' 1.arange,和python的range非常相似,只是多了个a 2.arange也是产生一个连续序列,但是不是列表,而是数组。 3.两数组可直接做运算(比如:直接加减乘除) 4.numpy内部完成循环,无需类似python的for循环遍历。 '''
f2e79b3ac9d22bdfd758e70526dea93e82c1f121
sPaMFouR/DIS
/Exercises/first.py
2,449
4.21875
4
import math import sys import os # print("Hello", "World") # print("Hello", "World", sep=":") # # # Python 3 has Python Functions (Python 2 Has Print Statements) # # from __future__ import print_function (For Using Python Function In Python 2) # # # Python Is An Interpreter (Compiles Line By Line Code To A 'Byte' Code) # # # Integers Can Be Very Long In Python (Would Result In Overflow Errors In C) # # a = 32 # b = a ** 234 # # x = 45 # y = math.cos(math.pow(math.sqrt(math.radians(x)), 2.4)) # # # Complex Numbers # c = 3 + 4j # print(c ** 2) # print(c.real) # print(c.imag) # # # Syntax Error # # print('John's Computer) # # print('John\'s Computer') # print("John's Computer") # # attempt = 1 # input_value = 2.42 # final_result = 24.4242424242 # output = """ # Attempt No. %d # -------------- # Tried Input Value: %6.3f # Obtained Answer: %6.3f # """ % (attempt, input_value, final_result) # # output1 = """ # Attempt No. {0:d} # -------------- # Tried Input Value: {1:6.3f} # Obtained Answer: {2:6.3f} # """.format(attempt, input_value, final_result) # # # print(output) # print(output1) # numbers = [] # while True: # user_input = input("Enter The Number: ").lower() # if user_input != 'stop': # numbers.append(float(user_input)) # else: # break # # mean = sum(numbers) / len(numbers) # print("Mean Is {0}".format(mean)) # In Python 2, Range would directly give a list. In Python 3, Range should be requested for a list - list(range(10)) num_list = [43, 23, 12, 34] for i, num in enumerate(num_list): print(i, num) print(sys.argv) # Tuple Example t = 1, 2, 3, 4 print(type(t)) def get_mean(num1, *nums): nums = list(nums) nums.insert(0, num1) total = 0 for number in nums: total += number return total / len(nums) def highly_flexible(*args, **kwargs): print(args) print(kwargs) highly_flexible(1, 2, 3, 4, 5, name='Avinash', designation='SRF') def make_function(n): def fun(x): return x**n return fun f = make_function(3) print(f(4)) import math alist = [1, 2, 3, 4, 4] aLog10 = list(map(math.log10, alist)) print(aLog10) def filter_function(x): if x < 2: return True else: return False aSub = list(filter(filter_function, alist)) print(aSub) a = [1, 2, 4, 5] # b = a # B Just Points To The Memory Location Of A # b = a[:] # This Expression creates A New list B (Independent of Modifications In A)
6312aa8e94de363260878583df600180ab08631f
bomcon123456/DSA_Learning
/Python/Chapter 1/ex33.py
3,766
3.65625
4
import platform # For getting the operating system name import subprocess # For executing a shell command def clear_screen(): """ Clears the terminal screen. """ # Clear command as function of OS command = "cls" if platform.system().lower() == "windows" else "clear" # Action return subprocess.call(command) == 0 inputArr = { "1": "NUMBER", "2": "NUMBER", "3": "NUMBER", "4": "NUMBER", "5": "NUMBER", "6": "NUMBER", "7": "NUMBER", "8": "NUMBER", "9": "NUMBER", "+": "OPs", "-": "OPs", "*": "OPs", "/": "OPs", } def calculateChar(a, b, ops): res = 0 a = float(a) b = float(b) if ops == "+": res = a + b elif ops == "-": res = a - b elif ops == "*": res = a * b elif ops == "/": res = a / b return res globalResult = "WHAT" def setGlobal(res): global globalResult globalResult = res def calculate(arr): operators = [] numbers = [] popNext = False wasNumber = False for c in arr: if inputArr[c] == "OPs": wasNumber = False operators.append(c) if c == "*" or c == "/": popNext = True else: if wasNumber: old = numbers.pop() new = old + c numbers.append(new) else: numbers.append(c) wasNumber = True if popNext: a = numbers.pop() b = numbers.pop() op = operators.pop() new = calculateChar(b, a, op) numbers.append(new) popNext = False wasNumber = False while len(operators) > 0: op = operators.pop() if len(numbers) >= 2: a = numbers.pop() b = numbers.pop() numbers.append(calculateChar(b, a, op)) else: break res = numbers.pop() setGlobal(res) return res def calculatorInput(): currentInput = [] c = "" while c != "x": clear_screen() if globalResult == "WHAT": for c in currentInput: print(c, end=" ") print() else: print("RESULT:", globalResult) setGlobal("WHAT") print("Press 1 for input 1") print("Press 2 for input 2") print("Press 3 for input 3") print("Press 4 for input 4") print("Press 5 for input 5") print("Press 6 for input 6") print("Press 7 for input 7") print("Press 8 for input 8") print("Press 9 for input 9") print("Press + for input +") print("Press - for input -") print("Press * for input *") print("Press / for input /") print("Press = for input =") print("Press x for input EXIT") print("Press r for input RESET") print("Press d for input DELETE") c = input("Press: ") if c == "d": currentInput.pop() elif c == "r": currentInput = [] elif c == "=": calculate(currentInput) currentInput = [] else: currentInput.append(c) calculatorInput() # calculate( # [ # "1", # "+", # "2", # "*", # "3", # "+", # "(", # "1", # "2", # "/", # "4", # "+", # "7", # "/", # "3", # "+", # "2", # "*", # "(", # "1", # "+", # "2", # ")", # ")", # ] # ) # calculate(["(", "1", "+", "2", ")", "*", "3", "+", "(", "1", "2", "/", "4", ")"]) # calculate(arr)
df77d66c4a626ff0daa44f9a8b2a7231a4745602
sveraecaterina/ESrep
/week9/spiral.py
287
3.609375
4
def spiral(x): sum=1 val=0 my_list=[y for y in range(1,x) if y%2==0 ] for item in my_list: for i in range(1,5): sum+=1+i*(item)+val i+=1 val+=4*(item) return print(sum) if __name__ == "__main__": x=501 spiral(x)
51501afd4094c4effe6e5e42da9eba0d6365a6bf
uoayop/study.algorithm
/programmers/42583.py
3,249
3.75
4
# from collections import deque # def solution(bridge_length, weight, truck_weights): # answer = 0 # ing_truck = deque() # ing_weight = 0 # truck_count = len(truck_weights) # count = 0 # while 1: # if (count == truck_count): # break # if (truck_count==1): # return bridge_length+1 # #트럭 하나 꺼냄 # if (truck_weights): # truck = truck_weights.pop(0) # ing_truck.append(truck) # ing_weight += truck # #print('[다리 건너기 전] {0}:{1} / {2}:{3}\n'.format("ing_truck",ing_truck,"ing_weight",ing_weight)) # #다리를 건너는 동안 # for i in range(bridge_length): # #만약 건너고 있는 트럭의 무게가 한계보다 가벼우면 트럭 하나 더 꺼냄 # if (ing_weight <= weight and truck_weights): # truck = truck_weights.pop(0) # ing_truck.append(truck) # ing_weight += truck # if (ing_weight > weight): # ing_truck.pop() # ing_weight -= truck # truck_weights.insert(0,truck) # #print('[ing_weight가 더 크면] {2} - {0}:{1} / {3}:{4}'.format("ing_weight",ing_weight,i+1,"answer",answer)) # print('[다리 건너는 중] {4} - {0}:{1} / {2}:{3} / {5}:{6}'.format("ing_truck",ing_truck,"ing_weight",ing_weight,i+1,"answer",answer)) # answer += 1 # #다리를 건넌 트럭은 빼줌 # end_truck = ing_truck.popleft() # ing_weight -= end_truck # count += 1 # #print('\n[다리 다건넘] {0}:{1} / {2}:{3} / {4}:{5}\n-----------------\n'.format("ing_truck",ing_truck,"ing_weight",ing_weight,"answer",answer)) # return answer # # bridge_length/ weight/ truck_weights # print(solution(2, 10, [7, 4, 5, 6])) # print(solution(100, 100, [10])) # print(solution(100, 100, [10, 10, 10, 10, 10, 10, 10, 10, 10, 10])) #다리를 건너는 트럭 from collections import deque def solution(bridge_length, weight, truck_weights): answer = 0 ing_truck = [0] * bridge_length #다리 위에 있는 트럭을 나타내는 리스트 : ing_truck while len(ing_truck)!=0: #다리에 있는 트럭의 개수가 0이 될때까지 반복 answer+=1 ing_truck.pop(0) #첫번째 요소 pop 해서 한칸씩 이동하기 # 대기 중인 트럭이 존재하면 : truck_weight if (truck_weights): if (sum(ing_truck) + truck_weights[0] <= weight): # (다리 위에 있는 트럭 무게 + 대기중인 첫번째 트럭 무게)가 다리의 한계보다 작으면 ing_truck.append(truck_weights.pop(0)) # 대기중인 트럭 pop 해서 다리위에 올려주기 else: #다리의 한계보다 크면 0을 삽입해서 대기하기 ing_truck.append(0) return answer # bridge_length/ weight/ truck_weights print(solution(5, 5, [2, 2, 2, 1, 1, 1, 1, 1])) # print(solution(2, 10, [7, 4, 5, 6])) # print(solution(100, 100, [10])) # print(solution(100, 100, [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]))
a556b77cafbfaae85f22141f89d4fa0ea21df944
pezaantonio/ticketalerts
/disneyWeb.py
3,618
3.625
4
# Anthony Peza # Python Programming # Disney Web # # The purpose of this program is alert me when disney tickets go on sale # import json import time import smtplib from bs4 import BeautifulSoup as soup from urllib.request import urlopen as uReq # Global Variables # disneyUrl = "https://disneyland.disney.go.com/events-tours/disneyland/after-dark-star-wars-nite/" isRepeating = True x = 0 # Functions # def webCheck(): global firstCheck print("Conducting first check\n") # This first reference is opening the connection to the disney website and grabbing the page disneyWebsiteClient = uReq(disneyUrl) # This second function is reading it pageHTML = disneyWebsiteClient.read() # This third function is closing the connection when I'm done disneyWebsiteClient.close() # This is now storing the information from pageHTML into a disneyPageSoup and parsing using the html parser disneyPageSoup = soup(pageHTML, "html.parser") # disneyPageSoup.find is looking for divs in the html and returning the "id" for everything in that div firstCheck = disneyPageSoup.find("h2") print("First check complete\nFirst check saved") def updateWebCheck(): global secondCheck print("\nConducting second check\n") # This first reference is opening the connection to the disney website and grabbing the page disneyWebsiteClientSecondAttempt = uReq(disneyUrl) # This second function is reading it secondPageHTML = disneyWebsiteClientSecondAttempt.read() # This third function is closing the connection when I'm done disneyWebsiteClientSecondAttempt.close() # This is now storing the information from pageHTML into a disneyPageSoup and parsing using the html parser disneyPageSoupSecondCheck = soup(secondPageHTML, "html.parser") # disneyPageSoup.find is looking for divs in the html and returning the "id" for everything in that div secondCheck = disneyPageSoupSecondCheck.find("h2") print("Second check complete\nSecond check saved\n") def sendEmail(): global disneyUrl with open("pw.json") as email: data = json.load(email) email = data['Email'] key = data['key'] msg = \ ( """ Subject: Disney automated alert\n\n Disney after dark, star wars nite tickets are on sale! Follow this link: https://disneyland.disney.go.com/events-tours/after-dark/?ef_id=Cj0KCQiAvc_xBRCYARIsAC5QT9mEKZQsw_mSfXcLzKOzoq2-Xp4jr5mRaohcdxEWLer0JEgT512UGWQaAjfqEALw_wcB:G:s&s_kwcid=AL!5054!3!398544259080!e!!g!!disneyland%20after%20dark%20tickets&CMP=KNC-FY20_DLR_ACT_LOC_L365AB_SCP_DLAD_Events_EXACT|G|5202059.DL.AM.01.02|MOK33LW|BR|398544259080&keyword_id=aud-687740961259:kwd-432464433963|dc|disneyland%20after%20dark%20tickets|398544259080|e|5054:3|&gclid=Cj0KCQiAvc_xBRCYARIsAC5QT9mEKZQsw_mSfXcLzKOzoq2-Xp4jr5mRaohcdxEWLer0JEgT512UGWQaAjfqEALw_wcB """ ) fromEmail = email toEmail = "axpeza@gmail.com" server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(fromEmail, key) server.sendmail(fromEmail, toEmail, msg) server.quit print("email sent") def checkCounter(): global x x += 1 countMessage = "\nTimes checked: " + str(x) print(countMessage) # Main Function # webCheck() while isRepeating: updateWebCheck() print("Checking pages...") if firstCheck == secondCheck: print("Checking again in 15 minutes") checkCounter() time.sleep(900) else: sendEmail() isRepeating = False
4797efdbe4ce004219a028030f5b8ce397366257
MerinGeorge1987/PES_PYTHON_Assignment_SET-3
/ass3Q54.py
1,071
4.15625
4
#!/usr/bin/python #Title: Assignment3---Question54 #Author:Merin #Version:1 #DateTime:03/12/2018 3:00pm #Summary:Write a program to handle the following exceptions in you program. # a) KeyboardInterrupt # b) NameError # c) ArithmeticError # Note: Make use of try, except, else: block statements. try: x = int(input("Enter any first number : ")) y = int(input("Enter any second number : ")) print ("The values given are ", x,y) res = x/y print ("The result of two divided numbers are ", res) # a) KeyboardInterrupt except KeyboardInterrupt: print("W: interrupt received, stopping....") # b) NameError except NameError: print ("You are trying to access a label which is not defined") # c) ArithmeticError except ArithmeticError: print ('This is an example of catching ArithmeticError') else: print ("Else: execute only if the error is not thrown in program") finally: print ("Finally: I will be executed all the times, irrespective of error thrown or not")
a29c8b3c479f55feabba716c906a53a20c0ca6a3
jinsuupark/chapter07
/ex07-02.py
1,562
3.828125
4
def intsum(*ints): total = 0 for num in ints: total += num return total # print(intsum(1,2,3)) # print(intsum(5,7,9,11,13)) # print(intsum(8, 9, 6, 2, 9, 1,5,7)) # 인수의 기본값 # calcstep( begin=1,end,step=1) 안된다 인수 초기화는 뒤에서부터 def calcstep(begin, end, step=1): total = 0 for num in range(begin, end + 1, step): total += num return total print("1 ~ 10 =", calcstep(1, 10, 2)) print("2 ~ 10 =", calcstep(1, 100)) def kim(): temp = "김과장의 함수" print(temp) def lee(): temp = 2**10 return temp def park(a): temp = a*2 print(temp) kim() print(lee()) park(10) #전역변수 salerate = 0.9 def kim(): print("오늘의 할인율 :", salerate) def lee(): price = 1000 print("가격:",price*salerate) kim() salerate = 1.1 lee() price = 1000 def sale(): global price price = 500 sale() print(price) ###################################### def calcsum(n): ''' 1~n까지의 합계를 구해 리턴한다 ''' total=0 for i in range(n+1): total += i return total help(calcsum) def findMin(*ints): min = ints[0] for i in ints: print(i) if min >= i: min = i # else: # pass return min def findMax(*ints): max=-ints[0] for i in ints: if max <= i: max = i return max min = findMin(5, 6, 4, -15, 7, -1, 2, 1) max = findMax(5, 6, 4, -15, 7, -1, 2, 1) print("최소값은",min) print("최대값은",max)
fa4686dc1117020d816cd725749123ce43d11778
FoxGriVer/PythonLabs
/lab2/leap.py
886
4.09375
4
def checkLeapYear(inputYear): if((inputYear % 4) != 0): print("{0} is not a leap year".format(inputYear)) elif ((inputYear % 100) == 0): if((inputYear % 400) == 0): print("{0} is a leap year".format(inputYear)) else: print("{0} is not a leap year".format(inputYear)) else: print("{0} is a leap year".format(inputYear)) def enterIntValue(): value = None while (type(value) is not int) or (value < 0): try: value = int(input("Enter a year A.D.(positive int value): ")) if(value < 0): raise Exception("Entered value is not positive") else: return value except ValueError: print("Entered value is not int") except Exception as e: print(e) year = enterIntValue() checkLeapYear(year)
677e7b6a91ba901fb4216661fa531c503522ad8d
sbasu7241/cryptopals
/Set1/Challenge8.py
1,066
3.84375
4
#!/usr/bin/env/python import base64 def count_repetitions(cipher_text,block_size): """"Breaks the ciphertext into block_size sized chunks and counts the no of repetitions.Returns the ciphertext and repetitions as a dictionary""" chunks = [] for i in range(0,len(cipher_text),block_size): chunks.append(cipher_text[i:i+block_size]) number_of_repetitions = len(chunks) - len(set(chunks)) result = { 'ciphertext':cipher_text, 'repetitions':number_of_repetitions } return result def main(): ciphertext = [] with open('chall_8_input.txt','r') as fil: for line in fil.readlines(): ciphertext.append(bytes.fromhex(line.strip())) block_size = 16 #for cipher in ciphertext: # print(cipher) repetitions = [count_repetitions(cipher,block_size) for cipher in ciphertext] most_repeat = sorted(repetitions,key=lambda x: x['repetitions'],reverse=True)[0] print("[+] Cipher text >> "+str(most_repeat['ciphertext'])) print("[+] No of repeating blocks >> "+str(most_repeat['repetitions'])) if __name__=="__main__": main()
eb627822fb8a4adf54c20dcce1ef7720ce77ca83
saravyas/saravyas
/PycharmProjects/sara/eh1.py
273
4.125
4
import sys print "enter a number" while True : try: number = int(raw_input("number\n")) except ValueError: print "error please enter a number" continue else : break print "you entered number " , number
38822e19b6bb01ff79a8c92a99d0e4b728cd7a76
rrwt/daily-coding-challenge
/daily_problems/problem_101_to_200/problem_101.py
1,262
4.25
4
""" Given an even number (greater than 2), return two prime numbers whose sum will be equal to the given number. A solution will always exist. See Goldbach’s conjecture. Example: Input: 4 Output: 2 + 2 = 4 If there are more than one solution possible, return the lexicographically smaller solution. If [a, b] is one solution with a <= b, and [c, d] is another solution with c <= d, then [a, b] < [c, d], If a < c OR a==c AND b < d. """ from typing import Tuple, List def get_prime_numbers_till(number: int, primes: List = [2, 3]) -> List[int]: # list in argument for memoization (next call will not calculate anything til the last number) for num in range(primes[-1] + 2, number, 2): for prime in primes: if num % prime == 0: break else: primes.append(num) return primes def get_prime_pair_using_primes(number: int) -> Tuple[int, int]: primes = get_prime_numbers_till(number) primes = [1] + primes prime_set = set(primes) for first in primes: if number - first in prime_set: return first, number - first if __name__ == "__main__": for _ in range(2, 101, 2): print(f"prime pairs for {_} are", get_prime_pair_using_primes(_))
68927391f12f9843d9b5fdb2ac142cb07b096441
ZR-Huang/AlgorithmsPractices
/Leetcode/每日打卡/April/887_Super_Egg_Drop.py
2,095
3.921875
4
''' You are given K eggs, and you have access to a building with N floors from 1 to N. Each egg is identical in function, and if an egg breaks, you cannot drop it again. You know that there exists a floor F with 0 <= F <= N such that any egg dropped at a floor higher than F will break, and any egg dropped at or below floor F will not break. Each move, you may take an egg (if you have an unbroken one) and drop it from any floor X (with 1 <= X <= N). Your goal is to know with certainty what the value of F is. What is the minimum number of moves that you need to know with certainty what F is, regardless of the initial value of F? Example 1: Input: K = 1, N = 2 Output: 2 Explanation: Drop the egg from floor 1. If it breaks, we know with certainty that F = 0. Otherwise, drop the egg from floor 2. If it breaks, we know with certainty that F = 1. If it didn't break, then we know with certainty F = 2. Hence, we needed 2 moves in the worst case to know what F is with certainty. Example 2: Input: K = 2, N = 6 Output: 3 Example 3: Input: K = 3, N = 14 Output: 4 Note: 1 <= K <= 100 1 <= N <= 10000 ''' class Solution: def superEggDrop(self, K: int, N: int) -> int: memo = {} def dp(k, n): if (k, n) not in memo: if n == 0: ans = 0 elif k == 1: ans = n else: lo, hi = 1, n # keep a gap of 2 X values to manually check later while lo + 1 < hi: x = (lo + hi) // 2 t1 = dp(k-1, x-1) t2 = dp(k, n-x) if t1 < t2: lo = x elif t1 > t2: hi = x else: lo = hi = x ans = 1 + min(max(dp(k-1, x-1), dp(k, n-x)) for x in (lo, hi)) memo[k, n] = ans return memo[k, n] return dp(K, N)
e642e502ec84a9b405f1fda5f5c151025db3c291
laihoward/leetcode_practice
/Dynamic-Programming/Climbing_Stairs.py
280
3.640625
4
class Solution(object): def climbStairs(self, n): fib_list=[1,2] if n<=2: return fib_list[n-1] for i in range(n-2): fib_list.append(fib_list[-1]+fib_list[-2]) print(fib_list) return fib_list[-1]
7a4ab3a8183b899792b6a8fb6dfa37ac3cd07be2
saa419/LPTHW
/ex33.py
455
4
4
#i = 0 #numbers = [] def whiloop(endnum, increm): i = 0 numbers = [] while i < endnum: print "At the top i is %d" % i numbers.append(i) i = i + increm print "Numbers now: ", numbers print "At the bottom i is %d" % i return numbers endnum = int(raw_input("What number should we end on? ")) increm = int(raw_input("How much should we increment by? ")) numbers = whiloop(endnum, increm) print "The numbers: " for num in numbers: print num
21d4b26d5af75103a520cb0ace70b214d00ab5ec
deekshasingh2k8/GitDemo
/pythonBasics/WhileDemo.py
391
4.46875
4
it = 10 while it > 1: if it == 9: it = it-1 # decrement the value of it so stop the infinite loop when it is 9 continue if it == 3: break # break is used to stop the while loop execution print(it) # 10 only as continue statement skips all the below lines of code and go to infinite loop when it = 9. it = it-1 print("while loop execution is done")
d47b74c92166263c24236fee8b3e936de3983f53
Nikkuniku/AtcoderProgramming
/ABC/ABC100~ABC199/ABC167/A.py
112
3.796875
4
s=list(input()) t=list(input()) last = t[-1] s.append(last) if s== t: print('Yes') else: print('No')
d56e7f4e0770f7e817a1de6ba312ec17962ef179
rahulchawla1803/customized-web-search-engine
/modules/main.py
2,075
3.640625
4
import threading from queue import Queue from Spider import spider from domain import * from general import * #PROJECT_NAME='thenewboston' #PROJECT_NAME='health' PROJECT_NAME='hindustantimes' #HOMEPAGE='https://thenewboston.com/' #HOMEPAGE='http://www.health.com/' HOMEPAGE='http://www.hindustantimes.com/' DOMAIN_NAME=get_domain_name(HOMEPAGE) #DOMAIN_NAME='health.com/food' #DOMAIN_NAME='health.com' QUEUE_FILE=PROJECT_NAME + '/queue.txt' CRAWLED_FILE=PROJECT_NAME + '/crawled.txt' NUMBER_OF_THREADS=100 #queue variable is basically thread queue queue=Queue() spider(PROJECT_NAME, HOMEPAGE, DOMAIN_NAME) #create worker threads (die when main exits) def create_workers(): for _ in range(NUMBER_OF_THREADS): t=threading.Thread(target=work) #print("check1") t.daemon=True # daemon so that thread dies when main exits t.start() # with t.start() thread will start executing the target, that is the work function, initially queue is empty so it will wait # do the next job in the queue def work(): while True: url=queue.get() spider.crawl_page(threading.current_thread().name, url) queue.task_done() # Each queued link is a new job def create_jobs(): for link in file_to_set(QUEUE_FILE): queue.put(link) queue.join() crawl() #str(len(set)) will give number of elements in the set and convert it into string #check if there are item in queue, and crawl them def crawl(): #print("check2") queue_links=file_to_set(QUEUE_FILE) if (len(queue_links)) > 0: print(str(len(queue_links))+ ' links in the queue') create_jobs() ''' READ queue.get(block=True, timeout=None) Initially threads are created and they are assigned to execute function "work()". In work(), queue.get() initially will be empty thus it will block that thread for timeout=None(that is unlimited time till queue has an element) Meanwhile crawl() will create_jobs() and as soon as the queue has element, the thread will start executing work() ''' create_workers() crawl()
22e037ad60fb17eb10647dd165d2700b84311581
hao276843248/pythontestcode
/testpailie.py
583
3.640625
4
def group_elements(eles): if len(eles) == 1: yield (eles,) return for g_tuple in group_elements(eles[1:]): yield (eles[:1],) + g_tuple for i in range(len(g_tuple)): yield ( g_tuple[:i] + ((eles[:1] + g_tuple[i]),) + g_tuple[i + 1:] ) if __name__ == '__main__': a = [] k = 0 for j in group_elements((1, 2, 3)): a.append(j) if len(j) == 2: k += 1 print(j) print(k) print(len(a)) # x = c41 +
960f3f5036312bcf233b5ed2515b3e8c50ba22e0
ayushbhandari02/Data-Structures
/BST.py
528
3.578125
4
from binary_tree import BinaryTree b = BinaryTree(3) try: b.insert_node(5) except Exception: print("error with the parameter passed") b.insert_node(4) b.insert_node(2) b.insert_node(1) b.insert_node(2.5) b.insert_node(1.5) print("After inserting all the nodes, traverse using post order ") b.view_post_order() print("deleting a node\n") b.delete_node(10) print("After deleting traversing the nodes using post order traverse") b.view_post_order() print("Level order traverse") b.level_order_traverse()
91350e1ba3aee448fc043e71800800ca7d1e5924
sfeng77/myleetcode
/medianOfTwoSortedArrays.py
2,511
4.0625
4
# There are two sorted arrays nums1 and nums2 of size m and n respectively. # # Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). # # Example 1: # nums1 = [1, 3] # nums2 = [2] # # The median is 2.0 # Example 2: # nums1 = [1, 2] # nums2 = [3, 4] # # The median is (2 + 3)/2 = 2.5 class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ m = len(nums1) n = len(nums2) if m >= n: return self.findMedian(nums1, 0, m, nums2, 0, n) else: return self.findMedian(nums2, 0, n, nums1, 0, m) def findMedian(self, nums1, s1, n1, nums2, s2, n2): #return median of nums1[s1:s1+n1] + nums2[s2:s2+n2], assuming n1 >= n2 m1 = self.median(nums1, s1, n1) m2 = self.median(nums2, s2, n2) #print s1, n1, m1, s2, n2, m2 if (n2 == 0): return m1 if (n2 == 1): if (n1%2 == 0): return self.med3unsorted(m2, nums1[s1+n1/2-1], nums1[s1+n1/2]) elif n1 == 1: return 0.5 * (m1 + m2) else: return 0.5 * m1 + 0.5 * self.med3unsorted(m2, nums1[s1+n1/2-1], nums1[s1+n1/2 + 1]) if (n2 == 2): b0, b1 = nums2[s2], nums2[s2+1] if n1 ==2: return self.med4unsorted(nums1[s1],nums1[s1+1], b0, b1) if (n1%2 == 0): return self.med4unsorted(nums1[s1 + n1/2-1], nums1[s1 + n1/2], max(b0, nums1[s1 + n1/2 -2]), min(b1, nums1[s1+n1/2 + 1])) return self.med3unsorted(nums1[s1+n1/2], max(b0, nums1[s1+n1/2-1]), min(b1, nums1[s1+n1/2+1])) if m1 == m2: return m1 elif m1 < m2: return self.findMedian(nums1, s1 + (n2-1) / 2, n1 - (n2-1) / 2, nums2, s2, n2 - (n2-1) / 2) else: return self.findMedian(nums1, s1, n1 - (n2-1) / 2, nums2, s2 + (n2-1)/2, n2 - (n2-1) / 2) def med3unsorted(self, a, b, c): return sorted([a, b, c])[1] def med4unsorted(self, a, b, c, d): nums = sorted([a, b, c, d]) return 0.5 * (nums[1] + nums[2]) def median(self, nums, start, n): # returns median of nums[start:start+n] if not nums: return -1 if n%2 == 0: return 0.5 * (nums[start + n/2] + nums[start + n/2-1]) else: return (nums[start + n/2])