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
85689ba651f7a647634f864967c0df6ab5236a9c
potato16/pythonl
/python101/python101.py
375
3.578125
4
print("Hello Azinomoto") #This is something boring and we do it all day age = 24 name ='idonottellyou' print('{0} was {1} years old when he wrote this book'.format(name,age)) print('Why did you ask it, go away!'.format(name)) print('{0:3.3f}'.format(222222.0/3)) print('{0:*^22}'.format('thao'),end='||') print('{chieu} damage {mau} hp'.format(chieu='Shadow Dance', mau=34))
fc2cb25e42595b8139707b837532e9fc30332f87
lewtwelf/SpartaPythonNotes
/codingChallange.py
1,891
3.8125
4
""" sumlist = [] for i in range(0,1000): if i % 3 == 0 or i % 5 == 0: sumlist.append(i) print(sum(sumlist)) def fibaRecurs(first, second): if second > 4000000: return first + second + fibaRecurs(first, second) def fibo(x): print(x, " ", end="") if x > 10: return x else: return x + fibo(x+1) sumlist = [] def two_val_fibo(first, second): if first % 2 == 0: sumlist.append(first) if first > 4000000: return first else: return (first + second) + two_val_fibo(second, (first + second)) two_val_fibo(1, 2) print(sum(sumlist)) list = [i for i in range(2,21)] def even_divi(): for i in range(1,1000000000): count = 0 for j in list: if i % j == 0: count += 1 if count == 19: return i print(even_divi()) def strange(): list1 = list(range(1,10)) print("first:", list1) for i in list1: print(i) list1.pop() return list1 print(strange()) if len(str(i)) == 3 and (int(str(i)[0]) + int(str(i)[1]) + int(str(i)[2])) % 3 == 0: #abirame's method prime=int(input('Enter a range: ')) p=[] for j in range(2,prime): for i in range(2,prime): if j!=i: if j%i==0: # print(f'{j} not a prime number') break else: #print(f'{j} is a prime number') p.append(j) print(sum(p)) def prime_time(): primes = [] primes.append(5) for i in range(2,2000001): if i % 2 != 0 and i % 5 != 0: for j in primes: if i * j primes.append(i) return primes print(sum(prime_time())) """ def strange(): list1 = ["a", "b", "c", "d", "e", "f"] list2 = [] for i in list1: list2.append(i) list1.remove(i) return (list1, list2) print(strange())
1962bff441dfff94a9f40f68503f29e24815eca4
jacobbjo/AI_A4
/trash/Sheep_backup.py
4,975
4.09375
4
import numpy as np import matplotlib.pyplot as plt from importJSON import Map # Global variables defining the sheep behavior #SHEEP_R = 0.7 # The space the sheep wants between them SPACE_MULT = 3 SPACE_R = 0.7 RANGE_R = 3 * SPACE_R BUMP_h = 0.2 # Value from the paper. Used in the bump function A = 5 B = 5 C = abs(A-B)/(np.sqrt(4*A*B)) EPS = 0.1 # ---------- The functions from the paper by Harman. Used for computing the agent acceleration # Separation S = 0.3 K = 0.4 M = 0.5 def separation(agent, neighbors): """ A function to calculate the separation steer for an agent :param agent: the agent :param neighbors: other agents in the visible set :return: """ s = np.zeros(2) # separation_steer for neighbor in neighbors: s -= (neighbor.pos - agent.pos) return s def cohesion(agent, neighbors): """ Calculates the cohesion displacement vector fpr the agent :param agent: the agent :param neigbors: other agents in the visible set :return: """ c = np.zeros(2) # center of the visible set for neighbor in neighbors: c += neighbor.pos#/len(neighbors) c /= len(neighbors) k = c - agent.pos # cohesion displacement vector return k def alignment(neighbors): """ Calculates the alignment (velocity matching) :param agent: the agent :param neighbors:other agents in the visible set :return: """ m = np.zeros(2) # separation_steer if len(neighbors) > 0: for neighbor in neighbors: m += neighbor.vel#/len(neighbors) m /= len(neighbors) return m def get_velocity(agent, neighbors): """ Returns the new velocity based on the neighbors :param agent: :param neighbors: :return: """ s = separation(agent, neighbors) k = cohesion(agent, neighbors) m = alignment(neighbors) return agent.vel + S*s + K*k + M*m class Sheep: def __init__(self, the_map, pos, vel=np.zeros(2)): self.radius = the_map.sheep_r self.pos = pos self.vel = vel self.max_vel = the_map.sheep_v_max self.max_acc = the_map.sheep_a_max if np.linalg.norm(vel) == 0: rand_pos = np.random.normal(0.5, 0.5, 2) self.dir = rand_pos / np.linalg.norm(rand_pos) else: self.dir = vel / np.linalg.norm(vel) self.pos_hist = [] self.next_vel = self.vel def get_acceleration(self, neighbors): # The gradient based term: finding the best position # Consensus term: Tries to adapt the velocity to the neighbors new_vel = get_velocity(self, neighbors) acc = (new_vel - self.vel)/0.1 return acc def find_new_vel(self, neighbors, close_neighbors, obstacles, dogs, dt): new_acc = self.get_acceleration(neighbors) if np.linalg.norm(new_acc) > self.max_acc: # Scale the acc vector new_acc /= np.linalg.norm(new_acc) self.next_vel += new_acc * dt if np.linalg.norm(self.next_vel) > self.max_vel: self.next_vel /= np.linalg.norm(self.next_vel) self.next_vel *= self.max_vel def update(self, dt): self.vel = self.next_vel if np.linalg.norm(self.vel) > 0: self.dir = self.vel / np.linalg.norm(self.vel) self.pos_hist.append(self.pos) self.pos += self.vel * dt def find_neighbors(sheep_list, the_sheep): neighbors = [] for list_sheep in sheep_list: if list_sheep == the_sheep: continue elif np.linalg.norm(list_sheep.pos - the_sheep.pos) < RANGE_R: neighbors.append(list_sheep) print(len(neighbors)) return neighbors def plot_sheep(sheep): plt.clf() plt.plot(0,0,"o") plt.plot(10,0,"o") plt.plot(0,10,"o") plt.plot(10,10,"o") for a_sheep in sheep: # Plots the position plt.plot(a_sheep.pos[0], a_sheep.pos[1], "o") # Plot velocity plt.plot([a_sheep.pos[0], a_sheep.vel[0] + a_sheep.pos[0]], [a_sheep.pos[1], a_sheep.vel[1] + a_sheep.pos[1]]) plt.pause(0.05) def test(): the_map = Map("../maps/M1.json") sheep1 = Sheep(the_map, np.array([1.0, 1.0]), np.array([0.1, 0.1])) sheep2 = Sheep(the_map, np.array([2.0, 2.0]), np.array([0.1, -0.1])) sheep3 = Sheep(the_map, np.array([2.3, 2.3]), np.array([-0.1, -0.1])) sheep4 = Sheep(the_map, np.array([1.8, 2.0]), np.array([-0.1, -0.1])) sheep5 = Sheep(the_map, np.array([1.0, 2.0]), np.array([0.1, 0.0])) sheep_list = [sheep1, sheep2, sheep3, sheep4, sheep5] plot_sheep([sheep1, sheep2, sheep3, sheep4, sheep5]) for timestep in range(1000): for sheep in sheep_list: sheep.find_new_vel(find_neighbors(sheep_list, sheep), [], [], [], the_map.dt) for sheep in sheep_list: sheep.update(the_map.dt) plot_sheep([sheep1, sheep2, sheep3, sheep4, sheep5]) plt.show() #test()
39a09545365aea8c01d72dc92bddef9e9b0a1290
RobRoseKnows/Project-Euler
/Problem 001-100/Problem 01-10/Problem1.py
2,038
4.375
4
#!~/anaconda2/bin/python # If we list all the natural numbers below 10 that are multiples of 3 or 5, # we get 3, 5, 6 and 9. The sum of these multiples is 23. # # Find the sum of all the multiples of 3 or 5 below N. # # Input Format # # First line contains T that denotes the number of test cases. This is # followed by T lines, each containing an integer, N. # # Constraints # 1 <= T <= 10^5 # 1 <= N <= 10^9 # # Output Format # # For each test case, print an integer that denotes the sum of all the # multiples of 3 or 5 below N. import sys import math def main(): test_cases = int(raw_input().strip()) for case in xrange(test_cases): N = int(raw_input().strip()) sum_of_multiples = findSumOfMultiples(N, 3) + findSumOfMultiples(N, 5) sum_of_common_multiples = findSumOfCommonMultiples(N, 3, 5) print sum_of_multiples - sum_of_common_multiples # Find the sum of the multiples using the "rainbow method" (that's what I # learned it as, there might be another name). Basically sum the first and # last multiple and multiply them by the number of pairs of numbers. def findSumOfMultiples(N, x): N -= 1 remainder = N % x final_multiple = N - remainder sum_of_pairs = final_multiple + x number_of_multiples = N / x # If there's an odd number of multiples we need to add the one in the # middle separately if(number_of_multiples % 2 == 0): return sum_of_pairs * (number_of_multiples / 2) else: sum_without_middle = sum_of_pairs * (number_of_multiples / 2) middle = ((number_of_multiples / 2) + 1) * x return sum_without_middle + middle # Since using the findSumOfMultiples twice will add all of the common # multiples twice, we need to find the sum of all them so we can subtract it # from the total. def findSumOfCommonMultiples(N, x, y): # Now we just do the same thing we did before but with the common multiple # instead of just x or y return findSumOfMultiples(N, x * y) main()
f9eded943ee01fe07f87a13ebf88fb1201fe3f9e
paul0920/leetcode
/question_leetcode/131_1.py
706
3.59375
4
def partition(s): """ :type s: str :rtype: List[List[str]] """ res = [] dfs(s, 0, [], res) return res def dfs(s, index, path, res): if index == len(s): res.append(list(path)) return for i in range(index + 1, len(s) + 1): sub_string = s[index: i] if not is_palindrome(sub_string): continue path.append(sub_string) dfs(s, i, path, res) path.pop() def is_palindrome(s): left = 0 right = len(s) - 1 while left < right: if s[left] == s[right]: left += 1 right -= 1 else: return False return True s = "aab" print partition(s)
32f1f3841ae8e6365774f1e1b6e3ce4f3ab0cebd
hammond756/uvadlc_practicals_2018
/assignment_1/code/modules.py
5,411
3.75
4
""" This module implements various modules of the network. You should fill in code into indicated sections. """ import numpy as np def exp_normalize_batch(x): b = x.max(axis=1)[:, None] y = np.exp(x - b) return y / y.sum(axis=1)[:, None] class LinearModule(object): """ Linear module. Applies a linear transformation to the input data. """ def __init__(self, in_features, out_features): """ Initializes the parameters of the module. Args: in_features: size of each input sample out_features: size of each output sample TODO: Initialize weights self.params['weight'] using normal distribution with mean = 0 and std = 0.0001. Initialize biases self.params['bias'] with 0. Also, initialize gradients with zeros. """ self.params = { 'weight': np.random.normal(loc=0, scale=0.0001, size=(in_features, out_features)), 'bias': np.zeros(out_features) } self.grads = { 'weight': np.zeros_like(self.params['weight']), 'bias': np.zeros_like(self.params['bias']) } def forward(self, x): """ Forward pass. Args: x: input to the module Returns: out: output of the module TODO: Implement forward pass of the module. Hint: You can store intermediate variables inside the object. They can be used in backward pass computation. # """ self.prev_x = x # Expand dimensions of parameters so we can matmul with batched input W = self.params['weight'][None, :] b = self.params['bias'][None, :] out = np.matmul(x, W) + b # TODO: is this needed? # remove extra dimension out = out.squeeze(0) return out def backward(self, dout): """ Backward pass. Args: dout: gradients of the previous module Returns: dx: gradients with respect to the input of the module TODO: Implement backward pass of the module. Store gradient of the loss with respect to layer parameters in self.grads['weight'] and self.grads['bias']. """ # TODO: Check this: this way of averaging feels kinda implicit self.grads['weight'] = np.matmul(self.prev_x.T, dout) self.grads['bias'] = dout.mean(axis=0) assert self.grads['weight'].shape == self.params['weight'].shape, "Gradient matrix should be the same shape as params: {}, {}".format(self.grads['weight'].shape, self.params['weight'].shape) dx = np.matmul(dout, self.params['weight'].T) return dx class ReLUModule(object): """ ReLU activation module. """ def forward(self, x): """ Forward pass. Args: x: input to the module Returns: out: output of the module TODO: Implement forward pass of the module. Hint: You can store intermediate variables inside the object. They can be used in backward pass computation. # """ self.prev_x = x out = x*(x > 0.0) return out def backward(self, dout): """ Backward pass. Args: dout: gradients of the previous module Returns: dx: gradients with respect to the input of the module TODO: Implement backward pass of the module. """ dx = dout*(self.prev_x > 0) return dx class SoftMaxModule(object): """ Softmax activation module. """ def forward(self, x): """ Forward pass. Args: x: input to the module Returns: out: output of the module TODO: Implement forward pass of the module. To stabilize computation you should use the so-called Max Trick - https://timvieira.github.io/blog/post/2014/02/11/exp-normalize-trick/ Hint: You can store intermediate variables inside the object. They can be used in backward pass computation. # """ self.S = exp_normalize_batch(x) out = self.S return out def backward(self, dout): """ Backward pass. Args: dout: gradients of the previous module Returns: dx: gradients with respect to the input of the module TODO: Implement backward pass of the module. """ # calculate components of jacobians dsoft = -np.einsum('ij,ik->ijk', self.S, self.S) # NxD * NxD -> NxDxD diag = np.multiply(self.S, (1 - self.S)) # -> NxD (diagonals) # replace N diagonals wis s(1-s) for i=j diag_idx = np.arange(dout.shape[1]) dsoft[:, diag_idx, diag_idx] = diag dx = np.einsum('ik,ijk->ij', dout, dsoft) return dx class CrossEntropyModule(object): """ Cross entropy loss module. """ def forward(self, x, y): """ Forward pass. Args: x: input to the module y: labels of the input Returns: out: cross entropy loss TODO: Implement forward pass of the module. """ idxs = np.argmax(y, axis=1) out = -np.log(x[range(x.shape[0]), idxs]) out = out.mean() return out def backward(self, x, y): """ Backward pass. Args: x: input to the module y: labels of the input Returns: dx: gradient of the loss with the respect to the input x. TODO: Implement backward pass of the module. """ dx = -y / (x + 1e-6) dx /= x.shape[0] return dx
00ad7c52e5e72b5f38474f381a2e2f677f557039
tlima1011/Python
/retangulo.py
398
3.703125
4
from math import sqrt, pow base: float; altura: float base = float(input('Base do retangulo: ')) #4.0 altura = float(input('Altura do retangulo: ')) #5.0 area = base * altura perimetro = 2 * (base + altura) diagonal = sqrt(pow(base, 2) + pow(altura, 2)) print(f'AREA = {area:.4f}') #20.0000 print(f'PERIMETRO = {perimetro:.4f}') #18.0000 print(f'DIAGONAL = {diagonal:.4f}') #6.4031
e4f79a1870563c2e4f02995c749082db8fb4e117
greenbean1/thinkful
/chi_squared.py
1,494
3.59375
4
import pandas as pd from scipy import stats import collections import matplotlib.pyplot as plt # Load the reduced version of the Lending Club Dataset loansData = pd.read_csv('https://spark-public.s3.amazonaws.com/dataanalysis/loansData.csv') # Clean Data: Delete rows with null values loansData.dropna(inplace=True) freq = collections.Counter(loansData['Open.CREDIT.Lines']) # Chi Square Test on whether 'Open CREDIT Lines' column has given frequencies chi, p = stats.chisquare(freq.values()) print chi, p ## Additional info, counts, bar graph, etc practice # Print summary statistics of data frame print loansData.describe() # calculate the number of instances in the list count_sum = sum(freq.values()) print "There are " + str(count_sum) + " total open credit lines." distinct_vals = 0 most_freq_val = 0 max_cnt = 0 # Print frequencies of data for k,v in freq.iteritems(): # Prints the frequency of each open credit line #print "The frequency of number " + str(k) + " is " + str(float(v) / count_sum) distinct_vals += 1 if v > max_cnt: max_cnt = v most_freq_val = k # Another way to count distinct credit lines same_val = len(freq) print "There are " + str(distinct_vals) + " unique open credit lines. This is the same as " + str(same_val) print "The most frequent value is " + str(most_freq_val) + " and appears " + str(max_cnt) + " times." plt.figure() plt.bar(freq.keys(), freq.values(), width=1) plt.xlabel('Open Credit Lines') plt.ylabel('Count') plt.show()
b7a6173153be52920ffd8383456da76935454c0e
doubleZ0108/IDEA-Lab-Summer-Camp
/src/util/find_classes.py
469
3.796875
4
""" 找到之前的数据是对几类对象进行分类 """ import os max = 0 save_name = "" os.chdir("../data/img") for filename in os.listdir(os.getcwd()): (name, appidx) = os.path.splitext(filename) if appidx == ".txt": with open(filename, "r") as file: line = file.readline() num = int(line[0]) if num > max: max = num save_name = name print(max) print(save_name)
c9c4600a233fe8acda8ad94b1949735ab7532959
elLui/python_tools_and_practice_v3.8
/python_3.8/display_inventory_project.py
779
3.9375
4
# inventory.py """Fantasy Game Inventory""" stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} def display_inventory(inventory): print("inventory: \n") item_total = 0 for k, v in inventory.items(): print(str(v) + ' ' + k) item_total += v print('Total number of items : ' + str(item_total)) display_inventory(stuff) print() """Combine a List of loot to a player inventory""" def add_loot_to_inventory(inventory, loot_list): for loot in loot_list: inventory.setdefault(loot, 0) inventory[loot] += 1 return(inventory) inv = {'gold coin': 50, 'rope': 4} dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] inv = add_loot_to_inventory(inv, dragon_loot) display_inventory(inv)
c14b764a3ea115112b347021d4ef66f7fc43c19a
pzfrenchy/SortingMethods
/InsertionSort/InsertionSort/InsertionSort.py
508
3.90625
4
list = [3,2,5,8,4] for i in range(1, len(list)): currentValue = list[i] #copy current value to temp location while i > 0 and list[i-1] > currentValue: #check if index greater than 0 and preceeding value greater than current list[i] = list[i-1] #shift higher value right i -= 1 #decrement index location list[i] = currentValue #insert current value into correct location print(list)
84dd9fb90572c96309cf464c4a29380a80c9240c
devopshndz/curso-python-web
/Python sin Fronteras/Python/Ejercicios/10- Funcion par o impar.py
585
4.03125
4
# escribir una funcion que diga si un numero es par o impar # utilizaremos el operador de modulo % que indica el resto de una division: 10 Mod 2=0 def es_Par(num): return num % 2 == 0 # retornamos la operacion de que el numero que demos %(mod) 2 sea igual a 0 # esto efectua la division entre 2 y al final debe dar True si su mod es 0 # sino arrojara False porque su mod sea 1 resultado = es_Par(int(input('Escribe un numero: '))) # creamos variable a la cual le asignaremos la funcion print(resultado) # imprimimos la variable
202f5faeab5277ec04a5c973792c02e5193865db
KonstantinSKY/LeetCode
/1337_The_K_Weakest_Rows_in_a_Matrix.py
1,039
3.5
4
"""1337. The K Weakest Rows in a Matrix https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/ """ import time from typing import List class Solution: def kWeakestRows1(self, mat: List[List[int]], k: int) -> List[int]: n = sorted([(mat[i], i) for i in range(len(mat))]) return [n[i][1] for i in range(k)] def kWeakestRows2(self, mat: List[List[int]], k: int) -> List[int]: n = sorted([(sum(mat[i]), i) for i in range(len(mat))]) return [n[i][1] for i in range(k)] def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: return sorted([i for i in range(len(mat))], key=lambda x: mat[x])[:k] if __name__ == "__main__": start_time = time.time() print(Solution().kWeakestRows([[1, 1, 0, 0, 0], [1, 1, 1, 1, 0], [1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 1, 1, 1, 1]], 3)) print(Solution().kWeakestRows([[1, 0, 0, 0], [1, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 0]], 2)) print("--- %s seconds ---" % (time.time() - start_time))
7247adf12a40bbcdf3c81d9d3cb5eead76986f17
purcellconsult/python_intro_juniper
/06_functional_programming.py
9,318
4.46875
4
import math import functools from random import randint ################################################ # Functional programming and comprehensions # ----------------------------------------- # Functional programming is a popular paradigm in # coding. Functional programming aspects of python # was inspired from Lisp developers who coded in # python and wanted elements of the language in python. # One way to learn functional programming in python # is to juxtapose it with normal procedural code ################################################ """ Lambdas -------- These are also known as anonymous functions. When we create functions in python we use the 'def' keyword followed by the name of the function. This is not typically the case with anonymous functions. Instead you'll need to use the lambda keyword. """ def equation(x, y): return (x * y) / x ** 2 eq1 = equation(5, 10) # 2.0 eq2 = equation(10, 19) # 1.9 eq3 = equation(4, 6) # 1.5 print(eq1) print(eq2) print(eq3) # rewrite the above using lambdas in python eq4 = lambda x, y: (x * y) / x ** 2 print(eq4) # prints the lambda's reference in memory print(eq4(5, 10)) # 2.0 print(eq4(100, 16)) # 0.16 print(eq4(17, 10)) # 0.5882352941176471 def hypo(a, b): """ Computes the hypotenuse of a right angled triangle. :param a: Leg of the right triangle :param b: The other leg of the right triangle :return: The result rounded to nearest 2nd number """ return round(math.sqrt(a**2 + b**2), 2) hypo1 = hypo(5, 10) hypo2 = hypo(7, 100) hypo3 = hypo(18, 20) print(f'hypo1 = {hypo1}') print(f'hypo2 = {hypo2}') print(f'hypo3 = {hypo3}') # let's rewrite the above using a lambda and store it in # a variable called 'hypot' hypot = lambda a, b: round(math.sqrt(a**2 + b**2)) print(hypot(5, 17)) def upper_case(the_string): """ Write a function that accepts a string and returns it uppercase. Make sure to check if argument is of type string. :param the_string: :return:the string uppercase """ if isinstance(the_string, str): if the_string.lower(): return the_string.upper() return the_string else: raise ValueError('Must enter in a string') upper1 = upper_case('hello World') upper2 = upper_case('This is a cool example') upper3 = upper_case('HELLO!') upper4 = upper_case("I'm leaving in 3, 2, 1 seconds!") # upper5 = upper_case(10) print(f'upper1 = {upper1}') print(f'upper2 = {upper2}') print(f'upper3 = {upper3}') print(f'upper4 = {upper4}') # print(f'upper5 = {upper5}') This will signal an exception # rewrite upper_case using a lambda in python # what are some of the limitations of using a lambda? the_case = lambda the_string : the_string.upper() print(the_case('bonjour')) print(the_case('jaMbo!')) print(the_case('hello WOrld')) print(the_case('hoLa')) """ Lambdas Lab ----------- 1) Do you need to create a lambda as a statement? You're free to use Google to conduct your research. Verify your claims by writing some code snippets. In other words show me the code. 2) What is meant that lambdas are 'syntatic' sugar for creating regular functions? 3) List 3 pros of using lambda functions? List three cons of using lambda functions? 4) Does lambdas have docstrings? 5) Explain what it means that lambdas are throw away functions in python. """ # passing a function into another function # ---------------------------------------- # functions are considered first order objects in python """ Lambdas are pretty cool for short one line snippets of code. However, they're more cooler when you extend their functionality. This can be done by combining the functionality of lambdas with other functions such as maps, filter, and reduce. """ # Map """ map(function, iterable, ...) ---------------------------- - Returns an iterator that applies function to every item of iterable, yielding the results. - If additional iterable arguments are passed then function must take that many arguments and is applied to the items from all iterables in parallel. """ def triple(lis=list(range(1, 11))): """ This function takes in a list of numbers and multiples those numbers by 3. :param lis: the list to pass into the function :return: the list with the values tripled """ print(f'The list before: {lis}') for index, value in enumerate(lis): lis[index] *= 3 print(f'The list after: {lis}') triple() # rewriting the above using a map and lambda triple_nums = list(map(lambda x: x * 3, list(range(1, 11)))) print(triple_nums) """ Lab: ---- Write a function that has two lists as the parameters and then returns a new list that sums the corresponding indices of the lists together. Example: lis1 = [5, 4, 10] list2 = [7, 8, 10] list3 = [12, 12, 20] Make sure to use one list to do this. Consider the zip() function: In [1]: x, y = [5, 10, 100], [100, 20, 15] In [2]: result1 = zip(x, y) In [3]: result1 Out[3]: <zip at 0x5870e68> In [4]: result2 = list(zip(x, y)) In [5]: result2 Out[5]: [(5, 100), (10, 20), (100, 15)] Once you get the function to work rewrite it using lambdas and maps """ def sum_lists(x=[1, 3, 5], y=[1, 10, 20]): """ Iterates over two lists and sums their corresponding values: :param x: list one :param y: list two :return: returns a third list with the values of list 1 and 2 summed together. """ new_list = [] if len(x) != len(y): raise ValueError('Lists must be same length!') for x, y in zip(x, y): new_list.append(x + y) return new_list print(sum_lists()) # rewriting the above using a map sum_of_lists = map(lambda x, y: x + y, [1, 3, 5], [5, 10, 100]) print(list(sum_of_lists)) """ Filter ------ filter(function, iterable) - Constructs an iterator from those elements of iterable for which function returns True. - Iterable may be either a sequence, a container which supports iteration, or an iterator. - If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed. """ def filter_function(x=list(range(1, 11)), y=5): """ :param x: A list :param y: The value to compare an element in x to :return: A list that contains values greater than y """ new_list = [] print(x) for element in x: if element > y: new_list.append(element) print(new_list) filter_function() # Here's the above rewritten using a map # filter_items = [x for x in range(10)] filter_example = list(filter(lambda x: x > 5, [x for x in range(10)])) print(filter_example([5, 10, 100])) # Reduce # ------ # def reduce_list(x=[1, 3, 6, 10, 100], y=3.5): # """ # Iterate over a list 'x' and multiply # the value by y. From there you can # :param x: the list of 'x' # :param y: the value to multiply 'y' by # :return: # """ # result, num = 1, 0 # for index, value in enumerate(x): # num += (value * y) # return num # # # print(reduce_list()) # # # ???? check up on this # # More tools in the itertools module # r1 = functools.reduce((lambda x, y: x * 3.5), [1, 3, 6, 10, 100]) # print(r1) # If you like the functional programming approach to python # You can use the itertools module for more solutions # Learn more about itertools here: https://docs.python.org/3/library/itertools.html """ Comprehensions in python ------------------------ They can emulate some of the benefits of using functional programming in python such as code succinctness and less typing on the programmer's part. -- List comprehensions -- Generators and yield -- Set comprehensions -- Dictionary comprehensions """ # List comprehensions # -------------------- # Let's use the juxtaposition approach # Example, let's compare the normal way # to building a list vs a list comprehension # Example #1 # ---------- # Build a list from 1-10 using a 'for' loop nums = [] for x in range(1, 11): nums.append(x) # rewrite this using a list comprehension nums1 = [x for x in range(1, 11)] # Example # 2 # ------------ # Create a list of 10 random numbers # The numbers must be within the range of 1-100 # Then, sum all 10 random numbers random_nums = [] for x in range(10): random_nums.append(randint(1, 100)) print(random_nums) print(sum(random_nums)) # rewriting the above using a list comprehension random_sum = [randint(1, 100) for x in range(10)] print(sum(random_sum)) # Example 3 # ---------- # Create a list that includes # the even numbers from 1-20 evens = [] for x in range(1, 21): if x % 2 == 0: evens.append(x) # rewrite the above using a list comprehension evens_example = [x for x in range(1, 21) if x % 2 == 0] """ List comprehension labs ----------------------- 1) Create a list comprehension that generates a nested list 2) Create a list comprehension that prints odd numbers form 1-100 3) Create a list comprehension that prints evens numbers, and nums divisible by 7 """ # Generators # Set comprehensions empty_set = set() for x in range(1, 10): empty_set.update({x}) print(empty_set) # Dictionary comprehensions # ------------------------- mappings = {'a': 1, 'b': 5, 'c': 20} {key: value ** 2 for key, value in mappings.items()} print(mappings)
b0be3e66a4c8835288598de3a0515e9aa269b77d
jzachem/num2words
/num2words.py
3,153
3.578125
4
import sys class num_convert: output = "" ones_dict = {"0": "zero", "1":"one", "2": "two", "3": "three", "4": "four", "5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine", "10": "ten", "11": "eleven", "12": "twelve", "13": "thirteen", "14": "fourteen","15": "fifteen", "16": "sixteen", "17": "seventeen", "18": "eighteen", "19": "nineteen"} tens_dict = {"2": "twenty", "3": "thirty", "4": "fourty", "5": "fifty", "6": "sixty", "7":"seventy", "8": "eighty", "9":"ninety"} def __init__(self): # print("In init") return def break_up(self, num): # print("In break_into_three_dig") hundreds = num % 1000 thousands = int((num/1000)) % 1000 millions = int((num/1000000)) % 1000 billions = int((num/1000000000)) % 1000 # print(billions, millions, thousands, hundreds) ret = [billions, millions, thousands, hundreds] # print (ret) return ret def handle_billions(self, billions): # print("{} billion".format(billions)) if billions > 0: self.handle_hundreds(billions) self.output = self.output + " billion " return def handle_millions(self, millions): # print("{} million".format(millions)) if millions > 0: self.handle_hundreds(millions) self.output = self.output + " million " return def handle_thousands(self, thousands): # print("{} thousand".format(thousands)) if thousands > 0: self.handle_hundreds(thousands) self.output = self.output + " thousand " return def handle_hundreds(self, hundreds): # print("{} hundred".format(hundreds)) hunds = int((int(hundreds) / 100)) tens = int((int(hundreds) % 100)) # print ("{} hunds".format(hunds)) # print ("{} tens".format(tens)) if (hunds > 0 ): self.output = self.output + self.ones_dict[str(hunds)] + " " +"hundred " if int(tens) >= 20: ten = int((int(tens) /10)) one = (int(tens) % 10) # print ("{} tens".format(ten)) self.output = self.output + self.tens_dict[str(int(ten))] + " " # print ("{} ones".format(one)) self.handle_ones(one) else: self.handle_ones(tens) return def handle_ones(self, ones): if ones > 0: self.output = self.output + self.ones_dict[str(int(ones))] return def convert(self, orig_num): num = int(orig_num) with_commas = "" if num != 0: # print("In convert") # print("\n") # print(num) num_list = self.break_up(num) self.handle_billions(num_list[0]) self.handle_millions(num_list[1]) self.handle_thousands(num_list[2]) self.handle_hundreds(num_list[3]) for index in range(3): if int(num_list[index]) > 0: with_commas = with_commas + str(num_list[index]) + "," with_commas = with_commas + str(num_list[3]) # print (with_commas) print ("\n" + with_commas + " is " + self.output + "\n") else: print("\n0 is zero\n") return def main(orig_num): # print("In main") # print (2**32 -1) if (int(orig_num) <= ((2**32) -1)): nc = num_convert() nc.convert(orig_num) else: print("Numbers larger than a 32 bit unsigned integer ({}) are not supported".format(2**32 -1)) return if __name__ == "__main__": main(sys.argv[1])
cbe17c9bac56ffe4aee581baca885262f40d3fb1
xjr7670/corePython
/6-12a.py
1,228
3.875
4
#!/usr/bin/env python #-*- coding:utf-8 -*- def findchr(string, char): l1 = len(string) l2 = len(char) t = False for i in range(0, l2): for j in range(0, l1): # 两次循环历遍,只是为了寻找第一个相同的字符 while char[i] == string[j]: # 如果发现有相同的字符,则开始逐个比较 k = j i += 1 j += 1 if i == l2: # 如果最终比较的长度达到了子字符串的长度 # 说明前面的匹配都成功,表示有子字符串包含在内 # 把t设为True t = True break if t: # 如果t是Ture,则后面的不需要再比较了 break if t: # 如果t是Ture,则后面的不需要再比较了 break if t: # k减去子字符串的长度,再加1,就是初次发现有相同字符的位置 return (k-l2+1) else: return -1 s1 = raw_input("please enter your string: ") s2 = raw_input("Please enter which you want to find: ") res = findchr(s1, s2) print res
92711fd8c910e4ea4a731d2cf7a74240e65141a3
mandarspringboard/notes
/Python_notes/yield_and_return_difference.py
1,489
4.15625
4
# -*- coding: utf-8 -*- """ Created on Wed Jun 17 16:44:50 2020 @author: Gokhale """ def wrapper_return(n): return countdown(n) def wrapper_yield(n): yield countdown(n) def countdown(n): while n > 0: yield n n -=1 if __name__ =='__main__': # wrapper_return __returns__ a generator function countdown # so gg is a generator function countdown gg = wrapper_return(10) # presence of return statement and interpreter magic/language specification # ensures that gg is a generator object countdown print(gg) # we can iterate over that generator object, which yields numbers for ii in gg: print(ii) print(f'{"-"*25}') # wrapper_yield is itself a generator because of the yield statement. # so gg is generator object wrapper_yield gg = wrapper_yield(10) print(gg) # what does wrapper_yield yield? It yields generator object countdown # so iterating over gg will only give the generator object countdown # the following loop will only give: generator object countdown for ii in gg: print(ii) print(f'{"-"*25}') # if we want values from countdown, we have to iterate over the # generator object countdown itself like the following gg = wrapper_yield(10) for cd in gg: # cd is the generator object countdown yielded by wrapper_yield for ii in cd: print(ii)
fc9a166508b02a9006723d3bb683f035648567c6
ankhuve/gammalPython
/mastermind.py
2,782
3.75
4
import random allcolors = ["yellow","blue","red","green","orange","black","white"] colors = ["yellow","blue","red","green","orange","black","white"] # Lista med användbara färger def randColorlist(colors): # Funktion för att skapa slumpad colorlist i = 0 # Skapa räknare colorlist = [] # Skapa tom lista while i < 5: # Slumpa fram fem färger från colors och lägg till i colorlist rand = random.choice(colors) colorlist.append(rand) colors.remove(rand) # Ta bort färgen från listan så att den inte väljs två gånger i += 1 return colorlist def guessColorlist(allcolors, colorlist): # Funktion för gissning av färger guesslist = [] c = 0 # Räknare while c < 5: c += 1 guess = "" while guess not in allcolors: # Felhantering try: print ("Gissa färg nr", c, ":") guess = raw_input("") except: 0+0 while guess in guesslist: try: print ("Du har redan gissat den färgen, ta en annan:") guess = raw_input("") except: 0+0 if guess == "ellaärsötast": # Fuskkod med sanning :) print (colorlist) guesslist.append(guess) return guesslist def checkColor(guesslist, colorlist): # Funktion för att kontrollera vilka färger som var rätt n = 0 correctColor = 0 for color in guesslist: if guesslist[n] in colorlist[:5]: correctColor += 1 n += 1 return correctColor # Returnera antalet rätta färger def checkPos(guesslist, colorlist): # Funktion för att kontrollera hur många färger som var på rätt plats n = 0 correctPos = 0 for color in guesslist: if guesslist[n] == colorlist[n]: correctPos += 1 n += 1 return correctPos # Returnera antalet rätta färger på rätt plats def main(): colorlist = randColorlist(colors) print ("Datorn har slumpat fram fem färger av dessa:\n", allcolors, "\n\nFörsök lista ut vilka färger datorn har valt!") guesslist = [] tries = 0 while guesslist != colorlist: # Kör programmet tills gissningen är korrekt guesslist = guessColorlist(allcolors, colorlist) correctColor = checkColor(guesslist, colorlist) correctPos = checkPos(guesslist, colorlist) tries += 1 if correctPos == 5: print ("Du listade ut färgerna, grattis! Det tog dig BARA", tries, "försök..") else: print ("Din gissning var:", guesslist, "\nDu hade", correctColor, "rätta färger och", correctPos, "var på rätt plats. Försök igen!\n") main()
a38fa2df9e7ac0215e5d06cf9fe37fa0707f6335
bingheimr/edX-Projects
/edX Midterm - Problem 5.py
955
3.890625
4
""" Write a Python function that returns a list of keys in aDict that map to integer values that are unique (i.e. values appear exactly once in aDict). The list of keys you return should be sorted in increasing order. (If aDict does not contain any unique values, you should return an empty list.) This function takes in a dictionary and returns a list. """ def uniqueValues(aDict): ''' aDict: a dictionary ''' uniqueVals = [] v = list(aDict.values()) k = list(aDict.keys()) for i in range(len(v)): tracker = 0 for x in range(i + 1, len(v)): if v[i] == v[x]: break else: tracker += 1 for y in range(i): if v[i] == v[y]: break else: tracker += 1 if tracker == (len(v) - 1): uniqueVals.append(k[i]) return sorted(uniqueVals)
6abd7fa34f0c407078c64d4f688acca753945b4b
rafaelperazzo/programacao-web
/moodledata/vpl_data/3/usersdata/106/426/submittedfiles/ex2.py
263
4
4
# -*- coding: utf-8 -*- from __future__ import division #entrada a = input ('Digite um valor para a:') #processamento if a>=0: b= (a**0.5) print (' a raíz quadrada de a será: %.2f' %b) if a<0: b= (a**2) print (' o quadrado de a sera: %.2f' %b)
6d00961dd3e125cc9bb531cbfbc1a63076ce4cde
TheRealCubeAD/BANDO
/BWM/BWM_2018_2/Konfetti9.py
5,669
3.75
4
import time # - - - - - Programminterne Moduswahl - - - - - # Abfragemodus: #modus = "quadrat" modus = "quadrat_schnell" #modus = "rechteck" #modus = "rechteck_schnell" # Ausgabemodus: modus_a = "farbe" #modus_a = "zahl" # Beginn des Programms print() print("- - - - - Programmstart - - - - -") print() print() if modus == "quadrat": # e = Groese der Ebene print() print("Wie gross soll das Quadrat sein?") b = int(input(">>> ")) h = b print() print("Wie viele Mindestfarben?") mindestfarben = int(input(">>> ")) print() print("Sollen die Denkschritte ausgegeben werden?", "( Ja: (1), Nein: (0) )") lautDenken = bool(int(input(">>> "))) elif modus == "quadrat_schnell": # e = Groese der Ebene b = 7 h = b lautDenken = False if h >= 7: mindestfarben = 3 else: mindestfarben = 1 elif modus == "rechteck": # e = Groese der Ebene print() print("Wie breit soll die Ebene sein?") b = int(input(">>> ")) print() print("Wie hoch soll die Ebene sein?") h = int(input(">>> ")) print() print("Wie viele Mindestfarben?") mindestfarben = int(input(">>> ")) print() print("Sollen die Denkschritte ausgegeben werden?", "( Ja: (1), Nein: (0) )") lautDenken = bool(int(input(">>> "))) elif modus == "rechteck_schnell": # e = Groese der Ebene print() print("Wie breit soll die Ebene sein?") b = int(input(">>> ")) print() print("Wie hoch soll die Ebene sein?") h = int(input(">>> ")) lautDenken = False e = min(b, h) if e >= 7: mindestfarben = 3 else: mindestfarben = 1 e = min(b, h) # n = Anzahl der Farben n = mindestfarben # Methode zur Ausgabe einer Matrix def printMatrix(matrix): RED = '\033[91m' BLUE = '\033[94m' GREEN = '\033[92m' LILA = '\033[95m' END = '\033[0m' for Reihe in matrix: s = " " for zahl in Reihe: if modus_a == "farbe": t = "●" elif modus_a == "zahl": t = str(zahl) if zahl == 0: s += RED + t + END + " " elif zahl == 1: s += BLUE + t + END + " " elif zahl == 2: s += GREEN + t + END + " " elif zahl == 3: s += LILA + t + END + " " print(s) # Methode zur Bestimmung eines richtig gestzten Quadrats def farbeGueltig(Ebene, x, y): # Probiere alle Groessen aus for i in range(1, e): # Probiere alle Richtungen aus for j in range(4): Quadrat = [] # Alle Farben eines Quadrats Quadrat.append( Ebene[y][x] ) # Fokus Punkt # rechts oben if j == 0 and x + i <= b - 1 and y + i <= h - 1: Quadrat.append( Ebene[y][x + i] ) # rechts Quadrat.append( Ebene[y + i][x] ) # oben Quadrat.append( Ebene[y + i][x + i] ) # rechts oben # rechts unten if j == 1 and x + i <= b - 1 and y - i >= 0: Quadrat.append( Ebene[y][x + i] ) # rechts Quadrat.append( Ebene[y - i][x] ) # unten Quadrat.append( Ebene[y - i][x + i] ) # rechts unten # links oben if j == 2 and x - i >= 0 and y + i <= h - 1: Quadrat.append( Ebene[y][x - i] ) # links Quadrat.append( Ebene[y + i][x] ) # oben Quadrat.append( Ebene[y + i][x - i] ) # links oben # links unten if j == 3 and x - i >= 0 and y - i >= 0: Quadrat.append(Ebene[y][x - i]) # links Quadrat.append(Ebene[y - i][x]) # unten Quadrat.append( Ebene[y - i][x - i] ) # links unten if len(Quadrat) == 4: for k in Quadrat: if Quadrat.count(k) >= 3 and k != -1: return False return True def findeFaerbung(Ebene): # Gehe die Ebene durch for y in range(h): for x in range(b): # Suche nach dem ersten unbesetzten Feld if Ebene[y][x] == -1: # Probiere alle Farben durch for f in Farben: Ebene[y][x] = f if lautDenken: print() printMatrix(Ebene) # Ueberpruefe die eingesetzte Farbe if farbeGueltig(Ebene, x, y): # Ueberpruefe die Ebene vollstaendig ist if x == b - 1 and y == h - 1: if not lautDenken: print() printMatrix(Ebene) return True # Suche weiter if findeFaerbung(Ebene): return True Ebene[y][x] = -1 if lautDenken: print() printMatrix(Ebene) return False while n <= e: # Alle erlaubten Farben Farben = [f for f in range(n)] # Ebene Ebene1 = [[-1 for x in range(b)] for y in range(h)] if lautDenken: print() print() print() print("n =",n) if findeFaerbung(Ebene1): break # Erhoehe die Anzahl der Farben um 1 n += 1 print() print("Ein", str(b)+"x"+str(h)+"-Feld", "braucht mindestens", n, "Farben.") print() print("Laufzeit:", str(time.process_time()), "s") # Programmende print() print() print() print(" - - - - - Programmende - - - - -") print()
d51bbfbcd5c0e0b5305d656c1252762256a3d598
stdg3/python3M
/course1/loops.py
222
4.09375
4
# Infinitive loop: while True: userInput = input("Please input positive number: ") if float(userInput) > 0: print("Your number is: %s" %userInput) break else: print("%s is wrong nnumber." %userinput) continue
f8008491066541b5c1a753066d43f40499b2de71
IsaSchin/exercises_python
/0.11.py
115
4.0625
4
print ("Exercício 11") num = int(input("Digite um número: ")) for x in range(num +1): print (x) print ("fim")
e2af54b476a4c730d9da49b408ef7674c5ea71a1
ameerfaisal89/BayesianNetworks
/graph.py
5,939
3.734375
4
''' Created on Apr 19, 2015 @author: jorge Creates classes DirectedGraph and UndirectedGraph and private classes _Vertex and _Edge that users should not need to use by name ''' import functools @functools.total_ordering class _Vertex(object): ''' A Vertex in a graph. End users should not create their own Vertex objects. They should call the function graph.addVertex instead. They can access the name and neighbor properties (but should not modify them) and can add their own properties ''' def __init__(self, name): ''' Create a new Vertex @param name of the vertex ''' self.name = name self.neighbors = set() # the Vertexes that this Vertex is connected to via Edges ''' Vertexes are compared according to their names ''' def __hash__(self): return hash(self.name) def __eq__(self,other): return self.name == other.name def __lt__(self,other): return self.name < other.name def __repr__(self): return str(self.name) @functools.total_ordering class _Edge(object): ''' An Edge in a graph. End users should not create their own Edge objects. They should call the function graph.addEdge instead. They can access the p,c and weight properties (but should not modify them) and can add their own properties ''' def __init__(self, p, c, weight=1): ''' Create a new Edge where: @param p is the 'parent' Vertex in case of a Directed Edge, or the smaller Vertex in case of an Undirected Edge @param c is the 'child' Vertex in case of a Directed Edge, or the larger Vertex in case of an Undirected Edge @param weight is the 'weight' of the Edge ''' self.p = p self.c = c self.weight = weight ''' Edges are compared according to the tuple (p,c) ''' def __hash__(self): return hash((self.p,self.c)) def __eq__(self,other): return (self.p,self.c) == (other.p,other.c) def __lt__(self,other): return (self.p,self.c) < (other.p,other.c) def __repr__(self): return str((self.p,self.c)) class DirectedGraph(object): ''' A Directed Graph Edge ends are represented as (parent, child) A child Vertex is a neighbor of a parent Vertex, but not viceversa ''' def addVertex(self,name): ''' Add a vertex with a given name to this graph if it did not already exist @param name of the vertex to add @return the _Vertex object that name refers to ''' if name not in self._vertexes: self._vertexes[name] = _Vertex(name) return self._vertexes[name] def addEdge(self,pName,cName,weight=1): ''' Add an edge to this graph if it did not already exist between the vertexes named pName and cName. Add those vertexes p and c if they did not exist Add c as a neighbor of p @param pName is the 'parent' Vertex @param cName is the 'child' Vertex @param weight is the 'weight' of the Edge @return the Edge object between p and c ''' if (pName,cName) not in self._edges: p = self.addVertex(pName) # addVertex is idempotent! c = self.addVertex(cName) p.neighbors.add(c) self._edges[(pName,cName)] = _Edge(p,c, weight) return self._edges[(pName,cName)] def vertexes(self): ''' @return the set of Vertexes in the graph. Users can add their own properties to them ''' return self._vertexes.values() def vertexObject( self, vName ): ''' @param vName is the vertex name @return the vertex object corresponding to the vertex name vname ''' return self._vertexes[ vName ]; def edges(self): ''' @return the set of Edges in the graph. Users can add their own properties to them ''' return self._edges.values() def __init__(self, vertexes = [], edges = []): self._vertexes = {} for v in vertexes: self.addVertex(v) self._edges = {} for e in edges: self.addEdge(*e) def __repr__(self): return 'DirectedGraph: [{}]'.format(', '.join([str(k) for k in sorted(self._edges.items())])) class UndirectedGraph(DirectedGraph): ''' An Undirected Graph. Only ene Edge per pair of nodes representing both directions. Edge uses canonical representation with their end names sorted. Both end Vertexes of an Edge are neighbors of each other. ''' def addEdge(self,uName,vName,weight=1): ''' Add an edge to this graph if it did not already exist. @param uName is one end point Vertex of this Edge @param vName is the other end point Vertex of this Edge @param weight is the 'weight' of the Edge @return the Edge object between u and v We remark that in Undirected graphs, the Vertexes u and v are fully symmetric. (That is, the edge (u,v) is the same as the edge (v,u). By convention they are represented canonically such that u<v, Thus this function calls the DirectedGraph version of addEdge using the canonical order and in addition adds u as a neighbor of v. ''' uName,vName = (uName,vName) if uName<vName else (vName,uName) # canonical orientation for the edge edge = super().addEdge(uName,vName,weight) self._vertexes[vName].neighbors.add(self._vertexes[uName]) return edge def __repr__(self): return 'UndirectedGraph: [{}]'.format(', '.join([str(k) for k in sorted(self._edges.values())]))
3a0b2fde590cf37ed79bd2eb62187142be877b1a
ChristinaDeLonghi/100DaysofCodeChallenge
/While Loops.py
895
4.3125
4
#code that continually repeats until a certain condition is no longer met import sys MASTER_PASSWORD = 'opensesame' #caps for variables that should not change throughout running the code. Better to put it at the top set of variables than only in the while loop itself. password = input("Please enter your password: ") attempt_count = 1 #want to limit the number of attempts allowed. while password != MASTER_PASSWORD: if attempt_count > 3: sys.exit("Too many password attempts")# message given to user #will exit the loop if the number of attempts is more than three. #breaks out of the loop if 'if' conditional is met. password = input ("Invalid password, try again: ") attempt_count += 1 #this adds the number of attempts plus one. #while starts a block of code that will continue to loop until the condition set out in the block is met.
d628a1a935b3f49c2273da42e40ea3172b18614a
bj0/aoc
/aoc/2018/d25_2.py
526
3.578125
4
import networkx as netx def get_data(): with open("d25.txt", "r") as f: data = f.read().rstrip() return [tuple(map(int, line.split(","))) for line in data.splitlines()] def mandist(s, t): return sum(abs(x - y) for x, y in zip(s, t)) def part1(points): g = netx.Graph() for point in points: for otherpoint in points: if mandist(point, otherpoint) <= 3: g.add_edge(point, otherpoint) return netx.number_connected_components(g) print(part1(get_data()))
e92935cf2203570c05f5d351b73694ee6d137d40
aegglin/leetcode
/python/valid_parentheses.py
919
3.984375
4
# Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', # determine if the input string is valid. # # An input string is valid if: # Open brackets must be closed by the same type of brackets. # Open brackets must be closed in the correct order. def isValid(self, s: str) -> bool: parens = [] for char in s: if char == "(" or char == "{" or char == "[": parens.append(char) else: if len(parens) > 0: curr_opening_paren = parens.pop() if (char == ")" and curr_opening_paren == "(") or \ (char == "]" and curr_opening_paren == "[" or \ (char == "}" and curr_opening_paren == "{")): continue return False return True if len(parens) == 0 else False
ff225c1c021de4a11a950f741e1f4effb29769c6
NeelJVerma/Daily_Coding_Problem
/Class_Scheduler/main.py
775
3.765625
4
""" Given an array of time intervals (start, end) for classroom lectures (possibly overlapping), find the minimum number of rooms required. """ def scheduler(l): l = sorted(l, key=lambda x: x[1]) queue = [] rooms = 1 queue.append(l[0]) for i in range(1, len(l)): while queue and queue[0][1] <= l[i][0]: queue.pop(0) queue.append(l[i]) rooms = max(rooms, len(queue)) return rooms print(True if scheduler([(0, 50), (30, 75), (60, 150)]) == 2 else False) print(True if scheduler([(0, 50), (30, 75)]) == 2 else False) print(True if scheduler([(0, 50)]) == 1 else False) print(True if scheduler([(1, 2), (4, 5), (4, 8), (4, 7)]) == 3 else False) print(True if scheduler([(4, 5), (5, 16), (1, 2)]) == 1 else False)
c8121089138a40ad043406819004d2d8c4f339bd
ProkRoman/python
/lesson 1.6.py
217
3.875
4
day1 = int(input("сколько км в первый день: ")) max = int(input("лучший результат в км: ")) days = 1 while day1 < max: day1 = day1 * 1.1 days = days + 1 print(days)
9b7d64ecc8fe6905286a35bc23ca240e8a5f9806
antonmeschede/Conversor-XLSX
/EXCEL-CSV.py
861
4.09375
4
import pandas as pd # another file reading the file, showing the columnbs and the user selects to see the results print('*' * 25) print('Conversor de XLSX para CSV') print('*' * 25) print('') # escolha = str(input('Olá, seja bem-vindo ao conversor! O que você deseja converter? ') file = input('Local do Arquivo: ') # nome = str(input('Qual o nome do arquivo? ')).lower # if nome == 'csv': df = pd.read_excel(file) writer = pd.ExcelWriter('teste.xlsx') df.to_csv(writer, index=False) writer.save() print('Pronto! Arquivo convertido para XLSX no desktop.') # elif type == 'xlsx': #df1 = pd.read_excel(file) #writer1 = pd.ExcelFile #df.to_csv(writer1, index=False) #writer1.save() #print('Pronto! Arquivo convertido para CSV no desktop,') # else: #print('O tipo desejado não satisfaz as capacidades do programa')
6e6de276de8f1333202046a69aefaa5a4e989798
OlyaIvanovs/python_playground
/oop/wizcoin.py
563
3.53125
4
class Wizcoin: def __init__(self, galleons, sickles, knuts): """Create a new WizCoin object with galleons, sickles and knuts.""" self.galleons = galleons self.sickles = sickles self.knuts = knuts def value(self): """The value in knuts of all coins in the WizCoin object.""" return (self.galleons*17*29) + (self.sickles * 29) + self.knuts def weight_in_grams(self): """Return thr weight of coins in grams.""" return (self.galleons * 31.03) + (self.sickles * 11.34) + (self.knuts * 5.0)
3230ceea034e4fb08bf0cfca6794c932f1a62699
Catering-Company/Capstone-project-2
/Part2/us_coin_calculator.py
2,718
4.53125
5
# CODE FOR COIN CALCULATOR, PROVIDED THAT THE CURRENCY IS SET TO DOLLARS. # -------------------------------------------------- # General_functions contains functions that are used throughout multiple parts of the program. from general_functions import us_coins, us_coins_dict, get_cent_amount, floor_calc # -------------------------------------------------- # Gets the coin-denomination that the user wants to turn their cents into. # If the user enters anything other than a valid coin-denomination then get_denomination returns # 'incorrect_usage' so that the user can be re-prompted via a while-loop in main(config). def get_denomination(): denomination = input("What denomination? $2, $1, 50c, 20c or 10c? ") if denomination in us_coins: return denomination else: print("Please choose $2, $1, 50c, 20c or 10c.") return "incorrect_usage" # -------------------------------------------------- # Given an amount of cents and a coin-denomination, coin_exchange prints # the number of said coins you can recieve in exchange for your cents, # along with the amount of cents you will have left. def coin_exchange(cents, denomination): coin_amount = floor_calc(cents, us_coins_dict[f"{denomination}"]) cent_remainder = cents % us_coins_dict[f"{denomination}"] if cent_remainder == 0: if coin_amount == 1: print(f"You can exchange your cents for exactly {coin_amount} {denomination} coin.") if coin_amount > 1: print(f"You can exchange your cents for exactly {coin_amount} {denomination} coins.") elif coin_amount == 0: print("You don't have enough cents to exchange!") elif coin_amount == 1: print(f"You can exchange your cents for {coin_amount} {denomination} coin with {cent_remainder}c to spare.") else: print(f"You can exchange your cents for {coin_amount} {denomination} coins with {cent_remainder}c to spare.") return 0 # -------------------------------------------------- # The main function: # The user is prompted for the amount of cents they have to trade. # They are then prompted for a coin-denomination. coin_exchange then calculates the amount of coins # of that denomination the user can receive, along with the amount of cents they will have left over. # This information is then printed in a human-readable format. def main(config): cents = get_cent_amount(config) while cents < 0: cents = get_cent_amount(config) denomination = get_denomination() while denomination == "incorrect_usage": denomination = get_denomination() coin_exchange(cents, denomination) # --------------------------------------------------
23d8fae62a6fc51c05a30be01e52252ede1a4a55
santina/Master_Thesis_UBC
/PubMed_100_Random_Papers/Python_Code/Sanity/check_empty_lines.py
1,191
3.609375
4
import argparse def getEmptyLines(filename, outfile): empty_lines = list() with open(filename) as f, open(outfile, 'w') as out: for lineNum, line in enumerate(f): # 0 base for lineNum if line.strip(): continue else: empty_lines.append(lineNum) for l in empty_lines: out.write(str(l) + '\n') print len(empty_lines) def printEmptyLines(filename): empty_lines = list() with open(filename) as f: for lineNum, line in enumerate(f): # 0 base for lineNum if line.strip(): continue else: empty_lines.append(lineNum) print empty_lines #print len(empty_lines) def countEmptyLines(filename): count = 0 with open(filename) as f: for lineNum, line in enumerate(f): # 0 base for lineNum if line.strip(): continue else: count += 1 return count def hasEmptyLine(filename): if countEmptyLines(filename) > 0: return True return False def main(): parser = argparse.ArgumentParser(description='Check or count empty lines') parser.add_argument('--f', type=str, help='input file') args = parser.parse_args() print hasEmptyLine(args.f) print countEmptyLines(args.f) printEmptyLines(args.f) if __name__ == '__main__': main()
2b9189775f83ffabd762141ad24c3391f825167c
smugokey/python-Problems
/Exercise 9.2.py
1,146
4.09375
4
# In 1939, Ernest Vincent Wright published a 50,000 word novel called Gadsby that0 # does not contain the letter “e.” Since “e” is the most common letter in English, that’s # not easy to do. # In fact, it is difficult to construct a solitary thought without using that most common # symbol. It is slow going at first, but with caution and hours of training you can # gradually gain facility. # All right, I’ll stop now. # 9.3 Search 97 # Write a function called has_no_e that returns True if the given word doesn’t have # the letter “e” in it. # Modify your program from the previous section to print only the words that have no # “e” and compute the percentage of the words in the list that have no “e.” # complete fin = open("C:/Users/PT WORLD/Downloads/words.txt") def has_no_e(word): return "e" in word print(has_no_e("string")) def has_no(): count = 0 total = 0 for word in fin: total += 1 if "e" not in word: normalize = word.strip() print(normalize) count += 1 return (count/total) * 100 print(has_no())
e2c6b187ddaea09ea04accca60024e46387ceffe
CyanD/YNU
/Python_Code/FunctionSet.py
454
4.1875
4
"""this is a function,to display all the item in a list the_list: the list you want to display indent: decide whether to intent level: intent size """ def print_lol(the_list,indent=False,level=0): for each_item in the_list: if isinstance(each_item,list): print_lol(each_item,indent,level+1) else: print('|',end='') if indent: print("\t"*level,end='') print(each_item)
d746edc50ec7fa5151309cb56bc12dd11f26a200
amaurya9/Python_code
/Compare_File.py
1,331
3.609375
4
import argparse import filecmp def compareFile(i,o): if i!=None and o!=None: #fd = open(args.i) #fd1=open(args.o) #if sum(1 for line in fd if line.rstrip()) == sum(1 for line in fd1 if line.rstrip()): fd = open(i) fd1 = open(o) if len(fd.readlines())!=len(fd1.readlines()): print("both the file are different") else: fd.seek(0,0) fd1.seek(0,0) line1=fd.readline() line2=fd1.readline() count=0 while line1!="" and line2!="": if line1==line2: pass else: count=+1 print("both the file is different") break line1=fd.readline() line2=fd1.readline() if count==0 and (fd.tell()==fd1.tell()): print("both the file is same") #print(filecmp.cmp(args.i,args.o)) else: print("please enter both the file name") fd.close() fd1.close() def main(): parser=argparse.ArgumentParser() parser.add_argument("-i",type=str) parser.add_argument("-o",type=str) args=parser.parse_args() compareFile(args.i,args.o) if __name__ == '__main__': main()
01134ef0d96afa7117dc561642a3f9ffae13aad1
FabioRomeiro/FATEC_codes
/1SEM/Algoritimos/Python/Lista de Exercicios String/7.py
546
3.6875
4
frase = input("Digite uma frase:").lower() numEspacosEmBranco = 0 numVogais=0 numA = 0 numE = 0 numI= 0 numO = 0 numU = 0 for i in frase: if i == ' ': numEspacosEmBranco += 1 if i in ['a','e','i','o','u']: numVogais += 1 if i == 'a': numA += 1 if i == 'e': numE += 1 if i == 'i': numI += 1 if i == 'o': numO += 1 if i == 'u': numU += 1 print("Numero de espaços em branco: %d\nNumero de vogais: %d\nA = %d\nE=%d\nI=%d\nO=%d\nU=%d" %(numEspacosEmBranco, numVogais,numA,numE,numI,numO,numU))
81406eae0381117c2038322e68ddcf4236186474
vinodekbote/Cracking-the-Coding-Interview
/permutation_string.py
1,111
4.1875
4
__author__ = 'rakesh' ''' the idea is to create a recursion tree of the string and it will print out all the different combination ''' ''' A[current], A[start] = A[start], A[current] this type of item assignment is not supported for string. All int values can be swapped like this ''' ''' python does not support string assignment either so you need to first convert into a list and then perform all operation ''' stringList = [] def permutationString(A, start, end): A = list(A) if start == end - 1: stringList.append("".join(A)) #this is the most important step since it will tell how many for current in range(start, end): #the loop will be determined by the loop and the value of the current temp = A[current] A[current] = A[start] A[start] = temp permutationString("".join(A), start + 1, end) ''' temp = A[current] A[current] = A[start] A[start] = temp ''' if __name__ == '__main__': string = '123' start = 0 end = len(string) permutationString(string, start, end) print stringList
dcdcfce858ba71394a31df4468b454825235f276
mohmilki/IF1311-10220013
/main-operasilogikadanboolean.py
1,179
4.09375
4
#latihan logika dan komparasi #membuat gabungan area rentang dari angka # +++++++++3-------------10++++++++++++ inputUser = float(input("masukkan angka yang bernilai\nkurang dari 3\n atau\n lebih besar dari 10\n:")) # +++++++++3----------- # memeriksa angka kurang dari 3 isKurangDari = (inputUser < 3) print ("Kurang dari 3=",isKurangDari) # ----------10++++++++++++ # memeriksa angka lebih dari 10 isLebihDari = (inputUser > 10) print ("Lebih dari 10=",isLebihDari) # ++++++++3------------10++++++++++ isCorrect = isKurangDari or isLebihDari print ("angka yang dimasukkan :",isCorrect) print ("\n",10*"=","\n") # kasus irisan # ----------3+++++++++++++++10------------- inputUser = float(input("masukkan angka yang bernilai\nlebih dari 3\n dan\n kurang dari 10\n:")) # memeriksa angka lebih dari 3 isLebihDari = (inputUser > 3) print ("Lebih dari 3=",isLebihDari) # memeriksa kurang dari 10 isKurangDari = (inputUser < 10) print ("Kurang dari 10=",isKurangDari) # hasil irisan # ----------3+++++++++++++++10------------- isCorrect = isLebihDari and isKurangDari print ("angka yang dimasukkan :",isCorrect)
4ebcb86766deb4e08a69dfa0118e306ed12fb2ac
yahua/LearnPython
/sorted.py
197
3.546875
4
#coding:gbk l = [36, 33, 56, 9] # 默认从小到大 print sorted(l) # 倒序 def reversed_cmp(x, y): if x>y: return -1 elif x<y: return 1 else: return 0 print sorted(l, reversed_cmp)
1ab9cac91b0ec6db3416bb73e9363c84bb8af925
rupeshpatil/python
/algo/bin.py
409
3.890625
4
def binarySearch(item, itemlist): first = 0 last = len(itemlist) -1 found = False while first <= last and not found: middle = (first + last) //2 if itemlist[middle] == item: found = True elif itemlist[middle] < item: first = middle + 1 else: last = middle - 1 return found binarySearch(12, [34,45,12,34,56,67,78].sort())
e5dbe56dc4d3ac51497ad138808cc8cb4bf7ce7b
Genionest/My_python
/Zprogram3/Fibonacci.py
232
3.546875
4
#斐波那契数列,非递归正解算法 print("请输入一个数:") n = int(input()) Fib = [] for i in range(0,n): Fib.append(0) if i < 2: Fib[i] = 1 else: Fib[i] = Fib[i-1] + Fib[i-2] print(Fib)
52b912b4c42c4ea0db40ccf7e6c817200ad6f05f
Tulip2MF/100_Days_Challenge
/Love Calculator.py
662
3.921875
4
name1 = input("Write your name: ").lower() name2 = input("Write other person's name: ").lower() joinedName = name1 + name2 def loveCounter(countParameter): count1 = 0 for i in countParameter: count1 += joinedName.count(i) return count1 trueCount = loveCounter("true") loveCount = loveCounter("love") percentage= int((str(trueCount) + str(loveCount))) if percentage<10 or percentage>90: print(f"Your Percentage is {percentage}, you go together like coke and mentos") if percentage < 50 and percentage > 40: print(f"Your Percentage is {percentage}, you are alright together") else: print(f"Your Percentage is {percentage}")
332a98d412af583a929955fe203e61ca4260cf2e
ricarcon/programming_exercises
/2020/week11.py
1,621
4.09375
4
def max_duffel_bag_value(tuples, num): temp = [] #first we'll take a look at which single cake has the highest value if we took just one type of cake for entry in tuples: weight, value = entry count = int(num/weight) temp.append((weight, count * value)) #sort by the total value in desc order ordered = sorted(temp, key=lambda x: x[1], reverse=True) #here's where we track how many of each to take map = {} #we maximize by subtracting the most cakes from the total weighted value and get more of the cakes we can get from the other types remainder = num for ordered_entry in ordered: weight, value = ordered_entry done = False count = 0 while not done: if remainder >= weight: remainder -= weight count += 1 else: done = True map[weight] = count total_value = 0 for entry in tuples: total_value += map[entry[0]] * entry[1] return (map, total_value) def main(): cake_tuples = [(7, 160), (3, 90), (2, 15)] capacity = 20 result = max_duffel_bag_value(cake_tuples, capacity) print("Max value: {}".format(result[1])) print("By getting cakes:") cake_map = result[0] for cake in cake_map: if cake_map[cake] != 0: print("\tCake of weight {}: {}".format(cake, cake_map[cake])) if __name__=="__main__":main()
d83ec512d170b13ff48b03ff326b32292a4acc4d
AMendoza04/Numerico
/Taller1/punto1b.py
931
3.5625
4
#11 -1b- 7 - 13 - 2 - 4 o 5 - 6 - 15 import math def horner(p, n, x, ans): y = p[0] d = 0 for i in range( 1 , n ): d = y + x * d y = x * y + p[i] ans.append(y) ans.append(d) def evalp(p, n, x): s = 0 for i in range(n): s = s + p[i] * x**(n - i - 1) return s def evald(p, n, x): s = 0 for i in range(n): s = s + p[i] * (n - i - 1) * x**(n - i - 2) return s n = 1 + int (input("Grado del polinomio: ")) print ( "Ingrese lo valores del polinomio: " ) #polinomio = [7, 6, -6, 0, 3, -4] poli = [] for i in range(n): v = float (input()) poli.append( v ) #n = len(polinomio) for i in range(n): print (poli[i]) x = float (input( "Ingrese el valor de x0: " )) ans = [] horner(poli, n, x, ans) print ("P(x0): ", ans[0]) print ("Q(x0): ", ans[1]) print ("Número de operaciones: ", 2*(n-1)) print ( evalp(poli , n, x)) print ( evald(poli , n , x))
92d8d793f018764bfcfec63a12c31cb6f83328a1
tarrade/proj_DL_models_and_pipelines_with_GCP
/src/model_mnists_skripts/tf_lazy_lowlevel.py
8,802
3.59375
4
""" Basic ideas frm https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/neural_network_raw.py - update using tf.data - update session """ import tensorflow as tf import numpy as np from src.constants import NUM_EPOCHS, BATCH_SIZE, LEARNING_RATE ############################################################################### #Load Data try: from tensorflow.keras.datasets import mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() except Exception: print("download manually to ./data/ from {}".format( "https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz" )) with np.load("./data/mnist.npz") as f: x_train, y_train = f['x_train'], f['y_train'] x_test, y_test = f['x_test'], f['y_test'] # classic numpy approach using reshape and # reshape and save image dimensions dim_img = x_train.shape[1:] x_train = x_train.reshape(len(x_train), -1) x_test = x_test.reshape(len(x_test), -1) # Convert Numpy Array to Tensor manually to avoid accidential reassignment: # x_train = tf.cast(x_train, dtype="float") # x_test = tf.cast(x_test, dtype="float") print("passed") def oneHotEncode(array): n = len(array) dense_array = np.zeros((n, len(set(array)))) dense_array[np.arange(n), array] = 1 return dense_array assert set(y_train) == set( y_test), "Classes in train and test set are different. which is correct?" classes = set(y_train) # 0-9 digits y_train = oneHotEncode(y_train) y_test = oneHotEncode(y_test) ############################################################################### # parser function for input data # Use `tf.parse_single_example()` to extract data from a `tf.Example` # protocol buffer, and perform any additional per-record preprocessing. def parser(record): """ Define a function to pass to map fct of tf.data.Dataset example: https://www.tensorflow.org/guide/datasets#using_high-level_apis """ # keys_to_features = { # "image_data": tf.FixedLenFeature((), tf.string, default_value=""), # "date_time": tf.FixedLenFeature((), tf.int64, default_value=""), # "label": tf.FixedLenFeature((), tf.int64, # default_value=tf.zeros([], dtype=tf.int64)), # } keys_to_features = { "image_data": tf.FixedLenFeature((), tf.float, default_value=""), "label": tf.FixedLenFeature((), tf.int32, default_value=tf.zeros([], dtype=tf.int64)), } parsed = tf.parse_single_example(record, keys_to_features) # Perform additional preprocessing on the parsed data. image = tf.image.decode_jpeg(parsed["image_data"]) image = tf.reshape(image, [299, 299, 1]) label = tf.cast(parsed["label"], tf.int32) return {"image_data": image, "date_time": parsed["date_time"]}, label ############################################################################### # Build Model # data specific parameters: num_classes = y_train.shape[-1] # MNIST total classes (0-9 digits) dim_input = x_train.shape[-1] # MNIST data input (img shape: 28*28) # Number of units in hidden layer (Hyperparameter) n_hidden_1 = 256 # 1st layer number of neurons n_hidden_2 = 256 # 2nd layer number of neurons # tf Graph input X = tf.placeholder("float", shape=[None, dim_input]) Y = tf.placeholder("int32", shape=[None, num_classes]) # # Create model a statful model class FNN(object): def __init__(self): self.w_1 = tf.Variable(tf.Variable(tf.random_normal([dim_input, n_hidden_1])), name='W1') self.b_1 = tf.Variable(tf.random_normal([n_hidden_1]), name='b1') self.w_2 = tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2]), name="W2") self.b_2 = tf.Variable(tf.random_normal([n_hidden_2]), name='b2') self.w_out = tf.Variable(tf.random_normal([n_hidden_2, num_classes]), name="W_out") self.b_out = tf.Variable(tf.random_normal([num_classes]), name='b_out') #self.weights = [self.w_1, self.b_1, self.w_2, self.b_2, self.w_out, self.b_out] def __call__(self, inputs, training=False): hidden_1 = tf.nn.relu(tf.matmul(inputs, self.w_1) + self.b_1) hidden_2 = tf.nn.relu(tf.matmul(hidden_1, self.w_2) + self.b_2) logits = tf.matmul(hidden_2, self.w_out) + self.b_out return logits # class FNN(tf.keras.Model): # def __init__(self): # super(FNN, self).__init__() # self.w_1 = tf.Variable(tf.Variable(tf.random_normal([dim_input, n_hidden_1])), name='W1') # self.b_1 = tf.Variable(tf.random_normal([n_hidden_1]), name='b1') # self.w_2 = tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2]), name="W2") # self.b_2 = tf.Variable(tf.random_normal([n_hidden_2]), name='b2') # self.w_out = tf.Variable(tf.random_normal([n_hidden_2, num_classes]), name="W_out") # self.b_out = tf.Variable(tf.random_normal([num_classes]), name='b_out') # #self.weights = [self.w_1, self.b_1, self.w_2, self.b_2, self.w_out, self.b_out] # def call(self, inputs, training=False): # hidden_1 = tf.nn.relu(tf.matmul(inputs, self.w_1) + self.b_1) # hidden_2 = tf.nn.relu(tf.matmul(hidden_1, self.w_2) + self.b_2) # logits = tf.matmul(hidden_2, self.w_out) + self.b_out # return logits # Construct model logits = FNN()(X) # Construct model logits = FNN()(X) # Define loss and optimizer # loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2( # logits=logits, labels=Y)) loss = tf.losses.softmax_cross_entropy(logits=logits, onehot_labels=Y) optimizer = tf.train.AdamOptimizer(learning_rate=LEARNING_RATE).minimize(loss) # train_op = optimizer.minimize(loss_op) # Evaluate model tp = tf.equal(tf.argmax(logits, axis=1), tf.argmax(Y, axis=1)) accuracy = tf.reduce_mean(tf.cast(tp, dtype="float")) # Initialize the variables (i.e. assign their default value) # init = tf.global_variables_initializer() # ToDo: depreciated ############################################################################## # tf.data , Preprocessing trainslices = tf.data.Dataset.from_tensor_slices((X, Y)) trainslices = trainslices.shuffle(buffer_size=3000, seed=123456, reshuffle_each_iteration=True) # trainslices = trainslices.map(parser) # to add to tf.data pipeline trainslices = trainslices.repeat(count=1) trainslices = trainslices.batch(batch_size=BATCH_SIZE, drop_remainder=True) # if False -> breaks assert in training loop iterator = trainslices.make_initializable_iterator() next_element = iterator.get_next() # tf.data.experimental.make_batched_features_dataset(BATCH_SIZE, traindata, num_epochs=NUM_EPOCHS) # #unified call possible (unclear how to to do with numpy arrays) # iterator = traindata.make_initializable_iterator( # batch_size=BATCH_SIZE, # features=traindata, # num_epochs=NUM_EPOCHS) testslices = tf.data.Dataset.from_tensor_slices((X, Y)) # Sequencing batch to mini-batches # https://github.com/tensorflow/tensorflow/blob/9230423668770036179a72414482d45ddde40a3b/tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py#L353 N_train = x_train.shape[0] n_batches = N_train / BATCH_SIZE step = int(n_batches/ 60) init = tf.global_variables_initializer() # Start training with tf.Session() as sess: # Run the initializer # sess.run(init) sess.run(init) print('Initalized graph') for i in range(1, NUM_EPOCHS+1): print("Epoch {}: ".format(i), end='') sess.run(iterator.initializer, feed_dict={X: x_train, Y: y_train}) batch = 0 while True: try: images, labels = sess.run(next_element) assert images.shape == ( BATCH_SIZE, dim_input), "Something is wrong with Batch shape: {}".format(images.shape) # Run optimization op (backprop) sess.run(optimizer, feed_dict={X: images, Y: labels}) if batch % step == 0: print('#', end='') batch += 1 except tf.errors.OutOfRangeError: # Calculate metrics for validation set / test set _loss, _acc = sess.run([loss, accuracy], feed_dict={X: x_train, Y: y_train}) print(", Training Loss= {:.2f}".format(_loss) + ", Training Accuracy= {:.3f}".format(_acc)) break print("Validation Accuracy:", sess.run(accuracy, feed_dict={X: x_test, Y: y_test})) print("Optimization Finished!")
d435123b428818b73dba5ecc56f6b049084f2993
iamaaditya/Project-Euler
/018.py
1,260
3.625
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 09 00:58:43 2014 @author: aaditya prakash """ import utilities import math import time import numpy as np problem_number = '018' problem_statement = """ Find the maximum total from top to bottom of the triangle below: Problem 67, related """ def MaximumTopBottom(strMatrix): lstRows =strMatrix.split('\n') bigList = [] for l in lstRows: lstVals = map(int, l.split(' ')) #map(int, lstVals) bigList.append(lstVals) #print(bigList) maxSum = 0 for i in range(len(bigList)-2,-1,-1): for j in range(len(bigList[i])): bigList[i][j] += max(bigList[i+1][j], bigList[i+1][j+1]) return bigList[0][0] timeStart = time.clock() strMatrix = """75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40 31 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23""" print(MaximumTopBottom(strMatrix)) print('Time (sec):' + str(time.clock() - timeStart)) answer = '1074'
f08d10047a3da1f95324156752ef78eb5df52395
mineai/evolf
/servicecommon/persistor/local/pickle/pickle_persistor.py
1,596
3.53125
4
import pickle from framework.interfaces.persistence.persistence import Persistence class PicklePersistor(Persistence): def __init__(self, file, base_file_name=".", folder=""): """ This constructor initializes the name of the file to persist at what path. :param base_file_name: Name of the file without the .json extension :param folder: Location of the file to persist :returns nothing """ super().__init__() self.base_file_name = base_file_name self.folder = folder self.file = file def persist(self): """ This function takes in a dictionary and persists at the path with the base_file_name :param dict: Dictornary to persist :returns nothing """ if not self.base_file_name: self.base_file_name = "default_pickle" if not self.folder[-1] == "/": self.folder += "/" with open(self.folder + self.base_file_name + '.pkl', 'wb') as fp: pickle.dump(self.file, fp) def restore(self): """ This function loads a json from the base_file_name in the specified folder in a dictionary format. :params none :returns dict: Dictionary created from the JSON """ if not self.folder[-1] == "/": self.folder += "/" file = self.folder + self.base_file_name +'.pkl' try: pickle_obj = pickle.load(file) except Exception as e: print(e) return pickle_obj
c4ffc231d97246d898292bb662e6e9160c2c0e4a
rafaelperazzo/programacao-web
/moodledata/vpl_data/61/usersdata/232/27281/submittedfiles/poligono.py
161
4.03125
4
# -*- coding: utf-8 -*- n=int(input('Digite o número de lados do polígono: ') nd=(n*(n-3))/2 print('O valor do número de diagonais do polígono é: %.1d' %nd)
00749418b5992e7111442681a4ae85dbca7bc577
q2806060/python-note
/day04/day04/exercise/right_align2.py
967
3.890625
4
# 输入三行文字,让这三行文字依次以 20个字符的宽度右对齐 # 输出 # 如: # 请输入第1行: hello world! # 请输入第2行: abcd # 请输入第3行: a # 输出结果为: # hello world! # abcd # a # 做完上面的题后再思考: # 能否以最长字符串的长度进行右对齐显示(左侧填充空格) s1 = input("请输入第1行: ") s2 = input("请输入第2行: ") s3 = input("请输入第3行: ") # 方法1 # zuida = len(s1) # if len(s2) > zuida: # zuida = len(s2) # if len(s3) > zuida: # zuida = len(s3) # 方法2 zuida = max(len(s1), len(s2), len(s3)) print("最长的字符串长度是:", zuida) # 右对齐方法1 # print(' ' * (zuida-len(s1)) + s1) # print(' ' * (zuida-len(s2)) + s2) # print(' ' * (zuida-len(s3)) + s3) # 右对齐方法2 fmt = "%" + str(zuida) + "s" print(fmt % s1) print(fmt % s2) print(fmt % s3)
dac6216046b0f60e61b11259f72a0e5e4f53e539
almogboaron/IntroToCsCourseExtended
/deriv_intergral.py
685
3.9375
4
import math def diff(f, h=0.001): """ Returns the derivative of a one parameter real valued function f. When h is not specified, default value h=0.001 is used """ return (lambda x: (f(x+h)-f(x))/h) def integral(f, h=0.001): """ definite integral of f between a, b """ return lambda a,b: \ h * sum(f(a+i*h) \ for i in range(0, int((b-a)/h ))) ########################################## ## Some real valued functions to play with ########################################## def square(x): return x**2 def penta(x): return x**5 def sin_by_million(x): return math.sin(10**6*x)
b25c07d1417e8727ed89b1cb7d56e495f9f6b249
Asperas13/leetcode
/problems/48.py
682
3.78125
4
class Solution: def rotate(self, matrix): """ Do not return anything, modify matrix in-place instead. """ i = 0 dim = len(matrix) while i < dim: offset = 0 while i + offset < dim: matrix[i + offset][i], matrix[i][i + offset] = matrix[i][i + offset], matrix[i + offset][i] offset += 1 i += 1 for j in range(dim): self.reverse(matrix[j]) def reverse(self, lst): i, j = 0, len(lst) - 1 while i < j: lst[i], lst[j] = lst[j], lst[i] i += 1 j -= 1 return lst
0db81e1bcbd379ad932e8948450d120730f725ec
Icedomain/LeetCode
/src/Python/885.螺旋矩阵-iii.py
671
3.609375
4
# # @lc app=leetcode.cn id=885 lang=python3 # # [885] 螺旋矩阵 III # class Solution: def spiralMatrixIII(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]: mat, d = [[r0,c0]], 0 x , y = r0 ,c0 while len(mat) < R * C: # s代表方向 d 代表走的距离 for s in (1,-1): d += 1 for y in range(y+s , y+s*(d+1) , s): if 0 <= x < R and 0 <= y < C: mat.append([x,y]) for x in range(x+s , x+s*(d+1) , s): if 0 <= x < R and 0 <= y < C: mat.append([x,y]) return mat
cf8c33d6fec23546fc1c676076dcc29596c496b2
bug-thiago/Exercicio-4
/Exercicio04/Questao6.py
226
3.75
4
u = input("Digite um nome de usuário e a sua respectiva senha (não podem ser iguais):\nUsername: ") p = input("Senha: ") while u == p: u = input("Erro: os valores não podem ser iguais.\nUsername: ") p = input("Senha: ")
a3eb55eb4af858431ac24de39bccc4e9ec918b3d
MichelMuemboIlunga/Python-From-Zero-To-Hero-For-Beginners
/1.Data Structure and Objects/1_variable.py
1,090
4.53125
5
# variable and data type (string, integer, float, arithmetic) # declaring variable variable = "I am a variable" # display the variable value in the console print(variable) # display the data type of the variable print(type(variable)) print("-------------- Done -------------------") # variable containing string data type name = "Michel" print("Hello " + name + "👋") print(type(name)) print("-------------- Done -------------------") # variable containing integer data type date_year = 2020 print(date_year) print(type(date_year)) print("-------------- Done -------------------") # variable containing float data type weight = 14.2020 print(weight) print(type(weight)) print("-------------- Done -------------------") # another way of declaring variable in one line a, b = 15, 20 # display the value of a first then b in one line print(a, b) print("-------------- Done -------------------") # display both value in two lines print(a, "\n", b) # or print("-------------- Done -------------------") print(a) print(b) print("-------------- Done -------------------")
59f7439bfb4410ef9c1052ab8111b8fc07193568
kaneLittle2020/QUEUE
/main.py
874
3.953125
4
class Queue: def __init__ (self, capacity): self.internalArray = [None] * capacity self.start = 0 self.end = capacity - 1 self.size = 0 def add (self, item): if (self.end != (len(self.array) - 1)): temp = self.end + 1 else: temp = 0 if (self.array[temp] == None): self.end = temp self.array [self.end] = value self.size += 1 print ("{}has been added to the queue.".format(value)) else: print ("Queue is full") def remove (self): print (self.array [self.start]) self.arrary [self.start] = None self.size = 1 if (self.start != (len(self.array) -1 )): self.start += 1 else: self.start = 0 newQueue = Queue(8) print(newQueue.array) newQueue.add ('a') print(newQueue.array) newQueue.add ('c') print(newQueue.array) newQueue.remove () print(newQueue.array)
217fd627aff637b66736c8bb77e6ab6a15af25bf
Dekuben/pyEx
/pythonExercises/ex19.py
567
3.625
4
def CheeseAndCrackers(cheeseCount, boxesOfCrackers): print "You have %d cheeses!" % cheeseCount print "You have %d boxes of crackers!\n" % boxesOfCrackers print "I can just give the function numbers directly:" CheeseAndCrackers(20,30) print "OR, I can use variables:" amountOfCheese = 10 amountOfCrackers = 50 CheeseAndCrackers(amountOfCheese, amountOfCrackers) print "We can even do math inside too:" CheeseAndCrackers( 10 + 20, 5+ 6) print "variables and math can also be combined:" CheeseAndCrackers(amountOfCheese + 100, amountOfCrackers + 1000)
0ba15f4a1e9826eb0c703742f000a72f6a6a441f
tommyconner96/Computer-Architecture
/class_notes.py
3,562
4.0625
4
import sys PRINT_WORLD = 1 HALT = 2 PRINT_NUM = 3 SAVE = 4 PRINT_REGISTER = 5 ADD = 6 PUSH = 7 POP = 8 CALL = 9 RET = 10 memory = [0] * 256 # LOAD A PROGRAM INTO MEMORY def load_program(): if len(sys.argv) != 2: print("Wrong number of arguments, please pass file name") sys.exit(1) memory_address = 0 with open(sys.argv[1]) as f: for line in f: # Split the line on the comment character (#) line_split = line.split('#') # Extract the command from the split line # It will be the first value in our split line command = line_split[0].strip() if command == '': continue # specify that the number is base 10 command_num = int(command, 10) memory[memory_address] = command_num memory_address += 1 # Program counter pc = 0 registers = [0] * 8 SP = 7 # registers[SP] == the current top of our stack registers[SP] = 256 load_program() running = True while running: # Read a command from memory # at the current PC location command = memory[pc] if command == PRINT_WORLD: print("Hello World") pc += 1 elif command == HALT: running = False pc += 1 elif command == PRINT_NUM: # Take a look at the next line in memory value = memory[pc + 1] # print that value print(value) pc += 2 elif command == SAVE: # Get the value we are saving value = memory[pc + 1] reg_address = memory[pc + 2] # Store the value at the correct register registers[reg_address] = value pc += 3 elif command == PRINT_REGISTER: # get the address of register to print reg_address = memory[pc + 1] print(registers[reg_address]) pc += 2 elif command == ADD: reg_addr_1 = memory[pc + 1] reg_addr_2 = memory[pc + 2] # Retrieve the values in both registers val1 = registers[reg_addr_1] val2 = registers[reg_addr_2] # Add and store result in reg_addr_1 registers[reg_addr_1] = val1 + val2 pc += 3 elif command == PUSH: # Read the given register address reg_address = memory[pc + 1] value_to_push = registers[reg_address] # move the stack pointer down registers[SP] -= 1 # write the value to push, into the top of stack memory[registers[SP]] = value_to_push pc += 2 elif command == POP: # Read the given register address reg_address = memory[pc + 1] # Read the value at the top of the stack # store that into the register given registers[reg_address] = memory[registers[SP]] # move the stack pointer back up registers[SP] += 1 pc += 2 elif command == CALL: # Push the return address onto the stack # Move the SP down registers[SP] -= 1 # Write the value of the next line to return to in the code memory[registers[SP]] = pc + 2 # Set the PC to whatever is given to us in the register reg_num = memory[pc + 1] print(memory[-10:]) pc = registers[reg_num] elif command == RET: # Pop the top of the stack and set the PC to the value of what was popped pc = memory[registers[SP]] registers[SP] += 1
2831a6b6772ac448a4715e94b68700f01b9410b2
echrisinger/Blind-75
/solutions/insert.py
1,122
3.578125
4
class Solution: def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: res = [] new_s, new_e = newInterval inserted = False for inter in intervals: s, e = inter if (new_s <= s <= new_e) or\ (new_s <= e <= new_e) or\ (s < new_s and e > new_e): new_s = min(new_s, s) new_e = max(new_e, e) else: if not inserted and s > new_e: res.append([new_s, new_e]) inserted = True res.append([s, e]) if not inserted: res.append([new_s, new_e]) return res # O(n) time, O(n) space -- ignoring res, O(1) # If you wanted to make this true O(1) space, # you could track the range of values to delete in intervals # and after completed shift all values left into that range # (that are right of that range) -- not sure how to # do that in Python. # Then, insertion will also take O(n) time at the given index # (first index after new start)
b3bcddcb48a595086ae2f62091b6c48d4c295580
jufei/BtsShell
/bts_infomodel/ute_common_converter/to_list.py
2,511
3.609375
4
# -*- coding: utf-8 -*- """Module contains converters to list of specified types. :author: Pawel Chomicki :contact: pawel.chomicki@nsn.com """ from .base import BaseConverter from .exception import ConvertError class ToTypeList(BaseConverter): """Class tries to convert current list to list of specified type. .. code-block:: python ToTypeList(convert_method=int).convert(["1", "2"]) # Returns [1, 2] ToTypeList(convert_method=int, skip_none=True).convert(["1", "2"]) # Returns [1, 2] ToTypeList(convert_method=int, skip_none=True).convert(None) # Returns None """ def __init__(self, convert_method, skip_none=False): """ :param convert_method: Method needed to convert value e.g. str, bool, int. :param boolean skip_none: Skip convert if the value is None. """ self._expected_type = convert_method self._skip_none = skip_none def convert(self, current_list): """Method to convert current list to list of specified type. :param list current_list: List to convert. :return: Converted list :rtype: list :raise: ConvertError if it is not possible to convert any value of the specified list. """ if current_list is None and self._skip_none is True: return current_list new_list = [] for index, each in enumerate(current_list): try: new_list.append(self._expected_type(each)) except ValueError: raise ConvertError('Value (%s) with index (%d) cannot be converted to (%s)' % (str(each), index, self._expected_type.__name__)) return new_list def to_type_list(rlist, convert_method, skip_none=False): """Method to made conversion to list of specified type. :param list rlist: List to convert. :param convert_method: Method needed to convert value e.g. str, bool, int. :param boolean skip_none: Skip conversion if provided rlist object is None. :return: Converted list. :rtype: list """ return ToTypeList(convert_method=convert_method, skip_none=skip_none).convert(rlist) def to_int_list(rlist, skip_none=False): """Method to made conversion to list of integers. :param list rlist: List to convert. :param boolean skip_none: Skip conversion if provided rlist object is None. :return: Converted list. :rtype: list """ return ToTypeList(convert_method=int, skip_none=skip_none).convert(rlist)
a7a08f61f6670cb915cd68a50245aabf185e4584
FACaeres/WikiProg
/estruturas-condicionais/exercicio04.py
142
4.34375
4
numero = int(input("Digite um numero: ")) if (numero % 7 == 0) or (numero % 3 == 0): print("Divisivel") else: print("Nao divisivel")
c1232a4384d18fa0fac2117425bd31e880424758
scnu-sloth/hsctf-2020-freshmen
/MISC-onePiece/src/game.py
1,469
3.734375
4
#!/usr/bin/env python3 import random import time import sys from map import * from secret import flag ''' NOTHING = 0 WALL = 1 BOMB = 2 PIECE = 3 PERSON = 4 HOLE = 5 ''' def randint(start, end): m = end - start + 1 return random.getrandbits(16) % m + start actions = ['u', 'd', 'l', 'r', '_'] seed = int(time.time()) random.seed(seed) x = 1 y = 1 px = randint(1, n-2) py = randint(1, n-2) while map[px][py] != NOTHING: px = randint(1, n-2) py = randint(1, n-2) def dig(): global map global x, y global px, py if x==px and y==py: print(flag) sys.exit(0) else: map[x][y] = HOLE print('DONE') def move(c): global x, y x2, y2 = x, y if c == 'u': y2 = y-1 elif c == 'd': y2 = y+1 elif c == 'l': x2 = x-1 elif c == 'r': x2 = x+1 else: print('ERROR') exit(-1) if map[x2][y2]==NOTHING: x = x2 y = y2 print('OK') return True elif map[x2][y2]==WALL: print('WALL') return False elif map[x2][y2]==BOMB: print('BOMB') exit(-1) elif map[x2][y2]==HOLE: print('HOLE') return False else: print('ERROR') exit(-1) def start(): while True: action = input()[0] if action not in actions: sys.exit(-1) if action=='_': dig() else: move(action) start()
5c1f50aff1ef5ef4925479878d54f8c87d60d4d3
ajwalsh08/randombracket
/ncaab.py
841
3.859375
4
# Import a random number generator. import random # Bring in the favorites and their chances of winning as a dictionary. with open('chances.txt') as f: favorites = dict(line.strip().split(",") for line in f) # Create a function that chooses winners using random numbers generation. def losers(d): lst = list() for team in d: outcome = random.randrange(1,100001) chance = float(d[team]) * 1000 if outcome < int(chance): pass else: lst.append(str(team)) return lst # Ask the user how many upsets they think will happen. upsets = raw_input("How many first-round upsets do you think will happen? ") # Run the function once. picks = losers(favorites) # Check its length. If it returns more than 5 teams, run it again. Else, print it. while len(picks) != int(upsets): picks = losers(favorites) else: print picks
dde1f8cec0c99fb30adbfe256ffddc02adb06cfe
nikk7007/Python
/Exercícios-do-Curso-Em-Video/01-50/034.py
244
3.890625
4
salario = int(input('Qual o seu salario? R$')) if salario <= 1250: salarioAumento = salario + (salario * (15 / 100)) else: salarioAumento = salario + (salario * (10 / 100)) print('Novo Salario: R${}'.format(salarioAumento))
3f422169871604625c12159db983a85f440ffc2a
tcltsh/leetcode
/leetcode/src/5.py
949
3.671875
4
class Solution(object): def judge(self, idx, step, s): front = idx + step tail = idx find = False ret = "" while True: if front >= len(s) \ or tail < 0 \ or s[front] != s[tail]: break find = True front += 1 tail -= 1 if (front - 1) < len(s) and (tail + 1) >= 0 and find is True: ret = s[tail+1: front] return ret def longestPalindrome(self, s): """ :type s: str :rtype: str """ retstr = "" for i in range(0, len(s)): for j in range(0, 2): now = self.judge(i, j, s) if len(now) > len(retstr): retstr = now return retstr if __name__ == "__main__": s = Solution() print s.longestPalindrome("bbbb") print s.longestPalindrome("cbbd")
1a797ca30a497773e72829c3e7c37a8b7450b6f2
Volkoff/firstPython
/listspractice.py
261
3.828125
4
list = ["Dog", "Cat", "Boop", None, None] print(list) tuple = ("Dog", "Cat", "Boop", None, None) print(tuple) set = {"Dog", "Cat", "Boop", None, None} print(set) dictionary = { 1:None } print(dictionary) iphone13 = "iphone13" iphone13+="pro" print(iphone13)
795202fc16a3df6a7088cb5e96b78a20eb0374dd
kermitnirmit/Advent-of-Code-2020
/day_21/solution.py
1,921
3.59375
4
from collections import defaultdict f = open("input.txt").read().strip().split("\n") lines = [] for rec in f: a,b = rec.split(" (") b = b.strip("()").split(", ") b[0] = b[0][len("contains") + 1:] lines.append((a.split(" "), b)) allergenmap = defaultdict(list) ingmap = defaultdict(set) # for every ingredient and allergen list (each line) for ing, al in lines: # for every allergen, add the list of possible ingredients it could be for a in al: allergenmap[a].append(ing) # for every ingredient, add the allergens in that line for i in ing: ingmap[i].add(a) not_possible = set() possibles = defaultdict(list) # for each ingredient and the possible allergens for ing, al in ingmap.items(): valid = True # loop over all of the possible allergens that the ingredient could be for a in al: # if this ingredient is in each ingredient list that corresponds to this allergen, it's a possible allergen if all(ing in anl for anl in allergenmap[a]): valid = False # add that possible allergen to what ing could be possibles[ing].append(a) # if not, it can not be an allergen if valid: not_possible.add(ing) # simple count of ingredients that are in the not possible count = 0 for ing, a in lines: for ii in ing: if ii in not_possible: count += 1 print(count) # remove the ones that are already defined from ones that arent. while any(len(v) != 1 for v in possibles.values()): for ing in possibles: if len(possibles[ing]) == 1: first = next(iter(possibles[ing])) for k, v in possibles.items(): if k == ing: pass else: if first in v: v.remove(first) # print properly print(",".join(x[0] for x in sorted(list(possibles.items()), key = lambda x : x[1])))
086f8f96ec5e2f19f12a7451526371b46640f2bf
zenwattage/csc1102018
/functiondeftest.py
137
3.59375
4
def test(age, amount, rate): loop_count = age while loop_count < age: age += age year += 1 print(test(5,10,20))
9e91aada659d4fa73b2b28e0f4bdf5f63766d250
a-falcone/puzzles
/adventofcode/2019/09a.py
7,862
3.65625
4
#!/usr/bin/env python3 """ --- Day 9: Sensor Boost --- You've just said goodbye to the rebooted rover and left Mars when you receive a faint distress signal coming from the asteroid belt. It must be the Ceres monitoring station! In order to lock on to the signal, you'll need to boost your sensors. The Elves send up the latest BOOST program - Basic Operation Of System Test. While BOOST (your puzzle input) is capable of boosting your sensors, for tenuous safety reasons, it refuses to do so until the computer it runs on passes some checks to demonstrate it is a complete Intcode computer. Your existing Intcode computer is missing one key feature: it needs support for parameters in relative mode. Parameters in mode 2, relative mode, behave very similarly to parameters in position mode: the parameter is interpreted as a position. Like position mode, parameters in relative mode can be read from or written to. The important difference is that relative mode parameters don't count from address 0. Instead, they count from a value called the relative base. The relative base starts at 0. The address a relative mode parameter refers to is itself plus the current relative base. When the relative base is 0, relative mode parameters and position mode parameters with the same value refer to the same address. For example, given a relative base of 50, a relative mode parameter of -7 refers to memory address 50 + -7 = 43. The relative base is modified with the relative base offset instruction: Opcode 9 adjusts the relative base by the value of its only parameter. The relative base increases (or decreases, if the value is negative) by the value of the parameter. For example, if the relative base is 2000, then after the instruction 109,19, the relative base would be 2019. If the next instruction were 204,-34, then the value at address 1985 would be output. Your Intcode computer will also need a few other capabilities: The computer's available memory should be much larger than the initial program. Memory beyond the initial program starts with the value 0 and can be read or written like any other memory. (It is invalid to try to access memory at a negative address, though.) The computer should have support for large numbers. Some instructions near the beginning of the BOOST program will verify this capability. Here are some example programs that use these features: 109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99 takes no input and produces a copy of itself as output. 1102,34915192,34915192,7,4,7,99,0 should output a 16-digit number. 104,1125899906842624,99 should output the large number in the middle. The BOOST program will ask for a single input; run it in test mode by providing it the value 1. It will perform a series of checks on each opcode, output any opcodes (and the associated parameter modes) that seem to be functioning incorrectly, and finally output a BOOST keycode. Once your Intcode computer is fully functional, the BOOST program should report no malfunctioning opcodes when run in test mode; it should only output a single value, the BOOST keycode. What BOOST keycode does it produce? """ import itertools from collections import deque class Intcode: def __init__(self,name,data): self.name = name self.d = {i:data[i] for i in range(len(data))} self.halted = False self.i = 0 self.lastout = 0 self.inputvals = deque([]) self.relbase = 0 def stopped(self): return self.halted def lastout(self): return self.lastout def locations(self,modes): ls = [] """0: position mode 1: immediate mode 2: relative mode """ for x in range(1,4): if modes % 10 == 0: ls.append(self.d.get(self.i + x, 0)) elif modes % 10 == 1: ls.append(self.i + x) elif modes % 10 == 2: ls.append(self.d.get(self.i + x, 0) + self.relbase) else: print("Unknown mode in {}".format(modes)) modes //= 10 return ls def run(self,inputvals): self.inputvals.extend(inputvals) if self.halted: print( "Amp {} is halted. Can not run.".format(self.name) ) return False while True: opcode, loc = self.d[self.i] % 100, self.locations(self.d[self.i] // 100) if opcode == 1: """Opcode 1 adds together numbers read from two positions and stores the result in a third position. The three integers immediately after the opcode tell you these three positions - the first two indicate the positions from which you should read the input values, and the third indicates the position at which the output should be stored.""" self.d[loc[2]] = self.d.get(loc[0],0) + self.d.get(loc[1],0) self.i += 4 elif opcode == 2: """Opcode 2 works exactly like opcode 1, except it multiplies the two inputs instead of adding them. Again, the three integers after the opcode indicate where the inputs and outputs are, not their values.""" self.d[loc[2]] = self.d.get(loc[0],0) * self.d.get(loc[1],0) self.i += 4 elif opcode == 3: """Opcode 3 takes a single integer as input and saves it to the position given by its only parameter. For example, the instruction 3,50 would take an input value and store it at address 50.""" self.d[loc[0]] = self.inputvals.popleft() self.i += 2 elif opcode == 4: """Opcode 4 outputs the value of its only parameter. For example, the instruction 4,50 would output the value at address 50.""" self.lastout = self.d.get(loc[0],0) print(self.lastout) self.i += 2 elif opcode == 5: """Opcode 5 is jump-if-true: if the first parameter is non-zero, it sets the instruction pointer to the value from the second parameter. Otherwise, it does nothing.""" if self.d.get(loc[0],0): self.i = self.d.get(loc[1],0) else: self.i += 3 elif opcode == 6: """Opcode 6 is jump-if-false: if the first parameter is zero, it sets the instruction pointer to the value from the second parameter. Otherwise, it does nothing.""" if self.d.get(loc[0],0): self.i += 3 else: self.i = self.d.get(loc[1],0) elif opcode == 7: """Opcode 7 is less than: if the first parameter is less than the second parameter, it stores 1 in the position given by the third parameter. Otherwise, it stores 0.""" self.d[loc[2]] = 1 if self.d.get(loc[0],0) < self.d.get(loc[1],0) else 0 self.i += 4 elif opcode == 8: """Opcode 8 is equals: if the first parameter is equal to the second parameter, it stores 1 in the position given by the third parameter. Otherwise, it stores 0.""" self.d[loc[2]] = 1 if self.d.get(loc[0],0) == self.d.get(loc[1],0) else 0 self.i += 4 elif opcode == 9: """Opcode 9 adjusts the relative base by the value of its only parameter. The relative base increases (or decreases, if the value is negative) by the value of the parameter.""" self.relbase += self.d.get(loc[0],0) self.i += 2 elif opcode == 99: self.halted = True return self.lastout else: print( "Unknown opcode {}".format(self.d[self.i]) ) with open("09.data", "r") as f: data = list(map(int, f.read().strip().split(","))) Intcode("BOOST", data).run([1])
34a03b688bb9775159237239b26469833c2e5376
BurnFaithful/KW
/Programming_Practice/Python/Base/Bigdata_day1002/LOOP06.py
209
3.734375
4
# 팩토리얼 factorial = 1 x = int(input("팩토리얼 구할 수 : ")) for i in range(x, 0, -1): if i == 1: print(f"{i}=", end='') else: print(f"{i}*", end='') factorial *= i print(factorial)
92b17e8306cc02da2d01e7602d65153950288915
Azurick05/Ejercicios_Nate_Academy
/Encontrar_numero/Numero_mayor_sin_usar_max.py
279
4.0625
4
""" Ejercicio 17) Crear un programa que encuentre el numero más grande de una lista (sin usar la función max). """ numeros = [1, 2, 3, 4, 5, 6, 7, 8, 70, 10, 13, 15, 16, 17, 20, 30] mayor = 0 for entero in numeros: if entero > mayor: mayor = entero print(mayor)
ceedaf8f03d605da04cd0ef28d14b7528768dbf6
MeitarEitan/Devops0803
/8.py
344
3.8125
4
myFile = open("newFile.txt", "r") allLines = myFile.readlines() for line in allLines: print(line, end='') myOtherFile=open("newFile.txt","a") myOtherFile.write("\nthis is the last line") myOtherFile.close() myFile.close() inputUser = input("Enter your name:") myNewFile=open("names.txt","w") myNewFile.write(inputUser) myNewFile.close()
4182f904ffed8003eee92fc460ffa05de07c5141
lsom11/coding-challenges
/leetcode/May LeetCoding Challenge/Implement Trie (Prefix Tree).py
1,479
4.125
4
class TrieNode: def __init__(self,char): self.char = char self.isWord =False self.children = {} class Trie: def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode("*") def insert(self, word: str) -> None: """ Inserts a word into the trie. """ current = self.root for char in word: if char in current.children: current = current.children[char] else: current.children[char] = TrieNode(char) current = current.children[char] current.isWord =True def search(self, word: str) -> bool: """ Returns if the word is in the trie. """ current =self.root for char in word: if char in current.children: current = current.children[char] else: return False if current.isWord: return True else: return False def startsWith(self, pre: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ prefix = True current = self.root for char in pre: if char in current.children: current = current.children[char] else: return False return prefix
7d2c06dd6baab97e61b1518ed9207721c75fa27b
TejasD10/python
/data_structures/misc/LCS.py
1,821
3.890625
4
import unittest def longest_subsequence(s1, s2): """ Determine the longest common subsequence in the strings s1 and s2 :param s1: String :param s2: String :return: A Tuple of the length and the longest common subsequence. """ # If one of the string is none, there is no common subsequence, hence return 0 if not s1 or not s2: return 0 # Create the matrix for use for tabulation result = [[0] * (len(s1) + 1) for _ in range(len(s2) + 1)] for row in range(1, len(result)): # Iterate over the rows for col in range(1, len(result[0])): # Iterate over the cols if s2[row - 1] == s1[col - 1]: # If they are the same they are adding to the longest subsequence result[row][col] = 1 + result[row - 1][col - 1] else: result[row][col] = max(result[row - 1][col], result[row][col - 1]) # Return the last element as the length of the longest common subsquence # Find the longest common subsequence lcs = [] row = len(result) - 1 col = len(result[0]) - 1 while row and col: # Check if the value is same as the adjacent cells, if not it is coming from diagonals if result[row][col] != result[row - 1][col] and result[row][col] != result[row][col - 1]: lcs.append(s1[col - 1]) col -= 1 row -= 1 elif result[row][col] == result[row][col - 1]: # Matches the column col -= 1 else: row -= 1 return ''.join(str(i) for i in reversed(lcs)), result[len(s2)][len(s1)] class TestLongestCommonSubsequence(unittest.TestCase): def test_longest_subsequence(self): lcs, length = longest_subsequence('abcdaf', 'acbcf') self.assertEqual(length, 4) self.assertEqual(lcs, 'abcf')
879c929183f98e70da6526822733576695d04f8c
baaanan01/practice3-4
/21_6.py
301
3.671875
4
import turtle def tree(forward_len=200, minim_len=5): turtle.forward(forward_len) if forward_len > minim_len: turtle.left(45) tree(0.6*forward_len, minim_len) turtle.right(90) tree(0.6*forward_len, minim_len) turtle.left(45) turtle.back(forward_len)
b6dafc74a6b08f9a403c648f034ffd58e33f82cd
funfun313/strings
/string1.py
150
3.609375
4
def tripleend(s): l = len(s) w=s[l-2:] return w+w+w print(tripleend("hello")) print(tripleend("hi")) print(tripleend("goodbye"))
17ab37243715033d028b421b0345fac86be7b59d
DovzhenkoVit/main_academy_homework
/homework_6.py
1,509
3.796875
4
sort_dict = {} def register_sort(*name): def wrapper(func): for sort_type in name: sort_dict[sort_type] = func def inner(*args, **kwargs): return func(*args, **kwargs) return inner return wrapper def sort(sort_type, *key): def wrapper(func): def inner(*args): result = sort_dict[sort_type](func(*args), *key) return result return inner return wrapper @register_sort("bubble") def bubble_sort(_list, key=lambda x: x): swapped = True while swapped: swapped = False for i in range(len(_list) - 1): left, right = key(_list[i]), key(_list[i + 1]) if left > right: _list[i], _list[i + 1] = _list[i + 1], _list[i] swapped = True return f"{_list} --> Bubble sort" @register_sort("quick") def quick_sort(_list, key=lambda x: x): if _list: pivot = key(_list[0]) low = [i for i in _list[1:] if key(i) < pivot] high = [i for i in _list[1:] if key(i) > pivot] pv_list = [i for i in _list if key(i) == pivot] result = quick_sort(low, key) + pv_list + quick_sort(high, key) return result else: return _list @sort("bubble") def some_func(): return [(8, 5), (8, 1), (4, 3), (2, 6)] @sort("quick", lambda x: x[1]) def other_func(a): return a if __name__ == '__main__': print(some_func()) print(other_func([(8, 5), (8, 3), (4, 1), (2, 6)]))
d0eadcbb12bb50d9bdbffdb96a8175be3cf9f325
minjekang/Python_Study
/Python/Rand.py
941
3.78125
4
from random import * # print(random()) # print(random() * 10) # 0.0 ~ 10.0 # print(int (random() * 10)) # 0 ~ 10 # print(int (random() * 10)) # print(int (random() * 10)) # print(int (random() * 10 + 1)) # 1 ~ 10 # print(int (random() * 10 + 1)) # 1 ~ 10 # print(int (random() * 10 + 1)) # 1 ~ 10 # print(int (random() * 10 + 1)) # 1 ~ 10 # print(int (random() * 10 + 1)) # 1 ~ 10 # print (int(random() * 45) + 1) # print (int(random() * 45) + 1) # print (int(random() * 45) + 1) # print (int(random() * 45) + 1) # print (int(random() * 45) + 1) # print (int(random() * 45) + 1) # print(randrange(1,46)) #1 ~ 45 # print(randrange(1,46)) #1 ~ 45 # print(randrange(1,46)) #1 ~ 45 # print(randrange(1,46)) #1 ~ 45 # print(randint(1,45)) # 1~45 # print(randint(1,45)) # 1~45 # print(randint(1,45)) # 1~45 # print(randint(1,45)) # 1~45 # Quiz i = randint(4,28) print("오프라인 스터디 모임은 매월" + str(i) +"일 입니다.")
b39c658b6f043df0003b4f96173b0239a765ca52
itwbaer/advent-of-code
/day4.py
2,918
4.5
4
""" A new system policy has been put in place that requires all accounts to use a passphrase instead of simply a password. A passphrase consists of a series of words (lowercase letters) separated by spaces. To ensure security, a valid passphrase must contain no duplicate words. aa bb cc dd ee is valid. aa bb cc dd aa is not valid - the word aa appears more than once. aa bb cc dd aaa is valid - aa and aaa count as different words. The system's full passphrase list is available as your puzzle input. How many passphrases are valid? """ def read_passwords(input_file): passwords = list() with open(input_file) as file: for file_row in file: passwords.append(file_row.strip('\n')) return passwords def passphrase_validity_part_1(input_file): passwords = read_passwords(input_file) valid_sum = 0 for password in passwords: # need a dictionary to store already used words used = dict() # process the password into list to make it easier to read password = password.split() # validate password, can't be duplicate valid = True for word in password: if word in used: valid = False else: used[word] = 1 valid_sum += 1 if valid else 0 return valid_sum print(passphrase_validity_part_1("day4_input.txt")) """ For added security, yet another system policy has been put in place. Now, a valid passphrase must contain no two words that are anagrams of each other - that is, a passphrase is invalid if any word's letters can be rearranged to form any other word in the passphrase. abcde fghij is a valid passphrase. abcde xyz ecdab is not valid - the letters from the third word can be rearranged to form the first word. a ab abc abd abf abj is a valid passphrase, because all letters need to be used when forming another word. iiii oiii ooii oooi oooo is valid. oiii ioii iioi iiio is not valid - any of these words can be rearranged to form any other word. Under this new system policy, how many passphrases are valid? """ def passphrase_validity_part_2(input_file): passwords = read_passwords(input_file) valid_sum = 0 for password in passwords: # need a dictionary to store already used words used = dict() # process the password into list to make it easier to read password = password.split() # validate password, can't be duplicate, can't be anagram valid = True for word in password: # instead of just checking word, check the sorted word word = list(word) word.sort() word = ''.join(word) if word in used: valid = False else: used[word] = 1 valid_sum += 1 if valid else 0 return valid_sum print(passphrase_validity_part_2("day4_input.txt"))
df37b3db6a4102090fcc8ea0b604dcbb99a63a78
avqzx/CS3_Git
/student_gui.py
7,014
4.03125
4
import tkinter as tk from student import Student from student import StudentListUtilities class StudentGui: DEFAULT_NAME = "" DEFAULT_GRADE = 9 DEFAULT_ADDRESS = "123 Main St, 456" DEFAULT_PHONE = "123 456 7890" def __init__(self): """Constructor for a GUI for Student.""" self._root = tk.Tk() # -------------- one message widget --------------------- header = "Enter student info" self._header = tk.Message(self._root, text=header) self._header.config(font=("times", 18, "italic"), bg="lightblue", width=300) # ----------------- some label widgets ------------------ self._label_name = tk.Label(self._root, text="Name", padx=20, pady=10) self._label_grade = tk.Label(self._root, text="Grade", padx=20, pady=10) self._label_address = tk.Label(self._root, text="Address", padx=20, pady=10) self._label_phone = tk.Label(self._root, text="Phone", padx=20, pady=10) # Assume this will be used to show list of students at the start self._label_answer_text = tk.Label(self._root, padx=20, pady=10) self._label_answer_value = tk.Label(self._root, padx=20, pady=10) # ----------------- some entry widgets ------------------ self._entry_name = tk.Entry(self._root) self._entry_name.insert(0, self.DEFAULT_NAME) self._entry_grade = tk.Entry(self._root) self._entry_grade.insert(0, str(self.DEFAULT_GRADE)) self._entry_address = tk.Entry(self._root) self._entry_address.insert(0, self.DEFAULT_ADDRESS) self._entry_phone = tk.Entry(self._root) self._entry_phone.insert(0, self.DEFAULT_PHONE) # ----------------- some button widgets ------------------ self._button_add = tk.Button(self._root, text="Add", command=self._add_student) self._button_remove = tk.Button(self._root, text="Remove", command=self._remove_student) self._button_student_info = tk.Button(self._root, text="Student Info", command=self._student_info) self._button_all_students = tk.Button(self._root, text="All Students", command=self._all_students) # ------------ place all widgets using grid layout ------------- self._header.grid(row=0, column=0, columnspan=2, sticky=tk.EW) self._label_name.grid(row=1, column=0, sticky=tk.E) self._entry_name.grid(row=1, column=1, padx=25, sticky=tk.W) self._label_grade.grid(row=2, column=0, sticky=tk.E) self._entry_grade.grid(row=2, column=1, padx=25, sticky=tk.W) self._label_address.grid(row=3, column=0, sticky=tk.E) self._entry_address.grid(row=3, column=1, padx=25, sticky=tk.W) self._label_phone.grid(row=4, column=0, sticky=tk.E) self._entry_phone.grid(row=4, column=1, padx=25, sticky=tk.W) self._label_answer_text.grid(row=5, column=0, pady=4, sticky=tk.E) self._label_answer_value.grid(row=5, column=1, sticky=tk.W) self._button_add.grid(row=6, column=0, padx=20, sticky=tk.EW) self._button_remove.grid(row=6, column=1, padx=20, sticky=tk.EW) self._button_student_info.grid(row=7, column=0, padx=25, pady=15, sticky=tk.EW) self._button_all_students.grid(row=7, column=1, padx=25, pady=15, sticky=tk.EW) # ------ Initialize a list to hold students as they are added ----- self._students = [] # to make testing easier # self._students = [ # Student("JP", 10), # Student("Jasmine", 10), # Student("Bresy", 11), # Student("Francisco", 11), # Student("Jonathan", 11), # Student("Jacob", 12), # ] self._display_students() @property def root(self): return self._root def _add_student(self): """event handler to add a student.""" # First, create a Student object with name and grade name = self._entry_name.get() grade = int(self._entry_grade.get()) student = Student(name, grade) # Now, try to set address and phone address = self._entry_address.get() try: student.address = address except ValueError: self._label_answer_text.config(text="Error") message = f"*** Failed to set {address} as new address ***" self._label_answer_value.config(text=message) return phone = self._entry_phone.get() try: student.phone = phone except ValueError: self._label_answer_text.config(text="Error") message = f"*** Failed to set {phone} as new phone ***" self._label_answer_value.config(text=message) return # Finally, add to our list of students and display updated list self._students.append(student) self._display_students() def _display_students(self): self._label_answer_text.config(text="Students") students = StudentListUtilities.to_gui_string(self._students) self._label_answer_value.config(text=students) def _remove_student(self): """event handler to remove a student.""" name = self._entry_name.get() index = StudentListUtilities.linear_search(name, self._students) if index == StudentListUtilities.NOT_FOUND: self._label_answer_text.config(text="Error") result = f"Name '{name}' not found." else: self._students.pop(index) self._label_answer_text.config(text="Students") result = StudentListUtilities.to_gui_string(self._students) self._label_answer_value.config(text=result) def _student_info(self): """event handler to display full info of a student.""" name = self._entry_name.get() index = StudentListUtilities.linear_search(name, self._students) if index == StudentListUtilities.NOT_FOUND: self._label_answer_text.config(text="Error") result = f"Name '{name}' not found." else: self._label_answer_text.config(text="Student Info") result = f"Record for {name} - {self._students[index]}" self._label_answer_value.config(text=result) def _all_students(self): """event handler to display all students.""" self._label_answer_text.config(text="Students") students = StudentListUtilities.to_gui_string(self._students) self._label_answer_value.config(text=students) demo = StudentGui() demo.root.title("Student GUI") demo.root.mainloop()
f39789e37a4cf4d0d5f994e6f1f2ae08b8c02a9e
cybelewang/leetcode-python
/code204CountPrimes.py
709
3.859375
4
""" 204 Count Primes Count the number of prime numbers less than a non-negative number, n. """ # https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes # 1 is not a prime number class Solution: def countPrimes(self, n): """ :type n: int :rtype: int """ if n < 2: return 0 prime = [True for i in range(n)] i = 2 while i**2 < n: if prime[i]: j = i**2 while j < n: prime[j] = False j += i i += 1 res = sum(1 for x in prime[2:] if x) return res obj = Solution() print(obj.countPrimes(16))
05c0fe1817d05ae9eec396618fbbca586f2fde19
lucienbertin19/python_exercise
/exercise.py
959
4.3125
4
''' To design and implement a Python application that prints all numbers between 1 and 100 with the square value in the allotted time specified. • Create a Python application that will loop between 1 and 100 for i in range(1, 101): print(i) • The numbers are to be printed out alongside their squared value for i in range(1, 101): print(i + " " + i**) • The app should stop when a squared value of 200 or more is reached if i**2 >= 200: break • Reconfigure the application to take in a user value to produce squared values up to x ''' # number to be inputed by user numberInput = int(input("Please enter the number to be used\n")) # loop through and check squared value is less than 200 else break for i in range(1, numberInput + 1): if i**2 >= 200: break print("***************** Number is {} *****************".format(i)) print("Number: {}\nSquare Value: {}\n".format(i, i**2))
a0e5ebee6c667189cb226d3721083edbfc39ba67
graevskiy/mit_6.0001
/PSet1/ps1a.py
700
3.5
4
#! python3 import sys if len(sys.argv) != 4: sys.exit('parameters to provide annual_salary portion_saved total_cost') try: annual_salary = int(sys.argv[1]) portion_saved = float(sys.argv[2]) total_cost = int(sys.argv[3]) except: sys.exit('one of your parameters is of incorrect types') assert portion_saved < 1, 'portion_saved must be <1' portion_down_payment = 0.25 current_savings = 0 r = 0.04 down_payment = portion_down_payment * total_cost monthly_salary = annual_salary / 12 monthly_savings = monthly_salary * portion_saved savings = 0 i = 0 while savings < down_payment: savings = monthly_savings + savings*(1+r/12) i += 1 print(f'You\'ll need {i} months')
7e52bd4e65afb2eec143b049a0118f9d44a9a311
ojhermann-ucd/comp10280
/p18p5.py
359
3.953125
4
""" Pseudocode take user input count each occurance of "xyz" count each occurance of ".xyz" take the difference print the results """ stringInput = input("Please enter what you would like: ") def xyzCheck(s): xyzCount= 0 xyzCount += s.count("xyz") xyzCount -= s.count(".xyz") return xyzCount print("There are ", xyzCheck(stringInput), "occurances.")
3764a2cda74f66ebc8cebddc04fea0866e9ffc3b
mdbasoglu/Phyton-Applications
/Tek mi cift mi.py
164
3.6875
4
nummer=int(input('Schreiben Sie bitte Ihre Nummer!')) if nummer % 2==0: print('Cif Sayidir') # yada print(f'{nummer} cift sayidir') else: print('tek sayidir')
a6715dcf3acb15423af8a7a1ec145259777a7a54
msuzun/GlobalAIHubPythonCourse
/Homeworks/HW3.py
489
3.984375
4
#question 3 loginUsernamePassword={"admin":"admin", "root":"1234567", "login":"qwerty"} print(loginUsernamePassword.keys()) username=input("Kullanıcı adinizi giriniz") password=input("Parolanızı giriniz") if username in loginUsernamePassword.keys(): if loginUsernamePassword[username] == password: print("Parolaniz dogru") else: print("Kullanici adiniz veya parolaniz yanlis") else: print("Kullanici adiniz veya parolaniz yanlis")
b3d108d971309d26b88949c0de3eff7c836e4287
pabloares/misc-python-exercises
/cesar-short.py
354
3.875
4
string = input("Introduce una frase: ") shift = int(input("Numero entre 1 y 25 para cifrar: ")) newstring = "" for i in string: n = ord(i) if n >= 65 and n <= 90: newstring += chr(((n-65+shift) % 26) + 65) elif n >= 97 and n <= 122: newstring += chr(((n-97+shift) % 26) + 97) else: newstring += i print(newstring)
88a31567cdc0b9ddfebc0a7916bea48e4bac1255
duwenzhen/leetcode
/833find.py
806
3.5
4
from typing import List class Solution: def findReplaceString(self, S: str, indexes: List[int], sources: List[str], targets: List[str]) -> str: nl = [] for i, v in enumerate(indexes): nl.append((v, sources[i], targets[i])) nl = sorted(nl, key=lambda x: x[0], reverse=True) for i,s,t in nl: l = len(s) if S[i:i + l] == s: S = S[:i] + t + S[i + l:] return S s = Solution() print(s.findReplaceString(S = "vmokgggqzp", indexes = [3,5,1], sources = ["kg","ggq","mo"], targets = ["s","so","bfr"])) print(s.findReplaceString(S = "abcd", indexes = [0, 2], sources = ["a", "cd"], targets = ["eee", "ffff"])) print(s.findReplaceString(S = "abcd", indexes = [0, 2], sources = ["ab","ec"], targets = ["eee","ffff"]))
590463ad832f16841bcdd9647d73520383e2a61f
joostrijneveld/Euler-Project
/Python/problem63.py
309
3.640625
4
import math def diglen(n): return len(str(n)) def main(): count = 0 for i in range(100): for j in range(100): n = pow(i,j) if diglen(n) == j: print "j = " + str(j) + " LEN= " + str(diglen(n)) + "Result: " + str(pow(i,j)) count = count + 1 print count if __name__ == "__main__": main()
9b716865be1e87a83017b9ff60f378276c433036
huangwenzi/mingyue
/main/control/image.py
2,171
3.734375
4
# 系统模块 # 三方模块 import pygame # 项目模块 # 窗口 class Image(): # 初始化 # parent : 父级窗口 # path : 图像资源地址 # name : 资源名 # tmp_type : 图像类型 # postion : 坐标 def __init__(self, parent, path, name, tmp_type, postion): self.parent = parent # 父级窗口 self.image_list = [] # 子级窗口列表 self.image = self.background = pygame.image.load(path) self.name = name # 对应名字 self.type = tmp_type # 游戏类型 self.width = self.image.get_width() # 图像宽度 self.height = self.image.get_height() # 图像高度 self.x = postion[0] # 相对父级的x坐标 self.y = postion[1] # 相对父级的y坐标 # 绘制窗口内的图像资源 def blit_image(self): self.parent.image.blit(self.image, (self.x, self.y)) # 循环反复调用绘制子级 for tmp_image in self.image_list: tmp_image.blit_image() # 添加一个窗口 # 统一以parent为绘制窗口 # path : 图像资源地址 # name : 资源名 # tmp_type : 图像类型 # postion : 坐标 # callback : 对应的回调函数 def add_image(self, path, name, tmp_type, postion, callback): # 添加图像到列表 tmp_image = Image(self.parent, path, name, tmp_type, postion) self.image_list.append(tmp_image) self.parent.image_callback[name] = callback # 获取点击的图像 def get_click_image(self, postion): # 循环反复调用查找子级 if self.x < postion.x and (self.x + self.width) > postion.x and self.y < postion.y and (self.y + self.height) > postion.y: # 查找点击到的图像,从后面开始找 list_len = len(self.image_list) for idx in range(0, list_len): tmp_image = self.image_list[list_len - idx - 1] ret,obj = tmp_image.get_click_image(postion) if ret == True: return True,obj return True,self return False,self
b3696040510322e2785026d3c9d6afcdef5582e3
bellcliff/algorithm
/sorting/quick.py
1,561
3.546875
4
# encoding: utf-8 import sys import os testpath = os.path.dirname(os.path.realpath(__file__)) + "/test" if not testpath in sys.path: sys.path.append(testpath) from TestStuf import TestStuf class QuickSorting(TestStuf): ''' from [[http://zh.wikipedia.org/wiki/%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F]] function quicksort(q) var list less, pivotList, greater if length(q) ≤ 1 { return q } else { select a pivot value pivot from q for each x in q except the pivot element if x < pivot then add x to less if x ≥ pivot then add x to greater add pivot to pivotList return concatenate(quicksort(less), pivotList, quicksort(greater)) } ''' def v1(self): def qsort(q): if not q: return [] return qsort([x for x in q[1:] if x < q[0]]) + q[0:1] + \ qsort([x for x in q[1:] if x >= q[0]]) self.L = qsort(self.L) def v2(self): def qsort(q): l = [] g = [] n = [] if len(q) <= 1: return q else: # select key key = q[len(q) - 1] for i in q[0: -1]: if i < key: l.append(i) else: g.append(i) n.extend(qsort(l)) n.append(key) n.extend(qsort(g)) return n self.L = qsort(self.L) pop = QuickSorting() pop.run(10)
211d6ce07287364d6800a059625419ac93e88e12
sohaib-93/SOIS_Assingment
/Embedded_Linux/Part_A/prog3.py
769
4.53125
5
# !/usr/bin/python3 # Python Assignment # Program 3: Implement a python code to find the distance between two points.(Euclidian distance) # Formula for Euclidian distance, Distance = sqrt((x2-x1)^2 + (y2-y1)^2) def edist(x1,y1,x2,y2): dist1 = (x2-x1)**2 + (y2-y1)**2 dist = dist1**0.5 return dist x1 = float(input("Please enter the x co-ordinate of point 1: ")) y1 = float(input("Please enter the y co-ordinate of point 1: ")) x2 = float(input("Please enter the x co-ordinate of point 2: ")) y2 = float(input("Please enter the y co-ordinate of point 2: ")) #p1 and p2 contain x & y co-ordinates of Point 1 and Point 2 in the form of Tuples. p1 = (x1,y1) p2 = (x2,y2) print ("The distance between Point 1", p1, "and Point 2", p2, " is:", edist(x1,y1,x2,y2))
568d2e1865bc08f62a448e6b4f720a9a1ec7435f
oclather/learn_python
/getImage/learn_class.py
3,226
4.21875
4
#coding=utf-8 #这里学习类、继承、多态 #学习完:获取对象信息。 接下来是:面向对象高级编程 class Student(object): #这是一个类:1、类的名称一般都大写;2、括号中是这个类的继承类,如果没有继承,则写object def __init__(self, name, sex, score): #这里可以理解为模板参数,将这一类中所有共有的参数都直接写进来。创建实例时必须要携带这些参数。self是本身就有的,不用传参数 self.__name = name #__代表这个参数是私有的。不能从外部访问 self.score2 = score #我们从外部设定内部参数值的时候,实际上是设定前面score2的值。例如:tony.score2=33 self.sex = sex def get_name(self): return self.__name def get_score(self): return self.score2 def print_score(self): print "%s: %s"%(self.__name, self.score2) def print_sex(self): print "%s: %s"%(self.__name, self.sex) def get_grade(self): if self.score2>=90: return "A" elif self.score2>=60: return "B" else: return "C" #Animall类 class Animal(object): def run(self): print "Animal is running!" class Dog(Animal): def __init__(self, name): self.name = name def print_name(self): print self.name def eating(self): print "Dog is eating meat." def run(self): print "Dog is running." class Cat(Animal): def fund_mouse(self): print "Cat is finding mouse." def run(self): print "Cat is running." class Country(object): def __init__ (self, name, color, area, peoples): self.name = name self.color = color self.area = area self.peoples = peoples def power(self): print "国家实力体现在面积和人口上:" print "%s的人口是:%d;面积是:%d。国力是:%d" %(self.name, self.peoples, self.area, self.peoples*self.area) if __name__ == '__main__': #这里是Student类的外部调用 tony = Student('Tony','male',88) #这是一个实例。实例=类名() 这样来实现。 lisa = Student('Lisa','female',99) #这也是一个实例。每个实例的数据可能不同,但是方法都是一致的。都是类中的方法。 #print tony.__score #访问限制了。 __的参数是私有的,不能在外部访问 tony.score2=33 print tony.get_score() tony.print_score() lisa.print_score() tony.print_sex() tony.nianji = ('3') #这里可以动态绑定一个额外的参数给实例 print tony.nianji print tony.get_grade() print lisa.get_grade() #这里是Animal类的外部调用 my_dog = Dog('Ben') my_dog.print_name() my_dog.run() my_dog.eating() my_cat = Cat() my_cat.run() my_cat.fund_mouse() SSS = Animal() def run_twice(A): #定义这个函数,调用animall中的run方法。如果传的数据类型不同,则显示不同的run方法。比如传cat,就显示Cat中的run() A.run() A.run() run_twice(my_cat) print type(SSS) #type函数用∫来显示变量的类型 print isinstance(my_cat,Animal)#用来判断每个实例是否是某个类型。形式: isinstance(实例,类名) #这里是Country类的外部调用 China = Country("China", "Red", 9600000, 1300000000) China.power() Japan = Country("Japan", "White", 77623, 188888888) Japan.power()
8ecf2bbb1b21bb514c0d5be41ffb3cbcdabad29a
chuliuT/Python3_Review
/Python3命名空间和作用域.py
1,025
3.890625
4
# var1 是全局名称 var1 = 5 def some_func(): # var2 是局部名称 var2 = 6 def some_inner_func(): # var3 是内嵌的局部名称 var3 = 7 g_count = 0 # 全局作用域 def outer(): o_count = 1 # 闭包函数外的函数中 def inner(): i_count = 2 # 局部作用域 import builtins print(dir(builtins)) total = 0 # 这是一个全局变量 # 可写函数说明 def sum(arg1, arg2): # 返回2个参数的和." total = arg1 + arg2 # total在这里是局部变量. print("函数内是局部变量 : ", total) return total # 调用sum函数 sum(10, 20) print("函数外是全局变量 : ", total) num = 1 def fun1(): global num # 需要使用 global 关键字声明 print(num) num = 123 print(num) fun1() print(num) def outer(): num = 10 def inner(): nonlocal num # nonlocal关键字声明 num = 100 print(num) inner() print(num) outer()
ab951b913e3f0adc872f65e695e8047f90c4d5a7
RickXie747/UNSW-18S1-COMP9021-
/Lab4/Q4.py
872
3.65625
4
def print_square(*L): if not L: raise square_exception('No Input!') for i in range(len(L[0])): if len(L[0]) != len(L[0][i]): raise square_exception(f'Wrong Input!') for j in range(len(L[0][i])): print(L[0][i][j], end = ' ') print() def is_magic_square(*L): sum = 0 for i in range(len(L[0][0])): sum += L[0][0][i] for i in range(len(L[0])): tmp_sum = 0 for j in range(len(L[0][i])): tmp_sum += L[0][i][j] if tmp_sum != sum: return False for i in range(len(L[0])): tmp_sum = 0 for j in range(len(L[0][i])): tmp_sum += L[0][j][i] if tmp_sum != sum: return False return True class square_exception(Exception): def __int__(self, message): self.message = message
aad2ea8c3d79e0e3f80dc50d43cf554be2a99061
Donsworkout/boj_algorithm_python
/divide_conquer/boj_1992.py
680
3.796875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Feb 8 18:12:18 2019 @author: donsdev """ def quad(size,x,y): if size == 1: print(arr[y][x],end='') return same = True for i in range(y,y+size): for j in range(x,x+size): if arr[i][j] != arr[y][x]: same = False if same == True: print(arr[y][x],end='') return offset = size // 2 print('(',end='') quad(offset,x,y) quad(offset,x+offset,y) quad(offset,x,y+offset) quad(offset,x+offset,y+offset) print(')',end='') arr = [] n = int(input()) for _ in range(n): arr.append(input()) quad(n,0,0)
58e4180b26ee33f6e0f696b68a0743adc9df8457
maynkjain/CSE544-Probability-and-Statistics-Assignment
/A1/nba.py
4,314
3.828125
4
import numpy def games(): """ This function performs 7 games and calculate the wins of each team based on the win probabilities. The win probabilities for both the teams are equal (=0.5). args: None return: - [eventA_Occured, eventBA_Occured] where, eventA_Occured: LAC is 3-1 after 4 games eventBA_Occured: DEN won 4-3 after event A had occured. """ lacWins = 0 denWins = 0 eventA_Occured = False eventBA_Occured = False for i in range (7): lacWon = numpy.random.binomial(1, 0.5) if (lacWon): lacWins = lacWins+1; else: denWins = denWins + 1; if (i == 3): if (lacWins == 3): eventA_Occured = True; if (denWins == 4 and eventA_Occured): eventBA_Occured = True return [eventA_Occured, eventBA_Occured] def homeGames(homes): """ This function performs 7 games and calculate the wins of each team based on the win probabilities. The win probability depends on the list (homes) (0.75 if homeground, 0.25 otherwise). args: - homes: This list tells the home for ith game return: - [eventA_Occured, eventBA_Occured] where, eventA_Occured: LAC is 3-1 after 4 games eventBA_Occured: DEN won 4-3 after event A had occured. """ lacWins = 0 denWins = 0 eventA_Occured = False eventBA_Occured = False for i in range (7): p = 0.75 if homes[i] == "LAC" else 0.25 lacWon = numpy.random.binomial(1, p) if (lacWon): lacWins = lacWins+1; else: denWins = denWins + 1; if (i == 3): if (lacWins == 3): eventA_Occured = True; if (denWins == 4 and eventA_Occured): eventBA_Occured = True return [eventA_Occured, eventBA_Occured] def gamesHelper(N): """ This function runs the 7 games with equal win probability, "N" number of times and prints the calculated probabilities. This function calls the games() function to calculate the probabilities. args: - N : it is the number of times the experiment is performed. return: None """ eventA_Occurrences = 0 eventBA_Occurrences = 0 for i in range(N): occurence = games() if (occurence[0]): eventA_Occurrences = eventA_Occurrences + 1 if (occurence[1]): eventBA_Occurrences = eventBA_Occurrences + 1 probA = eventA_Occurrences/N probBA = eventBA_Occurrences/N print("FOR N = " + str(N) + ", the simulated value for part (a) is " + str(probA)) print("FOR N = " + str(N) + ", the simulated value for part (c) is " + str(eventBA_Occurrences/eventA_Occurrences)) def homeGamesHelper(N): """ This function runs the 7 games with home-based win probability, "N" number of times and prints the calculated probabilities. This function calls the homeGames() function with a list, homes, where home[i] is the home for game i. args: - N : it is the number of times the experiment is performed. return: None """ eventA_Occurrences = 0 eventBA_Occurrences = 0 homes = ["LAC", "LAC", "DEN", "DEN", "LAC", "DEN", "LAC"] for i in range(N): occurence = homeGames(homes) if (occurence[0]): eventA_Occurrences = eventA_Occurrences + 1 if (occurence[1]): eventBA_Occurrences = eventBA_Occurrences + 1 probA = eventA_Occurrences/N probBA = eventBA_Occurrences/N print("FOR N = " + str(N) + ", the simulated value for part (e) is " + str(eventBA_Occurrences/eventA_Occurrences)) if __name__ == "__main__": """ This function is the driver for performing the experiments. It iterates over n (=3,4,5,6,7) to call the below helper functions which repeat the experiments for N ( = 10^n) times and print the probabilities: 1. 7 games with equal win probability (N times) - gamesHelper() 2. 7 games with home based win probability (N times) - homeGamesHelper() """ for n in range(3, 8): print ("Calculating... \n") N = pow(10, n) gamesHelper(N) homeGamesHelper(N) print("\n")
b03699a211be656dd5f8faf3c236caae9194d57b
rajat19/Hackerrank
/Tutorials/30-Days-of-Code/30-review-loop.py
359
3.8125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT def printc(s): for i in range(0, len(s), 2): print(s[i], end='') print(" ", end='') for i in range(1, len(s), 2): print(s[i], end='') print() if __name__ == "__main__": t = int(input()) while t>0: s = input() printc(s) t-=1
9d1a59167e53da032a25672c070f6a649d7ba9ff
Sohamraje137/Python-Learning
/Python_codes/ex03.py
214
4.28125
4
# inpu1=input("Please enter a test string\n") # if len(inpu1) <3: # print("\nShort") # else: # print("Okay") num=input("Please enter a number"); num1=int(num) if num1%2 == 0: print("Even") else: print("Odd")
6ce1e834e9b90fa13766bf881d4602b0fdb1c5a1
CharuTamar/SIG-PYTHON
/MODULE3/M3_4.py
135
3.71875
4
print("CHARU TAMAR 1803010065") sum=0 for i in range(0,11): if i%2==0: sum+=i print("Sum of even numbers from 0 to 10 is:",sum)