blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
bd166d1511218861ec60043fe1a79e4cc6dcc6b3
jadhavniket/niketrepository
/python/sampleaa.py
97
3.546875
4
num=input() l=[] for i in range(num): u=num%10 l.append(u) num=str(num//10) print(l)
4c93a21552ad5e93bdb06568a65f6268a375f6d5
sunchenglong/python-learn
/src/sse/test.py
125
3.84375
4
import re print re.match("\d-\d-\d","1-2-3") print re.match("\d-\d-\d","1-22-33") print re.match("\d+-\d+-\d+","2017-19-10")
fff4dfb33e3e51a619568e86740491aefbaf587c
cshintov/connect-four
/closure.py
850
3.828125
4
""" Showcase utility of higher order functions, closure and decorator """ def memoize(func): results = {} def inner(*args, debug=False): if debug: print(args) try: return results[args] except KeyError: if debug: print("Computing new result!") results[args] = func(*args) return results[args] return inner add = lambda x, y: x + y product = lambda x, y: x * y memoized_add = memoize(add) memoized_product = memoize(product) print(memoized_add(2, 3)) print(memoized_add(2, 3)) print(memoized_product(2, 3)) print(memoized_product(2, 3)) memoized_fib = None @memoize def fib(n): if n <= 1: return 1 return fib(n - 1) + fib(n - 2) # print([fib(n, debug=True) for n in range(10)]) print([fib(n) for n in range(10)])
7de77330283c9352ae4d5eeaf841fd6753ab3791
YCooE/Python-projects
/Math/poly_fit_cross_val/linreg.py
2,719
3.96875
4
import numpy class LinearRegression(): """ Linear regression implementation with regularization. """ def __init__(self, lam=0, solver="inverse"): """ Constructor for model. Parameters ---------- lam : float The regularization parameter solver : str The solver that shall be used to approach the linear systems of equations. Two options so far: - 'inverse': resorts to the matrix inverse of the data matrix - 'solve' : resorts to directly solving the linear systems of equations (is usually more precise). """ self.lam = lam self.solver = solver assert self.solver in ["inverse", "solve"] def fit(self, X, t): """ Fits the linear regression model. Parameters ---------- X : Array of shape [n_samples, n_features] t : Array of shape [n_samples, 1] """ # make sure that we have numpy arrays; also # reshape the array X to ensure that we have # a multidimensional numpy array (ndarray) X = numpy.array(X).reshape((X.shape[0], -1)) t = numpy.array(t).reshape((len(t),1)) # prepend a column of ones ones = numpy.ones((X.shape[0], 1)) X = numpy.concatenate((ones, X), axis=1) # compute weights (L7, slide 35) diag = self.lam * len(X) * numpy.identity(X.shape[1]) km = numpy.dot(X.T, X) + diag if self.solver == "solve": self.w = numpy.linalg.solve(km, numpy.dot(X.T, t)) elif self.solver == "inverse": self.w = numpy.linalg.inv(km) self.w = numpy.dot(self.w, X.T) self.w = numpy.dot(self.w, t) else: raise Exception("Unknown solver!") def predict(self, X): """ Computes predictions for a new set of points. Parameters ---------- X : Array of shape [n_samples, n_features] Returns ------- predictions : Array of shape [n_samples, 1] """ # make sure that we have numpy arrays; also # reshape the array X to ensure that we have # a multidimensional numpy array (ndarray) X = numpy.array(X).reshape((X.shape[0], -1)) # prepend a column of ones ones = numpy.ones((X.shape[0], 1)) X = numpy.concatenate((ones, X), axis=1) # compute predictions (L7, slide 35) predictions = numpy.dot(X, self.w) return predictions
6c931c1fbaf864db459df52e7def8db9b296d72d
Sinchiguano/codingProblems_Python
/codingProblems/FreeBodyObjects2.py
3,104
4.21875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 CESAR SINCHIGUANO <cesarsinchiguano@hotmail.es> # # Distributed under terms of the BSD license. """ """ from math import atan2, degrees, radians, sin, cos #Last problem, you created a new class called Force. Copy that #class below: import math #Add your code here! class Force: def __init__(self,magnitude,angle): self.magnitude=magnitude self.angle=angle def get_horizontal(self): horizontal = self.magnitude * cos(radians(self.angle)) return horizontal def get_vertical(self): vertical = self.magnitude * sin(radians(self.angle)) return vertical def get_angle (self,use_degrees=True): if use_degrees: return math.degrees(self.angle) else: return self.angle #In this problem, you're going to use that class to calculate #the net force from a list of forces. # #Write a function called find_net_force. find_net_force should #have one parameter: a list of instances of Force. The #function should return new instance of Force with the total #net magnitude and net angle as the values for its magnitude #and angle attributes. # #As a reminder: # # - To find the magnitude of the net force, sum all the # horizontal components and sum all the vertical components. # The net force is the square root of the sum of the squares # of the horizontal forces and the vertical foces (i.e. # (total_horizontal ** 2 + total_vertical ** 2) ** 0.5) # - To find the angle of the net force, call atan2 with two # arguments: the total vertical and total horizontal # forces (in that order). # - Remember to round both the magnitude and direction to one # decimal place. This can be done using round(magnitude, 1) # and round(angle, 1). # - The Force class has three methods: get_horizontal returns # a single force's horizontal component. get_vertical # returns a single force's vertical component. get_angle # returns a single force's angle in degrees (or in radians # if you call get_angle(use_degrees = False). # #HINT: Don't overcomplicate this. The Force class does a lot #of your work for you. Use it! You should not need any trig #functions except atan2, degrees, and radians. #Add your function here! def find_net_force(forces): total_horizontal=0.0 total_vertical=0.0 for i_force in forces: total_horizontal+=i_force.get_horizontal() total_vertical+=i_force.get_vertical() magnitude=round(math.sqrt((total_horizontal ** 2 + total_vertical ** 2)),1) angle=round(math.atan2(total_vertical,total_horizontal),1) return Force(magnitude,angle) #Below are some lines of code that will test your object. #You can change these lines to test your code in different #ways. # #If your code works correctly, this will originally run #error-free and print: #103.1 #-14.0 force_1 = Force(50, 90) force_2 = Force(75, -90) force_3 = Force(100, 0) forces = [force_1, force_2, force_3] net_force = find_net_force(forces) print(net_force.magnitude) print(net_force.get_angle(use_degrees = True))
4f6cb61ee7d16343c8338931f116b0902de966f8
Algoritm-Study-K/baekjoon
/2주차/7_문자열/1157_yonghee.py
255
3.84375
4
word = input().upper() letters = list(set(word)) count_letter = [] for c in letters: count_letter.append(word.count(c)) if count_letter.count(max(count_letter)) >= 2: print('?') else: print(letters[count_letter.index(max(count_letter))])
1bb75f9818ffe24971042c3e0e373b33588d6439
fromradio/ProjectEuler
/src/prime.py
1,111
3.59375
4
import operator def primeList(num): # cons = [True for i in range(0,int(num)+1)] cons[0] = False cons[1] = False p = 2 while p*p <= num: k = p*p while k <= num: cons[k] = False k += p i = p+1 while True: if cons[i]: p = i break i += 1 l = [] for i in range(2,int(num)+1): if cons[i]: l.append(i) return l def factor(n,primes): def impl(n,dic): if n == 1: return dic for p in primes: if n%p == 0: dic.setdefault(p,0) dic[p] += 1 return impl(n/p,dic) dic.setdefault(n,1) dic[n] += 1 return dic return impl(n,{}) # problem 60 def primePairs( pn ): # 3 and 7 must be two of the 5 numbers # pn = 1000 pl = primeList(pn) num = pn * pn bpl = primeList(num) # judge two prime numbers are pair def jp(p1,p2): if int(str(p1)+str(p2)) not in bpl: return False if int(str(p2)+str(p1)) not in bpl: return False else: return True # find all numbers be pair of 3 and 7 l = {} for p in pl: lp = [] for pt in pl: if jp(pt,p): lp.append(pt) l[p] = lp print l def main(): pass if __name__ == '__main__': main()
bc8acbd55f0409ddebd416b7f874ebe04ef564d8
lundbit/PythonBuilding
/ex7.py
1,835
4.125
4
# BREAK: print("Mary had a little lamb.") # you can append the function call to the string that contains a {} call # BREAK: print("Its fleece was white as {}.".format('snow')) # BREAK: print("And everywhere that Mary went.") # BREAK: print("." * 10) # what'd that do? It printed the period ten times # BREAK: assign a string to end and add 'end' to print call --> very interesting # the string shows up like a normal string and the end=' ' does not overwrite # the end='byenumber' and still works to connect the lines Ceese and Burger # something static about end = " " AHA its a parameter built into the function #end = "byenumber" #don't forget to add end as a variable below and see what happens # BREAK: remove a quote -> EOL while scanning string literal #end1 = C" # BREAK: mix single vs double quotes -> EOL while scanning string literal # end1 = 'C" end1 = "C" end2 = "h" end3 = "e" end4 = "e" end5 = "s" end6 = "e" end7 = "B" end8 = "u" end9 = "r" end10 = "g" end11 = "e" end12 = "r" # watch that comma at the end. try removing it to see what happens # as you found it it creates a syntax error # BREAK: remove end=' ' --> Cheese an Burger on separate lines # print(end1 + end2 + end3 + end4 + end5 + end6) # BREAK replace end with dog --> dog is invalid keyword argument for print() # print(end1 + end2 + end3 + end4 + end5 + end6, dog=' ') # BREAK replace end=' ' with end = '@' --> Cheese@Burger - another paramter! # print(end1 + end2 + end3 + end4 + end5 + end6, end='@') print(end1 + end2 + end3 + end4 + end5 + end6, end=' ') # declaring space variable end # BREAK: put quotes around end7 variable --> "Cheese end7urger" # print("end7" + end8 + end9 + end10 + end11 + end12) print(end7 + end8 + end9 + end10 + end11 + end12)
8140141f30802a8cc51cf706f2214a4109ef84b1
FSSlc/AdvancePython
/ch04/class_var.py
342
3.515625
4
#!/usr/bin/env python # coding: utf-8 class A: # 类变量 aa = 1 def __init__(self, x, y): # 这里赋值后是实例的变量 self.x = x self.y = y a = A(2, 3) A.aa = 11 # 修改类属性 a.aa = 100 # 这里会新建属性 aa 到实例中 print(a.x, a.y, a.aa) print(A.aa) b = A(3, 5) print(b.aa)
c6606dbdba8b1e22839a8f5b1795fe142cce6b08
daniel-hampton/computer_vision_scratch
/img_processing01.py
761
4.15625
4
""" First couple exercises/examples in the opencv Python tutorials. Goals Here, you will learn how to read an image, how to display it and how to save it back You will learn these functions : cv2.imread(), cv2.imshow() , cv2.imwrite() Optionally, you will learn how to display images with Matplotlib """ import cv2 # Read in the image. img = cv2.imread('moth.jpg', 0) # Display image in a window that closes when any key is pressed. cv2.namedWindow('image', cv2.WINDOW_NORMAL) cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows() # print dimensions of image. print(img) print(img.shape) print(type(img)) height, width = img.shape[:2] print('Image is {}x{} pixels'.format(width, height)) # Save the image cv2.imwrite('output/moth-gray.png', img)
c3ebbe41e5f1cc01b617d9c85cab580aab6bc3a6
matheusvictor95/Algoritmos-em-Phyton
/algoritmos/questao01_do_desafio_da_aula07.py
139
3.859375
4
x = int(input('Digite algum número ')) suc= x + 1 ant= x - 1 print(' O sucessor de {} é {} \n e o antecessor é {}\n'.format(x,suc,ant))
12f60a66b9b03681a392d47488754fb43ddd1da6
thouravi/guessgame
/guessgame.py
512
4.0625
4
import random secretNumber = random.randint(1,10) print ("I'm taking a guess between 1 to 10.") for guessTaken in range(1,4): guess = int(input("Take a guess:")) if guess < secretNumber: print ("Your guess is too low.") elif guess > secretNumber: print ("Your guess is too high.") else: break if guess == secretNumber: print ("You guessed it correct in {} guesses!".format(guessTaken)) else: print ("The number I was thinking of was {} !".format(secretNumber))
74c3209e61805591919d290f95976b851a2a8c18
tqa236/leetcode-solutions
/exercises/0229-MajorityElementII/majority_element_ii.py
322
3.53125
4
from collections import Counter from typing import List class Solution(object): def majorityElement(self, nums: List[int]) -> List[int]: threshold = len(nums) // 3 counter = Counter(nums) return [ element for element, count in counter.most_common() if count > threshold ]
ce3ebe75db318244b793283d642c50ebc6bb6c0e
nehatomar12/Data-structures-and-Algorithms
/Stack_and_Queue/balance_expression.py
754
3.65625
4
exp = "{([])}" #exp = "{([])}}" exp = "{}{(}))}" def check_exp(exp): s = [] for i in exp: if i in ("{", "[", "("): s.append(i) else: if not s: return False curr_char = s.pop() if i == "}": if curr_char != "{": return False if i == "]": if curr_char != "[": return False if i == ")" : if curr_char != "(" : return False if s: return False return True # num = input() # for i in range(0, int(num)): # exp = input() # check_exp(exp) if check_exp(exp): print("balanced") else: print("not balanced")
19da2a77b1b8c612f2fbe7135d193ea318678b29
TimothySjiang/leetcodepy
/Solution_1026_2.py
549
3.609375
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 maxAncestorDiff(self, root: TreeNode) -> int: if not root: return 0 return self.dfs(root, high=root.val, low=root.val) def dfs(self, root, high, low): if not root: return high - low high = max(high, root.val) low = min(low, root.val) return max(self.dfs(root.left, high, low), self.dfs(root.right, high, low))
b0e88810ba0ca7475b35e7ae005d4b363237ba89
Khalid-Sultan/Section-2
/radius and area of circle.py
390
4
4
C=eval(input("enter the center point")) P=eval(input("enter the point on the circumference")) def distance(C,P): x=C[0]-P[0] y=C[1]-P[1] import math dis=math.sqrt(x**2+y**2) return dis r=distance(C,P) def area(r): A=(22*r*r)/7 return A print('the distance between the center and the point on the circle is',distance(C,P),'and the area of the circle is',area(r))
4dbaef8f33dfa5755d338c888e5d1bed0869fff7
Nesquick0/Adventofcode
/2017/07/07.py
2,632
3.65625
4
class Tower(object): def __init__(self): self.weight = 0 self.parent = None self.children = [] def __str__(self): return "%d, %s, %s" % (self.weight, self.parent, self.children) def SumOfWeights(towers, name): sum = towers[name].weight for childName in towers[name].children: sum += SumOfWeights(towers, childName) return sum def FindWrong(towers): wrongTower = None wrongWeight = 10**9 for tower in towers: if (len(towers[tower].children) > 0): weight = SumOfWeights(towers, towers[tower].children[0]) for childName in towers[tower].children: if (weight != SumOfWeights(towers, childName)): if (wrongWeight > weight): wrongTower = tower wrongWeight = weight return wrongTower def main(): with open("input", "r") as file: input = file.readlines() towers = {} for line in input: line = line.strip().split(" ") name = line[0] weight = int(line[1][1:-1]) if (name not in towers): towers[name] = Tower() towers[name].weight = weight if (len(line) > 2): for i in range(3, len(line)): childName = line[i] if line[i][-1] != "," else line[i][:-1] if (childName not in towers): towers[childName] = Tower() towers[childName].parent = name towers[name].children.append(childName) # Part1. Top most tower for name, tower in towers.items(): if (tower.parent == None): print("No parent: %s" % (name)) break # for tower in towers: # print("%s, %s, %d" % (tower, towers[tower], SumOfWeights(towers, tower))) # Find wrong tower wrong = FindWrong(towers) print(wrong) # for childName in towers[wrong].children: # print("Sum: %d, Weight: %d, Name: %s" % (SumOfWeights(towers, childName), towers[childName].weight, childName)) # Find most common weight. weightDict = {} for childName in towers[wrong].children: sumWeight = SumOfWeights(towers, childName) if (sumWeight not in weightDict): weightDict[sumWeight] = 1 else: weightDict[sumWeight] += 1 # Sort weights and calculate wanted difference. sortedWeights = ([key for key in sorted(weightDict, key=weightDict.get, reverse=True)]) weightDiff = sortedWeights[0] - sortedWeights[1] # Find which tower has wrong weight and subtract. for childName in towers[wrong].children: if (SumOfWeights(towers, childName) == sortedWeights[1]): print(towers[childName].weight + weightDiff) break if (__name__ == "__main__"): main()
8f32ed58d7d769e51b6896c7e4c7fe92e34067c4
JamesXia23/python
/code/function/内嵌函数以及闭包.py
1,152
4
4
#内嵌函数(函数内部再定义函数) def fun1(): print("fun1被执行") def fun2(): print('fun2被执行') fun2() fun1() #闭包 #一个内部函数访问到外部的内容时,该函数称为闭包 def outer(x): def inner(y): return x * y return inner i = outer(5) #此时i为一个函数变量inner print(i(6)) #相当于调用了inner,结果为30 #如果在一个内部函数中想要修改外部变量 #那就意味着必须重新定义这个变量, #则外部变量就会被屏蔽 #def outer2(): # x = 5 # def inner2(): # x *= x # return x #重新定义了x,相当于x1 = x2 * x3 #(按道理先执行x2*x3,都是全局变量,但是由于定义了x1,所以全局x被屏蔽,而又是先执行x2*x3,在定义x1之前,所以找不到x2和x3的定义,会报错) # return inner2() #这里返回的不是函数变量,而是函数返回值 #outer2() #解决办法,将x设置为nonlocal变量,跟全局变量global关键字作用类似 def outer3(): x = 5 def inner3(): nonlocal x x *= x return x return inner3() outer3()
8da56531a3534b02599f13f6bc6e94680d240f9f
TylerBromley/fullstack_python_codeguild
/lab11-simple-calculator_v3.py
318
4.0625
4
# lab11-simple-calculator_v3.py # get an arithmetic expression from a user math_todo = input("Please enter an arithmetic expression: ") # evaluate the expression using built-in eval() function # and store it in a variable evaluated = eval(math_todo) # print the evaluated answer print(f"Your answer is: {evaluated}")
61e60ff9c7d80486e2d19183e8242a0ee4d6065e
JoelDavisP/Python-Practice-Book-Solutions
/chapter5/ppbook/2/set7/p26.py
349
3.953125
4
def even(x): return x%2 == 0 def filter_list_comp(fn,ls): """It applies a function to each element of a list and returns items of the list for which fn(item) is True. Input function name and a list. output values of list after function applied to be True. """ print [x for x in ls if fn(x)] filter_list_comp(even, range(15))
d4a4ce6f50aec13049b2997d064fd17b8895e3a0
Joao-paes-oficial/HackerRank
/Python/30 Days of Code/Dia_6.py
102
3.6875
4
n = int(input()) for i in range(0, n): string = str(input()) print(string[::2], string[1::2])
c7951f484d8f7d90bc550cee0d6772af87196266
Pradeepnitw/tutorials
/cc150/quicksort.py
1,632
3.71875
4
""" Tony Hoare 1980 Turing Award """ from random import random mute = False def swap(a, i, j): if i == j: return temp = a[i] a[i] = a[j] a[j] = temp def knuth_shuffle(a): for i in range(len(a)): ran = int(random()*(i+1)) swap(a, i, ran) def test_knuth_shuffle(): l = range(20) knuth_shuffle(l) if not mute: print "test shuffle range(20)", l def quicksort(a): """ Shuffle Partition Sort """ if not a: return knuth_shuffle(a) if not mute: print "a after shuffle", a _partition(a, 0, len(a) - 1) if not mute: print "a after partitions", a def _partition(a, lo, hi): if not a or lo >= hi: return i = lo + 1 j = hi if not mute: print "p={},lo={},hi={},a={}".format(a[lo], lo, hi, a) while i <= j: while i <= hi and a[i] <= a[lo]: i += 1 while a[j] > a[lo]: j -= 1 if j == lo: break if i > j: i = lo if not mute: print "i={},j={} swapping".format(i, j) print a swap(a, i, j) if not mute: print a if not mute: print "p={},i={},j={},a={}".format(a[lo], i, j, a) _partition(a, lo, j-1) _partition(a, j+1, hi) def run_tests(): test_knuth_shuffle() l = range(5) for i in range(10): quicksort(l) if not l == range(5): print "False assertion, l={}".format(l) assert False print "All tests passed" if __name__ == "__main__": run_tests()
17bd6a8be0fceb0f9ab865a9d52b69a2bc33c601
jiting1014/MH8811-G1901803D
/02/program2.py
60
3.59375
4
c=input('Celsius=') f=float(c)*1.8+32 print('Fahrenheit=',f)
b02171d6472529aba8a7a1b26552a63d4679330f
ditwoo/centernet-impl
/src/detector/utils/registry.py
1,573
3.5625
4
class Registry: """Store classes in one place. Usage examples: >>> import torch.optim as optim >>> my_registry = Registry() >>> my_registry.add(optim.SGD) >>> my_registry["SGD"](*args, *kwargs) Add items using decorator: >>> my_registry = Registry() >>> @my_registry >>> class MyClass: >>> pass """ def __init__(self): self.registered_items = {} def add(self, item): """Add element to a registry. Args: item (type): class type to add to a registry """ name = item.__name__ self.registered_items[name] = item def __call__(self, item): """Add element to a registry. Usage examples: >>> class MyClass: >>> pass >>> r = Registry() >>> r.add(MyClass) Or using as decorator: >>> r = Registry() >>> @r >>> class MyClass: >>> pass Args: item (type): class type to add to a registry Returns: same item """ self.add(item) return item def __len__(self): return len(self.registered_items) def __getitem__(self, key): if key not in self.registered_items: raise KeyError(f"Unknown or not registered key - '{key}'!") return self.registered_items[key] def __repr__(self) -> str: return "Registry(content={})".format(",".join(k for k in self.registered_items.keys()))
de7902f7a84c1a6109a9912f44319f56be9247ff
thomasmcclellan/pythonfundamentals
/00.01_exercise_01-07.py
1,113
4.125
4
# Review of 01-07 ############ # Problem 1 ############ # Given: s = 'django' # Use indexing to print out the following: # 'd' s[0] # 'o' s[-1] # 'djan' s[:4] # 'jan' s[1:4] # 'go' s[4:] # Reverse string s[::-1] ############ # Problem 2 ############ # Given: l = [3,7,[1,4,'hello']] # Reassign 'hello' to 'goodbye' 1[2][2] = 'goodbye' ############ # Problem 3 ############ # Using keys and indexing, grab 'hello' from the following dictionaries: d1 = {'simple_key':'hello'} d1['simple_key'] d2 = {'k1':{'k2':'hello'}} d2['k1']['k2'] d3 = {'k1':[{'nest_key':['this is deep', ['hello']]}]} d3['k1'][0]['nest_key'][1][0] #If didn't have last 0, would return the list, not just 'hello' ############ # Problem 4 ############ # Use a set to find the unique values of list below: my_list = [1,1,1,1,1,2,2,2,2,3,3,3,3] set(my_list) ############ # Problem 5 ############ # Given: age = 4 name = 'Sammy' # Use print formatting to print the following string: "Hello my dog's name is Sammy and he is 4 years old" print("Hellow my name dog's name is {a} and he is {b} years old.".format(a=age, b=name))
c9cc247125bf28e0895bfa759cd0e8392a9a0039
smart1004/learn_src
/pso_test/testd10_PyRETIS.py
11,295
3.796875
4
# http://www.pyretis.org/examples/examples-pso.html ''' PyRETIS1.0.0 Particle Swarm Optimization In this example, we will perform a task that PyRETIS is NOT intended to do. We will optimize a function using a method called particle swarm optimization and the purpose of this example is to illustrate how the PyRETIS library can be used to set up special simulations. The function we will optimize is the Ackley function which is relatively complex with many local minima as illustrated in the figure below. We will set up our optimization by first creating a new potential and a new engine to do the job for us. Illustration of particle swarm optimization Fig. 37 Illustration of the particle swarm optimization method. The particles (black circles) start in a random initial configuration as shown in the left image and search for the global minimum. All particles keep a record of the smallest value they have seen so far and they communicate this estimate to the other particles. Thus, the current best estimate based on all the particles is known, and the particles are drawn towards this position, but also towards their own best estimate. In the middle image, the positions have been updated and the particles have moved. After some more steps, the particles converge towards the global minimum at (0, 0). However, convergence is not guaranteed. Table of Contents Creating the Ackley function as a PotentialFunction Creating a custom engine for particle swarm optimization Putting it all together and running the optimization Adding plotting and animation Creating the Ackley function as a PotentialFunction Here, we will create the function we will optimize as a PotentialFunction. This can be done by creating a new file ackley.py and adding the following code: ''' import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D # pylint: disable=unused-import from pyretis.forcefield import PotentialFunction TWO_PI = np.pi * 2.0 EXP = np.exp(1) @np.vectorize def ackley_potential(x, y): # pylint: disable=invalid-name """Evaluate the Ackley function.""" return (-20.0 * np.exp(-0.2*np.sqrt(0.5*(x**2 + y**2))) - np.exp(0.5 * (np.cos(TWO_PI * x) + np.cos(TWO_PI * y))) + EXP + 20) class Ackley(PotentialFunction): """A implementation of the Ackley function. Note that the usage of this potential function differs from the usual usage for force fields. """ def __init__(self): """Set up the function.""" super().__init__(dim=2, desc='The Ackley function') def potential(self, system): """Evaluate the potential, note that we return all values.""" xpos = system.particles.pos[:, 0] ypos = system.particles.pos[:, 1] pot = ackley_potential(xpos, ypos) return pot # If you add: def main(): """Plot the Ackley function.""" xgrid, ygrid = np.meshgrid(np.linspace(-5, 5, 100), np.linspace(-5, 5, 100)) zgrid = ackley_potential(xgrid, ygrid) fig = plt.figure() ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212, projection='3d') ax1.contourf(xgrid, ygrid, zgrid) ax2.plot_surface(xgrid, ygrid, zgrid, cmap=plt.get_cmap('viridis')) plt.show() if __name__ == '__main__': main() ''' you can also plot the potential by running: python ackley.py Creating a custom engine for particle swarm optimization Here, we will create a new engine for performing the “dynamics” in the particle swarm optimization. The equations of motion are For the velocity v_i of particle i: v_i(t + 1) = \omega v_i(t) + c_1 r_1 (x_i^\ast - x_i(t)) + c_2 r_2 (x^\dagger - x_i(t)) where \omega is the co-called inertia weight (a parameter), c_1 and c_2 are acceleration coefficients (parameters), r_1 and r_2 are random numbers drawn from a uniform distribution between 0 and 1, x_i^\ast is particle i’s best estimate of the minimum of the potential and x^\dagger is the global best estimate. For the position x_i of particle i: x_i(t + 1) = x_i(t) + v_i(t) In both equations, t is the current step and t+1 is the next step. Before updating the positions, the potential energies for the individual particles are obtained and x_i^\ast and x^\dagger are updated. These equations are similar to the equations used by the MD integrators in PyRETIS, and the engine can be implemented as a sub-class of the MDEngine class. Create a new file name psoengine.py and add the following code: ''' # -*- coding: utf-8 -*- # Copyright (c) 2015, PyRETIS Development Team. # Distributed under the LGPLv2.1+ License. See LICENSE for more info. """A custom engine for particle swarm optimization.""" import numpy as np from pyretis.engines import MDEngine class PSOEngine(MDEngine): """Perform particle swarm optimization.""" def __init__(self, inertia, accp, accg): """Set up the engine. Parameters ---------- intertia : float The intertia factor in the velocity equation of motion. accp : float The acceleration for the previous best term. "The congnitive term". accg : float The acceleration for the global best term. "The social term". """ super().__init__(1, 'Particle Swarm Optimization') self.inertia = inertia self.accp = accp self.accg = accg self.pbest = None self.pbest_pot = None self.gbest = None self.gbest_pot = None def integration_step(self, system): """Perform one step for the PSO algorithm.""" particles = system.particles if self.pbest is None: self.pbest = np.copy(particles.pos) self.pbest_pot = system.potential() if self.gbest is None: pot = system.potential() idx = np.argmin(pot) self.gbest = particles.pos[idx] self.gbest_pot = pot[idx] rnd1 = np.random.uniform() rnd2 = np.random.uniform() particles.vel = (self.inertia * particles.vel + rnd1 * self.accp * (self.pbest - particles.pos) + rnd2 * self.accg * (self.gbest - particles.pos)) particles.pos += particles.vel particles.pos = system.box.pbc_wrap(particles.pos) pot = system.potential() # Update global? idx = np.argmin(pot) if pot[idx] < self.gbest_pot: self.gbest_pot = pot[idx] self.gbest = particles.pos[idx] # Update for individuals: idx = np.where(pot < self.pbest_pot)[0] self.pbest[idx] = np.copy(particles.pos[idx]) self.pbest_pot[idx] = pot[idx] return self.gbest_pot, self.gbest ''' Putting it all together and running the optimization We will now create a simulation for performing the optimization. First we need to import the new potential function and the new engine we have created: ''' import numpy as np from pyretis.core import create_box, Particles, System from pyretis.simulation import Simulation from pyretis.forcefield import ForceField from psoengine import PSOEngine from ackley import Ackley, ackley_potential We next use this to define a method for setting everything up for us: NPART = 10 STEPS = 1000 MINX, MAXX = -10, 10 TXT = 'Step: {:5d}: Best: (x, y) = ({:10.3e}, {:10.3e}), pot = {:10.3e}' def set_up(): """Just create system and simulation.""" box = create_box(low=[MINX, MINX], high=[MAXX, MAXX], periodic=[True, True]) print('Created a box:') print(box) print('Creating system with {} particles'.format(NPART)) system = System(units='reduced', box=box) system.particles = Particles(dim=2) for _ in range(NPART): pos = np.random.uniform(low=MINX, high=MAXX, size=(1, 2)) system.add_particle(pos) ffield = ForceField('Single Ackley function', potential=[Ackley()]) system.forcefield = ffield print('Force field is:\n{}'.format(system.forcefield)) print('Creating simulation:') engine = PSOEngine(0.7, 1.5, 1.5) simulation = Simulation(steps=STEPS) task_integrate = {'func': engine.integration_step, 'args': [system], 'result': 'gbest', 'first': True} simulation.add_task(task_integrate) return simulation, system Finally, we can make a method to execute the optimization: def main(): """Just run the optimization, no plotting.""" simulation, _ = set_up() for result in simulation.run(): step = result['cycle']['step'] best = result['gbest'] if step % 10 == 0: print(TXT.format(step, best[1][0], best[1][1], best[0])) Which is used as follows: if __name__ == '__main__': main() Execute the script a couple of time (save the code above in a new file, say pso_run.py) and execute it using: python pso_run.py Adding plotting and animation If you wish, you can also animate the results/optimization process. First modify the imports as follows: import numpy as np from pyretis.core import create_box, Particles, System from pyretis.simulation import Simulation from pyretis.forcefield import ForceField from psoengine import PSOEngine from ackley import Ackley, ackley_potential from matplotlib import pyplot as plt from matplotlib import animation, cm And add the following methods: def evaluate_potential_grid(): """Evaluate the Ackley potential on a grid.""" X, Y = np.meshgrid(np.linspace(MINX, MAXX, 100), np.linspace(MINX, MAXX, 100)) Z = ackley_potential(X, Y) return X, Y, Z def update_animation(frame, system, simulation, scatter): """Update animation.""" patches = [] if not simulation.is_finished() and frame > 0: results = simulation.step() best = results['gbest'] if frame % 10 == 0: print(TXT.format(frame, best[1][0], best[1][1], best[0])) scatter.set_offsets(system.particles.pos) patches.append(scatter) return patches def main_animation(): """Run the simulation and update for animation.""" simulation, system = set_up() fig = plt.figure() ax1 = fig.add_subplot(111, aspect='equal') ax1.set_xlim((MINX, MAXX)) ax1.set_ylim((MINX, MAXX)) ax1.axes.get_xaxis().set_visible(False) ax1.axes.get_yaxis().set_visible(False) X, Y, pot = evaluate_potential_grid() ax1.contourf(X, Y, pot, cmap=cm.viridis, zorder=1) scatter = ax1.scatter(system.particles.pos[:, 0], system.particles.pos[:, 1], marker='o', s=50, edgecolor='#262626', facecolor='white') def init(): """Just return what to re-draw.""" return [scatter] # This will run the animation/simulation: anim = animation.FuncAnimation(fig, update_animation, frames=STEPS+1, fargs=[system, simulation, scatter], repeat=False, interval=30, blit=True, init_func=init) plt.show() return anim if __name__ == '__main__': Back to top Source © Copyright 2015, The PyRETIS team. Created using Sphinx 1.7.1.
d956f40fc85da3cfd3e6fe84ad4f015fbcd4c25b
joaoDragado/roulette
/player.py
9,863
3.875
4
import random from bet import Bet # this will act as a superclass to individual player types. class Player(object): ''' Player Class Places bets on Outcomes, updates the stake with amounts won and lost. Uses Table to place bets on Outcomes; used by Game to record wins and losses. ''' def __init__(self, table=None, stake=100, roundsToGo=100, bet_amount=10): '''Constructs the Player with a specific Table for placing Bets. stake : The player’s current stake. Initialized to the player’s starting budget. roundsToGo : Initialized by the overall simulation control to the maximum number of rounds to play. active : indicates whether player is playing ; defaults to True. cash_out : indicates that player exits simulation. ''' self.table = table self.stake = stake self.roundsToGo = roundsToGo self.bet_amount = bet_amount self.active = True self.cash_out = False def setRounds(self, roundsToGo): '''Sets the total number of rounds for the players run.''' self.roundsToGo = roundsToGo def setStake(self, amount): '''Set the initial stake of the player''' self.stake = amount def playing(self): '''checks player status : returns boolean if player can continue.''' return self.active & (not self.cash_out) & (self.stake >= self.table.minimum) def set_bet(self): '''picks the next bet that the player wages on.''' pass def check_bet(self, bet): '''checks that the bet complies with table limits & is within players stake.''' return (bet.amount <= self.stake) & self.table.isValid(bet) def placeBets(self): '''Updates the Table with the various bets. This version creates a Bet instance from the black Outcome. It uses Table placeBet() to place that bet.''' # check the simulation is not over if self.roundsToGo < 1: self.cash_out = True # self.active = False # participate in roulette round self.roundsToGo -= 1 # check player status if self.cash_out: return # fetch bet bet = self.set_bet() # check bet eligibility ; if bet not compliant, exit if bet: if not self.check_bet(bet): self.active = False return # place bet on roulette table self.table.placeBet(bet) # remove wager from players stake. self.stake -= bet.amount def win(self, bet): '''Called by Game.cycle when the player won the bet. Calculate amount won (via the winAmount() method of theBet) & update players stake.''' self.stake += bet.winAmount() self.after_win(bet) def lose(self, bet): '''Placeholder method. the amount wagered was deducted from players stake when bet was placed.''' self.after_loss(bet) def after_win(self, bet): '''action to perform when player wins.''' pass def after_loss(self, bet): '''action to perform when player losses.''' pass def winners(self, outcomes): '''The set of Outcome instances that are part of the current win. Overriden by certain sublasses.''' pass class Passenger57(Player): '''Passenger57 constructs a Bet based on the Outcome named "Black". A player with a 1-track mind.''' def __init__(self, **kwargs): '''Constructs the Player with a specific table for placing bets. Sets up container lists to record wins & losses. ''' super().__init__(**kwargs) # by querying the wheel self._black = self.table.wheel.getOutcome('Black') self.wins = list() self.losses = list() def set_bet(self): '''Passenger57 always places the same bet on black.''' return Bet(self.bet_amount, self._black) def after_win(self, bet): '''appends winning amount to self.wins''' self.wins.append(bet.winAmount()) def after_loss(self, bet): '''appends losing amount to self.losses''' self.losses.append(bet.amount) class Martingale(Player): '''Martingale subclass of Player ; employs the betting strategy of : doubling their bet on every loss, and reseting their bet to a base amount on each win.''' def __init__(self, **kwargs): '''lossCount : losses counter ; the times to double the bet. betMultiple : the bet multiplier ; starts at 1, doubled in each loss ; reset to 1 on each win. This is always equal to 2^(lossCount) .''' super().__init__(**kwargs) self._black = self.table.wheel.getOutcome('Black') self.lossCount = 0 # this is easier to exist inside set_bet #self.betMultiple = 2**(self.lossCount) def set_bet(self): '''always bets on black, the amount determined by the lossCount''' running_amount = (2**(self.lossCount)) * self.bet_amount return Bet(running_amount, self._black) def after_win(self, _): '''reset lossCount to 0''' self.lossCount = 0 def after_loss(self, _): '''increase lossCount by 1''' self.lossCount += 1 class SevenReds(Martingale): '''SevenReds is a Martingale player who places bets in Roulette. This player waits until the wheel has spun red seven times in a row before betting black.''' def __init__(self, **kwargs): '''redCount : The number of reds yet to go. This starts at 7 , is reset to 7 on each non-red outcome, and decrements by 1 on each red outcome.''' super().__init__(**kwargs) self.redCount = 7 self._red = self.table.wheel.getOutcome('Red') self._black = self.table.wheel.getOutcome('Black') def winners(self,outcomes): '''The game will notify a player of each spin using this method. This will be invoked even if the player places no bets.''' if self._red in outcomes: self.redCount -= 1 else: self.redCount = 7 def set_bet(self): '''If redCount is zero, this places a bet on black, using the bet multiplier.''' if self.redCount <= 0 : running_amount = (2**(self.lossCount)) * self.bet_amount return Bet(running_amount, self._black) class PlayerRandom(Player): '''PlayerRandom is a subclass of Player who places bets in Roulette. This player makes random bets around the layout.''' def __init__(self, rng=None, seed=None, **kwargs): '''Inherits all arguments for Player superclass. Includes a random generator argument purely for mock testing purposes, identical to the one in the Wheel class.''' if rng is None: rng = random.Random() rng.seed(seed) self.rng = rng super().__init__(**kwargs) def set_bet(self): '''choose at random 1 outcome out of all 152 discrete outcomes. These are located in the dict wheel.all_outcomes in the form of the structure OutcomeName : Outcome. We obtain the outcomes by calling the iterator dict.values and wrapping it in a list for random.choice. We then set & return the Bet.''' rnd_outcome = self.rng.choice(list(self.table.wheel.all_outcomes.values())) return Bet(self.bet_amount, rnd_outcome) class Player1236(Player): '''Player1326 follows the 1-3-2-6 betting system. The player has a preferred Outcome (any even money bet - e.g. High). The amount wagered stems from the current betting state. The possible states are : Current state Multiplier On Win On Loss --------------------------------------------------- No Wins 1 One Win No Wins One Win 3 Two Wins No Wins Two Wins 2 Three Wins No Wins Three Wins 6 No Wins No Wins The multiplier is always applied to the initial bet amount. ''' def __init__(self, **kwargs): from player1236 import Player1326NoWins '''Initializes the state and the outcome. The state is set to the initial state of an instance of Player1326NoWins. The outcome is set to some even money proposition, e.g. "High".''' super().__init__(**kwargs) self.outcome = self.table.wheel.getOutcome('High') self.state = Player1326NoWins(self) def set_bet(self): '''Updates the Table with a bet created by the current state. This method delegates the bet creation to state object’s currentBet() method.''' return self.state.currentBet() def after_win(self, _): '''Uses the superclass method to update the stake with an amount won. Uses the current state to determine what the next state will be (by calling state‘s objects nextWon() method ) and saving the new state in state.''' self.state = self.state.nextWon() def after_loss(self, _): '''Uses the current state to determine what the next state will be. This method delegates the next state decision to state object’s nextLost() method, saving the result in state.''' self.state = self.state.nextLost() def create_player(player_class, table, stake=100, duration=100, bet_amount=10): '''Create a new player of a particular class of betting strategy. If player_class defined as string, use the commented code below : ''' #player_class_name = globals()[player_class] #player = player_class_name(table=table) player = player_class(table=table, bet_amount=bet_amount) player.setRounds(duration) player.setStake(stake) return player
dd7835af48650c16611088f3325fe1876dabaeba
Riyer01/SnakeRL
/BFSAgent.py
3,303
3.609375
4
import gym import gym_snake from hamilton import Hamilton from copy import deepcopy import matplotlib.pyplot as plt env = gym.make('snake-v0', grid_size = [8, 8]) observation = env.reset() def generateMoveQueue(path): move_map = {(-1, 0):3, (1,0):1, (0,1):2, (0,-1):0} if path: return [move_map[(y[0]-x[0], y[1]-x[1])] for x, y in zip(path, path[1:])] return [0] * 1000 def generateBFSPath(snake_head, food_location, grid): start = snake_head end = food_location path = BFS(grid, start, end) queue = generateMoveQueue(path) return queue def BFS(maze, start, end): '''"Brute-Force Search" :param maze(list): the maze to be navigated :param start(tuple): the starting coordinates (row, col) :param end(tuple): the end coordinates (row, col) :return: shortest path from start to end ''' queue = [start] visited = set() while len(queue) != 0: if queue[0] == start: path = [queue.pop(0)] # Required due to a quirk with tuples in Python else: path = queue.pop(0) front = path[-1] if front == end: return path elif front not in visited: for adjacentSpace in getAdjacentSpaces(maze, front, visited): newPath = list(path) newPath.append(adjacentSpace) queue.append(newPath) visited.add(front) return None def getAdjacentSpaces(maze, space, visited): ''' Returns all legal spaces surrounding the current space :param space: tuple containing coordinates (row, col) :return: all legal spaces ''' spaces = list() spaces.append((space[0]-1, space[1])) # Up spaces.append((space[0]+1, space[1])) # Down spaces.append((space[0], space[1]-1)) # Left spaces.append((space[0], space[1]+1)) # Right final = list() for i in spaces: if not maze.check_death(i) and i not in visited: final.append(i) return final num_games = 100 scores = [0] * num_games for i_episode in range(num_games): observation = env.reset() totalReward = 0 done = False t = 0 move_queue = [] while not done: #env.render(frame_speed=.0001) snake_head, food_location = tuple(env.controller.snakes[0].head if env.controller.snakes and env.controller.snakes[0] else [0, 0]), env.controller.grid.foodLocations[0] action = None if move_queue: action = move_queue.pop(0) else: move_queue = generateBFSPath(snake_head, food_location, deepcopy(env.controller.grid)) action = move_queue.pop(0) observation, reward, done, info = env.step(action) totalReward += reward t += 1 if done: scores[i_episode] = env.controller.score print("Episode finished after {} timesteps with reward {} and score {}".format(t, totalReward, env.controller.score)) break #Plot average score over previous 500 games averages = [] for i in range(500, len(scores)): averages.append(sum(scores[i-500:i])/float(500)) plt.plot(list(range(500, len(scores))), averages) plt.ylabel('Average Score over Last 500 Games') plt.xlabel('Number of Games') plt.show() print(sum(scores)/float(len(scores))) env.close()
683dcb5e7965cc822af8f46881cf7fd5de3be478
younkyounghwan/python_class
/lab1.py
574
3.765625
4
number="hi" print(number) number=10 print(number) a=5 b=25 c=a+b # 5+25=30을 출력하라 msg="%d+%d=%d" #출력하고자하는 문자열도 변수로 정의할 수 있다. print(msg%(a,b,c)) print("%d+%d=%d"%(a,b,c)) # 서식문자를 여러개 이용할 경우 괄호 안에 넣기 #문자열 출력 money=10000 print("나는 현재%d원이 있습니다."%money) #서식문자를 이용할 수 있다.컴마없이 변수이름 앞에 %를 쓴다. #입력 money = input("얼마를 가지고 게세요?") print("입력하신 값은 %s원입니다."%money) #%s로 받음
b4489eb1d4c8623f007d295e174eaddb18a935d1
misa9999/python
/courses/python3/ch123-unkown/48_lesson/groupby.py
708
3.734375
4
from itertools import groupby, tee students = [ {'name': 'Misa', 'note': 'A'}, {'name': 'Megumin', 'note': 'B'}, {'name': 'Yuuki', 'note': 'A'}, {'name': 'Mira', 'note': 'A'}, {'name': 'Aqua', 'note': 'C'}, {'name': 'Yui', 'note': 'B'}, {'name': 'Yukinoshita', 'note': 'A'}, {'name': 'Nami', 'note': 'A'}, {'name': 'Robin', 'note': 'B'}, {'name': 'Karen', 'note': 'C'}, ] sort_items = lambda item: item['note'] students.sort(key=sort_items) students_group = groupby(students, sort_items) for note, value in students_group: va1, va2 = tee(value) print(f'Note: {note}') for student in va1: print(f'\t{student}') tot = len(list(va2)) print(f'\t{tot} students with note: {note}') print()
37f5a6f46ac7bbbccca2c0330eeba92d61113497
SDRLurker/starbucks
/20170309/20170309_2.py
1,451
3.890625
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def findBottomLeftValue(self, root): """ :type root: TreeNode :rtype: int """ q = [] q.append(root) ans = root while q: for i in range(len(q)): cur = q.pop(0) if i == 0: ans = cur if cur.left: q.append(cur.left) if cur.right: q.append(cur.right) return ans.val def makeTree(vals): nodes = [] for i in vals: node = TreeNode(i) nodes.append(node) i = 0 while i < len(vals): nodes[i].left = nodes[(i+1) * 2 - 1] if (i+1) * 2 - 1 < len(vals) and vals[(i+1) * 2 - 1] else None nodes[i].right = nodes[(i+1) * 2] if (i+1) * 2 < len(vals) and vals[(i+1) * 2] else None i += 1 return nodes[0] import unittest class test_solution(unittest.TestCase): def test_all(self): s = Solution() vals = [2,1,3] trees = makeTree(vals) self.assertEqual(s.findBottomLeftValue(trees), 1) vals = [1,2,3,4,None,5,6,None,None,None,None,7] trees = makeTree(vals) self.assertEqual(s.findBottomLeftValue(trees), 7) if __name__ == "__main__": unittest.main()
49007104a978b21ad305c9ae13413da0dccd7e77
noy20-meet/meet2018y1lab4
/sorter.py
228
4.375
4
bin1="apples" bin2="oranges" bin3="olives" new_fruit = input('What fruit am I sorting?') if new_fruit== bin1: print('bin 1') elif new_fruit== bin2: print('bin 2') else: print('Error! I do not recognise this fruit!')
25b8d41f93e5396bb53a3cc1db4e8003029e4872
swell1009/ex
/teach your kids/ch09/DragDots.py
781
3.5625
4
# DragDots.py # Page 176 import pygame # Setup pygame.init() screen = pygame.display.set_mode([800, 600]) pygame.display.set_caption("Click and drag to draw") keep_going = True YELLOW = (255, 255, 0) # RGB color triplet for YELLOW radius = 15 mousedown = False while keep_going: # Game loop for event in pygame.event.get(): # Handling events if event.type == pygame.QUIT: keep_going = False if event.type == pygame.MOUSEBUTTONDOWN: mousedown = True if event.type == pygame.MOUSEBUTTONUP: mousedown = False if mousedown: # Draw/update graphics spot = pygame.mouse.get_pos() pygame.draw.circle(screen, YELLOW, spot, radius) pygame.display.update() # Update display pygame.quit() # Exit
5b21426639e81177c48019719f2ef4e1bead0146
sug5806/TIL
/Python/data_struct/Tree/prac.py
4,099
4.375
4
# traversal (순회) # 재방문 없이 어떤 자료구조의 모든 데이터(노드) 방문하는 것 class TreeNode: def __init__(self, data): self.data = data self.left_child = None self.right_child = None class Node: def __init__(self, data): self.data = data self.next = None # 전위 순회 def pre_order(tree_node): if tree_node is None: return print(tree_node.data, end=" ") pre_order(tree_node.left_child) pre_order(tree_node.right_child) # 중위 순회 def in_order(tree_node): if tree_node is None: return in_order(tree_node.left_child) print(tree_node.data, end=" ") in_order(tree_node.right_child) # 후위 순회 def post_order(tree_node): if tree_node is None: return post_order(tree_node.left_child) post_order(tree_node.right_child) print(tree_node.data, end=" ") class Stack: def __init__(self): self.container = list() def is_empty(self): if not self.container: return True else: return False def push(self, data): self.container.append(data) def pop(self): ret = self.container.pop() return ret def peek(self): return self.container[-1] class Queue: def __init__(self): self.head = None self.tail = None def is_empty(self): if self.head is None: return True else: return False def enqueue(self, tree_node): new_node = Node(tree_node) if self.is_empty(): self.head = new_node self.tail = new_node return self.tail.next = new_node self.tail = new_node def dequeue(self): if self.is_empty(): return None ret_node = self.head.data self.head = self.head.next return ret_node # 전위 순회 반복문 def iter_pre_order(cur): s = Stack() while True: while cur: print(cur.data, end=" ") s.push(cur) cur = cur.left_child if s.is_empty(): break cur = s.pop() cur = cur.right_child # 중위 순회 반복문 def iter_in_order(cur): s = Stack() while True: while cur: s.push(cur) cur = cur.left_child if s.is_empty(): break cur = s.pop() print(cur.data, end=' ') cur = cur.right_child # 후위 순회 반복문 def iter_post_order(cur): stack1 = Stack() stack2 = Stack() stack1.push(cur) while not stack1.is_empty(): cur = stack1.pop() stack2.push(cur) if cur.left_child: stack1.push(cur.left_child) if cur.right_child: stack1.push(cur.right_child) while not stack2.is_empty(): cur = stack2.pop() print(cur.data, end=" ") def level_order(cur): q = Queue() q.enqueue(cur) while not q.is_empty(): cur = q.dequeue() print(cur.data, end=" ") if cur.left_child: q.enqueue(cur.left_child) if cur.right_child: q.enqueue(cur.right_child) if __name__ == '__main__': n1 = TreeNode(1) n2 = TreeNode(2) n3 = TreeNode(3) n4 = TreeNode(4) n5 = TreeNode(5) n6 = TreeNode(6) n7 = TreeNode(7) n1.left_child = n2 n1.right_child = n3 n2.left_child = n4 n2.right_child = n5 n3.left_child = n6 n3.right_child = n7 print(f'전위 순회 재귀: ', end="") pre_order(n1) print() print(f'중위 순회 재귀: ', end='') in_order(n1) print() print(f'후위 순회 재귀: ', end='') post_order(n1) print() print() print(f'전위 순회 반복: ', end='') iter_pre_order(n1) print() print(f'중위 순회 반복: ', end='') iter_in_order(n1) print() print(f'후위 순회 반복: ', end='') iter_post_order(n1) print() print(f'레벨 순회 반복: ', end='') level_order(n1) print()
aa1c18a63a45be078098ed43676dbfb94601a0fb
bishii/QA_Scripts
/IoT/RaspberryPi/LED-Matrix/dot.py
1,771
3.6875
4
import time class Dot: def __init__(self, settings=("defaultDot",3,10,(0,0))): """ Constructor Inputs: settings: tuple of: 1) descriptive name of instance 2) FALSE interval (seconds) 3) TRUE interval (seconds) """ self.creationTime = time.time() self.dotName = settings[0] self.IntervalTimeTrue = settings[2] self.IntervalTimeFalse = settings[1] self.IntervalStartTime = time.time() self.CurrentState = False self.CurrentX = settings[3][0] self.CurrentY = settings[3][1] self.CurrentState = False def set_interval_start_time(self): self.IntervalStartTime = time.time() def set_x(self,xPos): self.CurrentX = xPos def set_y(self,yPos): self.CurrentY = yPos def get_coords(self): return (self.CurrentX, self.CurrentY) def get_obj_desc(self): return (self.dotName) def get_interval_time_false(self): return (self.IntervalTimeFalse) def get_interval_time_true(self): return (self.IntervalTimeTrue) def move_to(self,coordsTuple): self.CurrentX = coordsTuple[0] self.CurrentY = coordsTuple[1] def get_current_state(self): """ if current state is TRUE: if NOW > STOP INTERVAL TIME, then: set current state = FALSE return FALSE else: if NOW > NEXT INTERVAL START TIME, then: if NOW in DURATION OF BLINKING: Set current state = TRUE set interval_start_time = NOW. else: set current state = FALSE """ if self.CurrentState == True: if time.time() - self.IntervalStartTime >= self.IntervalTimeTrue: self.CurrentState = False self.set_interval_start_time() else: if time.time() - self.IntervalStartTime >= self.IntervalTimeFalse: self.CurrentState = True self.set_interval_start_time() return self.CurrentState
35d386bdafd4765e573252bd79b9e2c9191ebd0c
KaushikTK/compiler_design_programs
/exp_4 nfa to dfa/nfa_to_dfa.py
2,050
3.640625
4
from automata.fa.dfa import DFA from automata.fa.nfa import NFA states = input('Enter states separated by ",": ') states = states.split(',') states = set(states) symbols = input('Enter symbols separated by ",": ') symbols = symbols.split(',') symbols = set(symbols) transitions = {} print('Enter the transitions') while True: start = input('Enter the starting state: ') on = input('Enter the symbol for transition: ') t = {} data = transitions.get(start,'') if(data): print(str(data)) t = data.copy() li = input('Enter transition states separated by "," without any space : ') li = li.split(',') li = set(li) t[on] = li transitions[start] = t x = input('To continue entering more transitions, please enter "y" ') if(x != 'y'): break initialState = input('Enter initial state: ') finalState = input('Enter the final states separated by "," : ') finalState = finalState.split(',') finalState = set(finalState) for i in finalState: if(transitions.get(i,None) == None): transitions[i] = {"":{}} print(str(symbols)) print(str(states)) print(str(transitions)) print(str(initialState)) print(str(finalState)) nfa = NFA( states=states, input_symbols=symbols, transitions=transitions, initial_state=initialState, final_states=finalState ) #nfa = NFA( # states={'q0','q1','q2','q3','q4'}, # input_symbols={'0','1'}, # transitions={ # 'q0': {'': {'q2', 'q1'}}, 'q1': {'0': {'q3'}}, 'q2': {'1': {'q3'}}, 'q3': {'1': {'q4'}}, 'q4':{'':{}} # }, # initial_state='q0', # final_states={'q4'} #) #states={'q0', 'q1', 'q2'}, #input_symbols={'a', 'b'}, #transitions={ # 'q0': {'a': {'q1'}}, # # Use '' as the key name for empty string (lambda/epsilon) transitions # 'q1': {'a': {'q1'}, '': {'q2'}}, # 'q2': {'b': {'q0'}} #}, #initial_state='q0', #final_states={'q1'} dfa = DFA.from_nfa(nfa) print() print(dfa.final_states) print() print(dfa.transitions) print()
c0ead5646ce7c379bb7d34690cfbb4d8581d30fc
swatia-code/data_structure_and_algorithm
/strings/Count_number_of_words.py
1,608
4.0625
4
"""PROBLEM STATEMENT ----------------- Given a string consisting of spaces,\t,\n and lower case alphabets.Your task is to count the number of words where spaces,\t and \n work as separators. Input: The first line of input contains an integer T denoting the number of test cases.Each test case consist of a string. Output: Print the number of words present in the string. Constraints: 1<=T<=100 Example: Input: 2 abc\t\ndef ghi one two three \t four Output: 3 4 LOGIC ----- Iterate through the string and check if the chahracter is " " or '\'. If '\'is there check the next character and increment number of word count accordingly. CODE ----""" test_cases = int(input()) for i in range(test_cases): input_string = input() count_words = 0 counter = 0 j = 0 while(j<len(input_string)): if(input_string[j]>='a' and input_string[j]<='z'): counter = counter+1 j = j+1 elif(ord(input_string[j])==92): if(j==len(input_string)): counter = counter+1 elif(j+1<len(input_string) and input_string[j+1]=='n' or input_string[j+1]=='t'): if(counter>0): count_words = count_words+1 counter = 0 j = j+2 else: counter = counter+1 j = j+1 else: if(counter>0): count_words = count_words+1 counter = 0 j = j+1 else: j = j+1 if(counter>0): count_words = count_words+1 print(count_words)
ee7f91fb53b184647e66ee5b4257e7bb84181b18
whalenmlaura/Python
/2018.10.18 - LandscapingCalculator.py
1,475
4.03125
4
#""" #Assignment 2 - Landscape Calculator #October 18, 2018 #Name..: Laura Whalen #ID....: W0415411 #""" __AUTHOR__ = "Laura Whalen <W0415411@nscc.ca>" def main(): # input address = input("Please enter your house number: ") length = float(input("Please enter property length in feet: ")) width = float(input("Please enter property width in feet: ")) grass_type = input("Please enter the type of grass (fescue, bentgrass, or campus): ").lower() trees = float(input("Please enter the number of trees: ")) tree_cost = float(100 * trees) # processing def square_foot(length, width): total_square_foot = (length * width) return (total_square_foot) total_square_foot = square_foot(length, width) def total(): total_cost = (1000 + additional_cost + tree_cost + (total_square_foot * grass_cost)) print("\nThe total cost for house {0} is: ${1:.2f}".format(address, total_cost)) return(total_cost) if total_square_foot > 5000.00: additional_cost = 500.00 elif total_square_foot <= 5000.00: additional_cost = 0.00 if grass_type == "fescue": grass_cost = 0.05 total() elif grass_type == "bentgrass": grass_cost = 0.02 total() elif grass_type == "campus": grass_cost = 0.01 total() else: print("\nSorry, we do not carry that type of grass.") if __name__ == "__main__": main()
1838de61b53919a3ef748d0b7ba379397a584efe
eduhmc/CS61A
/Teoria/Class Code/23_ex.py
3,760
3.65625
4
# Morse tree abcde = {'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.'} def morse(code): whole = Tree(None) for letter, signals in code.items(): t = whole # YOUR CODE HERE return whole def decode(signals, tree): """Decode signals into a letter according to tree, assuming signals correctly represents a letter. tree has the format returned by morse(). >>> t = morse(abcde) >>> [decode(s, t) for s in ['-..', '.', '-.-.', '.-', '-..', '.']] ['d', 'e', 'c', 'a', 'd', 'e'] """ for signal in signals: tree = [b for b in tree.branches if b.label == signal][0] leaves = [b for b in tree.branches if b.is_leaf()] assert len(leaves) == 1 return leaves[0].label # Tree class Tree: """A tree with label as its label value.""" def __init__(self, label, branches=()): self.label = label for branch in branches: assert isinstance(branch, Tree) self.branches = list(branches) def __repr__(self): if self.branches: branch_str = ', ' + repr(self.branches) else: branch_str = '' return 'Tree({0}{1})'.format(repr(self.label), branch_str) def __str__(self): return '\n'.join(self.indented()) def indented(self, k=0): indented = [] for b in self.branches: for line in b.indented(k + 1): indented.append(' ' + line) return [str(self.label)] + indented def is_leaf(self): return not self.branches from io import StringIO # A StringIO is a file-like object that builds a string instead of printing # anything out. def height(tree): """The height of a tree.""" if tree.is_leaf(): return 0 else: return 1 + max([height(b) for b in tree.branches]) def width(tree): """Returns the printed width of this tree.""" label_width = len(str(tree.label)) w = max(label_width, sum([width(t) for t in tree.branches]) + len(tree.branches) - 1) extra = (w - label_width) % 2 return w + extra def pretty(tree): """Print a tree laid out horizontally rather than vertically.""" def gen_levels(tr): w = width(tr) label = str(tr.label) label_pad = " " * ((w - len(label)) // 2) yield w print(label_pad, file=out, end="") print(label, file=out, end="") print(label_pad, file=out, end="") yield if tr.is_leaf(): pad = " " * w while True: print(pad, file=out, end="") yield below = [ gen_levels(b) for b in tr.branches ] L = 0 for g in below: if L > 0: print(" ", end="", file=out) L += 1 w1 = next(g) left = (w1-1) // 2 right = w1 - left - 1 mid = L + left print(" " * left, end="", file=out) if mid*2 + 1 == w: print("|", end="", file=out) elif mid*2 > w: print("\\", end="", file=out) else: print("/", end="", file=out) print(" " * right, end="", file=out) L += w1 print(" " * (w - L), end="", file=out) yield while True: started = False for g in below: if started: print(" ", end="", file=out) next(g); started = True print(" " * (w - L), end="", file=out) yield out = StringIO() h = height(tree) g = gen_levels(tree) next(g) for i in range(2*h + 1): next(g) print(file=out) print(out.getvalue(), end="")
1289f844eb3b44a008f650f5dcd9ec2871271fc8
parihar08/PythonJosePortilla
/AdvancedPythonModules/PracticePuzzle.py
1,150
3.53125
4
#There is a zipfile called unzip_me_for_instructions.zip, unzip it and open the .txt file, #Read out the instructions and figure out what needs to be done # import shutil # # shutil.unpack_archive('ZipPracticePuzzle/unzip_me_for_instructions.zip','ZipPracticePuzzle/','zip') with open('ZipPracticePuzzle/extracted_content/Instructions.txt') as f: content = f.read() print(content) print('*********************************************') import re pattern1 = r'\d{3}-\d{3}-\d{4}' test_string = 'Here is a phone number 123-123-1234' print(re.findall(pattern1,test_string)) def search(file,pattern=pattern1): f = open(file,'r') text = f.read() #Open a file, look for a pattern, if it finds it, return the pattern if re.search(pattern,text): return re.search(pattern,text) else: return '' import os results = [] for folder, subfolders,files in os.walk(os.getcwd()+'/ZipPracticePuzzle/extracted_content'): for f in files: full_path = folder+'/'+f print(full_path) results.append(search(full_path)) for r in results: if r != '': print(r) print(r.group())
a4c87052fe39c76051848848d5c75b873f20d0b3
KoushikGodbole/PythonCodes
/FIleDuplicatesInSystem.py
1,085
3.6875
4
def findDuplicate(paths): """ :type paths: List[str] :rtype: List[List[str]] """ fileMap = dict() temp = "" duplicates = list() for s in paths: tempFile = s.split(" ") for i in range(len(tempFile)): if i == 0: filePath = tempFile[0] else: content = tempFile[i].split("(") if content[1] not in fileMap: temp = filePath+content[0] tempList = list() tempList.append(temp) fileMap[content[1]] = tempList else: tempList = fileMap[content[1]] temp = filePath+content[0] tempList.append(temp) fileMap[content[1]] = tempList for key,value in fileMap.items(): if len(value) > 1: duplicates.append(value) return duplicates files = ["root/a 1.txt(abcd) 2.txt(efgh)", "root/c 3.txt(abcd)", "root/c/d 4.txt(efgh)", "root 4.txt(efgh)"] res = findDuplicate(files) print(res)
ec870c1989843b7b80cd025976cc45cf1b4672ae
Nachiten/QueueBot-Discord
/tests/tests_all.py
1,606
3.5
4
from unittest import TestCase from clases.colas import Colas ''' # Descipcion: # Estos tests son independientes y prueban # el funcionamiento del comando All ''' # Corre antes de iniciar los tests def setUpModule(): print('[Corriendo tests de all]') # Corre luego de termianr todos los tests def tearDownModule(): print('[Terminando tests de all]') nombreCola1 = "soporte" nombreCola2 = "labo" nombreCola3 = "coloquio" class Tests_All(TestCase): # Corre antes de cada test def setUp(self): print("Configurando valores iniciales") # Corre luego de cada test def tearDown(self): print("Limpiando luego del test") Colas.eliminarTodasLasColas() def test_0_listar_una_cola(self): print("test_0_listar_una_cola") Colas.agregarCola(nombreCola1) mensajeEmbed = Colas.generarMensajeListandoColas() nombresColas = mensajeEmbed.fields[0].value cantidadUsuariosColas = mensajeEmbed.fields[1].value self.assertEqual(nombresColas, "soporte\n") self.assertEqual(cantidadUsuariosColas, "0\n") def test_1_listar_tres_colas(self): print("test_1_listar_tres_colas") Colas.agregarCola(nombreCola1) Colas.agregarCola(nombreCola2) Colas.agregarCola(nombreCola3) mensajeEmbed = Colas.generarMensajeListandoColas() nombresColas = mensajeEmbed.fields[0].value cantidadUsuariosColas = mensajeEmbed.fields[1].value self.assertEqual(nombresColas, "soporte\nlabo\ncoloquio\n") self.assertEqual(cantidadUsuariosColas, "0\n0\n0\n")
2cdf439d63623fb571d7eae7619e3423c71da1a5
OverCastCN/Python_Learn
/XiaoZzi/Practice100/29IntergerDecopose.py
434
3.953125
4
#coding:utf-8 """ 给一个不多于5位的正整数,要求:一、求它是几位数,二、逆序打印出各位数字。 """ a = raw_input('请输入一个不多于5位的正整数:') while len(a) > 5: print '请输入一个不多于5位的正整数' a = raw_input('请输入一个不多于5位的正整数:') print '它是%d位数'%len(a) def f(a): if len(a) > 0: print a[-1] return f(a[0:-1]) f(a)
3b7cd24b6884f8e1086f79fb7bbfd232366bd464
zachjbrowning/cs6441-ciphers
/cmd_control.py
6,432
3.875
4
from cipher_api import encode, decode, methods, overview, method_classes, in_depth from db_control import load_data, save_data, reset_data def prompt(): print(' > ', end='') return input() def help_cmd(): print("Potential commands:") commands = ['?', 'q', 'n', 'e', 'd', 's', 'c', 'i', 'r'] documentation = ['Help', 'Quit', 'Name change', 'Encode', 'Decode', 'Send message', 'Check messages', 'Information', 'Reset database'] for i in range(len(commands)): print(' - [' + commands[i] + '] : ' + documentation[i]) def encode_decode(is_encode, msg=None): print("Please choose a method:") for i in range(len(methods)): print(' - ' + str(i) + ' : ' + methods[i]) choice = prompt() correct = False while not correct: try: choice = int(choice) if choice < 0 or choice >= len(methods): raise ValueError correct = True except ValueError: correct = False print("Input was not an int or not a valid choice. Please choose a valid method. (Int between 0 and " + str(len(methods) - 1) + ")") choice = prompt() print("You are using the " + methods[choice] + " method!!") key = input("Please input your key: ") #NEED TO DO BETTER ERROR CHECKING HERE if choice in [2, 3]: key = "".join(key.split()) while not valid_string(key): key = input("Invalid key. Please input a string of only alphabetic characters and spaces: ") key = "".join(key.split()) elif choice is 4: key = " ".join(key.split()) while not valid_string(key): key = input("Invalid key. Please input a string of only alphabetic characters and spaces: ") key = " ".join(key.split()) else: if not key.isdigit(): while not key.isdigit(): key = input("Invalid key. Please input a number: ") if not msg: msg = input("Please input your message: ") if is_encode: return encode(method_classes[choice], key, msg) else: try: result = decode(method_classes[choice], key, msg) except ValueError: return "Message is not decodable. It is either invalid or has been corrupted." return result def valid_string(key_list): for word in key_list: for letter in word: if not letter.isalpha() and letter != ' ': return False return True def send_msg(name): data = load_data() recipient = input("Please input the name of the person you wish to contact: ") while recipient is '': recipient = input("Cannot have an empty name. Please try again: ") msg = encode_decode(True) if recipient in data['users']: data['users'][recipient][name] = msg else: data['users'][recipient] = { name : msg, } save_data(data) print("Message sent.") def check_msg(name): data = load_data() sender = None if name not in data['users']: print("No messages for you.") return else: if len(data['users'][name]) == 1: for person in data['users'][name]: sender = person print("You have one message from " + sender + ':') print("'" + data['users'][name][sender] + "'") else: persons = [x for x in data['users'][name]] print("You have multiple messages. Please select who's message you would like to read:") for i in range(len(persons)): print(" " + str(i) + ": " + persons[i]) p_id = input("Please select a message: [0-" + str(len(persons) - 1) + "]: ") while not p_id.isdigit() or int(p_id) < 0 or int(p_id) > len(persons) - 1: p_id = input("Invalid choice. Please insert number between 0 and " + str(len(persons) - 1) + ": ") sender = persons[int(p_id)] print("The message from " + sender + " is:") print("'" + data['users'][name][sender] + "'") choice = input("Would you like to decode your message? [Y/N] ") while choice not in ['Y', 'y', 'N', 'n']: choice = input("Invalid choice. Please choose between yes ('Y') and no ('N'): ") if choice is 'Y' or choice is 'y': result = encode_decode(False, msg=data['users'][name][sender]) print("Result:") print(result) def serve_info(): print("Please choose which cipher you would like more info on:") for i in range(len(methods)): print(' - ' + str(i) + ' : ' + methods[i]) choice = prompt() correct = False while not correct: try: choice = int(choice) if choice < 0 or choice >= len(methods): raise ValueError correct = True except ValueError: correct = False print("Input was not an int or not a valid choice. Please choose a valid method. (Int between 0 and " + str(len(methods) - 1) + ")") choice = prompt() print("A brief overview on the " + methods[choice] + " method:") print(overview[choice]) print(' ') more = input("Would you like a more in depth explanation of how this cipher works? [Y/N] ") while more not in ['Y', 'y', 'N', 'n']: more = input("Invalid choice. Please choose between yes ('Y') and no ('N'): ") if more in ['Y', 'y']: print(' ') print(in_depth[choice]) print(' ') def do_cmd(cmd, name): if cmd is '?': help_cmd() elif cmd is 'e': print('\n', encode_decode(True), '\n') elif cmd is 'd': print('\n', encode_decode(False), '\n') elif cmd is 'i': serve_info() elif cmd is 'n': name = input("Please input your name: ") while name is '': name = input("Cannot have an empty name. Please try again: ") elif cmd is 'r': choice = input("Are you sure you want to reset the database? [Y/N] ") if choice is 'Y' or choice is 'y': print("Resetting databse.") data = reset_data() save_data(data) else: print("Database not reset") elif cmd is 's': send_msg(name) elif cmd is 'c': check_msg(name) elif cmd is '': pass else: print("Invalid command. For help with commands use '?") return name
926c7141c1f6ad007ba57652c1de5c30913d1bbb
chetan1327/Engineering-Practical-Experiments
/Semester 4/Analysis of Algorithm/KMP.py
1,245
3.828125
4
# for proper examples refer https://www.geeksforgeeks.org/kmp-algorithm-for-pattern-searching/ # https://www.youtube.com/watch?v=V5-7GzOfADQ # uncomment print statements to see how the table is updated def prefixTable(pattern): prefix_table = [0] for i in range(1, len(pattern)): j = prefix_table[i-1] # print(f"(i,j): {i, j}") while(j > 0 and pattern[j] != pattern[i]): # print(f"In while j values: {j}, table[{j}]: {prefix_table[j-1]}, Pattern[{j}]: {pattern[j]}, Pattern[{i}]: {pattern[i]}") j = prefix_table[j-1] # print(f"J: {j}, Pattern[{j}]: {pattern[j]}, Pattern[{i}]: {pattern[i]}") prefix_table.append(j+1 if pattern[j] == pattern[i] else j) # print(f"Table: {prefix_table}") # print() return prefix_table print(prefixTable("abadab")) def kmp(text, pattern): table, ret, j = prefixTable(pattern), [], 0 print(table) for i in range(len(text)): while j > 0 and text[i] != pattern[j]: j = table[j - 1] if text[i] == pattern[j]: j += 1 if j == len(pattern): ret.append(i - j + 2) j = table[j - 1] return ret print(kmp("badbabababadaa", "ababada"))
dc46a8bfea15801f06752ddb74bcf0c9369eb82c
heyf/cloaked-octo-adventure
/leetcode/118_pascals-triangle.py
667
3.734375
4
#!/usr/bin/python3 # 118. Pascal's Triangle - LeetCode # https://leetcode.com/problems/pascals-triangle/description/ class Solution(object): def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ if numRows == 0: return [] res = [[1]] for i in range(1,numRows): row_res = [1] j = 1 while j < i: row_res.append( res[i-1][j-1] + res[i-1][j] ) j += 1 row_res.append(1) res.append(row_res) return res s = Solution() print(s.generate(0)) print(s.generate(5))
3a847330ebcaa1b06ce4d5443c88edd9b4ae9fc8
rmdimran/Mastering_Python
/Functions.py
197
3.984375
4
def say_hello(name, age): print("Hello " + name + " you are " + age + " years old!") say_hello("John", "35") """ x = input("ENter the name") y = input("enter the age") say_hello(x,y) """
677eeecdb84f436da5f3864eef89dc451337214c
lingzhi42166/Python
/1_基础/12_循环结构.py
1,337
3.515625
4
# range控制循环次数 提供两个参数 第一个参数 代表从该参数值开始 到参数2-1停止 #条件不成立 或循环结束后 执行else else主要用于 循环体内控制条件为不成立后执行else 比如给你三次登录机会 输入密码错误三次 则把循环条件设为false 被else捕捉执行 #break continue 不会执行else # python3中range有一个优化 就是每循环一次 就在原本的内存空间中 更新值 # python2中是 range几个数 就开辟几个内存空间 for i in range(1,10): #1~9 不包括10 print(i) for i in range(10):#0~9 i += 1 else: print(i) # while i = 0 while i<100: i+=1 print(i) i = 0 while i<100: i+=1 else:#条件不成立 或循环结束后 执行else print(i) #break(结束所属层次的循环) continue(提前结束本次循环 进行下一次循环 同样是同层次的) 跟js的一样 #break continue 不会执行else print('==========') for i in range(10): #==> let i = 0 ; i<10 i++ if(i==9): break print(i)#012345678 print('==========') for i in range(10): if(i==8): continue print(i)#012345679 for i in ["1",'2','3']: print(i) # 遍历 字典 返回key obj = {"key":"value"} for i in obj: print(i) print(obj[i]) for k,v in ([(0,0)]): print(k,v) # 0 0 for k,v in [(0,0)]: print(k,v) # 0 0
0575793c93bf6ef0c43d53a5c4f58ca3cac6cee0
kehochman/Python-Challenge
/PyBank/main.py
2,377
3.625
4
import os import csv budget = r'C:\Users\kehoc\Documents\GWU-ARL-DATA-PT-12-2019-U-C\02-Homework\03-Python\Instructions\PyBank\Resources\budget_data.csv' budget_analysis = os.path.join("Analysis", "budget_analysis.txt") # open and read csv with open(budget, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") csv_header = next(csvfile) # skip header row print(f"Header: {csv_header}") # find net amount of profit and loss P = [] months = [] #read through each row of data after header for rows in csvreader: P.append(int(rows[1])) months.append(rows[0]) # find revenue change rev_change = [] for x in range(1, len(P)): rev_change.append((int(P[x]) - int(P[x-1]))) # calculate average revenue change rev_average = sum(rev_change) / len(rev_change) # calculate total length of months total_months = len(months) # greatest increase in revenue greatest_increase = max(rev_change) # greatest decrease in revenue greatest_decrease = min(rev_change) # print the Results print("Financial Analysis") print("....................................................................................") print("Total Months: " + str(total_months)) print("Total: " + "$" + str(sum(P))) print("Average change: " + "$" + str(rev_average)) print("Greatest Increase in Profits: " + str(months[rev_change.index(max(rev_change))+1]) + " " + "$" + str(greatest_increase)) print("Greatest Decrease in Profits: " + str(months[rev_change.index(min(rev_change))+1]) + " " + "$" + str(greatest_decrease)) # output to a text file file = open("Analysis/output.txt","w") file.write("Financial Analysis" + "\n") file.write("...................................................................................." + "\n") file.write("Total Months: " + str(total_months) + "\n") file.write("Total: " + "$" + str(sum(P)) + "\n") file.write("Average Change: " + "$" + str(rev_average) + "\n") file.write("Greatest Increase in Profits: " + str(months[rev_change.index(max(rev_change))+1]) + " " + "$" + str(greatest_increase) + "\n") file.write("Greatest Decrease in Profits: " + str(months[rev_change.index(min(rev_change))+1]) + " " + "$" + str(greatest_decrease) + "\n") file.close()
53f03b45824b06ecaeaa33885c590c820c287d2f
EarthChen/LeetCode_Record
/easy/excel_sheet_column_title.py
757
3.8125
4
# Given a positive integer, # return its corresponding column title as appear in an Excel sheet. # # For example: # # 1 -> A # 2 -> B # 3 -> C # ... # 26 -> Z # 27 -> AA # 28 -> AB # class Solution: def convertToTitle(self, n): """ 将数字转换为excel的列名 :param n: int :return: str """ # 存放结果的字符串 res = '' # n不为0时进入循环 while n != 0: # 求余得到一个字符 ch = chr((n - 1) % 26 + 65) # 除以26求模 n = (n - 1) // 26 res = ch + res return res if __name__ == '__main__': solution = Solution() print(solution.convertToTitle(53))
4d0cb08fb2ec76a688dcb16d57b0afc274f55a52
harsham4026/ds-algo
/python/binary_search/only_once_in_sorted_array.py
1,807
4
4
""" Find the element that appears once in a sorted array, where all others appear twice. Given a sorted array in which all elements appear twice (one after one) and one element appears only once. Find that element in O(log n) complexity. """ """ A variant of the non_duplicate_element problem in lists where the list is sorted. Sorted = the strongest hint for an application of binary search. Now a binary search requires that we have a target element that we are searching. Here we don't have anything. However can we partition the array into two and be certain that the element doesn't exist in one part of the array? This is possible because if an element is present twice, and it is on the right side if the mid value is even and arr[mid] = arr[mid+1]. """ def only_once_in_sorted_array(arr: list) -> int: n = len(arr) if n == 0: return None # Edge case with no elements, is that valid? low = 0 high = n while low <= high: mid = (low + high ) // 2 if mid % 2 == 0: if mid + 1 < n and arr[mid] == arr[mid + 1]: low = mid + 1 elif mid > 0 and arr[mid] == arr[mid - 1]: high = mid - 1 else: return arr[mid] if mid % 2 != 0: if mid > 0 and arr[mid] == arr[mid - 1]: low = mid + 1 elif mid + 1 < n and arr[mid] == arr[mid + 1]: high = mid - 1 else: return arr[mid] # Tests tests = [ # List of the input array and the expected output. ([1, 1, 2], 2), ([], None), ([1], 1), ([2, 2, 3, 3, 4, 4, 6], 6), ([2, 2, 3, 4, 4, 6, 6], 3), ([0, 2, 2, 3, 3, 4, 4, 6, 6], 0), ] for (arr, expected) in tests: assert only_once_in_sorted_array(arr) == expected
e11196ff003aa513de2bc01ca0d1a24338917175
leandrominer85/Data-Analysis-Bitcoin-price-Klines
/python_code/data_visualizator.py
1,872
3.671875
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import plotly.graph_objects as go import pandas as pd import glob import os # In[12]: def data_vis(path = '..\data\cleaned'): ''' This function receives a path for the data. First it asks the user wich file(complete path) he wants. Uses this to load the dataframe. Then ask the dates for creating the graphs. Wich is used to create a filtered dataframe that feeds the Candestick graph Input: path - str; the path to the original data Output: Interactive candestick graph. ''' #Uses glob to get the list of files path = path files = glob.glob(path + "/*.csv") print("Select one of the data:") for i in files: print(i) #fet the file path file_path = input("File path") df = pd.read_csv(file_path, index_col="date") print() print("Select a date between {} and {}".format(df.index.min(), df.index.max())) print() #get the dates init_date = input("Begin date (format : year-month-day hour:min:sec). Ex: '2020-02-19 17:30:00'") final_date = input("Final date (format : year-month-day hour:min:sec). Ex: '2020-02-19 17:30:00'") #drop the unused column and filter the data df.drop("Unnamed: 0",axis=1, inplace=True) df2 = df[init_date:final_date] #get all fundings rates for the date range fundings = ["Funding Rate: {}".format(i) for i in df2["fundingRate"].values] #plot the graph fig = go.Figure(data=[go.Candlestick(x=df2.index, open=df2['open'], high=df2['high'], low=df2['low'], close=df2['close'], text =fundings) ]) fig.show() # In[13]: data_vis() # In[ ]: # In[ ]:
920b611d4aea28b23896e6c10b015128d2c002e6
akcezzz/Learning-the-Snake
/01-Python Object and Data Structures Basics/Data Types/Sets.py
283
4.09375
4
### Sets ### #Declaring a set myset = set({1,2}) #Sets elements are unique (cannot occur twice) myset.add(3) print(myset) #myset.add(3) will do nothing mylist = [1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4] myset = set(mylist) print(myset) #prints 1,2,3,4 only
81f575df7a6b1ec9e1e4b6f41e6c64e914188990
CodeForContribute/Algos-DataStructures
/searching&Sorting/InterPolationSearch.py
1,311
3.96875
4
""" Time Complexity: If elements are uniformly distributed, then O (log log n)). In worst case it can take upto O(n). Auxiliary Space: O(1) The Interpolation Search is an improvement over Binary Search for instances, where the values in a sorted array are uniformly distributed. Binary Search always goes to the middle element to check. On the other hand, interpolation search may go to different locations according to the value of the key being searched. For example, if the value of the key is closer to the last element, interpolation search is likely to start search toward the end side. """ def interpolation_search(arr, n, x): left = 0 right = n - 1 while left <= right and arr[left] <= x <= arr[right]: if left == right: if arr[left] == x: return left return -1 position = left + int(((x - arr[left]) * (right - left) / (arr[right] - arr[left]))) if arr[position] == x: return position elif arr[position] > x: right = position - 1 elif arr[position] < x: left = position + 1 return -1 if __name__ == '__main__': arr = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610] x = 55 n = len(arr) print(interpolation_search(arr, n, 55))
85fc1361f6c0ba879f996e367e2b6ddf94d1f6ca
DavidVollendroff/lambdata
/lambdata_davidvollendroff/df_utils.py
822
4.03125
4
""" Utility functions for working with DataFrames """ import pandas import numpy as np TEST_DF = pandas.DataFrame([1, 2, 3]) def explore_df(dataframe): """ Performs basic exploration tasks for a newly created dataframe """ print(dataframe.describe()) print('Null Values\n', dataframe.isnull().value_counts()) print('Head\n', dataframe.head()) print('Tail\n', dataframe.tail()) class SquareTetromino: """ A square shaped block for my PyTetris game. """ def __init__(self): self.type = "O" self.color = (255, 255, 0) mold = np.zeros([24, 10]) # framework for falling piece mold[1, 4:6] = 1 # placing 1s where the piece begins mold[2, 4:6] = 1 self.position = [mold, mold, mold, mold] # square looks the same under rotation
23cae418b32e0bd750bfc30745f86fff31ea9eea
DiegoMarulandaB/Curso-python-basico
/7_clase_operadores_logicos_comparacion/operadores_logicos_comparacion.py
1,087
3.75
4
#operadores lógicos y comparación """ py = consola interactiva ## Operadores lógicos ## True y False es_estudiante = True es_estudiante True trabaja= False trabaja False es_estudiante and trabaja False ## True es_estudiante = True es_estudiante True trabaja = True trabaja True es_estudiante and trabaja True ## or es_estudiante or trabaja True Da resultado como False, siempre y cuando es_estudiante = False trabaja = False ## Not, invierte el valor de una variable es_estudiante = True, pero al usar not cambia el resultado not es_estudiante False not trabaja True ## Operadores de comparación numero1 = 5 numero2 = 5 numero1 == numero2 True numero3 = 7 numero1 == numero3 False Operador distinto ! = numero1 ! = numero3 True Operador > mayor numero1 > numero3 False numero3 > numero1 True Operador < menor numero1 < numero3 True Operador mayor igual > = numero1 > = numero3 False numero1 < = numero2 True numero1 < = numero2 True numero1 < = numero3 True """ #Desde la carpeta 10, inician varios ejercicios y teoria
c011d288c08bac2e19f0e7aec2391c5597430739
sajjad0057/Practice-Python
/DS and Algorithm/Algorithmic_Tools/Greedy Algorithms/Largest_Number.py
466
4.1875
4
# num = input("Enter the number : ") # list = [] # for i in num: # list.append(i) # list.sort(reverse=True) # y = '' # for x in list: # y +=x # print("The Bigest Number is : ",y) num = int(input("Enter the Number of digit : ")) number = [] for i in range(num): number.append(int(input(f'Enter the digit no - {i+1} : '))) number.sort(reverse=True) print("The Largest number is : ",end='') for i in number: print(i,end="")
5303468ae76f078cad7b8b0bc668ac86b9faf3f4
Zer0xPoint/Algorithms4_python
/1.Fundamentals/1.Programming Model/14.py
202
3.765625
4
import copy matrix = [[1,2,3],[4,5,6],[7,8,9]] temp_matrix = copy.deepcopy(matrix) for y in range(len(matrix)): for x in range(len(matrix)): matrix[y][x] = temp_matrix[x][y] print(matrix)
1d506d329e3a830d7ca1a8bdf3cf1099555cd09f
srinitude/holbertonschool-higher_level_programming
/0x0B-python-input_output/1-number_of_lines.py
489
4.53125
5
#!/usr/bin/python3 """ This module allows you to count the number of lines in a text file """ def number_of_lines(filename=""): """ Returns the number of lines in a text file Args: filename (str): The name of the file """ if type(filename) is not str: raise TypeError("filename must be a string") num_lines = 0 with open(filename, encoding="utf-8") as text_file: for line in text_file: num_lines += 1 return num_lines
38dbd9e6e194459d02bf5bd09b9bf1ed71a6af2f
jihunchoi/cross-sentence-lvm-public
/scripts/diversity.py
1,640
3.765625
4
"""Measures diversity given a text file. distinct-1 computes the ratio of unique unigrams over the total number of words. distinct-2 computes the ratio of unique bigrams. Reference: A Diversity-Promoting Objective Function for Neural Conversation Models (Li et al. NAACL 2016) """ import argparse import json from collections import Counter import nltk def main(): parser = argparse.ArgumentParser() parser.add_argument('--type', default=1, type=int, choices=[1, 2]) parser.add_argument('--data', required=True) args = parser.parse_args() ngram_counter = {'contradiction': Counter(), 'neutral': Counter(), 'entailment': Counter(), 'all': Counter()} with open(args.data, 'r') as f: for line in f: obj = json.loads(line) hyp = obj['sentence2'] words = hyp.split() ngrams = list(nltk.ngrams(words, n=args.type)) if obj['gold_label'] not in ['entailment', 'contradiction', 'neutral']: continue ngram_counter['all'].update(ngrams) ngram_counter[obj['gold_label']].update(ngrams) print('---- distinct-{args.type} ----') for label, counter in ngram_counter.items(): num_total_ngrams = sum(counter.values()) num_unique_ngrams = len(counter.keys()) print('------') print(label) print(f'# total ngrams: {num_total_ngrams}') print(f'# unique ngrams: {num_unique_ngrams}') print(f'distinct-{args.type} = {num_unique_ngrams / num_total_ngrams}') if __name__ == '__main__': main()
cc047de320266b8b18e84ea61c119f793a1b521f
westgate458/LeetCode
/P0230.py
2,247
3.671875
4
# -*- coding: utf-8 -*- """ Created on Thu Aug 1 20:51:01 2019 @author: Tianqi Guo """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def kthSmallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int """ # Solution 1: iteratively # In-order traversal will result in sorted numbers from small to large # start traversal from root, counting c till k s, node, c = [], root, 0 # traversal goes on forever since it is guaranteed the answer exists while True: # if current node is not None while node: # place it into the stack s.append(node) # move on to its left child node = node.left # when the while loop ends, it means the left child is None # and the parent of that child is the smallest in its own subtree # pop this parent node = s.pop() # now this node is visited, and it is the c-th smallest number c += 1 # if we have counted to k if c == k: # value of this node is the k-th smallest number return node.val # if we have not reached k # move on to its right child node = node.right # Solution 2: recursively def helper(root, k): if not root: return (0, None) nodes_left, res = helper(root.left, k) if res != None: return (None, res) elif k == nodes_left + 1: return (None, root.val) else: nodes_right, res = helper(root.right, k - (nodes_left + 1)) if res: return (None, res) else: return (nodes_left + nodes_right + 1, None) _, res = helper(root, k) return res
fcd8bda5e4d8670e14f159fda80d1ca708a75596
mkobierski/hobby-code
/31/31.py
5,947
3.84375
4
#!/usr/bin/python -tt from copy import deepcopy import logging LOGGER = logging.getLogger(__name__) AVAILABLE_COINS = (200, 100, 50, 20, 10, 5, 2, 1) def factorization(sum_, allow_self=False, threshold=None): """Given a number of pence, return a list containing its coin combination using the least number of coins The parameter allow_self and threshold give control over which coins may be used to form the combination. With allow_self True, factoring a sum of 5 will return a factorization of 5, otherwise it will return 2 2 1. """ LOGGER.debug("Factorization of %s...", sum_) initial_sum = sum_ combination = [] for coin in AVAILABLE_COINS: if threshold is not None: if coin > threshold: continue while float(sum_)/coin >= 1: if allow_self != True and coin == initial_sum and coin != 1: break else: combination.append(coin) sum_ -= coin LOGGER.debug(combination) return combination def last_combination_reached(combination): """Check whether the last combination has been found. """ LOGGER.debug("Checking last combination reached... ") if combination[0] == 1: LOGGER.info("Found!") return True LOGGER.debug("") return False def regroup(combination, fact_num): """Regroups and refactors the combination's coins smaller than given fact_num to their next largest form. Ex. Given a sum of 6 written as 5 1, next iteration would be (2 2 1) 1, but we know 1 and 1 can be grouped into 2. Thus, this function would return 2 2 2. """ new_combination = [] sum_to_regroup = 0 for coin in combination: if coin < fact_num: sum_to_regroup += coin else: new_combination.append(coin) new_combination = new_combination + factorization(sum_to_regroup, allow_self=True, threshold=fact_num) return new_combination def sublist_in_list(sublist, list_): """Tests whether every instance of every element of a list is contained within another list. """ _list_ = deepcopy(list_) for item in sublist: if item in _list_: _list_.remove(item) else: return False return True def find_combination(previous_combination, current_largest): """Finds the next combination given a previous combination and a parameter tracking which number was last used to expand or regroup the combination. Two outcomes of this method can exist: - the next combination is trivial as we only need to expand the leftmost list entry which isn't a value of 1 - the next combination must be found by factoring and then regrouping the rightmost elements The current_largest attribute helps in determining which case we must consider to find the next combination. """ next_largest = current_largest LOGGER.debug("") LOGGER.debug("Finding combination and next largest...") LOGGER.debug("-"*30) current_combination = [] i = len(previous_combination) - 1 previous_combination.sort(reverse=True) LOGGER.debug("Previous combination: %s", previous_combination) # Find right-most non-1 index while previous_combination[i] == 1 and i >= 0: i += -1 factorization_num = previous_combination[i] LOGGER.debug("Factorization num: %s", factorization_num) factorization_list = factorization(factorization_num) LOGGER.debug("Factorization list: %s", factorization_list) current_combination = previous_combination[:i] + factorization_list + previous_combination[i+1:] LOGGER.debug("Current combination: %s", current_combination) next_largest = factorization_num LOGGER.debug("Current largest: %s", current_largest) if factorization_num > current_largest: # Case number two, we must regroup LOGGER.debug("Factorization num is greater than current largest") next_largest = factorization_num LOGGER.debug("Next largest: %s", next_largest) factorization_num = factorization_list[0] LOGGER.debug("New factorization num: %s", factorization_num) current_combination = regroup(current_combination, factorization_num) current_combination.sort(reverse=True) LOGGER.debug("Current combination: %s", current_combination) LOGGER.debug("Next largest: %s", next_largest) return (current_combination, next_largest) def print_all_combinations(list_of_combinations): """Print function""" for combination in list_of_combinations: print_combination(combination) def print_combination(combination): """Print helper function.""" for coin in combination: LOGGER.info(coin) LOGGER.info("\n") def main(sum_): """The main method of this computational program. Creates a list of combinations, runs a loop until the final combination is found, prints, then exits. """ LOGGER.warn("Using coins from the set: %s", AVAILABLE_COINS) i = 0 list_of_combinations = [] current_largest = 1 list_of_combinations.append(factorization(sum_, allow_self=True)) while not last_combination_reached(list_of_combinations[-1]): (combination, current_largest) = find_combination(list_of_combinations[-1], current_largest) list_of_combinations.append(combination) print_all_combinations(list_of_combinations) LOGGER.warn("Number of combinations: %s", len(list_of_combinations)) return 0 if __name__ == "__main__": logging.basicConfig(level=logging.WARN) try: while True: sum_ = input("Enter an integer number of pence:") main(sum_) except KeyboardInterrupt: print "Goodbye!" except SyntaxError: print "Goodbye!"
65b8d79dbff953c0306c4a1a79a771527b0518ac
JoungChanYoung/algorithm
/programmers/자릿수더하기.py
196
3.703125
4
#level1 연습문제 def solution(n): answer = 0 string = str(n) answer = sum([int(i) for i in string]) return answer if __name__ == "__main__": print(solution(123))
6efff7fab9ac39f1bcbaf6b062bace022b8634bc
lemonadegt/PythonPracticeWithMC
/rsp.py
861
3.515625
4
import random GAWI = "가위" BAWI = "바위" BO = "보" DRAW = "무승부" WIN = "당신의 승리" LOSE = "당신의 패배" rockscissorspaper = [GAWI, BAWI, BO] states = [DRAW, WIN, LOSE] result = '' selectednum = int(input("가위 바위 보 중에서 선택해 주세요\n(가위 = 0, 바위 = 1, 보 = 2) : ")) while (selectednum < 0) or (selectednum > 2): selectednum = int(input("다시 선택해 주세요\n(가위 = 0, 바위 = 1, 보 = 2) : ")) comselectednum = random.randint(0,2) if (selectednum - comselectednum) == 0: result = states[0] elif (selectednum - comselectednum) == 1 or (selectednum - comselectednum) == -2: result = states[1] else: result = states[2] print("당신의 선택은 " + rockscissorspaper[selectednum]) print("컴퓨터의 선택은 " + rockscissorspaper[comselectednum]) print("결과는 " + result)
7770f0ff432d3d4e3a6aefd9e55dfa5db5af4288
HeGreat/DeepLearning_code
/mutiThreading.py
1,393
4.03125
4
#多线程 import threading,time def run(num): print("子线程(%s)开始"%(threading.current_thread().name)) time.sleep(2) print("打印",num) time.sleep(2) print("子线程(%s)结束"%(threading.current_thread().name)) if __name__ == "__main__": print("主线程(%s)开始"%(threading.current_thread().name)) #target我们这个线程所要执行的函数名字 t=threading.Thread(target=run,name='run',args=(1,)) t.start() #等待线程结束 t.join() print("主线程(%s)结束"%(threading.current_thread().name)) import threading,time # num=0 # def run(n): # global num # for i in range(1000000): # num=num+n # num=num-n # if __name__ == "__main__": # t1=threading.Thread(target=run,args=(6,)) # t2=threading.Thread(target=run,args=(9,)) # t1.start() # t2.start() # t1.join() # t2.join() # print('num=',num) # 加锁,一个线程操作数据的时候,其他线程就不允许操作 lock=threading.Lock() num=0 def run(n): global num for i in range(100000): #自动上锁,自动解锁 with lock: num=num+n num=num-n if __name__ == "__main__": t1=threading.Thread(target=run,args=(6,)) t2=threading.Thread(target=run,args=(9,)) t1.start() t2.start() t1.join() t2.join() print('num=',num)
87f2dcfc5dd7d32665ec92491ffcae31ce994948
joaoantoniopereira/GitHub
/parse_kibana.py
271
3.59375
4
with open('test_results.json', 'r') as myfile: data=myfile.read().replace('\n', '') res=data.split(",") grade = [k for k in res if 'grade' in k] if any("FAIL" in s for s in grade): raise Exception("At least a test has failed") else: print "Everything is Ok"
c8fc1e1caa030003bd863fea4f7dc525f038ae03
rafaelperazzo/programacao-web
/moodledata/vpl_data/142/usersdata/227/62374/submittedfiles/av2_p3_civil.py
644
3.640625
4
# -*- coding: utf-8 -*- def media(n): soma = 0 for i in range(0,len(n),1): soma = soma + n[i] media = soma/len(n) return (media) #ESCREVA AS DEMAIS FUNÇÕES def somaA(x,y): mx=media(x) my=media(y) soma=0 for i in range(0,len(x),1): soma=soma+((x[i]-mx)*(y[i])-my) return(soma) def entradaLista(q): x = [] for i in range(0,q,1): valor = float(input('Digite um valor: ')) x.append(valor) return (x) q = int(input('Digite o tamanho da lista: ')) x = entradaLista(q) y = entradaLista(q) p =somaA(x,y)/((somaD(x)*somad(y)**(0,5)) p = abs(p) print('%.4f' % p)
d6c53a4258a53691fd6df0ddc38f85f51890f1ec
fabiopapais/opencv-essentials
/Basic/transformations.py
1,507
3.59375
4
import cv2 as cv import numpy as np img = cv.imread('../Resources/Photos/park.jpg') cv.imshow('Boston', img) # Translation def translate(img, x, y): translationMatrix = np.float32([[1, 0, x], [0, 1, y]]) dimensions = (img.shape[1], img.shape[0]) return cv.warpAffine(img, translationMatrix, dimensions) # Essentially what we are doing using warpAffine is # matrix multiplication and vector additions: # https://docs.opencv.org/3.4/d4/d61/tutorial_warp_affine.html translatedImage = translate(img, 100, -50) cv.imshow('Translated', translatedImage) # Rotation def rotate(img, angle, rotpoint=None): (height, width) = img.shape[:2] if rotpoint is None: rotpoint = (width // 2, height // 2) # this time, we are getting the rotation matrix from opencv rotationMatrix = cv.getRotationMatrix2D(rotpoint, angle, 1.0) dimensions = (width, height) return cv.warpAffine(img, rotationMatrix, dimensions) rotatedImage = rotate(img, -45, (100, 200)) cv.imshow('Rotated', rotatedImage) # Resizing (another nice way that ignores aspect ratio) resizedImage = cv.resize(img, (500, 500), interpolation=cv.INTER_CUBIC) cv.imshow('Resized', resizedImage) # Flipping flippedImage = cv.flip(img, -1) # The flip code specifies how your image will be flipped cv.imshow('Flip', flippedImage) # Cropping (not an opencv method, but useful, since images are arrays) cropped = img[50:200, 200:400] cv.imshow('Cropped', cropped) cv.waitKey(0) cv.destroyAllWindows()
05048b83980de141ee9306506824d569087957de
Viniciusadm/Python
/exerciciosCev/Mundo 1/Aula 9/024.py
245
3.875
4
cidade = str(input('Em qual cidade você nasceu? ')).strip().upper().split() resposta = cidade[0] == 'SANTO' if resposta == True: print('O nome da sua cidade começa com Santo') else: print('O nome da sua cidade não começa com Santo')
bcc5f5f0189362d6f4fce050501e3a7ba94e3b75
RedLeaves699/DM-training
/Homework week2/归纳法/1.py
1,569
3.796875
4
#第一题 def power(a, n): # 请在此添加代码 #-----------Begin---------- if n==0: return 1 else: return a*power(a,n-1) #------------End----------- #第二题 def fib(n): # 请在此添加代码 #-----------Begin---------- if n==0 or n==1: return 1 else: return fib(n-1)+fib(n-2) #------------End----------- #第三题 def gcd(m, n): # 请在此添加代码 #-----------Begin---------- if n==0: return m else : return gcd(n,m%n) #------------End----------- #第四题 def f(n): # 请在此添加代码 #-----------Begin---------- if n==0: return 1 else : return 1+1/f(n-1) #------------End----------- for n in range(10): print(f(n)) print('*'*20) #第五题 def fib2(n): # 请在此添加代码 #-----------Begin---------- if n==0: return 0 elif n==1: return 1 elif n%2==0: n=n/2 return (2*fib2(n-1)+fib2(n))*fib2(n) elif n%2==1: n=(n+1)/2 return fib2(n-1)**2+fib2(n)**2 #------------End----------- if __name__=="__main__": for (a,n) in [(0, 0), (10, 0), (20, 2), (12, 4), (30, 10)]: print(power(a, n)) print('*'*20) for n in range(10): print(fib(n)) print('*' * 20) for (m,n) in [(12,3), (12, 31), (24,13), (2,1237000)]: print(gcd(m,n)) print('*' * 20) for n in range(10): print(f(n)) print('*' * 20) for n in range(11): print(fib2(n))
01580d1945c5883ea37f139bec279fe4bef93a59
strengthen/LeetCode
/Python3/152.py
3,202
3.8125
4
__________________________________________________________________________________________________ sample 48 ms submission class Solution: def maxProduct(self, nums: List[int]) -> int: def split(nums: List[int], n: int): """ Split the list at elements equal to n """ ret = [] while (True): try: find_index = nums.index(n) except ValueError: ret.append(nums) return ret ret.append(nums[:find_index]) nums = nums[find_index + 1:] def prod(lst: List[int]): """ Return the product of all numbers in the list. If the list is empty, return one. """ ret = 1 for n in lst: ret *= n return ret def maximize(lst: List[int]): """ Return the maximun product possible in the list. Assume it doesn't include zeros. """ ret = prod(lst) if ret > 0: return ret # If the product is negative, there must be an odd # number or negative numbers in the list # If the list is 1-element long, is already maximized if len(lst) == 1: return ret # Search the first and last negative elements for i, n in enumerate(lst): if n < 0: first_negative = i break for i, n in enumerate(reversed(lst), start=1): if n < 0: last_negative = len(lst) - i break # Check which slice's product is larger (in magnitude) first_prod = prod(lst[:first_negative + 1]) last_prod = prod(lst[last_negative:]) return ret // max(first_prod, last_prod) splitted = split(nums, 0) has_zero = len(splitted) > 1 maximized = [maximize(l) for l in splitted if len(l) > 0] if maximized: if has_zero: return max(max(maximized), 0) else: return max(maximized) else: if has_zero: return 0 else: raise ValueError("Given empty list") __________________________________________________________________________________________________ sample 13120 kb submission class Solution: def maxProduct(self, nums: List[int]) -> int: if len(nums) == 1: return nums[0] import sys gmax = nums[0] imax = nums[0] imin = nums[0] for j in range(1, len(nums)): if nums[j] < 0: imax,imin = imin, imax imax = max(nums[j], nums[j]*imax) imin = min(nums[j], nums[j]*imin) if imax > gmax: gmax = imax return gmax __________________________________________________________________________________________________
e38f38e932550d964eb5c320fa3f58ec95b16e7c
arunansu/UdacityML
/TechnicalInterview/TechnicalInterview/Question4.py
2,173
4.15625
4
#Question 4: Find the least common ancestor between two nodes on a binary search tree. #The least common ancestor is the farthest node from the root that is an ancestor of both nodes. #For example, the root is a common ancestor of all nodes on the tree, #but if both nodes are descendents of the root's left child, #then that left child might be the lowest common ancestor. #You can assume that both nodes are in the tree, and the tree itself adheres to all BST properties. #The function definition should look like "question4(T, r, n1, n2)", #where T is the tree represented as a matrix, where the index of the list is equal to the integer #stored in that node and a 1 represents a child node, r is a non-negative integer representing the root, #and n1 and n2 are non-negative integers representing the two nodes in no particular order. #For example, one test case might be #question4([[0,1,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[1,0,0,0,1],[0,0,0,0,0]],3,1,4), and the answer would be 3. class Node(object): def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def populateTree(T,r,root): i = 0 for column in T[r]: if column == 1 and i < root.value: root.left = Node(i) elif column == 1 and i > root.value: root.right = Node(i) i += 1 if root.left != None: populateTree(T, root.left.value, root.left) if root.right != None: populateTree(T, root.right.value, root.right) def LCA(root, n1, n2): if root.value == None: return None elif root.value > n1 and root.value > n2: return LCA(root.left, n1, n2) elif root.value <= n1 and root.value < n2: return LCA(root.right, n1, n2) return root.value def question4(T, r, n1, n2): root = Node(r) populateTree(T, r, root) return LCA(root, n1, n2) print question4([[0,1,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[1,0,0,0,1],[0,0,0,0,0]],3,1,4) #3 print question4([[0,0,0,0,0],[1,0,1,0,0],[0,0,0,0,0],[0,1,0,0,1],[0,0,0,0,0]],3,0,2) #1 print question4([[0,0,0,0,0],[1,0,0,0,0],[0,1,0,1,0],[0,0,0,0,0],[0,0,1,0,0]],4,0,3) #2
d7e32c5b37ab9e48b54367f8f097d943285f30ef
dankami/StudyPython
/algorithm/Coroutine.py
625
3.90625
4
# 协程demo # 生产消费者模式 # def foo(): # print("starting...") # while True: # res = yield 4 # print("res:",res) # g = foo() # print(next(g)) # print("*"*20) # print(next(g)) # def consume(): # while True: # number = yield # print("开始消费", number) # consumer = consume() # next(consumer) # for num in range(0, 100): # print("开始生产", num) # consumer.send(num) import time def countNum(): for num in range(0, 10): print(num) time.sleep(1) yield conCountNum = countNum() next(conCountNum) print("hello")
ade6364bb0a065c423d748449d41043bf9eefdac
arcaputo3/daily_coding_problem
/arrays/find_elt_rotated_arr.py
2,575
3.953125
4
""" This problem was asked by Amazon. An sorted array of integers was rotated an unknown number of times. Given such an array, find the index of the element in the array in faster than linear time. If the element doesn't exist in the array, return null. For example, given the array [13, 18, 25, 2, 8, 10] and the element 8, return 4 (the index of 8 in the array). You can assume all the integers in the array are unique. We will be sending the solution tomorrow, along with tomorrow's question. As always, feel free to shoot us an email if there's anything we can help with. [1, 2, 3, 4] """ def binary_search(arr, l, r, x): """ Finds the index of the elt in a sorted array. If the item doesn't exit, returns null. """ # Check base case if r >= l: mid = l + (r - l) // 2 # If element is present at the middle itself if arr[mid] == x: return mid # If element is smaller than mid, then it # can only be present in left subarray # Else the element can only be present # in right subarray if arr[mid] > x: return binary_search(arr, l, mid - 1, x) return binary_search(arr, mid + 1, r, x) else: # Element is not present in the array return None def find_pivot(arr, lo, hi): """ Finds pivot in a rotated array. """ # Base Cases if hi < lo: return None if hi == lo: return lo mid = (lo + hi) // 2 # Pivot is index such that current element > next element # In these cases we have found pivot if mid < hi and arr[mid] > arr[mid + 1]: return mid if mid > lo and arr[mid] < arr[mid - 1]: return mid - 1 # If lo element greater than mid element, pivot is between lo and mid if arr[lo] >= arr[mid]: return find_pivot(arr, lo, mid - 1) # o.w. pivot between mid and hi return find_pivot(arr, mid + 1, hi) def find_elt(arr, x): """ Finds index of element x in rotated sorted array.""" lo, hi = 0, len(arr) - 1 # Get pivot element ind = find_pivot(arr, lo, hi) # If no pivot, array is sorted - reg. binary search if not ind: return binary_search(arr, lo, hi, x) # Lucky case x is pivot element if x == arr[ind]: return ind # If first elt. if arr[0] > x: return binary_search(arr, ind + 1, hi, x) return binary_search(arr, 0, ind - 1, x) if __name__ == "__main__": # Test cases print(find_elt([13, 18, 25, 2, 8, 10], 8)) print(find_elt([4, 5, 6, 8, 1, 2, 3, 4], 2))
1f172d54156b2b1cdb3bdba06f8d099d333efb20
lari5685/nsuts
/number_8.py
239
3.734375
4
max = 10**6 min = 0 while True: num = min + (max - min )//2 print('? '+ str(num)) inp = input() if inp == '=': print('! ' + str(num)) break if inp == '>': min = num + 1 elif inp == '<': max = num - 1
e1ac9a49b0a884a64f18a5f454dd33b346f4f580
navi29/HackerRank-30-Days-of-Code-Python-Solutions
/Day-8.py
591
4.0625
4
#--------------------------------------------- #Problem Statement: https://www.hackerrank.com/challenges/30-dictionaries-and-maps/problem #--------------------------------------------- #Language: Python #--------------------------------------------- #Solution: #--------------------------------------------- n = int(input()) name_numbers = [input().split() for _ in range(n)] phone_book = {k: v for k,v in name_numbers} for i in range(n): name = input() if name in phone_book: print('%s=%s' % (name, phone_book[name])) else: print('Not found')
eb4bc01d7c293d7a109963bb79568df3363866a0
rrabit42/Python-Programming
/문제해결과SW프로그래밍/Lab7-Turtle graphics&loop statement(break,continue...)/lab7-2.py
221
4
4
""" 엘텍공과대학 소프트웨어학부 1871063 김서영 """ import turtle t = turtle.Pen() t.color("blue") t.begin_fill() for i in range(5): t.forward(100) t.right(144) t.end_fill()
c45347468b74321acc2a553d948cedd59e3e6ed1
XUAN-CW/python_learning
/sundry/11-循环代码优化测试.py
452
3.5625
4
#循环代码优化测试 import time start = time.time() for i in range(1000): result = [] for m in range(10000):#循环里的东西尽量往外提 result.append(i*1000+m*100) end = time.time() print("耗时:{0}".format((end-start))) start2 = time.time() for i in range(1000): result = [] c = i*1000 for m in range(10000): result.append(c+m*100) end2 = time.time() print("耗时:{0}".format((end2-start2)))
06363053e61596c338e7a9fc1bd8de614fb1ee25
Zeisha/Learning
/ListCode/BankFile.py
2,551
4
4
import os.path as record import random class Bank: def __init__(self, accountnumber): if record.exists(f"{accountnumber}.txt"): # read data to variables from record with open(f"{accountnumber}.txt", "r") as reader: values = reader.readlines() self.firstname , self.lastname = values[0].split(" ") self.accountnumber = accountnumber self.balance = 0.0 self.transaction = [] else: #put values to record from user input self.firstname = input("Please enter first name: ") self.lastname = input("Please enter Last name: ") self.accountnumber = random.random() self.balance = 0.0 self.transaction = [] with open(f"{self.accountnumber}.txt", "w") as writer: writer.write(self.firstname) writer.write(self.lastname) writer.write(f"\n{self.accountnumber}") print("Your AccountNumber is:" + str(self.accountnumber)) writer.write(f"\n{self.balance}") def deposit(self, amount): print(f"Adding money {amount} to existing balance {self.balance}") self.balance += amount with open(f"{self.accountnumber}.txt", "r+") as depositentry: f1 = depositentry.readlines() f1[2] = str(self.balance) #with open(f"{self.accountnumber}.txt", "w") as writer: depositentry.writelines(f1) self.transaction.append(amount) def withdraw(self, amount): if amount <= self.balance : print(f"Removing money {amount} from current balance {self.balance}") self.balance = self.balance - amount with open(f"{self.accountnumber}.txt", "r+") as withdrawentry: f1 = withdrawentry.readlines() f1[2] = str(self.balance) #with open(f"{self.accountnumber}.txt", "w") as writer: withdrawentry.writelines(f1) self.transaction.append(-amount) else: print("You do not have sufficient balance to withdraw") def recent_transaction(self): print(f"Current Balance is {self.balance}") print("Recent 2 transactions are ") self.transaction.reverse() for tran in self.transaction: print(tran) if __name__ == "__main__": b = Bank("Memo1006885") b.deposit(100) b.withdraw(200) b2 = Bank("German104") b2.deposit(40000) b2.withdraw(10000)
b1c09c0e3a1d3c33559ccb98a3820d3f1b729116
ryohang/java-basic
/python/DetectLoopInList.py
514
3.875
4
class Node: def __init__(self, val, nextVal=None): self.val = val self.next = nextVal def detectLoop(head): p1 = head p2 = head.next while p1!=None and p2!=None: if p1 == p2: return True else: p1 = p1.next p2 = p2.next if p2==None: return False p2 = p2.next return False n1 = Node(1) n2 = Node(2) n3 = Node(3) n1.next = n2 n2.next = n3 n3.next = n1 print(detectLoop(n1))
3900b6117c6f69857a7103603db66d76c5b6b42f
Tetfretguru/it_carreer
/Graficado/agrupamiento_jerarquico.py
2,343
3.640625
4
import random import numpy as np class Vector: def __init__(self, x, y): self.x = x self.y = y def get_coordenadas(self): return (self.x, self.y) def __str__(self): return f'{self.x}#{self.y}' def generar_vector(): """ Cada vector tiene caracteristicas heredadas de una clase """ vectores = [] for _ in range(6): vector = Vector(random.randint(0,6), random.randint(0,6)) vectores.append(vector) return vectores """ Ahora vamos a obtener la distacia metrica usando Manhattan """ def get_distancia_manhattan(vector_a, vector_b): return abs(vector_a.x - vector_b.x) + abs((vector_a.y - vector_b.y)) def main(): vectores = generar_vector() """ Codigo para graficar """ #Ahora, el alg agrupara vectores en clusters clusters = [] #cluster vacío para ir agregando #Definimos un primer vector al azar primer_vector = random.choice(vectores) clusters.append([primer_vector]) vectores.remove(primer_vector) #Una vez añadido al cluster lo sacamos de la lista de vectores """ Memoization para agilizar el cómputo. Guardamos las distancias en un dict""" distancias = {} cluster = clusters[-1][::] #el primer vector del cluster lo asignamos a la variable while vectores: menor_distancia = '' #void for vector_tracked in cluster: for vector in vectores: if f'{vector_tracked}*{vector}' not in distancias.keys(): distancia = get_distancia_manhattan(vector_tracked, vector) distancias[f'{vector_tracked}*{vector}'] = distancia if menor_distancia: if distancias[menor_distancia] > distancias[f'{vector_tracked}*{vector}']: menor_distancia = f'{vector_tracked}*{vector}' else: menor_distancia = f'{vector_tracked}*{vector}' #Los pasamos a enteros siguiente_v_x = int(menor_distancia.split('*')[1].split('#')[0]) siguiente_v_y = int(menor_distancia.split('*')[1].split('#')[0]) for vector in vectores: if vector.x == siguiente_v_x and vector.y == siguiente_v_y: cluster.append(vector) vectores.remove(vector) clusters.append(cluster[::]) break for cluster in clusters: for vector in clusters: print(vector) print('') print('--' * 20) print('') if __name__ == '__main__': main()
bb110c536fc39b10657a159ebd92765994fc2fab
MichSzczep/PythonLab
/zad4d.py
548
3.53125
4
import random matrix1=[] matrix2=[] summed_matrix=[] for j in range (128): numbers=[] for i in range (128): numbers.append(random.randrange(100)) matrix1.append(numbers) for j in range (128): numbers=[] for i in range (128): numbers.append(random.randrange(100)) matrix2.append(numbers) for j in range (128): numbers=[] for i in range (128): numbers.append(matrix1[j][i]+matrix2[j][i]) summed_matrix.append(numbers) print(matrix1) print(matrix2) print(summed_matrix)
96c36a3439cdcd702d9c289ab0b6b822d496235a
nagireddy96666/Interview_-python
/nestedif.py
124
4.0625
4
n=input("enter a num") if n==1: print n elif n==2: print n elif n==3: print n else: print "enter valid num"
488271a8a5285c2f1e7cbbc45f06fc850d02cd94
pussinboot/euler-solutions
/euler_25.py
308
3.859375
4
def gen_fibb(): """ Generate an infinite sequence of fibonacci numbers. """ f1 = 0 f2 = 0 new = 1 while True: yield new f1 = f2 f2 = new new = f1 + f2 g = gen_fibb() n = next(g) i = 1 while len(str(n)) < 1000: i += 1 n = next(g) print(n) print(i)
3eb7c8b2f97cf53f233e3fff42e65ec40ede9a6d
marcossouz/python-estudos
/arquivos-python/arq.py
223
3.59375
4
# # Escreve duas linhas no arquivo in.txt # Uma por vez # fout = open('in.txt', 'w') print (fout) line1 = 'This here\'s the wattle,\n' line2 = 'the emblem of our land.\n' fout.write(line1) fout.write(line2) fout.close()
89b2f91a52db6dbec0cf2bb7cbabdd039a40d2d7
porkstoners/LP3THW
/ex3.py
359
3.75
4
# A comment, this is so you can read your program laters. # Anything after the # is ignored by python print("I could have a code like this.") # and the comment after is ignored # You can alos use a comment to "disable" or comment out code: # print("This will not run") print("This will run") print("Well What about this ### can i print these hashes ??? ")
6184c2da91f8ea96c61c17c2e6984c8eb934275c
cappe987/MMA500-project
/Main.py
2,779
3.65625
4
from AI import AI import random import enum class PlayerType(enum.Enum): Human = True AI = False class Game: def __init__(self, size, p1, p2): self.board = [] self.size = size self.turn = 'X' self.moves = 0 self.p1 = p1 self.p2 = p2 self.AI1 = AI(size, "X") self.AI2 = AI(size, "O") for i in range(size): self.board.append([]) for _ in range(size): self.board[i].append(' ') def printBoard(self): num = self.size for i in range(self.size): print(" ", end="") for i in range(self.size): print("/\\", end="") print() for i in range(self.size): num = num - 1 for _ in range(num): print(" ", end="") print("|", end="") for j in range(self.size): print(str(self.board[i][j]) + "|", end="") print() for _ in range(num): print(" ", end="") print("/", end="") for _ in range(self.size): print("\\/", end="") print() # print("\n---------------") # /\ # |5 | # \/ def doBestMove(self): if (self.turn == 'X'): (bestI, bestJ) = self.AI1.doMove(self.board, self.moves, self.turn, self.AI2.paths) print("Placing X in position " + str(bestI) + ":" + str(bestJ)) self.board[bestI][bestJ] = "X" self.turn = 'O' self.moves = self.moves + 1 elif (self.turn == "O"): (bestI, bestJ) = self.AI2.doMove(self.board, self.moves, self.turn, self.AI1.paths) print("Placing O in position " + str(bestI) + ":" + str(bestJ)) self.board[bestI][bestJ] = "O" self.turn = 'X' self.moves = self.moves + 1 def playGame(self): while self.moves != self.size*self.size: if self.turn == 'X': if self.p1 == PlayerType.Human: self.humanInput() else: self.doBestMove() else: if self.p2 == PlayerType.Human: self.humanInput() else: self.doBestMove() self.printBoard() def botPlay(self): for _ in range(self.size*self.size): # while True: self.doBestMove() self.printBoard() input("Press enter to continue") def humanInput(self): if(self.turn == 'X'): print("Player X") x = int(input("Input x: ")) y = int(input("Input y: ")) self.board[x][y] = "X" self.turn = "O" elif(self.turn == 'O'): print("Player O") x = int(input("Input x: ")) y = int(input("Input y: ")) self.board[x][y] = "O" self.turn = "X" game = Game(7, PlayerType.Human, PlayerType.AI) game.printBoard() # game.playGame() game.botPlay() # Keep track of paths for humans. # Human play currently does not work and the PlayerType isn't used.
d468ae7b16dca77443c98f75e81022145456ef30
yahusun/p0427
/4_dict/dict_age.py
847
4
4
# 請讀取輸入, 建立一個 dictionary 記錄班上的同學名字以及他們對應的歲數. # 寫一個函數 prAge(name), 如果 name 存在 dictionary, 印出名字和歲數, 否則印出 N/A, 例如: prAge('Bob') 印出 Bob 10, prAge('John') 印出 N/A ages = {} def prAge(name): if ages.get(name): print(name, ages.get(name)) else: print("n/a") def test(): num = int(input()) for i in range(0,num): line = input() tokens = line.strip().split() #tokens後面是被切割好的字串list name = tokens[0] age = int(tokens[1]) ages[name] = age print(ages) num = int(input()) for i in range(0, num): line = input() prAge(line) test() #要測試的話需要打python3 dict_age.py < input1.txt ,這樣才會讀到那份字典的資料
803e18f2c5fb5221d3a729e8d3a7f195bfe64dd1
vhrehfdl/Algorithm
/Programmers/비밀지도.py
562
3.8125
4
def convert(n, element): total = "" for i in range(n): total += str(element % 2) element = int(element / 2) return total[::-1] def solution(n, arr1, arr2): answer = [] for i in range(0, n): arr1_convert = convert(n, arr1[i]) arr2_convert = convert(n, arr2[i]) map = "" for j in range(0, len(arr1_convert)): if arr1_convert[j] == "1" or arr2_convert[j] == "1": map += "#" else: map += " " answer.append(map) return answer
552ccb7d046975bca1aab2b6c81e65c33816c801
krishnodey/Python-Tutoral
/decimal_to_binary_conversion_with_recursion.py
638
4.40625
4
''' let's write a program which will convert a decimal number into a binary number with recursion logic: We are not going to use built in functions base of binary number system is 2 we will write a function and inside that function if number is grater than 1 we call the function itself or else we will print the modulus of that number ''' def to_Binary(number): if number > 1: to_Binary(number // 2) print(number % 2, end=" ") #use end to the result in one line number = int(input("enter the number: ")) to_Binary(number) #thanks for watching
f87e40bcb139d988c8762900e4ca93f423ea5fc7
skinnybeans17/ACS-1100-Intro-to-Programming
/lesson-1/example-1.py
636
3.609375
4
#when you see a hashtag before some text, that means it's a comment #comments are notes that Python ignores and doesn't run as compile #line 6 is an example of some code, try running it #we will explain this code in more depth soon! print("Your Coding Adventure Begins") # Challenge: use print() to print the following... # Print your name # Print this course # Print your favorite color # Any line of code in Python that begins with # is a comment! # comments are for notes. These lines are not run as code. # Instead they are there to explain what is going on. # Challenge: Use a comment to explain the the print() function
14448fdf092025b4d05db9bbbe2f9e29b6031a59
Ian0113/Python-Test
/final_test_20181204/MySQLite.py
1,818
3.578125
4
import sqlite3 class typeForSQL: CHAR = " char" TEXT = " text" AI = " integer primary key autoincrement" INT = " integer" NOT_NULL = " not null" class MySQLite: def __init__(self, dbName): self.conn = sqlite3.connect(dbName) def createTable(self, tableName, dictField): try: self.conn.execute('drop table if exists \'{}\';'.format(tableName)) newList = [] for (K, V) in dictField.items(): newList.append("{} {}".format(K, V)) field = ",".join(newList) self.conn.execute('create table {}({});'.format(tableName, field)) return True except: return False def cleanTable(self, tableName): try: self.conn.execute('delete from {};'.format(tableName)) self.conn.execute('delete from sqlite_sequence WHERE name = \'{}\';'.format(tableName)) return True except: return False def insertData(self, tableName, dictData): try: field = ",".join(dictData.keys()) value = "\'"+"\',\'".join(dictData.values())+"\'" self.conn.execute('insert into {}({}) values ({});' .format(tableName, field, value)) return True except: return False def getAllData(self, tableName, tableField="*"): try: return self.conn.execute('select {} from {};' .format(tableField, tableName)) except: return False def commit(self): try: change = self.conn.total_changes self.conn.commit() return change except: return False def __del__(self): self.conn.close()
c19b193da66226eb40fbe4aef47ee0dd53794286
James-Oswald/IEEE-Professional-Development-Night
/10-26-20/sumArraySingles.py
165
3.671875
4
#https://www.codewars.com/kata/59f11118a5e129e591000134 def repeats(array): return sum([i for i in array if array.count(i) == 1]) print(repeats([4,5,7,5,4,8]))
0d9b597fa4b66aa6508b13e64d17e30ab924f6f7
touhiduzzaman-tuhin/python-code-university-life
/Anisul/9.py
259
4.21875
4
base = int(input("Enter base : ")) height = int(input("Enter height : ")) area = .5 * base * height print("Area of Triangle : ", area) print("\n") radius = float(input("Enter Radius : ")) area = 3.1415 * radius * radius print("Area of Circle : ", area)
91ac89d8b95a2e39a5c6861419c10b759f8d9345
llondon6/nrutils_dev
/workflows/romspline/example.py
3,546
3.75
4
import numpy as np ################################ # Class for generating some # # test data for showing how # # to use the code in the # # Jupyter/IPython notebooks # ################################ class TestData(object): """Generate the test data used as in example IPython notebooks for demonstrating the construction, properties, and errors of a reduced-order spline interpolant. """ def __init__(self, num=4001, noise=0., uv=0.): """Create a TestData object. Input ----- num -- number of samples to evaluate the function in domain [-1,1] noise -- amplitude of stochastic fluctuations added to smooth function values (default is 0.) uv -- amplitude of high-frequency (i.e., ultra-violet) features added to smooth function values (default is 0.) Attributes ---------- x -- samples y -- values of sampled function """ # Generate test data self.x = np.linspace(-1, 1, num) self.y = self.f(self.x, noise=noise, uv=uv) def f(self, x, noise=0., uv=0.): """Function to sample for reduced-order spline examples Inputs ------ x -- values to sample the (smooth) function noise -- amplitude of stochastic fluctuations added to smooth function values (default is 0.) uv -- amplitude of high-frequency (i.e., ultra-violet) features added to smooth function values (default is 0.) Output ------ sampled function values Comments -------- The function being evaluated is f(x) = 100.*( (1.+x) * sin(5.*(x-0.2)**2) + exp(-(x-0.5)**2/2./0.01) * sin(100*x) ) """ # Validate inputs x = np.asarray(x) # Return smooth function values ans = 100.*( (x+1.)*np.sin(5.*(x-0.2)**2) + np.exp(-(x-0.5)**2/2./0.01)*np.sin(100*x) ) # Return smooth function values with high-frequency (UV) features if uv != 0.: assert type(uv) in [float, int], "Expecting integer or float type." ans += float(uv)*self.uv(x) # Return smooth function values with stochastic noise if noise != 0.: assert type(noise) in [float, int], "Expecting integer or float type." ans += float(noise)*np.random.randn(len(x)) return ans def dfdx(self, x): """Analytic derivative of f Inputs ------ x -- values to sample the derivative of the function f(x) (see self.f method) Outputs ------- ans -- values of analytically calculated derivative of the function """ x = np.asarray(x) a = 10.*(-0.2+x)*(1.+x)*np.cos(5.*(-0.2 + x)**2) b = 100.*np.exp(-50.*(-0.5+x)**2)*np.cos(100.*x) c = np.sin(5.*(-0.2+x)**2) d = -100.*np.exp(-50.*(-0.5+x)**2)*(-0.5+x)*np.sin(100.*x) ans = 100.*(a+b+c+d) return ans def uv(self, x, width=20): """Generate high-frequency oscillations Inputs ------ x -- values to sample the high-frequency oscillations width -- number of samples corresponding to the period of the high-frequency oscillations (default is 20) Outputs ------- array of high-frequency oscillating values """ X = x[width] - x[0] return np.sin(len(x)/X * x)
37d18e81c1b88973f3cb34c1d7bee5815959f413
MansiRaveshia/Data-Structures-and-Algorithms
/datastructure/sumof2lists.py
723
3.515625
4
from singlylinklist import LinkedList,Node def sumlist(l1,l2): x=l1.head y=l2.head carry=0 s=LinkedList() while x or y: if not x: i=0 else: i=x.data if not y: j=0 else: j=y.data z=i+ j + carry if z>=10: carry=1 r=z%10 s.append(r) else: carry=0 s.append(z) if x: x=x.next if y: y=y.next s.print_list() l1=LinkedList() l2=LinkedList() l1.append(1) l1.append(3) l1.append(4) l2.append(2) l2.append(3) l2.append(7) #l2.append(13) sumlist(l1,l2)
48c11b7574af1174cbad894277dacb3b74bcbfdf
nBidari/Year9DesignCS4-PythonNB
/ProjectEuler/MultiplesOfThreeAndFive.py
230
3.75
4
answerList = [] counter = 0 def multipleOfThree(num): return num % 3 == 0 def multipleOfFive(num): return num % 5 == 0 for i in range(1000): if multipleOfThree(i) or multipleOfFive(i): counter = counter + i print(counter)
4cfbbdfb90d871f5a7b736d60a2f52d0b9bc5f4c
gszlxm/python
/RE/zuoye.py
546
3.703125
4
#作业: 1. 熟记正则表达式元字符 # 2. 使用regex对象复习re模块调用的函数 # 3. 找一个文档, 使用正则表达式匹配: # [1] 所有以大写字母开头的单词 # [2] 所有的数字, 包含整数, 小数, 负数, 分数, 百分数 import re pattern = '\b[A-Z]+\w*' fr= open("day01.txt") f = fr.read() regex = re.findall(pattern, f) print(regex) #pattern = r'\d+\.\d+|-\d+|\d+/\d+|\d+\%|\d+' #pattern = r'\d+/\d+' pattern = r'-?\d*\.?/?\d+%?' regex = re.findall(pattern, f) print(regex) fr.close()
ca88127de765599f2bdd340aa8ce65b0d1acb6a1
Prashant944/python-class
/year.py
2,208
3.984375
4
#Q1 year = int(input("Please Enter the Year Number you wish:")) if (year%4 == 0 and year%100!=0 or year%400 ==0): print("The year is Leap Year!") else: print("The year is Not Leap Year") #Q2 length = int(input("Enter the length: ")) breadth = int(input("Enter the breadth: ")) if length==breadth: print("It is a square") else: print("It is a rectangle") #Q3 print ("Enter first age") first = input() print ("Enter second age") second = input() print ("third age") third = input() if first >= second and first >= third: print ("Oldest age",first) elif second <= first and second <= third: print ("Oldest age",first) elif third <= first and third <= second: print ("Oldest age",first) else: print ("All are equal") #Q4 age = int(input("Enter your age: ")) sex = input("Enter your sex(M or F): ").upper() marital_status = input("Enter marital status(Y or N): ").upper() if sex=="F": print("Urban Areas") else: if age>=20 and age<40: print("Work anywhere") elif age>=40 and age<60: print("Urban Areas") else: print("Error") #Q5 quantity = int (input("Enter the quantity:")) Cost = 100 if quantity > 1000: print ("Cost is")(quantity*100)- (.1*quantity*100) else: print ("Cost is",quantity*100) #6 1=[] for a in range(10): intiger=int(input("enter nos.:")) l.append(integer) print(l) for b in l: print(b) #Q7 while True: print("It's an infinite loop") #Q8 l = list(map(int,input().split())) l_square = [] for i in l: l_square.append(i**2) print(l_square) #9 for num in range(1,101): for i in range(2,num): if (num%i==0): break else: print(num) break #Q10 def pypart(n): for i in range(0, n): for j in range(0, i+1): print("* ",end="") print("\r") n = 5 pypart(n) #11 l = list(map(int,input("Enter list elements: ").split())) element = int(input("Enter the element to search: ")) if element in l: print("Element found") del l[l.index(element)] print(l)
57f09af366f9a65de2dd22babd9517276c81fc02
cyruskarsan/ProfanityCheck
/tests/sq.py
1,493
3.953125
4
import sqlite3 from sqlite3 import Error def sql_connection(): try: con = sqlite3.connect('mydatabase.db') return con except Error: print(Error) def sql_table(con): cursorObj = con.cursor() #cursorObj.execute("CREATE TABLE employees(id integer PRIMARY KEY, name text, salary real, department text, position text, hireDate text)") cursorObj.execute("CREATE TABLE projects(id integer, name text)") con.commit() def sql_insert(con, entities): cursorObj = con.cursor() # cursorObj.execute("INSERT INTO employees VALUES(1, 'John', 700, 'HR', 'Manager', '2017-01-04')") cursorObj.execute('''INSERT INTO employees(id, name, salary, department, position, hireDate) VALUES(?, ?, ?, ?, ?, ?)''', entities) con.commit() entities = (3, 'Cyrus', 10000, 'IT', 'Tech', '2019-08-05') def sql_update(con): cursorObj = con.cursor() data = ("tegro",1) cursorObj.execute('UPDATE employees SET name = ? where id= ?', data) con.commit() def sql_fetch(con): cursorObj = con.cursor() #choosing what we want to fetch (select) #cursorObj.execute('SELECT * FROM employees WHERE salary>500') cursorObj.execute('SELECT ID, name FROM employees WHERE salary>500') rows = cursorObj.fetchall() for row in rows: print(row) con.commit() def sql_addMany(con): cursorObj = con.cursor() data = [(1, "bad"), (2, "word")] cursorObj.executemany("INSERT INTO projects VALUES(?,?)", data) con.commit() con = sql_connection() sql_update(con) con.close()