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
b4a6ccd014e2d135ca70b9a08b831d6f900f4f0e
Ikhsanhaw/algorithm-collection
/python/check_anagram.py
104
3.6875
4
def check_anagram(str1, str2): return "".join(sorted(str1.lower())) == "".join(sorted(str2.lower()))
4cb7664ef86894fe6ea9fd927085f94e9f0932a0
rahuldbhadange/Python
/Python/python programs/control structures/while loop/7 continue1.py
312
4.25
4
#Continue stmt: It is used in the loops #when continue stmt is used in the loop, then it skips the execution of #current iteration and Ctrl goes to next iteration x=0 while(x<=10): x=x+1 if(x==5): continue # here iteration 5 is skipped print(x,"hello") print("end")
3d426a57b9803f6d6efbccdec4ca67416f3331f0
PMForest/Lesson_1
/lesson_1.5.py
613
3.875
4
user_profit = int(input("Введите сумму прибыли: ")) user_cost = int(input("Введите сумму издержек: ")) if user_profit > user_cost: print('Вы наконец можете выдать сотрудникам "ЗП"') print('Коэффицент рентабельности равен: ', user_profit / (user_profit + user_cost )) man = int(input("Введите кол. сотрудников: ")) print('Прибыль на одного сотрудника: ', user_profit / man) else: print('Вы "ПОТРаЧЕнЫ" Бегите!')
a0be954389da5caf89b947c9ff9c9e4a861d2ea2
kamalp009/DataStructures
/edit_distance.py
805
3.578125
4
import time start_time = time.time() print("--- %start seconds ---" % (time.time() - start_time)) def memoize(func): mem = {} def memoizer(*args, **kwargs): key = str(args) + str(kwargs) if key not in mem: mem[key] = func(*args, **kwargs) return mem[key] return memoizer @memoize def levenshtein(s, t): if s == "": return len(t) if t == "": return len(s) if s[-1] == t[-1]: cost = 0 else: cost = 1 #For operations replace,remove,insert res = min([levenshtein(s[:-1], t)+1, levenshtein(s, t[:-1])+1, levenshtein(s[:-1], t[:-1]) + cost]) return res print(levenshtein("Python", "Peithen")) print("--- %end seconds ---" % (time.time() - start_time))
437c456fd6f2fbe1b2fdbb9bef3b287a4db76a91
hideyukiinada/ml
/project/kmeans.py
6,825
3.765625
4
#!/usr/bin/env python """ K-means clustering implementation. Notes ----- As the below Wikipedia article points out, there is no guarantee that this implementation finds the optimal clustering result. Reference --------- https://en.wikipedia.org/wiki/K-means_clustering __author__ = "Hide Inada" __copyright__ = "Copyright 2018, Hide Inada" __license__ = "The MIT License" __email__ = "hideyuki@gmail.com" """ import os import logging import numpy as np log = logging.getLogger(__name__) logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO")) # Change the 2nd arg to INFO to suppress debug logging class NoConvergenceException(Exception): """Exception for not reaching convergence within specified number of iterations""" pass def random_unique_choice(input_size, output_size): """ Returns a subset of elements of an array consisting of elements that range from 0 to input_size-1. For example, if input_size is 4 and output_size is 2, two unique numbers will be picked from [0, 1, 2, 3]. Parameters ----------- input_size: int Size of elements from which the the subset of elements to choose from output_size: int Number of unique elements to be returned Returns ------- out: ndarray Array of unique indices Notes ----- This function is provided to ensure that the result will not contain any duplicated numbers. np.random.choice(a, size) may return duplicates by design. For example, np.random.choice(4, 2) can return array([2, 2]). """ output_array = list() current_array_size = input_size current_array = np.arange(0, input_size) for i in range(output_size): index_picked = int(np.random.choice(current_array_size, 1)) number_picked = current_array[index_picked] output_array.append(number_picked) tmp = np.delete(current_array, index_picked) current_array = tmp.copy() current_array_size -= 1 return np.array(output_array) class KMeans(): @staticmethod def clustering(observations, K=2, iteration_limit=1000000): """ Parameters ---------- observations: ndarray Observations K: int Number of clusters Returns ------- observation_assignment_to_centroids: ndarray Array of 0-based indices of cluster assignment for each observation. For example, [3 1 0 2] means the first observation is assigned to the 4th cluster (index 3). Raises ------ ValueError If len(observations.shape) != 2. NoConvergenceException(Exception) If convergence is not reached within the specified number of iterations. Notes ----- Observation has to have exactly two axes (i.e. length of the shape): For example, np.array([1, 2, 3]) will throw an exception as the shape is (3,) and the length of the shape is 1. 2-D coordinates and 3-D coordinates work. [[1, 2], [3, 4]] has the shape (2, 2) and length of the shape is 2. [[1, 2, 3], [3, 4, 5]]) has the shape (2, 3) and length of the shape is 2. """ shape = observations.shape # e.g. (m, 2), (m, 3) shape_len = len(shape) if shape_len != 2: raise ValueError("Observation has to have exactly two axes such as [[1, 2, 3], [3, 4, 5]]") num_observations = shape[0] # m # Initialize centroid positions # Pick K observations randomly and assign them to centroid positions. # This is called Forgy method. indices_picked = random_unique_choice(num_observations, K) log.debug("indices_picked: %s" % (str(indices_picked))) few_observation_positions = observations[indices_picked] log.debug("few_observation_positions:\n%s" % (str(few_observation_positions))) centroid_positions = few_observation_positions.copy() first_run = True convergence = False for iter in range(iteration_limit): if convergence: break log.debug("Centroid positions:\n%s" % (str(centroid_positions))) # centroid to point distance # For each observation, multiple columns are assigned. # Each column holds the distance to each centroid from the observation on the row. d_table = np.zeros((num_observations, K)) # distance_between_centroid_to_observation_table # Calculate the distance from each observation to all centeroids. for j in range(K): v = observations - centroid_positions[j] # vector from centroid to each observation d = np.linalg.norm(v, axis=1) # distance between the centroid[j] and each observation # Note: You need to leave 'd' as the 1-D vector. The following will fail: # tmp = d.reshape(1, (d.shape[0])) # Make it a row vector # distance = np.transpose(tmp) # Transpose to a column vector d_table[:, j] = d # Fill the column with the distance log.debug("d_table:\n%s" % (str(d_table))) # for each row (observation), find the minimum value across columns, index of which is the closest centroid. observation_assignment_to_centroids = np.argmin(d_table, axis=1) log.debug("observation_assignment_to_centroids:\n%s" % (str(observation_assignment_to_centroids))) # for each set of observations belonging to the same cluster, calculate the average position # We want to isolate a set of observation that belongs to cluster[k] for each iteration, and # calculate the average position. for j in range(K): indices_belonging_to_the_cluster = ( observation_assignment_to_centroids == j) # True means that the element belongs to the cluster mean_position = np.mean(observations[indices_belonging_to_the_cluster], axis=0) centroid_positions[j] = mean_position if first_run: first_run = False else: # If observations are assigned to the same cluster as the last run, we consider that as convergence if np.array_equal(observation_assignment_to_centroids, prev_observation_assignment_to_centroids): log.info("Converged. Iteration: %d" % (iter + 1)) convergence = True break prev_observation_assignment_to_centroids = observation_assignment_to_centroids.copy() if convergence is False: raise NoConvergenceException("Cluster assignment did not converge.") return observation_assignment_to_centroids
acb33b2069fa3c13e8f67328e2ad4f9ffb42fdbe
raghum96/pythonTutorial
/WhileLoop.py
139
3.59375
4
i = 0 while i < 10: # print(i) i = i + 1 for i in range(0, 100, 7): if i > 0 and i % 11 == 0: print(i) break
ad5f18a81a433dad87f76f6dfb42c26d51ff8116
GenericKen/dominionstats
/iso_lex.py
1,586
3.609375
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ Do lexical analysis turns. """ import ply.lex import re import card_info tokens = ( 'NEWLINE', 'CARD', 'PLAYER', 'NUMBER', 'TRASHING', 'TRASHES', 'IS_TRASHED', 'GAINING', 'PLAYS', 'BUYS', 'GAINS', 'TOKEN', 'DISCARDS', 'REVEALS', 'RETURNING', 'REVEALING', 'TO_THE_SUPPLY', 'GETTING', 'WHICH_IS_WORTH', 'TURNS_UP_A', 'REVEALS_A', 'REPLACING', 'WITH_A', 'TRASHES_IT', ) t_NEWLINE = r'\n' def t_CARD(t): '<span[^>]*>(?P<card_name>[^<]*)</span>' maybe_plural = t.lexer.lexmatch.group('card_name') t.value = card_info.SingularOf(maybe_plural) return t def t_PLAYER(t): 'player(?P<num>\d)' t.value = int(t.lexer.lexmatch.group('num')) return t def t_NUMBER(t): '\d+' t.value = int(t.value) return t for tok in tokens: if not 't_' + tok in locals(): locals()['t_' + tok] = tok.lower().replace('_', ' ') def t_error(t): """ Skip single character input on error, let's us ignore boring text """ t.lexer.skip(1) lexer = ply.lex.lex() def iso_lex(turn_str): """ Given a turns string, return a list of ply tokens. """ ret = [] lexer.input(turn_str) # Tokenize while True: tok = lexer.token() if not tok: break # No more input ret.append(tok) return ret def type_lex(turn_str): """ Like iso_lex, but return only a list of token types. """ ret = [] for tok in iso_lex(token_list): ret.append(tok.type) return ret
3d20057bf7d4236ccb252f256a82dc3f3b3f0272
peperoschach/logica-de-programacao
/estruturas-condicionais/aula-pratica/exercicio-1.py
1,307
4.21875
4
''' - Faça um algoritmo que receba três valores, representando os lados de um triângulo fornecidos pelo usuário. Verifique se os valores formam um trriângulo e classifique como: a) Equilátero (Três lados iguais) b) Isósceles (dois lados iguais) c) Escaleno (três lados diferentes) - Lembre-se de que, para formar um triângulo, nenhum dos lados pode ser igual a zero, e um lado não pode ser maior do que a soma dos outros dois. ''' lado_a = float(input('Digite o lado A _')) lado_b = float(input('Digite o lado B _')) lado_c = float(input('Digite o lado C _')) if ((lado_a > 0) and (lado_b > 0) and (lado_c > 0)): if ((lado_a + lado_b > lado_c) and (lado_a + lado_c > lado_b) and (lado_b + lado_c > lado_a)): #Escaleno if ((lado_a != lado_b) and (lado_a != lado_c)): print('Triângulo Escaleno!') else: #Equilátero if ((lado_a == lado_b) and (lado_a == lado_c)): print('Triângulo Equilátero!') else: #Isósceles print('Triângulo Isósceles') else: print('Ao menos um dos valores indicados não servem para formar um triângulo') else: print('Ao menos um dos valores indicados não servem para formar um triângulo')
4953d97b3eb62e5af2a4d06ded3a64d733d4ea3d
AdriGeaPY/programas1ava
/zprimero/Sentencies_Simples/tu propio iva.py
311
3.78125
4
print("¿cuanto cuesta tu producto?") producto=input() producto=int(producto) print("¿cuanto porcentaje de IVA?") iva=input() iva=int(iva) print("tu producto con IVA cuesta: ", producto + producto*iva/100) print("tu producto costaba: ",producto, "y le he sumado el", iva ,"% de IVA,que es:", producto*iva /100)
369fbd6f91ac006c8ad13dc096bcb4cf53b62663
MuhammadHafizhRafi/I0320065_Muhammad-Hafizh-Rafi-Susanto_Abyan_Tugas-5
/I0320065_Soal 2_Tugas 5.py
1,096
3.9375
4
print("=======Membuat Program Grading Nilai=======") print("==========Masukan Nama dan Nilai===========") nama_siswa = input("Masukan Nama Siswa :") nilai_siswa = float(input("Masukan Nilai Siswa :")) if nilai_siswa < 60: print("Halo,", nama_siswa + "! Nilai anda setelah dikonversi adalah E") elif nilai_siswa>= 60 and nilai_siswa <= 64: print("Halo,", nama_siswa + "! Nilai anda setelah dikonversi adalah C") elif nilai_siswa >=65 and nilai_siswa <=69: print("Halo,", nama_siswa + "! Nilai anda setelah dikonversi adalah C+") elif nilai_siswa >=70 and nilai_siswa <=74: print("Halo,", nama_siswa + "Nilai anda setelah dikonversi adalah B") elif nilai_siswa >=75 and nilai_siswa <=79: print("Halo,", nama_siswa + "Nilai anda setelah dikonversi adalah B+") elif nilai_siswa >=80 and nilai_siswa <= 84: print("Halo,", nama_siswa + "Nilai anda setelah dikonversi adalah A-") elif nilai_siswa >=85 and nilai_siswa <= 100: print("Halo,", nama_siswa + "Nilai anda setelah dikonversi adalah A+") else: print("nilai yang selain disebutkan tidak valid")
b01b2e33adff4533a71753c13f27fc6c014b4051
toasterbob/python
/Fundamentals1/Dictionaries/iteration_and_comprehension.py
3,507
4.53125
5
# Dictionary iteration d = dict(name = 'Elie', job = 'Instructor') for k in d: print(k) # name # job # If you want access to both the keys and the values, call items on the # dictionary and iterate through the result d = dict(name = 'Elie', job = 'Instructor') for key, value in d.items(): print("{}: {}".format(key,value)) # name:Elie # job:Instructor # Dictionary comprehension # - We can convert dictionaries into lists using list comprehension d = {'a': 1, 'c': 3, 'e': 5} [v for k,v in d.items()] # [1, 5, 3] [k for k,v in d.items()] # ['a', 'e', 'c'] [[k,v] for k,v in d.items()] # [['a', 1], ['c', 3], ['e', 5]] # But we can also convert other data types into dictionaries using dictionary comprehension! str1 = "ABC" str2 = "123" {str1[i]: str2[i] for i in range(0,len(str1))} # {'A': '1', 'B': '2', 'C': '3'} { num:("even" if num % 2 == 0 else "odd") for num in range(1,5) # {1: 'odd', 2: 'even', 3: 'odd', 4: 'even'} # theirs num_list = [1,2,3,4] { num:("even" if num % 2 == 0 else "odd") for num in num_list } # Tuples # Tuples are another collection in Python, but they are immutable. # This means that you can't reassign values in tuples like you can with lists. # Because of this immutability, however, operations on tuples are faster than lists. # If you're defining a collection of values that won't change, use a tuple instead of a list. x = (1,2,3) 3 in x # True x[0] = "change me!" # TypeError: 'tuple' object does not support item assignment #Tuple methods # count - Returns the number of times a value appears in a tuple x = (1,2,3,3,3) x.count(1) # 1 x.count(3) # 3 # index - Returns the index at which a value is found in a tuple. t = (1,2,3,3,3) t.index(1) # 0 t.index(5) # ValueError: tuple.index(x): x not in tuple t.index(3) # 2 - only the first matching index is returned # Sets # Sets do not have duplicate values, and elements in sets aren't ordered. # You cannot access items in a set by index. Sets can be useful if you need # to keep track of a collection of elements, but don't care about ordering. # To test whether a value is a member of a set, use the in operator # Sets cannot have duplictes s = set({1,2,3,4,5,5,5}) # {1, 2, 3, 4, 5}# Creating a new set s = set({1,4,5}) # Creating a new set s = set({1,4,5}) # Creates a set with the same values as above s = {4,1,5} 4 in s # True 8 in s # False # Set methods # add - Adds an element to a set. If the element is already in the set, the set doesn't change s = set([1,2,3]) s.add(4) s # {1, 2, 3, 4} s.add(4) s # {1, 2, 3, 4} # clear - Removes all the contents of the set s = set([1,2,3]) s.clear() s # set() # copy - Creates a copy of the set s = set([1,2,3]) another_s = s.copy() another_s # {1, 2, 3} another_s is s # False another_s.add(4) another_s # {1, 2, 3, 4} s # {1, 2, 3} # difference - Returns a new set containing all the elements that are in # the first set but not in the set passed to difference set1 = {1,2,3} set2 = {2,3,4} set1.difference(set2) # {1} set2.difference(set1) # {4} # intersection - Returns a new set containing all the elements that are in both sets set1 = {1,2,3} set2 = {2,3,4} set1.intersection(set2) # {2,3} # symmetric_difference - Returns a new set containing all the elements # that are in exactly one of the sets set1 = {1,2,3} set2 = {2,3,4} set1.symmetric_difference(set2) # {1,4} # union - Returns a new set containing all the elements that are in either set set1 = {1,2,3} set2 = {2,3,4} set1.union(set2) # {1,2,3,4} #
e59c3c24c8ff614cd0ba286561684673d97a9d4c
hecmec/fs-crawler-elasticsearch-py
/threading/locked_ops_threads.py
661
3.765625
4
import time import threading class SomeClass(object): def __init__(self,c): self.c=c self.lock = threading.Lock() def inc(self): self.lock.acquire() try: new = self.c+1 # if the thread is interrupted by another inc() call its result is wrong time.sleep(0.001) # sleep makes the os continue another thread self.c = new finally: self.lock.release() x = SomeClass(0) threads = [] for _ in range(1000): t= threading.Thread(target=x.inc) threads.append(t) t.start() for th in threads: th.join() print( x.c) # now there are 1000
97ae55f04af8315709e2a144deb7d841ea7330df
candreas3/Python
/Calc.py
381
3.640625
4
import tkinter from tkinter import * from tkinter import messagebox top = Tk() top.geometry("200x400") def stop(): exit() def hello(): messagebox.showinfo("Say Hello", "Hello World") B1 = Button(top, text="Say Hello", command=hello) B2 = Button(top, text="Cancel", command=stop) B2.place(x=120, y=50) B1.place(x=35, y=50) top.mainloop()
2586033bb1ba91b4b253ab66402378d7967a5c19
mjzac/advent-of-code
/2019/3.py
3,031
3.59375
4
# https://adventofcode.com/2019/day/3/ the_grid = {} origin = (0, 0) intersections = [] def parse_cmd_to_idx(cmd, curr_x, curr_y): """ Parses the command and return `(next_x, next_y, num_steps, negative_direction)` """ direction = cmd[0] steps = int(cmd[1:]) if direction is "U": return (curr_x, curr_y - steps, steps, True) elif direction is "D": return (curr_x, curr_y + steps, steps, False) elif direction is "R": return (curr_x + steps, curr_y, steps, False) elif direction is "L": return (curr_x - steps, curr_y, steps, True) raise ValueError def part1(x, y): intersections.append((abs(x - origin[0]) + abs(y - origin[1]))) def part2(x, y, steps): intersections.append(the_grid[(x, y)][1] + steps) def set_point_visited(x, y, wire_number, steps): try: current_value = the_grid.get((x, y), None) if current_value is not None and current_value[0] != wire_number: part2(x, y, steps) # part1(x, y) the_grid[(x, y)] = "X" else: the_grid[(x, y)] = (wire_number, steps) except IndexError: print(x, y) exit(1) def traverse(cmd, curr_x, curr_y, wire_num, steps_taken): next_x, next_y, steps, negative_direction = parse_cmd_to_idx(cmd, curr_x, curr_y) if next_x == curr_x: # traverse along y axis range_start_idx = ( max(curr_y, next_y) if negative_direction else min(curr_y, next_y) ) range_end_idx = ( min(curr_y, next_y) if negative_direction else max(curr_y, next_y) ) range_step = -1 if negative_direction else 1 for idx, y_cord in enumerate(range(range_start_idx, range_end_idx, range_step)): set_point_visited(curr_x, y_cord, wire_num, steps_taken + idx) if next_y == curr_y: # traverse along x axis range_start_idx = ( max(curr_x, next_x) if negative_direction else min(curr_x, next_x) ) range_end_idx = ( min(curr_x, next_x) if negative_direction else max(curr_x, next_x) ) range_step = -1 if negative_direction else 1 for idx, x_cord in enumerate(range(range_start_idx, range_end_idx, range_step)): set_point_visited(x_cord, curr_y, wire_num, steps_taken + idx) return (next_x, next_y, steps_taken + steps) def run(): with open("3input.txt") as f: wire_one_path = f.readline().split(",") curr_x = origin[0] curr_y = origin[1] steps_taken = 0 for cmd in wire_one_path: curr_x, curr_y, steps_taken = traverse(cmd, curr_x, curr_y, 1, steps_taken) curr_x = origin[0] curr_y = origin[1] wire_two_path = f.readline().split(",") steps_taken = 0 for cmd in wire_two_path: curr_x, curr_y, steps_taken = traverse(cmd, curr_x, curr_y, 2, steps_taken) return sorted(intersections)[1] if __name__ == "__main__": print(run())
9798957126726b44ecfd1833dd4f80ed00989967
wasimashraf88/Python-tutorial
/immuteable.py
615
4.03125
4
from random import randint def generator(): return randint(1,10) def rand_guess(): random_number = generator() guess_left = 3 flag = 0 while guess_left >0: guess = int(input("Pick your number to" "enter the lucky draw\n")) if guess == random_number: flag = 1 break else: print("Wrong Guess!!") guess_left -= 1 if flag is 1: return True else: return False if __name__ == '__main__': if rand_guess() is True: print("Congrats!! You Win.") else : print("Sorry, You Lost!")
0b8eb0dae8cf0ae457372a564712aef1c34a187e
okvarsh/Hackerrank-Codes
/10 Days of Statistics/D7-Pearson-Correlation-Coefficient1.py
1,510
4.53125
5
''' Objective In this challenge, we practice calculating the Pearson correlation coefficient. Check out the Tutorial tab for learning materials! Task Given two -element data sets, and , calculate the value of the Pearson correlation coefficient. Input Format The first line contains an integer, , denoting the size of data sets and . The second line contains space-separated real numbers (scaled to at most one decimal place), defining data set . The third line contains space-separated real numbers (scaled to at most one decimal place), defining data set . Constraints , where is the value of data set . , where is the value of data set . Data set contains unique values. Data set contains unique values. Output Format Print the value of the Pearson correlation coefficient, rounded to a scale of decimal places. Sample Input 10 10 9.8 8 7.8 7.7 7 6 5 4 2 200 44 32 24 22 17 15 12 8 4 Sample Output 0.612 Explanation The mean and standard deviation of data set are: The mean and standard deviation of data set are: We use the following formula to calculate the Pearson correlation coefficient: ''' n = int(input()) X = list(map(float, input().split())) Y = list(map(float, input().split())) mx = sum(X)/n my = sum(Y)/n stdx = (sum([(i - mx)**2 for i in X]) / n)**0.5 stdy = (sum([(i - my)**2 for i in Y]) / n)**0.5 covariance = sum([(X[i] - mx) * (Y[i] - my) for i in range(n)]) correlation_coefficient = covariance / (n * stdx * stdy) print(round(correlation_coefficient,3))
cda7a87a77685c3ad7a285d0f77b1d75eb491fb9
avneeshbhargava/Python30
/Pyt30/cal2.py
1,019
3.84375
4
class calu(): def __init__(self,a,b): self.a = a self.b = b def Add(self): # it can be any varibale return self.a + self.b # this should be same as init method variable def subtract_fun(self): return self.a - self.b def divide_function(self): return self.a / self.b def multiply_function(self): return self.a * self.b a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) obj=calu(a,b) choice = 1 while choice !=0: print("0. Exit") print("1. Add") print("2. Subtraction") print("3. Multiplication") print("4. Division") choice = int(input("Enter choice: ")) if choice == 1: print("Result: ",obj.Add()) elif choice == 2: print(obj.subtract_fun()) elif choice == 3: print(obj.multiply_function()) elif choice == 4: print(obj.divide_function()) elif choice == 0: print("Exiting!") else: print("Invalid choice!!")
245d2dbca55a41edf7779131f66a41c1111ca96e
gmhorn/euler
/utils/contfrac.py
3,069
3.640625
4
import itertools import math import collections class SquareRootCF(object): """ Represents the continued fraction for sqrt(N) with N not a perfect square as a continued fraction. """ _trip = collections.namedtuple('_trip', ['m', 'd', 'a']) def __init__(self, N): # TODO: assert N not perfect square self._N = N self._calculated = False def _calculate(self): """ Calculates partial quotients of the (periodic) continued fraction expansion of sqrt(n) for n not a perfect square. Algorithm from: http://en.wikipedia.org/wiki/Methods_of_computing_square_roots Meant to only be called once from a "public" method. Have not evaluated whether algorithm can lose precision for n with large period. """ triples = [] t = SquareRootCF._trip(0, 1, int(math.floor(self._N**0.5))) a_0 = t.a # Repeat iterations until we get a triple repeating while t not in triples: # Calculate the next pertial quotient a_i and add # the quotient triple to the list triples.append(t) m = t.d*t.a - t.m d = (self._N - m*m)/t.d a = int(math.floor((a_0+m)/d)) t= SquareRootCF._trip(m, d, a) # Once we've found a repeat, we find where t is in our # ordered list of quotient triples, and take the slice. # The slice before is the non-periodic portion, and the # slice after is the periodic portion. We save both. break_point = triples.index(t) non_periodic, periodic = triples[:break_point], triples[break_point:] self._periodic = [x.a for x in periodic] self._non_periodic = [x.a for x in non_periodic] self._calculated = True @property def period(self): if not self._calculated: self._calculate() return len(self._periodic) def quotients(self): """ Returns iterator over the partial quotients. """ if not self._calculated: self._calculate() return itertools.chain(self._non_periodic, itertools.cycle(self._periodic)) def convergents(self): """ Returns iterator over the convergents. """ h_m2, h_m1 = 0, 1 # h_(n-2) and h_(n-1) seeded to values for h_(-2), h_(-1) k_m2, k_m1 = 1, 0 # k_(n-2) and k_(n-1) seeded to values for k_(-2), k_(-1) quotients = self.quotients() # Calculate iterations, starting with 0th for a_n in quotients: h_n = a_n*h_m1 + h_m2 k_n = a_n*k_m1 + k_m2 yield h_n, k_n h_m2, h_m1 = h_m1, h_n # swap for next iteration k_m2, k_m1 = k_m1, k_n # swap for next iteration h_m2, h_m1 = 0, 1 def __str__(self): if not self._calculated: self._calculate() a0 = self._non_periodic[0] np = ','.join(map(str, self._non_periodic[1:])) p = ','.join(map(str, self._periodic)) return '[%i;%s(%s)]' % (a0, np, p)
fd752027bf2b5686cdab14a3838c6ec22161856f
jahnavi-gutti/Averge-level-programs-in-python
/sprial matix.py
360
3.75
4
#print sprial matrix def spiral(arr): ans=[] while arr: ans+=arr.pop(0) arr=list(zip(*arr))[::-1] return ans arr=[] r,c=[int(v) for v in input().split()] for i in range(r): cur=[int(v) for v in input().split()] arr.append(cur) print(spiral(arr)) """ 3 3 1 2 3 4 5 6 7 8 9 [1, 2, 3, 6, 9, 8, 7, 4, 5] """
5f00da372ce14f7fe1726d254ae3d8e16df5ac7d
Tahssnn/python
/Bölüm 9-Hatalar ve İstisnalar/Hatalar ve İstisnalar/HatalarIstisnalar.py
4,396
4.125
4
""" Hatalar ve istisnalar programda oluşabilecek hataları önceden yakalayarak programımızı ona göre düzenleyebiliriz. Python'da bir çok hata türü vardır. NameError ValueError SyntaxError ZeroDivisionError .. https://docs.python.org/3/library/exceptions.html bu siteden tüm hatalara bakabiliriz. Tabi ki ezberlememize gerek yok prograrmımızı çalıştırdıkça oluşan hatalarımızı görerek yakalayabiliriz. """ """ try , except blokları try ,except bloklarının yapısı şu şekildedir; try: Hata çıkarabilecek kodlar buraya yazılıyor. Eğer hata çıkarsa program uygun olan except bloğuna girecek. Hata oluşursa try bloğunun geri kalanındaki işlemler çalışmayacak. except Hata1: Hata1 oluştuğunda burası çalışacak. except Hata2: Hata2 oluştuğunda burası çalışacak. // // // """ try: a = int("324234dsadsad") # Burası ValueError hatası veriyor. print("Program burada") except: # Hatayı belirtmezsek bütün hatalar bu kısma giriyor. print("Hata oluştu") # Burası çalışır. print("Bloklar sona erdi") #------------------------------------------------------------------------------ try: a = int(input("Sayı1:")) b = int(input("Sayı2:")) # Hata burada oluşuyor. ValueError'a bloğuna giriyoruz. print(a / b) except ValueError: print("Lütfen inputları doğru girin.") except ZeroDivisionError: print("Bir sayı 0'a bölünemez.") #------------------------------------------------------------------------------ try: a = int(input("Sayı1:")) b = int(input("Sayı2:")) print(a / b) except (ValueError,ZeroDivisionError): # aynı satırda hatalarımızı genelleştirebiriz print("ZeroDivision veya ValueError hatası") """ try,except,finally blokları Bazen programlarımızda her durumda mutlaka çalışmasını istediğimiz kodlar bulunabilir. Bunun için biz kendi try,except bloklarına ek olarak bir tane finally bloğu ekleyebiliriz. finally blokları hata olması veya olmaması durumunda mutlaka çalışacaktır. Yapısı şu şekildedir; try: Hata çıkarabilecek kodlar buraya yazılıyor. Eğer hata çıkarsa program uygun olan except bloğuna girecek. Hata oluşursa try bloğunun geri kalanındaki işlemler çalışmayacak. except Hata1: Hata1 oluştuğunda burası çalışacak. except Hata2: Hata2 oluştuğunda burası çalışacak. // // // finally: Mutlaka çalışması gereken kodlar buraya yazılacak. Bu blok her türlü çalışacak. """ try: a = int(input("Sayı1:")) b = int(input("Sayı2:")) print(a / b) # Hata burada oluşuyor. ZeroDivisionError'a bloğuna giriyoruz. except ValueError: print("Lütfen inputları doğru girin.") except ZeroDivisionError: print("Bir sayı 0'a bölünemez.") finally: # Bu kısım her durumda mutlaka çalışır print("Her durumda çalışıyorum.") """ Hata fırlatmak¶ Bazen kendi yazdığımız fonksiyonlar yanlış kullanılırsa kendi hatalarımızı üretip Pythonda bu hataları fırlatabiliriz. Bunun içinde raise anahtar kelimesini kullanacağız. Hata fırlatma şu şekilde yapılabilmektedir; raise HataAdı(opsiyonel hata mesajı) """ # Verilen string'i ters çevirmek def terscevir(s): if (type(s) != str): raise ValueError("Lütfen doğru bir input girin.") else: return s[::-1] """ alabileceğimiz hata şu forma dönüşür ValueError Traceback (most recent call last) <ipython-input-23-affc1a0b50fd> in <module>() ----> 1 print(terscevir(12)) <ipython-input-20-8f7e1cd7e827> in terscevir(s) 2 def terscevir(s): 3 if (type(s) != str): ----> 4 raise ValueError("Lütfen doğru bir input girin.") 5 else: 6 return s[::-1] ValueError: Lütfen doğru bir input girin. #********************************************** """
af3b0055ab2b9e5e7c2c125122bab2901260920e
fernandalavalle/isitketo_webapp
/app/match_food.py
730
3.640625
4
import re import food _PLURAL_SUFFIX_PATTERN = re.compile(r'e?s$', flags=re.IGNORECASE) def match(food_name): for fix_fn in (_remove_plural, _add_plural): fixed_name = fix_fn(food_name).lower() if food.find_by_name(fixed_name): return fixed_name return None def _remove_plural(food_name): return _PLURAL_SUFFIX_PATTERN.sub('', food_name) def _add_plural(food_name): food_lower = food_name.lower() if food_lower.endswith('ies'): return food_name[:-3] + 'y' elif food_lower.endswith('x') or food_lower.endswith('s'): return food_name + 'es' elif food_lower.endswith('y'): return food_name[:-1] + 'ies' else: return food_name + 's'
9213e72b1fdaabf14c802ca6289af7da79cfc8df
king2934/PL
/Python/Studys/6.py.keyboard.input/py_input.py
103
3.6875
4
#!/usr/bin/python3 #coding=utf-8 str = input("请输入:"); print ("你输入的内容是: ", str)
0525ded9504960ef44d3d319724d08c2a88a5479
ninja-22/HOPTWP
/CH1/MergingLists.py
199
4.21875
4
list1 = [1, 2, 3] list2 = [4, 5, 6] list1.extend([7, 8, 9]) print(f"This is the merged list using the extend method: {list1}") print(f"This is the merged list using concatenation: {list1 + list2}")
b01295c1d0f7c3416f4a0be4b821756e1d8b0e89
Poonammahunta/New_world
/ques2.py
298
3.765625
4
#Name = ques5.py import math temp = 1 s = int(raw_input("Enter how many input: ")) while True: if s <= temp: D = int(raw_input("Enter digits: ")) temp += temp print tuple(D) continue C = 50 H = 30 Q = math.sqrt((2*C*D)/H) print int(Q)
b85cd32209a2a9f0643c2495fc625193d99c3f57
Phantom1911/leetcode
/algoexpert/zipLinkedList.py
1,600
4.0625
4
# This is an input class. Do not edit. class LinkedList: def __init__(self, value, next): self.value = value self.next = next def zipLinkedList(linkedList): fhh = linkedList shh = splitll(fhh) shhrev = reversell(shh) return interweavell(fhh, shhrev) def interweavell(first, second): head = first while first is not None and second is not None: firstnext, secondnext = first.next, second.next first.next = second second.next = firstnext first = firstnext second = secondnext return head def reversell(head): if head is None or head.next is None: return head restrev = reversell(head.next) temp = restrev while temp.next != None: temp = temp.next temp.next = head head.next = None return restrev def splitll(fhh): slow, fast = fhh, fhh while slow is not None and fast is not None and fast.next is not None: slow = slow.next fast = fast.next.next if fast is None: # even length LL temp = fhh while temp.next != slow: temp = temp.next temp.next = None return slow else: temp = fhh while temp != slow: temp = temp.next slow = slow.next temp.next = None return slow if __name__=="__main__": six = LinkedList("6", None) five = LinkedList("5", six) four = LinkedList("4", five) three = LinkedList("3", four) two = LinkedList("2", three) one = LinkedList("1",two) ans = zipLinkedList(one) print(ans.value)
a3b5c99e66e3ff4d50b4cb5647153d2e6ecbd972
Choi-Jinwoo/Algorithm
/자료구조/LRU/main.py
408
3.53125
4
cache_size = 5 company_list = ['apple', 'samsung', 'dell', 'lg', 'dell', 'lg', 'dell', 'lenovo', 'asus', 'lenovo', 'apple'] cache = [] for company in company_list: if company in cache: cache.remove(company) cache.insert(len(company_list) - 1, company) else: if len(cache) >= cache_size: cache.pop(0) cache.append(company) print(cache) print(cache)
7633a58dabe2c20ed976b5c3ff10ea50b07616e4
unit02/370A2
/testing
858
3.5
4
#!/user/bin/python import sys import os firstDirectory = sys.argv[1] secondDirectory = sys.argv[2] def checkInputDirectories(): #Neither of the inputs are directories if not (os.path.isdir(firstDirectory)) and not ( os.path.isdir(secondDirectory)): print("Those aren't directories!") #The first directory is real, must create second one elif (os.path.isdir(firstDirectory)) and not ( os.path.isdir(secondDirectory)): createNewDirectory(secondDirectory) #The second directory is real, must create first one elif not (os.path.isdir(firstDirectory)) and ( os.path.isdir(secondDirectory)): createNewDirectory(firstDirectory) #Otherwise they are both directories yay! def createNewDirectory(directoryToMake): os.makedirs(directoryToMake) if __name__ == "__main__": checkInputDirectories()
06a7746ceff6271b636177ccbbba032b598af5f3
Danucas/back_segmentation
/rgb.py
961
3.609375
4
#!/usr/bin/python3 """ .PNG correcter """ from PIL import Image import os import math def to_rgba(file_path): """ transform rgb png based to rgba """ print(file_path) img = Image.open(file_path).convert('RGBA') img.save(file_path) data = list(img.getdata()) def list_to_image(filt, name='test', file_format='RGB'): tupArray = [] for i in range(0, len(filt)): tupArray.append(( filt[i], filt[i], filt[i], 255 )) length = int(math.sqrt(len(filt))) im = Image.new('RGBA', (length, length)) im.putdata(tupArray) path = os.path.abspath(os.getcwd()) filename = '{}/{}.png'.format( path, name ) im.save(filename) def list_files(path): """ list available .png files to transform """ for image in os.listdir(path): if '.png' in image: print(image) to_rgba(path + '/' + image)
98d3780ed619a223b20759d48b0b9dc380b22fdb
wshzd/NLP
/Tips/get_nn_paramter_num.py
537
3.609375
4
def get_total_parameters(): """ get total parameters of a graph :return: """ total_parameters = 0 for variable in tf.trainable_variables(): # shape is an array of tf.Dimension shape = variable.get_shape() # print(shape) # print(len(shape)) variable_parameters = 1 for dim in shape: # print(dim) variable_parameters *= dim.value # print(variable_parameters) total_parameters += variable_parameters return total_parameters
c68485cc690a9c093821f21c472a45c5c93ca052
JohanHansen-Hub/PythonProjects
/Arkiv/SøkeAlgoritmer/sequential_search.py
317
3.6875
4
eksamplelist = [5,3,8,1,9,2] def sequentialSearch(the_list, item): position = 0 found = False while position < len(the_list) and not found: if the_list[position] == item: found == True else: position += 1 return found print(sequentialSearch(eksamplelist, 9))
6550723e477e71bc5323e68cd722bc4f66421a6e
AladinBS/holbertonschool-higher_level_programming
/0x0B-python-input_output/14-pascal_triangle.py
528
3.765625
4
#!/usr/bin/python3 def pascal_triangle(n): """ Pascal tri matrix: pascal tri n: nmbr lines """ prev = [] matrix = [] for ran in range(n): res_list = [] x2 = 0 x1 = -1 for z in range(len(prev) + 1): if x1 == -1 or x2 == len(prev): res_list += [1] else: res_list += [prev[x1] + prev[x2]] x2 += 1 x1 += 1 matrix.append(res_list) prev = res_list[:] return matrix
7155530161b1e784fc6ea7c7c75022ccc4e5d325
rsingla92/learning-tensorflow
/getting_started/mechanics_101/fully_connected_feed.py
9,955
3.625
4
"""Trains and Evaluates the MNIST network using a feed dictionary.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import os import sys import time from six.moves import xrange import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data from tensorflow.examples.tutorials.mnist import mnist # Basic model parameters as external flags FLAGS = None def placeholder_inputs(batch_size): """Generate placeholder variables to represent the input tensors. These placeholders are used as inputs by the rest of the model building code and will be fed from the downloaded data in the .run() loop, below. Args: batch_size: The batch size will be baked into both placeholders. Returns: images_placeholder: Images placeholder. labels_placeholder: Labels placeholder. """ # Note that the shapes of the placeholders match the the shapes of the full # image and label tesnsors, except the first dimension is now batch_size # rather than the full size of the train or test data sets. # Two placeholder ops that define input shapes (and batch_size). images_placeholder = tf.placeholder(tf.float32, shape=(batch_size, mnist.IMAGE_PIXELS)) labels_placeholder = tf.placeholder(tf.int32, shape=(batch_size)) return images_placeholder, labels_placeholder def fill_feed_dict(data_set, images_pl, labels_pl): """ Fills the feed_dict for training the given step. A feed_dict takes the form of: feed_dict = { <placeholder>: <tensor of values to be passed>, ... } :param data_set: the set of images and labels from input_data.read_data_sets() :param images_pl: the images placeholder, from placeholder_inputs() :param labels_pl: labels placeholder, from placeholder_inputs(). :return: feed_dict: dictionary mapping placeholders to values """ # Data is queried for next batch_size st of images and labels # Tensors matching the placeholders are filled, and a dict object # is generated. images_feed, labels_feed = data_set.next_batch(FLAGS.batch_size, FLAGS.fake_data) feed_dict = { images_pl: images_feed, labels_pl: labels_feed, } return feed_dict def do_eval(sess, eval_correct, images_placeholder, labels_placeholder, data_set): """Runs one evaluation against the full epoch of data. Args: sess: The session in which the model has been trained. eval_correct: The Tensor that returns the number of correct predictions. images_placeholder: The images placeholder. labels_placeholder: The labels placeholder. data_set: The set of images and labels to evaluate, from input_data.read_data_sets(). """ # Run a full single epoch of evaluation true_count = 0 steps_per_epoch = data_set.num_examples // FLAGS.batch_size num_examples = steps_per_epoch * FLAGS.batch_size for step in xrange(steps_per_epoch): feed_dict = fill_feed_dict(data_set, images_placeholder, labels_placeholder) true_count += sess.run(eval_correct, feed_dict=feed_dict) precision = float(true_count) / num_examples print('Num examples: %d\nNum correct: %d\nPrecision @1: %0.04f' % (num_examples, true_count, precision)) def run_training(): """ Train MNIST for a number of steps. """ # Ensures the correct data has been downloaded and unpacks it into a dict of # DataSet instances. data_sets = input_data.read_data_sets(FLAGS.input_data_dir, FLAGS.fake_data) # Tell TF that the model will be built into the default Graph. # 'with' command indicates all of the ops are associated with the specified # instance - this being the default global tf.Graph instance # A tf.Graph is a collection of ops that may be executed together as a group. with tf.Graph().as_default(): # Generate placeholders images_placeholder, labels_placeholder = placeholder_inputs(FLAGS.batch_size) # Build a graph that computes predictions from the inference model. # Inference function builds the graph as far as needed to return the tensor # containing output predictions. # Takes images placeholder in and builds on top a pair of fully connected layers. # using ReLU activation. It then has a ten node linear layer with outputs. logits = mnist.inference(images_placeholder, FLAGS.hidden1, FLAGS.hidden2) # Add the ops for loss calculation loss = mnist.loss(logits, labels_placeholder) # Add ops that calculate and apply gradients train_op = mnist.training(loss, FLAGS.learning_rate) # Add op to compare logits to labels during evaluation eval_correct = mnist.evaluation(logits, labels_placeholder) # Summary tensor based on collection of summaries summary = tf.summary.merge_all() # Add the variable initalizer init = tf.global_variables_initializer() # Create a saver saver = tf.train.Saver() # Create a session for running ops # Alternatively, could do 'with tf.Session() as sess:' sess = tf.Session() # Instantiate SummaryWriter for output summary_writer = tf.summary.FileWriter(FLAGS.log_dir, sess.graph) ### Built everything ! ### # Now run and train. # run() will complete the subset of the graph as corresponding to the # ops described above. Thus, only init() is given. sess.run(init) for step in xrange(FLAGS.max_steps): start_time = time.time() # Fill a feed dictionary with actual set of images feed_dict = fill_feed_dict(data_sets.train, images_placeholder, labels_placeholder) # Run a step. # What is returned is the activations from the training_op # and the loss operation. # If you want to insepct the values of ops or variables, include # them in the list passed to sess.run() # Each tensor in the list of values corresponds to a numpy array in the returned tuple. # This is filled with the value of that tensor during this step of training. # Since train_op is an Operation with no output value, it can be discarded. # BUT...if loss becomes NaN, the model has likely diverged during training. _, loss_value = sess.run([train_op, loss], feed_dict=feed_dict) duration = time.time() - start_time # Let's log some stuff so we know we're doing ok. if step % 100 == 0: print('Step %d: loss = %.2f (%.3f sec)' % (step, loss_value, duration)) #Update events file # This can be used by TensorBoard to display the summaries. summary_str = sess.run(summary, feed_dict=feed_dict) summary_writer.add_summary(summary_str, step) summary_writer.flush() # Save a checkpoint and evaluate the model periodically if (step + 1) % 1000 == 0 or (step + 1) == FLAGS.max_steps: checkpoint_file = os.path.join(FLAGS.log_dir, 'model.ckpt') saver.save(sess, checkpoint_file, global_step=step) print('Training Data Eval:') do_eval(sess, eval_correct, images_placeholder, labels_placeholder, data_sets.train) # Evaluate against the validation set. print('Validation Data Eval:') do_eval(sess, eval_correct, images_placeholder, labels_placeholder, data_sets.validation) # Evaluate against the test set. print('Test Data Eval:') do_eval(sess, eval_correct, images_placeholder, labels_placeholder, data_sets.test) def main(_): if tf.gfile.Exists(FLAGS.log_dir): tf.gfile.DeleteRecursively(FLAGS.log_dir) tf.gfile.MakeDirs(FLAGS.log_dir) run_training() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--learning_rate', type=float, default=0.01, help='Initial learning rate.' ) parser.add_argument( '--max_steps', type=int, default=2000, help='Number of steps to run trainer.' ) parser.add_argument( '--hidden1', type=int, default=128, help='Number of units in hidden layer 1.' ) parser.add_argument( '--hidden2', type=int, default=32, help='Number of units in hidden layer 2.' ) parser.add_argument( '--batch_size', type=int, default=100, help='Batch size. Must divide evenly into the dataset sizes.' ) parser.add_argument( '--input_data_dir', type=str, default=os.path.join(os.getenv('TEST_TMPDIR', '/tmp'), 'tensorflow/mnist/input_data'), help='Directory to put the input data.' ) parser.add_argument( '--log_dir', type=str, default=os.path.join(os.getenv('TEST_TMPDIR', '/tmp'), 'tensorflow/mnist/logs/fully_connected_feed'), help='Directory to put the log data.' ) parser.add_argument( '--fake_data', default=False, help='If true, uses fake data for unit testing.', action='store_true' ) FLAGS, unparsed = parser.parse_known_args() tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
8d1a4bdcdc2561106225df1eab8dd8998b2bd062
BrantLauro/python-course
/module01/classes/class09a.py
2,657
4.375
4
from style import blue, red, purple, none a = 'Hello World!' print(f'The string {blue}is{none} {purple}{a} {none}\n' f'The {blue}index 2nd{none} is {purple}{a[2]} {none}\n' f'The string {blue}until the 3rd index{none} is {purple}{a[:3]} {none}\n' f'The string {blue}starting in the 3rd index{none} is {purple}{a[3:]} {none}\n' f'The string {blue}counted every 2{none} is {purple}{a[::2]} {none}\n' f'The string has {blue}{len(a)}{none} characters \n' f'The string has {blue}{a.count("o")}{none} letters "o" \n' f'The string has {blue}{a.count("O", 0, 3)}{none} letters "O" starting on 0 index until the 3rd index\n' f'The string has a the word {blue}"World" starting in the index{none}: {purple}{a.find("World")} {none}\n' f'The string has the word {blue}"Python"{none}? {purple}{"Python" in a} {none}\n' f'If it substitutes {blue}"World"{none} to {blue}"Python"{none} would be: {purple}{a.replace("World", "Python")} {none}\n') b = input('Type something: ') print(f'{b} in {blue}uppers{none} stay: {purple}{b.upper()} {none}\n' f'{b} in {blue}lowers{none} stay: {purple}{b.lower()} {none}\n' f'{b} {blue}capitalized{none} stay: {purple}{b.capitalize()} {none}\n' f'{b} was a {blue}title{none} stay: {purple}{b.title()} {none}\n' f'{b} {blue}with no spaces in the right{none} stay: {purple}{b.rstrip()} {none}\n' f'{b} {blue}with no spaces in the left{none} stay: {purple}{b.lstrip()} {none}\n' f'{b} {blue}with no spaces in the right and left{none} stay: {purple}{b.strip()} {none}\n' f'{b} {blue}capitalized after taken away the spaces{none} stay: {purple}{b.strip().capitalize()} {none}\n' f'{blue}Splitting off all words in {b}{none} would be: {purple}{b.split()} {none}\n') print('''The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!''')
35991d745a16e4942ae80d668fcf21c4f3434c73
laurencesk/DojoAssignments
/Python and Django/Python OOP/Hospital.py
1,141
3.640625
4
class Hospital(object): def __init__(self,name,capacity): self.patients = [] self.name = name self.capacity = capacity def admit(self,patient): self.patients.append(patient) self.bedsAvailable = self.capacity-len(self.patients) return self def discharge(self,patient): self.patients.remove(patient) self.bedsAvailable = self.capacity-len(self.patients) return self def info(self): print self.name, self.capacity, self.bedsAvailable return self class Patients(object): idNum = 1 def __init__(self,name,allergies): self.idNum = Patients.idNum Patients.idNum +=1 self.name = name self.allergies = "" self.bedNumber =1 def assignBed(self): self.bedNumber = Hospital.bedsAvailable+1 return self def patientInfo(self): print self.idNum, self.name, self.allergies, self.bedNumber # p1 =Patients("someone","medicine").patientInfo() p2 =Patients("someone else","none").patientInfo() hos1 = Hospital("The H",5).admit(p1).info()
5d8557cc988c36ea8d75e308d22004c8b1e3d90e
faterazer/LeetCode
/0206. Reverse Linked List/Solution.py
687
3.890625
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseList_MK1(self, head: ListNode) -> ListNode: ''' Iterative version. ''' prev, curr = None, head while curr: tmp = curr.next curr.next = prev prev = curr curr = tmp return prev def reverseList(self, head: ListNode) -> ListNode: ''' Recursive version ''' if not head or not head.next: return head new_head = self.reverseList(head.next) head.next.next = head head.next = None return new_head
c12db270226c15377472d7c76db79220c4768f3a
nacastellanos/practice_begginner
/collantz.py
897
3.59375
4
__author__ = 'HP' # Este es el juego, empezamos con un n>1, y el objetivo es encontrar el numero de pasos que se necesita para que n llegue a 1 def collantz(n): contador = 0 if n != 1: while n > 1: if n % 2 == 0: print "paso numero ", contador print "n=", n n = n/2 n = int(n) contador = contador + 1 else: print "paso numero ", contador print "n=", n n = n*3 + 1 n = int(n) contador = contador + 1 if contador > 1500: print "mala suerte, duro mucho pensando" break if n == 1: print "Felicitaciones, tomo", contador, "pasos llegar a 1" else: print "Di un numer mayor que 1, porfavor" return collantz(1
abd8b723b1fb885d8a73e05be6e3386238149bc4
uniyalabhishek/LeetCode-Solutions
/Python/227. BasicCalculatorII.py
2,579
4.0625
4
# Problem link: https://leetcode.com/problems/basic-calculator-ii/ # Implement a basic calculator to evaluate a simple expression string. # The expression string contains only non-negative integers and # +, -, *, / operators and empty spaces. # The integer division should truncate toward zero. # Example 1: # Input: "3+2*2" # Output: 7 # Example 2: # Input: " 3/2 " # Output: 1 # Example 3: # Input: " 3+5 / 2 " # Output: 5 # Note: # You may assume that the given expression is always valid. # Do not use the eval built-in library function. """ Approach: 1. Segregate the string into a list with the digits and operations. 1.1 Count the operations along the way. 2. Go through the list twice. 2.1 Once to compute all "*" and "/". 2.2 Second to compute all "+" and "-". 3. Return the final element left in the expression. """ class Solution: def segregate(self, s): result = list() operator_count = {"+": 0, "-": 0, "*": 0, "/": 0} item = "" for index, char in enumerate(s): if char.isspace(): if item != "": result.append(int(item)) item = "" if char in ["+", "-", "*", "/"]: operator_count[char] += 1 if item != "": result.append(int(item)) item = "" result.append(char) if char.isnumeric(): item += char if item != "": result.append(int(item)) return result, operator_count def calculate(self, s: str) -> int: exp, operator_count = self.segregate(s) # print("Initial", exp) # print(operator_count) ops = { "+": (lambda x, y: x + y), "-": (lambda x, y: x - y), "*": (lambda x, y: x * y), "/": (lambda x, y: x // y), } index = 0 while index < len(exp): if exp[index] in ["/", "*"]: exp[index - 1] = ops[exp[index]]( exp[index - 1], exp[index + 1]) exp.pop(index) exp.pop(index) index -= 1 index += 1 index = 0 while index < len(exp): if exp[index] in ["-", "+"]: exp[index - 1] = ops[exp[index]]( exp[index - 1], exp[index + 1]) exp.pop(index) exp.pop(index) index -= 1 index += 1 return exp[0]
325af06ca17cd658d5fb27fbe9e2cb30573c0366
vijaysawant/Python
/ReadConfigFileCreateDict.py
1,098
3.890625
4
''' program will take server.conf file as input file then parse that file and create dictiory ''' def ParseConfigFile(FileName): result = {} section_details = {} section_name = " " # for SERVER-1 and SERVER-2 section_found = False fd = open(FileName) if fd != None: lines = fd.readlines() for line in lines: # avoid line starts with comments if line.startswith("#"): #if line[0] == "#": continue if line.startswith("["): if section_found == True: result[section_name] = section_details section_found = False if section_found == False: section_name = line[1:-2] section_found = True section_details = {} elif section_found == True: config_line = line.split("=") if "#" in config_line[1]: config_line[1] = config_line[1].split("#")[0] section_details[config_line[0]] = config_line[1] else: result[section_name] = section_details return result def main(): file_name = input("Enter config file name:") result = ParseConfigFile(file_name) print result if __name__=="__main__": main()
77073a40b8b371a545c460824854e7cf9ccea4a8
made-ml-in-prod-2021/mrtimmy89
/online_inference/src/data/preprocess_data.py
367
3.5
4
""" A small script to make from a .csv file with given data the similar but without a column "target" """ import pandas as pd SOURCE_FILEPATH = "data/raw/heart.csv" PROCESSED_FILEPATH = "data/processed/data_without_prediction.csv" df = pd.read_csv(SOURCE_FILEPATH, index_col=["age"]) df_modified = df.drop(["target"], axis=1).to_csv(PROCESSED_FILEPATH)
2cc528ace7e386386b6fdeae4abb1e2251b5a0a7
Areejz/100DaysOfCode-
/Day12.py
137
3.625
4
x=5 y=7 z="please, Iwant {} Sandwihes and {} donutes" print(z.format(x,y)) print(z.replace("i","we")) print(z.replace("a","A"))
7794bd56295c80d21c356510265020112af8b0bc
yovana13/SoftUni
/Python Fundamentals/My Mid Exam 07.11/Magic Cards.py
1,277
3.921875
4
list_cards = input().split(":") new_list_cards = [] action = input() while action!="Ready": command = action.split()[0] if action == "Shuffle deck": new_list_cards.reverse() if command == "Add": if action.split()[1] in list_cards: new_list_cards.append(action.split()[1]) else: print("Card not found.") elif command == "Insert": index = int(action.split()[2]) if action.split()[1] in list_cards: if index == 0: new_list_cards.insert(index,action.split()[1]) elif 0<index<len(new_list_cards): new_list_cards.insert(index, action.split()[1]) else: print("Error!") else: print("Error!") elif command == "Remove": if action.split()[1] in new_list_cards: new_list_cards.remove(action.split()[1]) else: print("Card not found.") elif command == "Swap": index1=new_list_cards.index(action.split()[1]) index2 = new_list_cards.index(action.split()[2]) temp = new_list_cards[index1] new_list_cards[index1] = new_list_cards[index2] new_list_cards[index2] = temp action = input() print(" ".join(new_list_cards))
d08b72138b8e70d57065aab5c700b5c12bf769fd
OliverGeisel/sudokusat-example
/my_solver/oliver/speedtest.py
514
3.5625
4
import time from typing import Tuple def time_needed(func, *args, **kwargs) -> Tuple[float, object]: """ A simple function to get the time, which an other function need :param func: The function :param args: Arguments for func. Need to be in a list :param kwargs: Named-Arguments for func. Need to be in a dictionary :return: Time to execute the func """ start = time.perf_counter() result = func(*args, **kwargs) end = time.perf_counter() return end - start, result
c7a350dbe8c922a23bbd3843cbbd52e1bf19d4ee
AbnerZhangZN/PythonLearning
/003_advanced characteristics/day004_03.py
1,061
3.546875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #setup 15 高级特性-生成器 print([x*x for x in range(10)]) g = (x * x for x in range(10)) for s in g: print(s) def fib(max): n, a, b = 0, 0, 1 while n<max: print(b) a, b = b, a+b n = n+1 return 'done' fib(10) def fibG(max): n, a, b = 0, 0, 1 while n<max: yield b a, b, n = b, a+b, n+1 return 'done' for s in fibG(10): print(s) g = fibG(6) while True: try: x = next(g) print('g:', x) except StopIteration as e: print('Genarator return value:', e.value) break def triangles(): L = [] while True: oldL = L[:] L.append(1) i = 0 if len(L)>1: while i<len(L)-1: if i==0: L[i] = 1 i = i+1 continue L[i] = oldL[i-1]+oldL[i] i = i+1 L[-1] = 1 #print(L) yield L return 'Done' def trianglesSimple(): L = [1] while True: yield L L = [1] + [L[i]+L[i+1] for i in range(len(L)-1)] + [1] n = 0 results = [] for t in trianglesSimple(): print(t) results.append(t) n = n + 1 if n == 10: break
b372db6c59740769a5ad61bbff8110b19c2780ac
gustavoclay/PythonStudy
/classrooms/class/TWP290.py
327
3.71875
4
#for each print ("FOR:") for letra in 'aeiou': print (letra) #while print ("WHILE:") texto = 'aeiou' k = 0 while k < len(texto): letra = texto[k] print (letra) k += 1 #for each for i in range(5): print(i) #while lista = list(range(5)) k = 0 while k < len(lista): i = lista[k] print (i) k += 1
9bf28321005097b4664b7c9af816c7490bddd63b
bo8888/python
/day1/zuoye.py
1,695
3.90625
4
# 2、name = input(“>>>”) # name变量量是什什么数据类型? # string # name = input(">>>>>>>") # print(type(name)) # 4.⽤print打印出下⾯内容: # ⽂能提笔安天下, # 武能上⻢定乾坤. # ⼼存谋略何⼈胜, # 古今英雄唯是君. # print(""" # 文能提笔安天下, # 武能上马定乾坤. # 心存谋略略何人胜, # 古今英雄唯是君. # """) # 5.利⽤if语句写出猜⼤⼩的游戏: # 设定⼀个理想数字⽐如:66,让⽤户输⼊数字,如果⽐66⼤,则显示猜测的结果⼤了;如果⽐66⼩,则显示猜测的结果⼩了;只有等于66, # 显示猜测结果正确。给⽤户三次猜测机会,如果三次之内猜测对了,则显示猜测正确,退出循# 环,如果三次之内没有猜测正确, # 则⾃动退出循环,并显示‘太笨了你....’。 # import re # n = 0 # while True: # num = input("请输入一个数字,按Q退出:") # if not re.match("[qQ0-9]", num): # print("输入错误") # elif num.upper() == "Q" : # break # elif int(num) >66: # print("猜大了") # elif int(num) < 66: # print("猜小了") # else: # print("猜对了") # break # n +=1 # if n >= 3: # print("你太笨了") # break import re n = 0 while n < 3: num = input("请输入一个数字,按Q退出:") if not re.match("[qQ0-9]", num): print("输入错误") elif num.upper() == "Q" : break elif int(num) >66: print("猜大了") elif int(num) < 66: print("猜小了") else: print("猜对了") break n +=1 else: print("你太笨了")
03808c66914ad0d356c001ea7d8afd22dc9619cf
weslleyrodrigues/Estudos
/EstudosPython/formatacaoStrings.py
1,050
3.890625
4
#F- Strings nome = 'Weslley Rodrigues' idade = 21 #int altura = 1.80 #float e_maior = idade > 18 #bool peso = 60 print ('Nome: ', nome) print ('Idade: ', idade) print ('Altura: ', altura) print ('É maior: ', e_maior) print ('Peso: ', peso) print (idade * altura) imc = peso/(altura**2) #eleva ao quadrado print(nome, 'tem', idade, 'anos de idade e seu IMC é: ', imc) # Segunda forma de exibir valores print (f'{nome} tem {idade} anos de idade e seu IMC é {imc:.2f}') # :.2f estou arredondando o vador para 2 casas decimais após a virgula # Terceira forma de exibir valores print('{} tem {} anos de idade e seu IMC é {:.2f}'.format(nome,idade,imc)) # :.2f estou arredondando o vador para 2 casas decimais após a virgula # Caso eu queira exibir em outra ordem #enumero as posições print('{0} tem {2} anos de idade e seu IMC é {1}'.format(nome,idade,imc)) # utilizar parametros nomeados #utilizo as siglas inves dos numeros print('{n} tem {i} anos de idade e seu IMC é {im}'.format(n=nome, i=idade, im=imc))
474b8e7c6ee5088b64e1f1bd7f8f2d330e142689
raaghavvd/Python-Projects
/BookMgmtSys/Frontend.py
2,718
3.640625
4
from tkinter import * from Backend import Database db = Database() def get_selected_row(event): global selected_tuple index=list1.curselection()[0] selected_tuple=list1.get(index) e1.delete(0,END) e1.insert(END,selected_tuple[1]) e2.delete(0,END) e2.insert(END,selected_tuple[2]) e3.delete(0,END) e3.insert(END,selected_tuple[3]) e4.delete(0,END) e4.insert(END,selected_tuple[4]) def view_list(): list1.delete(0,END) #deletes everything in the listbox when the button is pressed for row in db.view(): list1.insert(END,row) #inserts rows at the end. def search_database(): list1.delete(0,END) for row in db.search(title_val.get(),author_val.get(),year_val.get(),isbn_val.get()): list1.insert(END,row) def add_database(): db.insert(title_val.get(),author_val.get(),year_val.get(),isbn_val.get()) list1.delete(0,END) list1.insert(END,(title_val.get(),author_val.get(),year_val.get(),isbn_val.get())) def delete_row(): db.delete(selected_tuple[0]) def update_row(): db.update(selected_tuple[0],title_val.get(),author_val.get(),year_val.get(),isbn_val.get()) window = Tk() window.wm_title("Book Database") l1= Label(window,text='Title') l1.grid(row=0,column=0) l2= Label(window,text='Author') l2.grid(row=0,column=2) l3= Label(window,text='Year') l3.grid(row=1,column=0) l4= Label(window,text='ISBN') l4.grid(row=1,column=2) title_val=StringVar() e1= Entry(window, textvariable=title_val) e1.grid(row=0,column=1) author_val=StringVar() e2= Entry(window, textvariable=author_val) e2.grid(row=0,column=3) year_val=StringVar() e3= Entry(window, textvariable=year_val) e3.grid(row=1,column=1) isbn_val=StringVar() e4= Entry(window, textvariable=isbn_val) e4.grid(row=1,column=3) #Adding a listbox to view all the contents of the database list1=Listbox(window, height=6, width= 35) list1.grid(row=2,column=0,rowspan=6,columnspan=2) #Adding a Scroll Bar sb1=Scrollbar(window) sb1.grid(row=2,column=2,rowspan=6) list1.configure(yscrollcommand=sb1.set) sb1.configure(command=list1.yview) list1.bind('<<ListboxSelect>>',get_selected_row) #Adding buttons b1=Button(window,text="View all",width=12,command=view_list) b1.grid(row=2,column=3) b2=Button(window,text="Search Entry",width=12,command= search_database) b2.grid(row=3,column=3) b3=Button(window,text="Add Entry",width=12,command= add_database) b3.grid(row=4,column=3) b4=Button(window,text="Update",width=12,command= update_row) b4.grid(row=5,column=3) b5=Button(window,text="Delete",width=12,command=delete_row) b5.grid(row=6,column=3) b6=Button(window,text="Close",width=12,command= window.destroy) b6.grid(row=7,column=3) window.mainloop()
1d116430a556f0bf9f634a1ab00dbbcb57f685a6
oscarpalacious/conwaysgameoflifewritteninpython
/run.py
2,863
3.546875
4
import argparse import csv import string parser = argparse.ArgumentParser(description='Welcome to a humble version of Conway\'s Game of Life. Enjoy!') parser.add_argument('-f', '--file', help='Path or filename for your .csv configuration file. Defaults to "Blinker.csv".', default='Blinker.csv') args = parser.parse_args() class Cycle: num_cols = 0 num_rows = 0 prevState = [] def __init__(self, stateFile): self.stateFile = stateFile self.loadStateFromFile() try: while(True): self.parcour() except KeyboardInterrupt: pass def loadStateFromFile(self): with open(self.stateFile, 'r') as csvfile: readerObject = csv.reader(csvfile, delimiter=',') for row in readerObject: if self.num_cols == 0: self.num_cols = len(row) self.num_rows += 1 self.prevState.append(map(int, row)) def parcour(self): # We assume a new, empty state the same size self.nextState = None self.nextState = [[0 for y in range(self.num_rows)] for x in range(self.num_cols)] for y, row in enumerate(self.prevState): for x, cell in enumerate(row): """ a List of all eight neighbors, ordered clockwise from top left: 0 1 2 7 c 3 6 5 4 """ neighbors = None neighbors = [0] * 8 # We determine the neighbors' respective # state, case by case. # first if y - 1 < 0 or x - 1 < 0: neighbors[0] = 0 else: neighbors[0] = self.prevState[y-1][x-1] # second if y -1 < 0: neighbors[1] = 0 else: neighbors[1] = self.prevState[y-1][x] # third if y - 1 < 0 or x + 2 > self.num_cols: neighbors[2] = 0 else: neighbors[2] = self.prevState[y-1][x+1] # fourth if x + 2 > self.num_cols: neighbors[3] = 0 else: neighbors[3] = self.prevState[y][x+1] # fifth if y + 2 > self.num_rows or x + 2 > self.num_cols: neighbors[4] = 0 else: neighbors[4] = self.prevState[y+1][x+1] # sixth if y + 2 > self.num_rows: neighbors[5] = 0 else: neighbors[5] = self.prevState[y+1][x] # seventh if y + 2 > self.num_rows or x - 1 < 0: neighbors[6] = 0 else: neighbors[6] = self.prevState[y+1][x-1] # eigth if x - 1 < 0: neighbors[7] = 0 else: neighbors[7] = self.prevState[y][x-1] # We now determine this cell's next state. liveNeighbors = 0 liveNeighbors = sum(neighbors) if cell == 1 and liveNeighbors < 2: self.nextState[y][x] = 0 if cell == 1 and liveNeighbors == 2 or liveNeighbors == 3: self.nextState[y][x] = 1 if cell == 1 and liveNeighbors > 3: self.nextState[y][x] = 0 if cell == 0 and liveNeighbors == 3: self.nextState[y][x] = 1 self.printStates() def printStates(self): print self.prevState print self.nextState self.prevState = None self.prevState = self.nextState Cycle(args.file)
e7008a275e0b5a57f7d79e9561166fe79b25b942
xy2333/Leetcode
/leetcode/maxPathSum.py
532
3.625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def maxPathSum(self, root): def helper(node): if not node: return [None, 0] lp, rp = helper(node.left), helper(node.right) np = node.val + max(lp[1], rp[1]) return [max(node.val + lp[1] + rp[1], lp[0], rp[0]), np if np > 0 else 0] return helper(root)[0]
d692a514c0d5f01ec931358f5f245587e8e1db62
sbeaumont/AoC
/2017/AoC-2017-9.py
821
3.90625
4
#!/usr/bin/env python3 """Solution for Advent of Code challenge 2017 [---](http://adventofcode.com/2017/day/9)""" PUZZLE_INPUT_FILE_NAME = "AoC-2017-9-input.txt" level = 0 in_garbage = False skip = False score = 0 garbage_count = 0 with open(PUZZLE_INPUT_FILE_NAME, 'r') as puzzle_input_file: for c in puzzle_input_file.read(): if skip: skip = False elif c == '!': skip = True elif not in_garbage: if c == '{': level += 1 elif c == '}': score += level level -= 1 elif c == '<': in_garbage = True elif in_garbage: if c == '>': in_garbage = False else: garbage_count += 1 print(score, garbage_count)
966605f3b8b2e7a9884ea530cd1fc2c82f96d76a
arpit0891/project-euler-1
/042.py
1,123
3.75
4
#!/usr/bin/python # -*- coding: utf-8 -*- #The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are: #1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... #By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word. #Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words? #Answer: #162 from time import time; t=time() from mathplus import isqrt words = eval('(%s)' %(open('042-words.txt').read())) M = 100 triangle_numbers = [n*(n+1)/2 for n in range(1, M)] def is_triangle_word(s): num = sum((ord(c)-ord('A')+1) for c in s) if num in triangle_numbers: return True if num < triangle_numbers[-1]: return False n2 = num*8+1 n = isqrt(n2) return n*n == n2 print(len(list(filter(is_triangle_word, words))))#, time()-t
e395683560e3de2781ac06b6ae719d9c84ef4211
AndrewMiranda/holbertonschool-machine_learning-1
/supervised_learning/0x05-regularization/1-l2_reg_gradient_descent.py
1,657
3.859375
4
#!/usr/bin/env python3 """File That contains the function l2_reg_gradient_descent""" import numpy as np def l2_reg_gradient_descent(Y, weights, cache, alpha, lambtha, L): """ Function that calculates updates the weights and biases of a neural network using gradient descent with L2 regularization: Args: Y is a one-hot numpy.ndarray of shape (classes, m) that contains the correct labels for the data classes is the number of classes m is the number of data points weights is a dictionary of the weights and biases of the neural network cache is a dictionary of the outputs of each layer of the neural network alpha is the learning rate lambtha is the L2 regularization parameter L is the number of layers of the network """ m = Y.shape[1] W_copy = weights.copy() Layers = range(L + 1)[1:L + 1] for i in reversed(Layers): A = cache["A" + str(i)] if i == L: dZ = cache["A" + str(i)] - Y dW = (np.matmul(cache["A" + str(i - 1)], dZ.T) / m).T dW_L2 = dW + (lambtha / m) * W_copy["W" + str(i)] db = np.sum(dZ, axis=1, keepdims=True) / m else: dW2 = np.matmul(W_copy["W" + str(i + 1)].T, dZ2) tanh = 1 - (A * A) dZ = dW2 * tanh dW = np.matmul(dZ, cache["A" + str(i - 1)].T) / m dW_L2 = dW + (lambtha / m) * W_copy["W" + str(i)] db = np.sum(dZ, axis=1, keepdims=True) / m weights["W" + str(i)] = (W_copy["W" + str(i)] - (alpha * dW_L2)) weights["b" + str(i)] = W_copy["b" + str(i)] - (alpha * db) dZ2 = dZ
158c49cc828b133841ef360285dd5cfe09901f68
RainWuAme/BiologyProject
/LearnPy.py
3,168
3.65625
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 2 20:31:43 2018 @author: user """ print ("\n How old are you?"), age = input() print("So, you are ",age," years old.") age = input("how old are you? ") height = input("How tall are you? ") weight = input("how much do you weigh? ") print(f"So, you're {age} old, {height} tall and {weight} heavy.") #%% filename = "test.txt" txt = open(filename) print(txt.read()) print("type the filename again:") file_again = input(">") txt_again = open(file_again) print(txt_again.read()) #%% apple = 40 orange =40 banana = 32 if apple < orange: print ("Apple is more in the box") elif apple > orange: print ("orange is more in box") else: print("no. of apple and orange in box") #%% test1= [1, "two", 3, "four", 5] for number in test1: if type(number) == int: print(number) elif type(number) != int: print(number) #%%20181030 i = 0 numbers = [] while i < 6: print(f"At the top i is {i}") numbers.append(i) i = i + 1 print("Numbers now: ", numbers) print(f"At the bottom i is {i}") print("The numbers: ") for num in numbers: print(num) #%% 20181030 #from sys import exit def gold_room(): print("this room is full of gold. How much do you take") choice = input("> ") if "0" in choice or "1" in choice: how_much = int(choice) else: dead("Man, learn to type a number.") if how_much < 50: print("Nice, you're not greedy, you win!") exit(0) else: dead("you are greedy!") def bear_room(): print("There is a bear here.") print("The bear has a bunch of honey.") print("The fat bear is in front of another door.") print("How are you going to move the bear?") bear_moved = False while True: choice = input("> ") if choice == "take honey": dead("The bear looks at you then slaps your face off.") elif choice == "taunt bear" and not bear_moved: print("The bear has moved from the door.") print("You can go through it now.") bear_moved = True elif choice == "taunt bear" and bear_moved: dead("The bear gets pissed off and chews your leg off.") elif choice == "open door" and bear_moved: gold_room() else: print("I got no idea what that means.") def cthulhu_room(): print("Here you see the great evil Cthulhu.") print("He, it, whatever stares at you and you go insane.") print("Do you flee for your life or eat your head?") choice = input("> ") print(choice) if "flee" in choice: start() elif "head" in choice: dead("Well that was tasty!") else: cthulhu_room() def dead(why): print(why, "Good job!") exit(0) def start(): print("You are in a dark room.") print("There is a door to your right and left.") print("Which one do you take?") choice = input("> ") if choice == "left": bear_room() elif choice == "right": cthulhu_room() else: dead("You stumble around the room until you starve.") start()
9d7f388946727f518a293df0a42272fb97313b38
zhanghaofeng/junos-automation
/python/sub-array.py
430
3.53125
4
nums = [4, 3, 2, 1] def solution(nums): if sum(nums) % 2 == 1: return False if len(nums) == 0 or len(nums) == 1: return False target = sum(nums) / 2 current = 0 for k,v in enumerate(nums): current += v print(current, target) if current == target: return nums[0:k+1], nums[k+1:] if current > target: return False print(solution(nums))
566a8e4b7f13c5564a098a24011766f2b5679d4c
AmitBaanerjee/Data-Structures-Algo-Practise
/hackerrank/divisble-sum-pairs.py
1,363
4
4
Divisible sum pairs You are given an array of n integers, ar=ar[0],ar[1],.. and a positive integer,k . Find and print the number of (i,j) pairs where i<j and ar[i] + ar[j] is divisible by k. For example, ar=[1,2,3,4,5,6] and k=3. Our three pairs meeting the criteria are [1,4],[2,3] and [4,6]. Function Description Complete the divisibleSumPairs function in the editor below. It should return the integer count of pairs meeting the criteria. divisibleSumPairs has the following parameter(s): n: the integer length of array ar ar: an array of integers k: the integer to divide the pair sum by Input Format The first line contains 2 space-separated integers, n and k. The second line contains n space-separated integers describing the values of ar . import math import os import random import re import sys # Complete the divisibleSumPairs function below. def divisibleSumPairs(n, k, ar): counter=0 for i in range(len(ar)): j=i+1 while j<len(ar): if (ar[i]+ar[j])%k==0: counter+=1 j+=1 return counter if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nk = input().split() n = int(nk[0]) k = int(nk[1]) ar = list(map(int, input().rstrip().split())) result = divisibleSumPairs(n, k, ar) fptr.write(str(result) + '\n') fptr.close()
e96db991a825e54d59b05bccd8ae123cbef658d0
JenZhen/LC
/lc_ladder/Adv_Algo/data-structure/union-find/Connecting_Graph_II.py
1,609
4.09375
4
#! /usr/local/bin/python3 # https://www.lintcode.com/en/old/problem/connecting-graph-ii/ # Given n nodes in a graph labeled from 1 to n. There is no edges in the graph at beginning. # You need to support the following method: # 1. connect(a, b), an edge to connect node a and node b # 2. query(a), Returns the number of connected component nodes which include node a. # Example # 5 // n = 5 # query(1) return 1 # connect(1, 2) # query(1) return 2 # connect(2, 4) # query(1) return 3 # connect(1, 4) # query(1) return 3 """ Algo: D.S.: Union-Find Solution: UnionFind template with number of nodes within a group Time: O(1) Corner cases: """ class ConnectingGraph2: """ @param: n: An integer """ def __init__(self, n): # do intialization if necessary self.count = [1] * (n + 1) # 以i为ROOT的GROUP有几个元素 self.father = [i for i in range(n + 1)] def find(self, a): if self.father[a] == a: return a self.father[a] = self.find(self.father[a]) return self.father[a] """ @param: a: An integer @param: b: An integer @return: nothing """ def connect(self, a, b): # write your code here root_a = self.find(a) root_b = self.find(b) if root_a != root_b: self.father[root_a] = root_b self.count[root_b] += self.count[root_a] """ @param: a: An integer @return: An integer """ def query(self, a): # write your code here return self.count[self.find(a)] # Test Cases if __name__ == "__main__": s = Solution()
4bb1af44c35c0db884c524f794b56dc89ce0683d
lkalman/intro_prog_2019
/tasks.py
4,467
4
4
## tasks remaining for `ask_player_and_move()` def get_player_moves( die1, die2 ): """ Return a list of moves the given player wants to make """ ## temporary: return [] def is_move_possible( board, player, fromPoint, toPoint ): """ Checks if a given move is legitimate (only makes sure that there is no checker waiting on the bar (unless the move is from the bar), and that the target point contains `player`'s checkers, no checker or exactly one of opponent's checkers. """ ## temporary: return True def possible_moves( board, player, die ): """ Return a list of alternative moves that this player can make on this board with this die rolled. """ ## temporary: return [] ## This is the hardest one: def legitimate_moves( board, player, die1, die2 ): """ Return a list of move sequences that are legitimate. Unfortunately, in some cases we have to calculate all legitimate move sequences in order to decide if a given move sequence is feasible, because of the maximality criterion (the maximum possible distance must be made). """ ## Algorithm: We will set up an empty list of move ## sequences in which we will collect the legitimate ## sequences. ## We will also set up a ``todo list'' containing ## triples of the form `[move-sequence, board, remaining-roll]`, ## where `move-sequence` is a sequence of planned moves, ## and `remaining-roll` is what numbers we still have ## based on the roll. Initially, the todo list will ## contain one or two elements, with the `move-sequence` ## being empty (no planned moves so far); if `die1` and ## `die2` are different numbers, we will have two triples, ## with `remaining-roll` being different depending on the ## order of dice; if the roll is doubles, we have only ## one triple, `remaining-roll` containing four times the ## number rolled. ## Then we will go through the todo list, and try to ## produce a new sequence from each element; if we have ## finished a sequence (because there are no remaining ## rolls or because no further move is possible), we append ## the result to our list of finished sequences; otherwise, ## we update the current todo element, and append the result ## to the end of our todo list: we will get there later on. ## Finally, we could just return the list of finished move ## sequences, but we don't: we first have to keep only the ## maximal ones, because that's the rule in backgammon. finished = [] if die1 == die2: todo = \ [ # list of todo elements [ # first and only triple [], # move-sequence of first triple board, [die1, die1, die1, die1] # remaining-roll ] # end of triple ] # end of todo list else: todo = \ [ # list of todo elements [ # first triple [], # move-sequence of first triple board, [die1, die2] # remaining-roll ], # end of first triple [ # second triple [], # move-sequence of second triple board, [die2, die1] # remaining-roll ] # end of second triple ] # end of todo list next_todo_index = 0 # our position in the todo list while True: # only stop if nothing more to do if next_todo_index == len( todo ) - 1: # nothing more to do break else: ## missing: ## Try to continue `move-sequence` with first element ## of `remaining-roll`. ## Append result to `finished` if failure or no more ## elements in `remaining-roll`; append result to ## `todo` if successful. ## Prepare for next todo element: next_todo_index += 1 ## We will choose the maximal ones in a separate function: return maximalMoveSequences( finished ) def maximalMoveSequences( moveSequences ): ## temporary: return moveSequences
b324c161b9a1f63dabbaf9e352dd17a4b312c9b6
gvheisler/SimpleProblemsPython
/SimpleProgrammingProblems/Elementary/03.py
236
4.3125
4
#03 - Modify the previous program such that only the users Alice and Bob are greeted with their names. print("Please, insert your name:") name = input() if name.lower() == "alice" or name.lower() == "bob": print("Welcome,", name)
a184e44fb8ae0d6ae63fb8cda591c31a6bf53cc7
muchafilip/matrix_fun
/testing_class.py
738
3.671875
4
from matrix_class_final import Matrix import re assert hasattr(Matrix, 'multiply'), "something went wrong" def ask_user(message): print(message) matrix = [] while True: row = input() if row != '' and re.match("^[0-9 \r\n]+$", row): try: matrix.append(list(map(int, row.split(' ')))) except ValueError: print('invalid character, try again') row = input() else: return matrix def main(): m1 = Matrix(ask_user('enter rows for m1 and press enter')) m2 = Matrix(ask_user('enter rows for m2 and press enter')) print('Result:') [print(i) for i in m1.multiply(m2)] if __name__ == "__main__": main()
ea9700c1866ea2fa5d81cf72d00978958646fc9b
PauloJoaquim/cursopython
/ex091.py
1,167
3.734375
4
#Paulo = Necessário assistir a aula para colocar em ordem from random import randint from operator import itemgetter dados = dict() maior = 0 for c in range(1, 5): dados[f'Jogador {c}'] = randint(1, 6,) print(f'O jogador 1 tirou {dados["Jogador 1"]}\n' f'O jogador 2 tirou {dados["Jogador 2"]}\n' f'O jogador 3 tirou {dados["Jogador 3"]}\n' f'O jogador 4 tirou {dados["Jogador 4"]}') print('-='*30) print('Ranking dos jogadores:') ranking = dict() ranking = sorted(dados.items(), key=itemgetter(1), reverse=True) for r in range(1, 5): print(f'{r}º {ranking[r-1]}') #Guanabara '''from random import randint from time import sleep from operator import itemgetter jogo = {'jogador1': randint(1, 6), 'jogador2': randint(1, 6), 'jogador3': randint(1, 6), 'jogador4': randint(1, 6)} ranking = list() print('Valores sorteados:') for k, v in jogo.items(): print(f'{k} tirou {v} no dado') sleep(1) ranking = sorted(jogo.items(), key=itemgetter(1), reverse=True) print('-='*30) print(' == RANKING DOS JOGADORES == ') for i, v in enumerate(ranking): print(f' {i+1}º lugar: {v[0]} com {v[1]}.') sleep(1)'''
9da4dc81b8053732fc8910c2d9fb1b83a2878bfe
Lithobius/lazylithobius
/bioinfo_assignments/gene_calculations.py
2,939
3.96875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # From homework in Introduction to Bioinformatics at Harvard, 2018 # 9. Write a python program that can calculate the length of each gene (txStart to txEnd), # length of full transcript (concatenated exons) and length of all introns concatenated. # Write the output as a tab-delimited table, with RefSeq ID on first column, # and the three numbers (length of gene, transcript, introns) after.** #class to be populated with the various fields we need class gene(object): def __init__(self, refseq, geneStart, geneEnd, exStart, exEnd): self.refseq = refseq self.geneStart = geneStart self.geneEnd = geneEnd self.exstart = exStart self.exend = exEnd #class to be popuated with the calculations class gene2(object): def __init__(self, refseq, genelen, trans, intron): self.refseq = refseq self.genelen = genelen self.trans = trans self.intron = intron #open the file and pull out the useful stuff def readrefGene(file): with open(file) as f: for line in f: fields = line.strip().split() refseq = fields[1] geneStart = int(fields[4]) geneEnd = int(fields[5]) exStart = fields[9] exEnd = fields[10] yield gene(refseq, geneStart, geneEnd, exStart, exEnd) #do the calculations we need def calculate(data): for g in data: #keep the things that are the same, the same refseq = g.refseq genelen = int(g.geneEnd) - int(g.geneStart) #empty lists to fill with exons transtemp1 = [] transtemp2 = [] #fill lists for n in g.exstart: transtemp1.append(n) for n in g.exend: transtemp2.append(n) #format lists ; remove all commas and split up numbers transtemp2 = ''.join(transtemp2) transtemp2 = transtemp2.split(",") transtemp2 = transtemp2[:-1] transtemp1 = ''.join(transtemp1) transtemp1 = transtemp1.split(",") transtemp1 = transtemp1[:-1] #transcripts lengths transtemp3 = [int(transtemp2[x]) - int(transtemp1[x]) for x in range(len(transtemp1))] #total transcription length trans = sum(transtemp3) #introns! intron = int(genelen) - trans #put data into class for printing yield gene2(refseq, genelen, trans, intron) #the program! if __name__ == "__main__": import csv refGene = "/Users/katelaptop/Documents/Harvard/STAT215/Homework/Homework5-master/refGene.txt" genes = readrefGene(refGene) calcs = calculate(genes) #write file! with open("refGeneCalc.csv", "w") as out: writecsv = csv.writer(out, delimiter = '\t') writecsv.writerow(['RefSeq','GeneLength','TranscriptLength','IntronLength']) for g in calcs: writecsv.writerow([g.refseq, g.genelen, g.trans, g.intron])
27ef6f971512e3703e04cd3e702a1567ce669a22
nizmitz/modul_python
/day_1/test14_page_57.py
897
3.703125
4
class Cat: def __init__(self, mass, lifespan, speed): self.mass_in_kg = mass self.lifespan_in_years = lifespan self.speed_in_kph = speed def vocalize(self): print("Meow") def print_facts(self): print("The {} ".format(type(self).__name__.lower()), end="") print("weighs {}kg,".format(self.mass_in_kg), end="") print(" has a lifespan of {} years and ".format(self.lifespan_in_years), end="") print("can run at a maximum speed of {}kph.".format(self.speed_in_kph)) class Cheetah(Cat): def vocalize(self): print("Chirrup") class Lion(Cat): def vocalize(self): print("ROAR") cheetah = Cheetah(72, 12, 120) lion = Lion(190, 14, 80) cheetah.print_facts() lion.print_facts() print("=" * 10) print("Cheetah Vocal :") cheetah.vocalize() print("Lion Vocal :") lion.vocalize()
5cc4bb6fc5b64e5e670dd892ec629d2fc95f50ce
dankoga/URIOnlineJudge--Python-3.9
/URI_2062.py
290
3.828125
4
words_qty = input() words_list = [[word] for word in input().split()] for word in words_list: if len(word[0]) == 3: if word[0][:2] == 'OB': word[0] = 'OBI' if word[0][:2] == 'UR': word[0] = 'URI' print(' '.join([word[0] for word in words_list]))
2a552b25577da6d86653770d861e6ebaa6087e39
RinLaNir/Algorithms_and_data_structures
/Lab 12/12.9(1376).py
2,063
3.671875
4
class Node: def __init__(self, item): self.mItem = item self.mNext = None class Stack: mTopNode: Node def __init__(self): self.mTopNode = None def empty(self) -> bool: return self.mTopNode is None def push(self, item): new_node = Node(item) if not self.empty(): new_node.mNext = self.mTopNode self.mTopNode = new_node def pop(self): current_top = self.mTopNode item = current_top.mItem self.mTopNode = self.mTopNode.mNext del current_top return item def top(self): return self.mTopNode.mItem def getCharDigit(digit): if digit <= 9: str_digit = str(digit) else: str_digit = chr(ord("A") + digit - 10) return str_digit def convert(dec_number, base): if dec_number == 'ERROR': return 'ERROR' stack = Stack() while dec_number > 0: stack.push(dec_number % base) dec_number //= base converted = "" while not stack.empty(): converted = converted + getCharDigit(stack.pop()) return converted def bin_to_dec(digit, base): counter = 0 l = len(digit) number = 0 if base <= 10: for i in range(0, l): if '0'<=digit[i]<=str(base-1) and counter <= 10: counter += 1 number += int(digit[i])*(base**(l-i-1)) else: return 'ERROR' else: for i in range(0, l): if '0'<=digit[i]<='9' and counter <= 10: counter += 1 number += int(digit[i])*(base**(l-i-1)) elif 'A'<=digit[i]<=chr(base + ord('A') - 11): number += int(ord(digit[i]) - ord("A") + 10)*(base**(l-i-1)) else: return 'ERROR' return number while True: try: m,k,num = input().split() except: break res = convert(bin_to_dec(num,int(m)),int(k)) if res == 'ERROR': print(f"{num} is an illegal base {m} number") else: print(f"{num} base {m} = {res} base {k}")
bd8d4ac8d21f46f51bb65f8eb69e6aec1f70030a
jeff-ali/deliverable
/billsearch-with-asterisks.py
2,892
3.78125
4
import os import sys import re from xml.etree import ElementTree from zipfile import ZipFile def bill_search_asterisk(regular_expression): """ This method will unzip the Data Engineering Deliverable file and scan the XML files for a regex match. It will return a list of bills that match the regex along with the text summary it contains. The matching regex will be surrounded by asterisks. :param regular_expression: A regular expression. """ # regex validation checking try: regex = re.compile(regular_expression) except re.error: print('Please provide a valid regular expression.') return input_zip = 'Data Engineering Deliverable - BILLSTATUS-116-sres.zip' output_folder = input_zip[:-4] inner_folder = 'BILLSTATUS-116-sres (3)' bills_to_return = [] # unzip the file try: with ZipFile(input_zip, 'r') as zip_file: zip_file.extractall(output_folder) except Exception as zip_exception: print(f'Exception while unzipping: {zip_exception}') # parse the XML files for the regular expression try: for file_path in os.scandir(f'{output_folder}/{inner_folder}'): if file_path.path.lower().endswith('.xml'): xml_tree = ElementTree.parse(file_path.path) root_node = xml_tree.getroot() # if the billSummaries text does not exist, continue past this XML file if root_node.find('.//billSummaries').text is None: continue bill_summary_text = root_node.find('.//billSummaries//text').text if regex.search(bill_summary_text): # parse the bill_summary_text to remove the <p> tags parsed_text = ElementTree.fromstring(bill_summary_text).text bill_string = f"{root_node.find('.//billType').text} {root_node.find('.//billNumber').text}: " # use the tuple provided by match.span() to find the endpoints of the matched regex # increment the remaining tuples by 2 to account for the added asterisks matches_replaced = 0 for match in regex.finditer(parsed_text): index1 = match.span()[0] + matches_replaced index2 = match.span()[1] + matches_replaced parsed_text = f'{parsed_text[:index1]}*{parsed_text[index1:index2]}*{parsed_text[index2:]}' matches_replaced += 2 bills_to_return.append(f'{bill_string}{parsed_text}') except Exception as search_exception: print(f'Exception while searching: {search_exception}') print('Found the following bills:') for bill in bills_to_return: print(bill) if __name__ == "__main__": bill_search_asterisk(sys.argv[1])
a41d6084a01beb7a31904ff14ce033fc8ac0ac15
tr1503/LeetCode
/Two Points/intervalListIntersection.py
754
3.609375
4
# Use two points to compare the end of A and the start of B together and the start of A and the end of B together # If they have intersection, get the max of starts and the min of ends # time is O(n), space is O(1) class Solution: def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]: i = 0 j = 0 ans = [] while i < len(A) and j < len(B): if A[i][1] < B[j][0]: i += 1 elif B[j][1] < A[i][0]: j += 1 else: ans.append([max(A[i][0], B[j][0]), min(A[i][1], B[j][1])]) if A[i][1] < B[j][1]: i += 1 else: j += 1 return ans
343bab6ceff40e9166b7626256c949573297d338
JSlote/poggle
/wordPickler.py
2,396
3.859375
4
# _ _ _ ____ ____ ___ ___ _ ____ _ _ _ ____ ____ # | | | | | |__/ | \ |__] | | |_/ | |___ |__/ # |_|_| |__| | \ |__/ | | |___ | \_ |___ |___ | \ .py # # This script loads a list of all the officially useable Scrabble(TM) words and # puts them in a tree in which each level is a character in the word. This tree # is made from dictionaries of dictionaries of ... of dictionaries. It is then # pickled to words.tree. This file should be only run once, on new installs of # the game. import cPickle as pickle print "Pickling word list..." #Recursive function to append words to dictionary def dictAppender(charList,dictionary,wordpermanent): #base case: the word has reached an end if len(charList) == 0: dictionary[True] = wordpermanent #add an entry at the current pos that looks like True:"word" return dictionary #return this base dictionary up through the dictionaries #keep reading down the word else: char = charList[0] if char == "Q": # deals with the fact that Poggle has no dice w/ just a "Q" character char = "QU" if char in dictionary: # if it's the char's already in there, don't make a new dictionary dictionary[char] = dictAppender(charList[len(char):],dictionary[char],wordpermanent) #call the function again, # taking care to remove 2 chars from the beginning of the list if char is QU return dictionary else: dictionary[char] = {} # make a new dictionary to be the char key's value # go through the algorithm for all the rest of the chars in the word dictionary[char] = dictAppender(charList[len(char):],dictionary[char],wordpermanent) #call the function again, # taking care to remove 2 chars from the beginning of the list if char is QU return dictionary #Word list is the Enable list, in the Public Domain. http://www.puzzlers.org/dokuwiki/doku.php?id=solving:wordlists:about:start wordFile = open("words.txt", "r") words = wordFile.readlines() dictionary = {} for word in words: word = word.strip().upper() if len(word) >2 and len(word) < 17: #print len(word), dictionary = dictAppender(word,dictionary,word) #print word #raw_input("") pickle.dump(dictionary, open("words.tree", "wb"),-1) # the -1 means most modern protocol. Change to 2 if experiencing issues print "Process Complete"
3ecaac78dac620868752b26e468a5311be07bf48
rjubio/python-practice
/python/warm22.py
113
3.625
4
def front_times(str,n) front = str[:3] new = "" for i in range(n): new+=front return new
04a8d022bcbdc22ec055b89b4ae3f1769d7703a7
rshah918/SentenceManipulator
/SentenceManipulator.py
3,164
4.40625
4
# function named "split_sentence", takes an argument named "sentence" def split_sentence(sentence): #splits the sentence split1 = sentence.split() return split1 # sets variable = to input sentence sentence = raw_input('\n' + 'Please type any sentence of your choice:' + '\n') print "I will now split your sentence" # displays each word in the split sentence for word in split_sentence(sentence): print "\n" + "\t" + word + "\n" print "Done! Your sentence is now split!" print '\n' + "-------------------" + "-------------------" print "Now I wll organize your sentence by the length of each word:" # creates new list newlist = [] # if a word isnt in the list, append it to the list for word in split_sentence(sentence): if word not in newlist: newlist.append(word) # sorts the list by length of each word lenlist = sorted(newlist, key = len) #prints the list print lenlist # prints a dotted line in the command prompt print '\n' + "-------------------" + "-------------------" print "Let's add this list of words to a new file." # variable named "filename" is set equal to the user picked filename filename = raw_input("What would you like this new file to be called?:" + '\n') # adds a '.txt' to the user picked filename new_file = filename + '.txt' # creats a new file under the user picked name and sets it in write mode g = open(new_file, 'w+') # data that is outputted in the function split_sentence is set = to variable "ofile" ofile = lenlist # coverts the function output to a string, writes it to "f" g.write(str(ofile)) g.close() g = open(new_file, 'r') g.seek(0) file_contents = g.read() print "I have now added the list into your new text file." print "Here is your new file:" + '\n' print filename + ':' + '\n' # prints the file to the command prompt print file_contents print '\n' + "-------------------" + "-------------------" print "Now we add another sentence to this file" new_sentence = raw_input('What sentence do you want to add to your new file?:' + '\n') new_split_sentence = split_sentence(new_sentence) print "Ok, lets split that sentence" for word in split_sentence(new_sentence): newlist.append(word) print '\n' + '\t' + word + '\n' alphalist = sorted(newlist) g.close() g = open(new_file, 'w') g.write(str(alphalist)) g.close() g = open(new_file, 'r') g.seek(0) appended_file = g.read() print "I have added it to your file and organized it in alphabetical order" print "Here is your new file:" + '\n' print filename +':' + '\n' print appended_file print "-------------------" + "-------------------" print "-------------------" + "-------------------" print "-------------------" + "-------------------" print "-------------------" + "-------------------" print 'Goodbye.' g.close() # 1: split the sentence after taking user input DONE # 2: print the split sentence with line numbers DONE # 3: organize the words by the length of each word DONE # 4: add the list to a new file DONE # 5: ask what the file should be called DONE # 6: write to the new file DONE # 7: add another sentence to the file # 8: split and reorganize in alphabetical order, and print. # 9: close the file.
08aa3424c493307424d13b6c9aa82cac56a91d73
thebouv/advent2020
/day3.py
747
3.609375
4
with open('day3.txt') as file: lines = file.read().splitlines() def main(): slope1 = findtrees(1, 1) slope2 = findtrees(3, 1) slope3 = findtrees(5, 1) slope4 = findtrees(7, 1) slope5 = findtrees(1, 2) print(f"part 1: {slope2}") print(f"part 2: {slope1*slope2*slope3*slope4*slope5}") def findtrees(rateX, rateY): xpos = 0 ypos = 0 trees = 0 maxpos = len(lines[0]) - 1 botpos = len(lines) - 1 while ypos < botpos: xpos += rateX ypos += rateY if ypos > botpos: break if xpos > maxpos: xpos = xpos - maxpos - 1 if lines[ypos][xpos] == '#': trees += 1 return trees if __name__ == "__main__": main()
b99df2e1f5a09fab099c126ac9e8fa4cd3ef7f5c
jmocay/solving_problems
/binary_tree_find_nodes_with_sum_k.py
1,660
3.796875
4
""" Given the root of a binary search tree, and a target k, return two nodes in the tree whose sum equals k. For example, given the following tree and k of 20 10 / \ 5 15 / \ 11 15 Return the nodes 5 and 15 """ from collections import deque """ Runs in O(n log(n)) time. """ def find_nodes_with_sum_k(root, k): q = deque([root]) while len(q) > 0: node_1 = q.popleft() node_2 = find_helper(root, node_1, k - node_1.val) if node_2 != None: return (node_1.val, node_2.val) if node_1.left != None: q.append(node_1.left) if node_1.right != None: q.append(node_1.right) return None def find_helper(root, node, val): if root.val == val and root != node: return root if val < root.val and (root.left != None): return find_helper(root.left, node, val) elif val >= root.val and (root.right != None): return find_helper(root.right, node, val) return None class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None def create_tree(): node_5 = Node(5) node_10 = Node(10) node_11 = Node(11) node_15_1 = Node(15) node_15_2 = Node(15) node_10.left = node_5 node_10.right = node_15_1 node_15_1.left = node_11 node_15_1.right = node_15_2 return node_10 if __name__ == '__main__': root = create_tree() for summ in [10, 15, 16, 20, 21, 25, 26, 30, 31]: print('sum:', summ, find_nodes_with_sum_k(root, summ))
01aee1b1cccd7024108b637c757d7b77ad41b329
ilya-il/projecteuler.net
/p041.py
2,367
3.875
4
#!/usr/bin/python3 # coding: utf-8 # IL 30.10.2017 """ ProjectEuler Problem 41 """ __author__ = 'ilya_il' def check_pandigital_number(s): if len(s) == 9 and len(set(s)) == 9 and s.find('0') == -1: return True else: return False def get_prime_numbers2(upper_bound): # get prime numbers # https://ru.wikipedia.org/wiki/Решето_Эратосфена nums = [n for n in range(2, upper_bound)] n = 0 while nums[n]**2 <= upper_bound: if nums[n] != 0: # n - index of prime number # pn - prime number pn = nums[n] for i in range(pn + n, upper_bound - 2, pn): nums[i] = 0 n += 1 # reduce list - leave only prime numbers nums = [x for x in nums if x != 0] return nums def check_prime(n, pn_list): """ Check if number is prime by dividing it by real prime numbers in cycle (see problem 3) :param n: number to check :param pn_list: list of prime numbers :return: False/True """ for i in pn_list: if n % i == 0 and n != i: return False return True def narayana_algorithm(input_str): """ Narayana algorithm of permutations https://ru.wikipedia.org/wiki/Алгоритм_Нарайаны :param input_str: list on symbols (or string) - initial permutation :return: list of all permutations """ res = [] # sort initial to work properly a = sorted(input_str) b = list(a[::-1]) c = len(a) res.append(''.join(a)) while a != b: # step 1 j = -1 for i in range(c - 2, -1, -1): if a[i + 1] > a[i]: j = i break # step 2 k = -1 for i in range(c - 1, -1, -1): if a[i] > a[j]: k = i break # swap a[j], a[k] = a[k], a[j] # step 3 x = a[j+1:c][::-1] y = a[0:j+1] a = y + x res.append(''.join(a)) return res def solve_problem(): nums = get_prime_numbers2(200000) for i in range(3, 11): s = [str(x) for x in range(1, i)] perm = narayana_algorithm(s) # print(perm) for n in perm: if check_prime(int(n), nums): print('Prime number - {}'.format(n)) solve_problem()
ab9b38e5edf3d8dcba8d638ea2cf09bfeaf015d2
Kingcitaldo125/Python-Files
/src/palindrome_test.py
439
4
4
#Palindrome test def palindromes(word): """ Returns a boolean""" for i in word: temps1 = i for i in word[::-1]: temps2 = i if temps1 == temps2: return True else: return False string1 = "tacocat"#true string2 = "hello"#false string3 = "stanleyyelnats"#true mytest = palindromes(string1) my2nd = palindromes(string2) my3rd = palindromes(string3) print(mytest) print(my2nd) print(my3rd)
38f9221195a9d26527c0e033e01e007655e902dd
tejalvs/leetcode
/solutions/1678. Goal Parser Interpretation.py
754
3.5625
4
class Solution:    def interpret(self, command: str) -> str:        result=''        testList=list(command)        for i in range(len(testList)):            if testList[i]=='G':                result=result+testList[i]                continue            elif testList[i]=="(" and testList[i+1]==")":                result=result+'o'                i=i+1                continue            elif testList[i]=='a' and testList[i+1]=='l':                result=result+testList[i]+testList[i+1]                i=i+1                continue        return result                                                    
8044bf89499e353a8fd05a03df25eddec25dca53
claytonjwong/leetcode-py
/bicontest33.py
1,434
3.6875
4
# # https://leetcode.com/contest/biweekly-contest-33/ranking # # Rank Name Score Finish Time Q1 (3) Q2 (4) Q3 (5) Q4 (6) # 4704 / 11366 claytonjwong 7 0:37:57 0:08:07 0:37:57 # from typing import List # # 1556. Thousand Separator # # Q: https://leetcode.com/problems/thousand-separator/ # A: https://leetcode.com/problems/thousand-separator/discuss/805674/Javascript-Python3-C%2B%2B-1-Liners # class Solution: def thousandSeparator(self, n: int) -> str: return str(n) if n < 1000 else self.thousandSeparator(n // 1000) + '.' + str(n % 1000).zfill(3) # # 1557. Minimum Number of Vertices to Reach All Nodes # # Q: https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/ # A: https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/805698/Javascript-Python3-C%2B%2B-In-Degree-0 # class Solution: def findSmallestSetOfVertices(self, N: int, E: List[List[int]]) -> List[int]: deg = [0] * N for [_, tail] in E: deg[tail] += 1 return list(filter(lambda x: -1 < x, [-1 if x else i for i, x in enumerate(deg)])) # simplified class Solution: def findSmallestSetOfVertices(self, N: int, E: List[List[int]]) -> List[int]: all = set([i for i in range(N)]) for [_, tail] in E: if tail in all: all.remove(tail) return all
77a638bc222f7bdfe931bda106501657afae5e20
GusRigor/calcNumerico
/Integral/Ex2/main.py
1,496
3.78125
4
#Calculando a integral numérica da funcao # f(x) = 1/(xˆ2)-1 no intervalo 0 a 0.8 #Pelo método do trapézio def fx(x): return 1/((x**2)-1) def d2fx(x): return -2*(-3**2 - 1)/(x**2 - 1)**3 def area(a,b): return (fx(a) + fx(b))*(b-a)*0.5 def max(a, b, inc): maior = -999 temp = 0 while True: if(a >= b): break temp = d2fx(a) if(temp > maior): maior = temp a = a + inc return maior def erro(a,b, n): return ((b-a)**3) * max(a, b, 0.01) * (1/(12*(n**2))) #Funcao para o modulo def mod(x): if(x < 0): return x * (-1) return x #Termino da funcao n = 8 #num de divisoes1 n1 = 800 #num de divisoes2 ini = 0.0 fim = 0.8 wdiv = 0.1 #tamanho de cada passo wdiv1 = 0.001 a = ini b = ini + wdiv resultado = 0 while True: if(a >= fim): break resultado = resultado + area(a,b) a = b b = b + wdiv #fim do laco e resultado tera o valor aproximado da integral print('Para divisoes com tamanho h = 0.1') print(f'A integral de f(x): {resultado}') e = mod(erro(ini, fim, n)) print(f'O erro é de: {e}') print() a = ini b = ini + wdiv1 resultado = 0 while True: if(a >= fim): break resultado = resultado + area(a,b) a = b b = b + wdiv1 #fim do laco e resultado tera o valor aproximado da integral print('Para divisoes com tamanho h = 0.001') print(f'A integral de f(x): {resultado}') e = mod(erro(ini, fim, n1)) print(f'O erro é de: {e}')
f56d2b796f5649f935192cf07cd97175f2826313
super-sebajin/General-Code
/NumericalIntegration.py
2,594
3.71875
4
#Author: Sebastian R. Papanikolaou Costa #NumericalIntegration.py - Examples of two Python classes that can be further developed to perform numerical integrations found in elementary calculus texts. ####The goal of these two classes was to experiment with the OOP features Python offers. Future work will include an update too follow PEP 8. Also, the class ####Function will be rewritten to implement two special attributes in its initializer: a 'domain' attribute and a'range' attribute, such that the terminology ####is mathematically consistent with the standard definition of a function. #class Function class Function: functions = {0: math.sin, 1: math.cos, 2: math.tan, 3: math.exp} def __init__(self,option_code=0,x=0): self._option_code = option_code self._x = x @property def code(self): return self._option_code @code.setter def code(self,new_code): self._option_code = new_code @property def x(self): return self._x @x.setter def x(self,new_x): self._x = new_x def f_x(self): if self.code in self.functions: return self.functions[self.code](self.x) def __add__(self,other): sum = self.f_x() + other.f_x() return sum def __mul__(self,other): product = self.f_x() * other.f_x() return product def __truediv__(self,other): quotient = self.f_x() / other.f_x() return quotient #class NumericalIntegration class NumericalIntegration: #defaults to math.sin def __init__(self,func=0): self.function = Function(func) ##(source: https://en.wikipedia.org/wiki/Numerical_integration # #rectangle rule of numerical integration------------------------------------------------------------ def rectangle_rule(self, limit_a,limit_b): self.function.x = limit_a return (limit_b - limit_a)*self.function.f_x() ##midpoint rule of numerical integration---------------------------------------------------------------- def midpoint_rule(self,limit_a,limit_b): self.function.x = (limit_a + limit_b) / 2 return (limit_b - limit_a) * self.function.f_x() ##trapezoidal rule of numerical integration----------------------------------------------------------------- def trapezoidal_rule(self, limit_a, limit_b): self.function.x, x_a, f_a = limit_a, self.function.x, self.function.f_x() self.function.x, x_b, f_b = limit_b, self.function.x, self.function.f_x() return (limit_b - limit_a)*(f_a + f_b)/2
441448e8118470dc14281e4bd2f170e5c2fe3ae4
jmalaverri/metafactsGenerator
/datehandler.py
13,047
3.734375
4
from datetime import datetime import re def fix(st): t = st.find('-') if t > 0: rest = st[t:] y = st[:t] else: rest = '' y = st return '%04d%s'%(int(y), rest) def isValidDate(dt): try: if dt == '-': return True m = re.search('(\d{0,4}\-\d{0,2}-\d{0,2})|(\d{0,4}\-\d{0,2})|((\d{0,4}))', fix(dt)) if m is None: print('Wrong format: ', dt) return False if m.group(1) != None: _ = datetime.strptime(m.group(1), '%Y-%m-%d') if m.group(2) != None: _ = datetime.strptime(m.group(2), '%Y-%m') if m.group(3) != None: _ = datetime.strptime(m.group(3), '%Y') return True except ValueError: print('Bad Date!', dt) return False """ string to date """ def str2date(dt): m = re.search('(\d{0,4}\-\d{0,2}-\d{0,2})|(\d{0,4}\-\d{0,2})|((\d{4}))', dt) try: if m is None: #date = "0" return '0' if m.group(1) != None: return datetime.strptime(m.group(1), '%Y-%m-%d') if m.group(2) != None: return datetime.strptime(m.group(2), '%Y-%m') if m.group(3) != None: return datetime.strptime(m.group(3), '%Y') except ValueError: print('here!', dt) return '0' def median(ti): a = str2date(ti[0]) b = str2date(ti[1]) return (a + (b - a)/2).strftime("%Y-%m-%d") """ body = [{predicate: 'hasChild', type: 'ts', ts: '2019'}, {predicate: 'isMarried', type: 'ti', ti: [2009, 2012]}] header = 'hasChild' """ def handleDates(body, header_predicate, flag=''): G, C, R = 0, 1, 2 if len(body) == 1: if body[0]['type'] == 'ts': # case 1 return G, body[0]['ts'], None elif body[0]['type'] == 'ti': # case 2 return G, None, body[0]['ti'] else: return G, None, None else: for atom in body: if atom['predicate'] == header_predicate: # case 1, 2 | p1 ts1 & p2 ts2 => p2 ts2 if atom['type'] == 'ts': # case 1 | return G, atom['ts'], None elif atom['type'] == 'ti': # case 2 | return G, None, atom['ti'] else: return G, None, None # cases with p3 # case 3 if body[0]['type'] == 'ts' and body[1]['type'] == '': return G, body[0]['ts'], None if body[0]['type'] == '' and body[1]['type'] == 'ts': return G, body[1]['ts'], None # case 3 | if body[0]['type'] == 'ti' and body[1]['type'] == '': return G, None, body[0]['ti'] if body[0]['type'] == '' and body[1]['type'] == 'ti': return G, None, body[1]['ti'] # case 4 if body[0]['type'] == 'ts' and body[1]['type'] == 'ts' and body[0]['ts'] == body[1]['ts']: return G, body[0]['ts'], None if body[0]['type'] == 'ti' and body[1]['type'] == 'ti' and body[0]['ti'] == body[1]['ti']: return G, None, body[0]['ti'] # case 5 if body[0]['type'] == 'ts' and body[1]['type'] == 'ts' and body[0]['ts'] != body[1]['ts']: return G, None, sorted([body[0]['ts'], body[1]['ts']]) # TODO check # case 6a if body[0]['type'] == 'ts' and body[1]['type'] == 'ti' and body[0]['ts'] <= body[1]['ti'][0]: return G, None, [body[0]['ts'], body[1]['ti'][1]] if body[1]['type'] == 'ts' and body[0]['type'] == 'ti' and body[1]['ts'] <= body[0]['ti'][0]: return G, None, [body[1]['ts'], body[0]['ti'][1]] # case 6b if body[0]['type'] == 'ts' and body[1]['type'] == 'ti' and body[0]['ts'] >= body[1]['ti'][1]: return G, None, [body[1]['ti'][0], body[0]['ts']] if body[1]['type'] == 'ts' and body[0]['type'] == 'ti' and body[1]['ts'] >= body[0]['ti'][1]: return G, None, [body[0]['ti'][0], body[1]['ts']] # case 6c if body[0]['type'] == 'ts' and body[1]['type'] == 'ti' and body[0]['ts'] > body[1]['ti'][0] and body[0]['ts'] < body[1]['ti'][1]: if flag == 'conservative': return C, None, body[1]['ti'] elif flag == 'restrictive': return R, body[0]['ts'], None else: return G, None, None if body[1]['type'] == 'ts' and body[0]['type'] == 'ti' and body[1]['ts'] > body[0]['ti'][0] and body[1]['ts'] < body[0]['ti'][1]: if flag == 'conservative': return C, None, body[0]['ti'] elif flag == 'restrictive': return R, body[1]['ts'], None else: return G, None, None # case 7a if body[0]['type'] == 'ti' and body[1]['type'] == 'ti' and body[0]['ti'][1] < body[1]['ti'][0]: if flag == 'conservative': return C, None, [body[0]['ti'][0], body[1]['ti'][1]] elif flag == 'restrictive': return R, None, [median(body[0]['ti']), median(body[1]['ti'])] else: return G, None, None if body[0]['type'] == 'ti' and body[1]['type'] == 'ti' and body[1]['ti'][1] < body[0]['ti'][0]: if flag == 'conservative': return C, None, [body[1]['ti'][0], body[0]['ti'][1]] elif flag == 'restrictive': return R, None, [median(body[1]['ti']), median(body[0]['ti'])] else: return G, None, None # case 7b if body[0]['type'] == 'ti' and body[1]['type'] == 'ti' and body[0]['ti'][0] >= body[1]['ti'][0] and body[0]['ti'][1] <= body[1]['ti'][1]: if flag == 'conservative': return C, None, body[1]['ti'] elif flag == 'restrictive': return R, None, body[0]['ti'] else: return G, None, None if body[0]['type'] == 'ti' and body[1]['type'] == 'ti' and body[1]['ti'][0] >= body[0]['ti'][0] and body[1]['ti'][1] <= body[0]['ti'][1]: if flag == 'conservative': return C, None, body[0]['ti'] elif flag == 'restrictive': return R, None, body[1]['ti'] else: return G, None, None # case 7c if body[0]['type'] == 'ti' and body[1]['type'] == 'ti' and body[0]['ti'][0] < body[1]['ti'][0] and body[0]['ti'][1] > body[1]['ti'][0]: if flag == 'conservative': return C, None, [body[0]['ti'][0], body[1]['ti'][1]] elif flag == 'restrictive': return R, None, [body[1]['ti'][0], body[0]['ti'][1]] else: return G, None, None if body[0]['type'] == 'ti' and body[1]['type'] == 'ti' and body[1]['ti'][0] < body[0]['ti'][0] and body[1]['ti'][1] > body[0]['ti'][0]: if flag == 'conservative': return C, None, [body[1]['ti'][0], body[0]['ti'][1]] elif flag == 'restrictive': return R, None, [body[0]['ti'][0], body[1]['ti'][1]] else: return G, None, None # case 7d if body[0]['type'] == 'ti' and body[1]['type'] == 'ti' and body[0]['ti'][1] == body[1]['ti'][0]: if flag == 'conservative': return C, None, [body[0]['ti'][0], body[1]['ti'][1]] elif flag == 'restrictive': return R, body[0]['ti'][1], None else: return G, None, None if body[0]['type'] == 'ti' and body[1]['type'] == 'ti' and body[1]['ti'][1] == body[0]['ti'][0]: if flag == 'conservative': return C, None, [body[1]['ti'][0], body[0]['ti'][1]] elif flag == 'restrictive': return R, body[1]['ti'][1], None else: return G, None, None """Parse a string date from Yago into a YYYY-MM-DD format.""" def parse_date(dt): m = re.search('(\d{0,4}\-\d{0,2}-\d{0,2})|((\d{4})\-##\-##)', dt) try: if m is None: #date = "0" return '0' if m.group(1) != None: #return datetime.strptime(m.group(1), '%Y-%m-%d') return m.group(1) if m.group(2) != None: #return datetime.strptime(m.group(3), '%Y') return m.group(3) except ValueError: return '0' """ Allen Date Checker Based on https://github.com/crsmithdev/arrow/files/678027/Allen_interval_rules_arrow.txt """ # TODO delete all unused functions def __getdates(d): return d[0] if d[0] else "9999", d[1] if d[1] else "9999" def ContainedBy(x, y): xi, xf = __getdates(x) yi, yf = __getdates(y) return (xi > yi) and (xf < yf) def Contains(x, y): xi, xf = __getdates(x) yi, yf = __getdates(y) return (yi > xi) and (yf < xf) def FinishedBy(x, y): xi, xf = __getdates(x) yi, yf = __getdates(y) return (yf == xf) and (yi > xi) def Finishes(x, y): return (xf == yf) and (xi > yi) def IsEqualTo(x, y): xi, xf = __getdates(x) yi, yf = __getdates(y) return (xi == yi) and (xf == yf) def Meets(x, y): xi, xf = __getdates(x) yi, yf = __getdates(y) return (xf == yi) def MetBy(x, y): xi, xf = __getdates(x) yi, yf = __getdates(y) return (yf == xi) def OverlapedBy(x, y): xi, xf = __getdates(x) yi, yf = __getdates(y) return (yi < xi) and ((yf > xi) and (yf < xf)) def Overlaps(x, y): xi, xf = __getdates(x) yi, yf = __getdates(y) return (xi < yi) and ((xf > yi) and (xf < yf)) def StartedBy(x, y): xi, xf = __getdates(x) yi, yf = __getdates(y) return (yi == xi) and (yf < xf) def Starts(x, y): xi, xf = __getdates(x) yi, yf = __getdates(y) return (xi == yi) and (xf < yf) def TakesPlaceAfter(x, y): xi, xf = __getdates(x) yi, yf = __getdates(y) return xi > yf def TakesPlaceBefore(x, y): xi, xf = __getdates(x) yi, yf = __getdates(y) return xf < yi """ Using Allen Temporal Constrainst to pick 1 ranges from 2 ranges """ def getRange(range1, range2): if range1[0] <= range2[0]: first = range1 second = range2 else: first = range2 second = range1 if second[0] == first[1] or TakesPlaceBefore(first, second): # there is no intersection between the 2 ranges return (first[0], second[1]) elif Contains(first, second): return second else: return (second[0], first[1]) """ Obtain date from item result """ def getRangeFromItem(item): if 'date' in item: return (item['date'], None) else: r1 = (item['born'], item['died']) r2 = (item['start'], item['end']) return getRange(r1, r2) """ Choose dates from atoms and metafacts in body to propagate to header """ def pickRange2Propagate(range1, range2): if range1[1] == None: if range2[1] == None: # timestamp + timestamp return (min((range1[0], range2[0])), max((range1[0], range2[0]))) else: # timestamp + interval return (min((range1[0], range2[0])), range2[1]) else: if range2[1] == None: # interval + timestamp return (min((range1[0], range2[0])), range1[1]) else: # interval + interval return getRange(range1, range2) """ Extract a valid range from a metafact """ def getRangeFromMF(mf): in_date_time = mf['inDateTime'] after = mf['after'] before = mf['before'] return (in_date_time if after == None else after, before) ## *************************************************************************************** ## TODO evaluate if needed; if not, remove """#### Selecting a timestamp from a group of dates ``` timestamp timestamp -> timestamp timestamp interval -> timestamp interval timestamp -> timestamp interval interval -> timestamp ``` In all cases we pick the lowest of all dates as **inDateTime**""" def pickTimestamp(dates): temp = [x for x in dates if x != None] return min(temp) """#### Selecting a time interval from a group of dates ``` timestamp timestamp -> interval timestamp interval -> interval interval timestamp -> interval interval interval -> interval ``` In all cases we pick the lowest of all dates as **after** and the greatest as **before**""" def pickTimestamp(dates): temp = [x for x in dates if x != None] return min(temp), max(temp) """#### Obtain all the appropriate dates from a metafact and results form a query""" def obtainDates(mf, item): in_date_time = mf['inDateTime'] after = mf['after'] before = mf['before'] """ f1 = after if after else in_date_time f2 = before f3 = item['date'] if 'date' in item else """ def selectTimestamp(mf, item, obj): in_date_time = mf['inDateTime'] after = mf['after'] before = mf['before']
18de61b5b5bde24ec24bb42d257aedda3511a358
cesarschool/cesar-school-fp-lista-de-exercicios-02-otaciliosiqueira
/questoes/questao_3.py
1,143
4.21875
4
## QUESTÃO 3 ## # Implementar um programa que calcula o desconto previdenciário de um funcionário. # O programa deve, dado um salário, retornar o valor do desconto proporcional ao mesmo. # O cálculo de desconto segue a regra: o desconto deve 11% do valor do salário, entretanto, # o valor máximo de desconto é 318,20. # Sendo assim, ou o programa retorna 11% sobre o salário ou 318,20. ## ## # A sua resposta da questão deve ser desenvolvida dentro da função main()!!! # Deve-se substituir o comado print existente pelo código da solução. # Para a correta execução do programa, a estrutura atual deve ser mantida, # substituindo apenas o comando print(questão...) existente. ## def main(): sal = float(input('Digite seu salário: R$ ')) desconto = 0.11 * sal if not desconto >= 318.20: print('De acordo com o seu salário(R$ {:.2f}) seu desconto(11%) é de R$ {:.2f}'.format(sal, desconto)) else: desconto = 318.20 print('De acordo com o seu salário(R$ {:.2f}) seu desconto é de R$ {:.2f}'.format(sal, desconto)) if __name__ == '__main__': main()
ff3c89b88cba25fa15366ffa07c2c88e7a5c1ef2
akshkr/mac_learn
/library/algorithms/linear_reg/linearreg.py
1,065
4.34375
4
import numpy as np """This is the implementation of algorithms of linear regression""" """This function computes the cost of the data using the linear regression cost function formula. The .dot function is used for matrix multiplication""" def ComputeCost(X, y, theta): J = 1/(2*y.size)*np.sum(np.square(X.dot(theta)-y)) return J """This function calculates the most suitable theta for the given dataset to have lowest cost""" def gradientDescent(X, y, theta, iteration, alpha): J_temp = np.zeros(iteration) for i in range(iteration): theta = theta - alpha*(1/y.size)*(X.T.dot(X.dot(theta)-y)) J_temp[i]=ComputeCost(X,y,theta) return(theta, J_temp) """References for the usage. Find the used functions or operator here""" """ 1. .T operator - transpose operator [1, 2, 3, 4] return itself after transpose because it is considered as a single dimension in numpy array [[1, 2, 3, 4]] returns [[1],[2],[3],[4]] after its transpose because it is considered as a two dimensional array in numpy 2. .dot operator - matrix multiplication operator """
5b1e8111cd4498ec86392da26dbf99490a57ba59
thbighead/TEP
/backtracking_gera_subconjuntos.py
1,147
3.828125
4
def backtracking(node, conjunto, subconjuntos, t_min, t_max): if len(node[0]) >= t_max: subconjuntos += [tuple(node[0])] # adiciono o subconjunto pois ele jah atingiu o t_max e soh vai gerar filhos de tamanhos que naum me interessam elif node[1] < len(conjunto): # se ainda tiver como gerar mais nodes filhos eu os gero ponteiro = node[1] + 1 backtracking([node[0], ponteiro], conjunto, subconjuntos, t_min, t_max) # naum adiciono novo item backtracking([node[0] + [conjunto[ponteiro-1]], ponteiro], conjunto, subconjuntos, t_min, t_max) # adiciono o novo item else: # nesse caso, naum tem mais para onde descer na minha arvore (naum tem mais como gerar nodes filhos) if len(node[0]) >= t_min: subconjuntos += [tuple(node[0])] # adiciono o subconjunto pois ele tem o tamanho minimo estipulado (t_min) def gera_conjunto(n): # conjunto do tipo {1, 2, 3, ..., n} return range(1, n + 1) def gera_subconjuntos(n, t_min, t_max): node = [[], 0] conjunto = gera_conjunto(n) print "conjunto:", conjunto subconjuntos = [] backtracking(node, conjunto, subconjuntos, t_min, t_max) print subconjuntos # main gera_subconjuntos(5, 2, 4)
c75ce2981069243c8f41fedde393db158dd326d4
damn-ice/PY-Random
/WEB SCRAPING/Extractor/test_tkinter.py
1,858
3.5625
4
from tkinter import * class App(Tk): def __init__(self): super().__init__() self.geometry('1000x500') self.title('Data Crawler') self.iconbitmap('snake.ico') first_label = Label(text="Website") first_label.grid(row=0, column=0, padx=20, pady=10) first_button = Button(text='CRAWL', command=testing, fg='red', relief=RIDGE) App.first_entry = Entry(width=90) App.first_entry.grid(row=0, column=2, pady=10) output = Text() output.grid(row=1, column=1, columnspan=4, pady=20) first_button.grid(row=2, column=2) def testing(): x = App.first_entry.get() print(x) App.first_entry.delete(0, END) app = App() def handle_keypress(event): """Print the character associated to the key pressed""" print(event.char) # Bind keypress event to handle_keypress() app.bind("<Key>", handle_keypress) app.configure(bg='black') app.mainloop() # import tkinter as tk # class App(tk.Frame): # def __init__(self, master): # super().__init__(master) # self.pack() # self.entrythingy = tk.Entry() # self.entrythingy.pack() # # Create the application variable. # self.contents = tk.StringVar() # # Set it to some value. # self.contents.set("this is a variable") # # Tell the entry widget to watch this variable. # self.entrythingy["textvariable"] = self.contents # # Define a callback for when the user hits return. # # It prints the current value of the variable. # self.entrythingy.bind('<Key-Return>', # self.print_contents) # def print_contents(self, event): # print("Hi. The current entry content is:", # self.contents.get()) # root = tk.Tk() # myapp = App(root) # myapp.mainloop()
8201ceea1d37e00f29adb42a5b72cce852122864
jphuse/PythonExamples
/The Python Workbook/Exercize 5.py
273
3.6875
4
less = int(raw_input("How many bottles are one liter or less? ")) more = int(raw_input("How many bottles are more than one liter? ")) oneliter = less * 0.10 morethanoneliter = more * 0.25 total = oneliter + morethanoneliter print "You will recieve $%s" % total
18dccb80011ecebb5a89f7ac877dec73fba9a9fe
KakaC009720/Ptyhon_train
/類別練習2.py
1,288
3.625
4
class student: def __init__(self, name, gender): self.Name = name self.Gender = gender self.Grades = [] def __gt__(self, tar): if self.avg() > tar.avg(): return True else: return False def avg(self): return ('%.1f' %(sum(self.Grades) / len(self.Grades))) def add(self, grade): self.Grades.append(grade) def fcount(self): fail = 0 for i in self.Grades: if i < 60: fail += 1 return fail def show(self): print('Name:', self.Name) print('Gender:', self.Gender) print('Grades:', self.Grades) print('Avg:', self.avg()) print('Fail Number:', self.fcount()) print() def top(*students): for i in students: i.show() top = max(students) #print(top) return top s1 = student("Tom","M") s2 = student("Jane","F") s3 = student("John","M") s4 = student("Ann","F") s5 = student("Peter","M") s1.add(80) s1.add(90) s1.add(55) s1.add(77) s1.add(40) s2.add(58) s2.add(87) s3.add(100) s3.add(80) s4.add(40) s4.add(55) s5.add(60) s5.add(60) top_student = top(s1,s2,s3,s4,s5) print('Top Student:') top_student.show()
748b947ce7b8729520f0df0b65d0748b8f019cc0
scottdaniel/gradschool
/the_beginning.py
426
3.59375
4
program = None def text_prompt(msg): try: return raw_input(msg) except NameError: return input(msg) print('Welcome to Grad School') program = text_prompt('What program would you like to join?') print('You have chosen: ',program) print('It is your first day of grad school') print('Suddenly, Satan appears') program = text_prompt('He says: grad school is hell, would you like to continue?') print('You lose')
391d03f373fa3521b4ba845e37649f9d0ba83132
PenguinRage/BruteforceVigenere
/brute_decrypt.py
2,224
3.5625
4
#!/usr/bin/env python import string, re from collections import Counter from itertools import cycle #SUBS def fileLen(textFile): with open(textFile) as f: for i, l in enumerate(f): pass return i + 1 def fileToText(textFile): """ Return text from file specified """ with open(textFile, 'r') as myfile: return myfile.read() def fileToList(textFile): """ Return text as list """ with open(textFile, 'r') as myfile: return myfile.read().splitlines() def hugeCleanString(rawString): """ Return string with no punctuation, no spaces, all caps """ return ''.join(filter(str.isalpha, rawString.lower())) def twinsIndex(cipherString): """ Returns the twin index of a string """ cipherStringLength = len(cipherString) twinsCount = 0.0 # Get twinsies, ONLY A to Z, NO overlapping twinsies like 'xxx' regex = re.compile(r'([A-Z])\1') for match in regex.finditer(cipherString): twinsCount += 1 # Do math, get twIndex :3 return twinsCount / ( cipherStringLength-1 ) * 26 # Define alphabet alphabet = map(chr, range( ord('a'), ord('z')+1)) # Get the cipher text cipherText = hugeCleanString(fileToText('cipher.txt')) # Import SOWPODS into a list sowpodsList = fileToList('sowpods.txt') # Get file length sowpodsLength = fileLen('sowpods.txt') decryptedOut = '' decryptCount = 0 for sowpodsItem in sowpodsList: # Create a tuple of cipherCharacter, keyCharacter KeyCipherTuple = zip(cipherText, cycle(sowpodsItem)) decipheredResult = '' frequencyCountRaw = 0 cypherFrequencySum = 0.0 for KeyCipherTupleValues in KeyCipherTuple: decipheredTemp = reduce(lambda x, y: alphabet.index(x) - alphabet.index(y), KeyCipherTupleValues) decipheredResult += alphabet[decipheredTemp % 26] # Let's do some frequency analysis on each line maybe? frequencyCountRaw = Counter(decipheredResult) cypherLength = len(decipheredResult) decryptedOut += decipheredResult + '\n' decryptCount += 1 # decipheredResult,' WITH ',sowpodsItem,' AND ', print (decryptCount,'of ',sowpodsLength) # Write to text file with open('cipherresults.txt', 'w') as myfile: myfile.truncate() myfile.write(decryptedOut)
ba3b8c5e27dce674c1571b23b407ae93af720ed2
mrhjs225/Learning_language
/python_ruby/override.py
360
4.03125
4
class C1: def m(self): return "parent" class C2(C1): def m(self): return "child" def m2(self): return "child2" # pass ## 메소드가 존재하지 않는 클래스를 표시할때 이렇게 표시함 class C3(C2): def m(self): return super().m2()+" second child" o = C2() print(o.m()) o2 = C3() print(o2.m())
dede4d9cbb8a8130f20d6be59557d17707461fb9
rudrasingh21/Numpy
/018 NumPy Array.py
3,744
3.71875
4
#018 NumPy Array :- ''' one D -> [] two D -> [[]] three D -> [[[]]] ''' my_list = [1,2,3] print(my_list) #[1, 2, 3] print(type(my_list)) #<class 'list'> import numpy as np arr = np.array(my_list) print(arr) #[1 2 3] print(type) #<class 'type'> #************* my_matrix = [[1,2,3],[4,5,6],[7,8,9]] print(my_matrix) #[[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(type(my_matrix)) #<class 'list'> my_matrix_arr = np.array(my_matrix) print(my_matrix_arr) ''' [[1 2 3] [4 5 6] [7 8 9]] ''' print(type(my_matrix_arr)) #<class 'numpy.ndarray'> arr_range = np.arange(0,10) print(arr_range) #[0 1 2 3 4 5 6 7 8 9] arr_range_subset = np.arange(0,10,2) print(arr_range_subset) #[0 2 4 6 8] #**************Generating an Array of all Zeros:- arr_zeros = np.zeros(3) print(arr_zeros) #[0. 0. 0.] arr_2D = np.zeros((2,3)) print(arr_2D) ''' [[0. 0. 0.] [0. 0. 0.]] ''' arr_1D = np.ones(6) print(arr_1D) #[1. 1. 1. 1. 1. 1.] arr_2D_ones = np.ones((2,2)) print(arr_2D_ones) ''' [[1. 1.] [1. 1.]] ''' #*******************linspace #linspace(start , stop , evenly space point) #Third Argument :- NUmber of points you want. linspae_arr = np.linspace(0,10,3) #between 0 to 10 , 3 evenly space points print(linspae_arr) #[ 0. 5. 10.] linspae_arr_another = np.linspace(0,10,12) print(linspae_arr_another) ''' [ 0. 0.90909091 1.81818182 2.72727273 3.63636364 4.54545455 5.45454545 6.36363636 7.27272727 8.18181818 9.09090909 10. ] ''' #****************Identity Matrix**************** Iden_Mat = np.eye(4) print(Iden_Mat) ''' Ountput:- Will be a 4*4 identity Matrix [[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]] ''' #************************Create Array of random numbers********** rand_array = np.random.rand(5) print(rand_array) #[0.073011 0.35436969 0.72476755 0.75223365 0.0692636 ] #2 D Random Numbers Matrix rand_array_2D = np.random.rand(3,3) print(rand_array_2D) ''' [[0.25336486 0.05801956 0.09694529] [0.48460495 0.80074545 0.09981986] [0.74957578 0.89116841 0.64404476]] ''' #Randint rand_int = np.random.randint(1,100) print(rand_int) #25 rand_int_size = np.random.randint(1,100,10) #size is defined as 10 print(rand_int_size) #[39 36 25 82 77 66 96 80 60 78] #**********************reshape**************** arr1 = np.arange(25) print(arr1) #[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24] rand_array = np.random.randint(1,100,5) print(rand_array) #[90 36 28 50 55] arr1_reshape = arr1.reshape(5,5) print(arr1_reshape) ''' [[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19] [20 21 22 23 24]] ''' ''' NOTE:- IF all matrix will not fill up , it will through an error. EG:- reshape(5,5) :- must have 25 element on driver array reshape(5,6) :- must have 30 element , otherwise it will through an error. ''' print(arr1_reshape.shape) #(5, 5) :- It has a shape of (5,5) and two dimentional array. #*************Max and Min value*************** max_value = rand_array.max() print(max_value) #above will give max number in rand_array (which is randomly generated) #TO get index location of max value:- print(rand_array.argmax()) #4 :- it's a index location min_value = rand_array.min() print(min_value) #12 :- #above will give min number in rand_array (which is randomly generated) print(rand_array.argmin()) #1 :- :- it's a index location print(rand_array.shape) #(5,) :- It is showing rand_array has 5 element and one dimentional array #*******************datatype****************** print(rand_array.dtype) #int32
653ed2bb3c4833348fac4acc291283b3f9a026ed
suhassrivats/Data-Structures-And-Algorithms-Implementation
/Problems/Leetcode/143_ReorderList.py
1,533
4.1875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. Time Complexity: The above algorithm will have a time complexity of O(N) where ‘N’ is the number of nodes in the LinkedList. Space Complexity: The algorithm runs in constant space O(1). """ if head is None or head.next is None: return None # find the middle of the list slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next head_second_half = self.reverse(slow) head_first_half = head # rearrange to produce output in expected order while head_first_half and head_second_half: temp = head_first_half.next head_first_half.next = head_second_half head_first_half = temp temp = head_second_half.next head_second_half.next = head_first_half head_second_half = temp # Set last node to None if head_first_half: head_first_half.next = None def reverse(self, head): prev = None while head: next_node = head.next head.next = prev prev = head head = next_node return prev
3fb3edce524850dfdc618bc407b47c3f57d89978
TENorbert/Python_Learning
/learn_python.py
637
4.125
4
#!/usr/bin/python """ python """ ''' first_name = input("Enter a ur first name: ") last_name = input("Enter your last name: ") initial = input("Enter your initial: ") person = initial + " " + first_name + " " + last_name print("Ur name is %s" %person) print("Ur name is %s%s%s" %initial %first_name %last_name) ''' catNames = [] while True: print('Enter the name of cat ' + str(len(catNames) + 1) + '(or enter Nothing to stop.):') name = input() if name == '': break catNames = catNames + [name] ##Append indirectly using list concatenation print('The cat names are:') for name in catNames: print(' ' + name)
d949d5fc68c39f6092d8a0cb3a83fa75ad43e46b
womonge/lecture10
/question2.py
296
4.03125
4
#A program for a simple type of a secret code. def main(): sentence=input("Write the sentence you want coded :") for char in sentence: code=ord(char) coded_char=code+5 new_chr=chr(coded_char) print(new_chr,end='') main()
300c776ef0c3046017fa26b509976d23f5146208
diontran/GameSearchROPASCI360
/Manuel_upper/Board.py
5,640
3.75
4
import itertools class Board: """A class representing the board to the player, providing information for the player to make a decision""" def __init__(self, player_type): self.player_type = player_type self.game_state = {'R':[], 'P':[], 'S':[], 'r':[], 'p':[], 's':[]} #A list of list of hex, where each list represents one row on the board board_hex = [[(4, -4),(4, -3),(4, -2),(4, -1),(4, -0)], [(3, -4),(3, -3),(3, -2),(3, -1),(3, 0),(3, 1)], [(2, -4),(2, -3),(2, -2),(2, -1),(2, 0),(2, 1),(2, 2)], [(1, -4),(1, -3),(1, -2),(1, -1),(1, 0),(1, 1),(1, 2),(1, 3)], [(0, -4),(0, -3),(0, -2),(0, -1),(0, 0),(0, 1),(0, 2),(0, 3),(0, 4)], [(-1, -3),(-1, -2),(-1, -1),(-1, 0),(-1, 1),(-1, 2),(-1, 3),(-1, 4)], [(-2, -2),(-2, -1),(-2, 0),(-2, 1),(-2, 2),(-2, 3),(-2, 4)], [(-3, -1),(-3, 0),(-3, 1),(-3, 2),(-3, 3),(-3, 4)], [(-4, 0),(-4, 1),(-4, 2),(-4, 3),(-4, 4)]] def get_row(self,row_num): """Function returns the list of hex corresponding to row number from top to bottom, row 0 being the first row""" return self.board_hex[4-row_num] def update_move(self,action,player_side): """Update the board's game state according to the action player passed into""" #Add the token to the board if action[0] == 'THROW': self.game_state[action[1]].insert(0,action[2]) if action[0] == 'SLIDE' or action[0] == 'SWING': original_pos = action[1] new_pos = action[2] #update list of key in game state accordingly if self.player_type == 'upper' and player_side == 'player': search_keys = ['R', 'P', 'S'] elif self.player_type == 'upper' and player_side == 'opponent': search_keys = ['r', 'p', 's'] elif self.player_type == 'lower' and player_side == 'player': search_keys = ['r', 'p', 's'] elif self.player_type == 'lower' and player_side == 'opponent': search_keys = ['R', 'P', 'S'] for key in search_keys: if original_pos in self.game_state.get(key): updated_list = self.game_state.get(key) updated_list.remove(original_pos) updated_list.insert(0, new_pos) self.game_state[key] = updated_list #Battle if there are other tokens in the spot tokens_in_pos = [] for key in self.game_state.keys(): for pos in self.game_state[key]: if pos == action[2]: tokens_in_pos.insert(0, key) kill_types = self.kill_tokens(tokens_in_pos) #Remove tokens in kill_types all_kill_types = [] if kill_types != []: for type in kill_types: all_kill_types.insert(0, type) all_kill_types.insert(0, type.lower()) if all_kill_types != []: for token in all_kill_types: self.game_state[token].remove(action[2]) def get_player_token(self): """Function returns a dictionary of player's tokens""" if self.player_type == 'upper': included_keys = ['R', 'P', 'S'] else: included_keys = ['r', 'p', 's'] return {k:v for k,v in self.game_state.items() if k in included_keys} def generate_possible_move(self,pos): """Function returns a list of possible new positions that the current token in pos can move to""" possible_positions = [] #Positions for swinging directions = [(0,-1),(1,-1),(1,0),(0,1),(-1,1),(-1,0)] for tuple in directions: new_pos = ((pos[0] + tuple[0]) , (pos[1] + tuple[1])) if new_pos in list(itertools.chain(*self.board_hex)): possible_positions.insert(0,new_pos) return possible_positions def token_win(type1, type2): """Function that returns if token type 1 beats token type 2""" t1 = type1.upper() t2 = type2.upper() if t1 == 'R': if t2 == 'S': return True else: return False if t1 == 'P': if t2 == 'R': return True else: return False if t1 == 'S': if t2 == 'P': return True else: return False def kill_tokens(self,tokens_in_pos): """Function receives a list of types of tokens in the same position, and remove the one which loses in battle""" capital = [] for type in tokens_in_pos: if type.upper() not in capital: capital.insert(0, type.upper) #Case where all three types in same position if 'R' in capital and 'P' in capital and 'S' in capital: return capital #All tokens removed #Cases where two token types battle elif 'R' in capital and 'P' in capital: return ['R'] elif 'P' in capital and 'S' in capital: return ['P'] elif 'S' in capital and 'R' in capital: return ['S'] else: return [] def player_no_token(self): if self.player_type == 'upper': keys = ['R', 'P', 'S'] else: keys = ['r', 'p', 's'] number_of_tokens = 0 for key in keys: number_of_tokens += len(self.game_state[key]) if number_of_tokens == 0: return True else: return False
0800693f507414060c6a5309aaea51a206c4502e
AishwaryaJadhav9850/GeeksforGeeks-Mathematical-
/GeeksForGeek_Perfect Numbers.py
668
4.03125
4
# -*- coding: utf-8 -*- """ Created on Wed Dec 2 17:49:17 2020 @author: aishw """ #User function Template for python3 import math class Solution: def isPerfectNumber(self, N): if N==1 or N==2: return 0 num=1 n=int(math.sqrt(N))+1 for i in range(2,n+1): if N%i==0: num=num+i+(N//i) if num>N: return 0 if num==N: return 1 else: return 0 if __name__ == '__main__': N=int(input()) ob = Solution() print(ob.isPerfectNumber(N)) # } Driver Code Ends
7b14f6e8042fa081a0d9f0e8de1555c8ef18fb78
hosemagi/Project-Euler-Solutions
/fixitforspoon.py
305
3.625
4
import math def primefactor(n): listofprimes = [] for x in range(2, int(math.ceil(math.sqrt(n) + 1))): if n % x == 0: return False return True for z in range(2, 1000): isprime = primefactor(z) if isprime != 1: listofprimes.append(z) print(listofprimes)
cc8e00e2ea2a7c8a7162fd4b4fd339c7cd529056
jslee-programer/coding-test
/coding-test/dfs_bfs/test1/service.py
773
3.640625
4
class Service: def __init__(self): pass def __repr__(self): pass def run(self): pass def recursive_fn(self, i): print('재귀 함수') if i == 100: return print(f'{i} 번째 재귀 함수에서, {i + 1} 번째 재귀함수를 호출 합니다.') self.recursive_fn(i + 1) print(f'{i} 번째 재귀함수를 종료합니다.') # 반복적으로 구현한 n! @staticmethod def factorial_iterative(n): result = 1 for i in range(1, n + 1): result *= i return result # 재귀적으로 구현한 n! def factorial_recursive(self, n): if n <= 1: return 1 return n * self.factorial_recursive(n - 1)
b8adc89141fd65b531fc86b3d50dacf51be19e2e
pankajdeep/Assignment-6
/Assignment-6.py
1,507
4.3125
4
#Q.1- Create a function to calculate the area of a sphere by taking radius from user. import math def area_of_sphere(radius): area=4*(math.pi)*(radius**2) return area r=int(input("Enter radius of sphere")) print("Area of Sphere is :",area_of_sphere(r)) #Q.2- Write a function “perfect()” that determines if parameter number is a perfect number. #Use this function in a program that determines and prints all the perfect numbers between 1 and 1000. #[An integer number is said to be “perfect number” if its factors, including 1(but not the number itself), sum to the number. #E.g., 6 is a perfect number because 6=1+2+3]. def perfect(num): sums=0 for j in range(1,num): if(num%j==0): sums=sums+j if(sums==num): print(num) print("Perfect Numbers between 1 and 1000 are :") for i in range(2,1000): perfect(i) #Q.3- Print multiplication table of n using loops, where n is an integer and is taken as input from the user. def multiply(num): for i in range(0,11): print(num,"*",i,"=",num*i) num=int(input("Enter integer whose multiplication table you want to print")) multiply(num) #Q.4- Write a function to calculate power of a number raised to other ( a^b ) using recursion. def power(a,b): if(b>1): return(a*power(a,b-1)) elif(b==0): return 1 else: return a num1=int(input("Enter value of a")) num2=int(input("Enter value of b")) print(num1,"^",num2,"=",power(num1,num2))
2b1e379e1b0d335789db391779ed65d1e16f9a50
loganwastlund/cs1410
/caloric_balance_assignment/caloric_balance/test_main_quitAction.py
2,125
3.65625
4
""" Do Not Edit this file. You may and are encouraged to look at it for reference. """ import sys if sys.version_info.major != 3: print('You must use Python 3.x version to run this unit test') sys.exit(1) import unittest import main import sys class TestQuitAction(unittest.TestCase): def input_replacement(self, prompt): self.assertFalse(self.too_many_inputs) self.input_given_prompt = prompt r = self.input_response_list[self.input_response_index] self.input_response_index += 1 if self.input_response_index >= len(self.input_response_list): self.input_response_index = 0 self.too_many_inputs = True return r def print_replacement(self, *text, **kwargs): line = " ".join(text) + "\n" self.printed_lines.append(line) return def exit_replacement(self, value): self.exit_called = True self.exit_value = value return def setUp(self): self.too_many_inputs = False self.input_given_prompt = None self.input_response_index = 0 self.input_response_list = [""] main.input = self.input_replacement self.printed_lines = [] main.print = self.print_replacement self.exit_called = False self.exit_value = -1 return def tearDown(self): return def test001_quitActionExists(self): self.assertTrue('quitAction' in dir(main), 'Function "quitAction" is not defined, check your spelling') return def test002_quitActionCallsExit(self): from main import quitAction index = {} expected = {} self.input_response_list = ["???"] original_exit = sys.exit sys.exit = self.exit_replacement quitAction(index) sys.exit = original_exit self.assertDictEqual(index, expected) self.assertGreaterEqual(len(self.printed_lines), 1) self.assertTrue(self.exit_called) self.assertEqual(self.exit_value, 0) return if __name__ == '__main__': unittest.main()
595864f76b98a92c1655e61c253476039bf578af
zodoctor/lectures-fall2018
/lecture3/square-pulse-fourier-series
3,153
4.0625
4
#!/usr/bin/env python """a simple script to demonstrate how to numerically compute fourier coefficients for a function """ __author__ = "Reed Essick <reed.essick@kicp.uchicago.edu>" #------------------------------------------------- import numpy as np import matplotlib matplotlib.use("Agg") from matplotlib import pyplot as plt from argparse import ArgumentParser #------------------------------------------------- FIGNAME = 'square-pulse-fourier-series-%s.png' #------------------------------------------------- parser = ArgumentParser() parser.add_argument('N', type=int, help='the maximum number of fourier compenents to keep in your iteration') parser.add_argument('-n', '--num-points', default=100, type=int, help='number of plotting points') parser.add_argument('-T', '--period', default=1., type=float) parser.add_argument('-v', '--verbose', default=False, action='store_true') args = parser.parse_args() #------------------------------------------------- # first, let's define our function. We'll use a simple square pulse def func(t, T=1.): """expects t to be a np.ndarray""" t = t%T # take the remainder because this is a periodic function return (t<0.5*T).astype(int) # define a square pulse that lasts have the period def inner(t, a, b, T=1.): return (2./T)*np.trapz(a*b, x=t) def plot(t, f, f_approx): fig = plt.figure() ax = fig.gca() ax.plot(t, f) ax.plot(t, f_approx) ax.set_xlabel('time') return fig #------------------------------------------------- # now, let's make some plots, computing fourier coefficients as we go ### plot the function itself t = np.linspace(0, args.period, args.num_points) f = func(t, T=args.period) ### the zero's order is simply the function's mean (DC-component) fo = inner(t, 1, f, T=args.period)/2. f_approx = fo*np.ones(args.num_points) fig = plot(t, f, f_approx) figname = FIGNAME%0 if args.verbose: print(figname) fig.savefig(figname) plt.close(fig) ### iterate through the rest of the terms, computing coefficients and adding them to the approximation coeffs = [] for n in range(1, args.N): freq = 2*np.pi*n/args.period c = np.cos(freq*t) s = np.sin(freq*t) a = inner(t, c, f, T=args.period) b = inner(t, s, f, T=args.period) f_approx += a*c + b*s coeffs.append( (a, b) ) fig = plot(t, f, f_approx) figname = FIGNAME%n if args.verbose: print(figname) fig.savefig(figname) plt.close(fig) ### make a spectrum fig = plt.figure() ax_C = plt.subplot(2,1,1) ax_p = plt.subplot(2,1,2) ax_C.plot(0, fo, marker='o', color='b') ax_p.plot(0, 0, marker='o', color='r') for n, (a, b) in enumerate(coeffs): freq = (n+1)/args.period ax_C.plot(freq, (a**2+b**2)**0.5, marker='o', color='b') ax_p.plot(freq, np.arctan2(b, a)*180/np.pi, marker='o', color='r') ax_C.set_yscale('log') ax_C.set_ylabel('C') ax_p.set_ylabel('$\phi$') ax_p.set_xlabel('frequency') ax_p.set_ylim(ymin=-91, ymax=91) for ax in [ax_C, ax_p]: ax.set_xlim(xmin=-0.5, xmax=(args.N+0.5)/args.period) figname = FIGNAME%'spectrum' if args.verbose: print(figname) fig.savefig(figname) plt.close(fig)
f1f2cc76eb66ad8093c935b53480590f25114698
hiro21/sample_python
/e2fDectionaly.py
322
3.65625
4
e2f = { "dog":"chien", "cat":"chat", "walrus":"morse", } # walrusを出力 print (e2f["walrus"]) # e2f convert f2e f2e = {} for i, v in e2f.items(): print (i, v) f2e[v] = i print('output f2e') print(f2e) # call chien by f2e print (f2e["chien"]) # e2f convert set e2fSet = set(e2f) print (e2fSet)
93d80653a94201de365dd76fa4e44383a6e661f8
raynan222/Aprendizado
/Aulas/Op, Logicos.py
572
3.953125
4
while True: a=int(input()) b=int(input()) """if True and True: True if False or True: False if a==2 or b==2: print("acetou mizeravi") c=True print(c) break if a!=b: print("hmm entao e difente ne....") if a>b: print("A é maior") else: print("so resta B ser maior ne") """ if not a==b: print("eita") elif a==2 and b==2: print("kkkkkkkk trouxa") if not False: print("desnecessauro") if not b!=a: print("meeee")