blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
dd9db3117e5591581050b0a0b2951a87831533a0 | HollisHolmes/MIT_6.006 | /PS2/minheap.py | 4,074 | 4.03125 | 4 | class MinHeap:
"""
array based min heap implementation of a priority queue
Things to note:
1) left child, right child, and parent indexing with 2*i, 2*i+1, i//2
does not work if the array starts at index 0. ex:
index 1 and 2 should have parent 0, but 2//1 = 1 which is wrong
we need a placeholder, say None, at index 0 then add elements starting at 1.
2) queue is implemented as an python list. len() attribute is called often
in the minHeap methods. This is fine. Python augments their lists with a len
attribute that is both maintained and accessible in O(1) time.
"""
def __init__(self):
"""Initialy empy heap"""
self.queue = [None]
self.min_index = None
self.size = 0
def __len__(self):
"""Define len method"""
#account for None element at index 0
return len(self.queue) -1
def parent (self, pos):
"""Get the index of a node's parent"""
return pos//2
def leftChild(self, pos):
"""Get the index of a node's left child"""
return pos * 2
def rightChild(self, pos):
"""Get the indes of a node's right child"""
return pos * 2 + 1
def isLeaf(self, pos):
"""Check if a node is a leaf"""
if pos > len(self)//2 and pos <= len(self)-1:
return True
return False
def swap(self, pos1, pos2):
"""Swap the value of two nodes"""
if pos1==0 or pos2==0:
raise IndexError('cant access element 0 of the queue')
self.queue[pos1], self.queue[pos2] = self.queue[pos2], self.queue[pos1]
def insert(self, element):
"""Insert a value into the min heap, move this value up the heapify
to maintain the minheap property"""
self.queue.append(element)
print('queue after insert {}'.format(self.queue))
current = len(self)
print('current {}'.format(current))
#need to drag this newly inserted value up the min heap
while current!=1 and self.queue[current] < self.queue[self.parent(current)]:
self.swap(current, self.parent(current))
current = self.parent(current)
print('floating elemnt up: {}'.format(self.queue))
def minHeapify(self, pos):
"""Check if a node is greater than both of its children, if so,
correct this obstruction of the min heap property"""
#check if node has child, ie is not a isLeaf
if not self.isLeaf(pos):
#if parent is bigger than either child
if self.queue[pos]>self.queue[self.leftChild(pos)] or self.queue[pos]>self.queue[self.rightChild(pos)]:
#swap with the larger of the children
#if left child is bigger swap with left child
print(self.leftChild(pos))
if self.queue[self.leftChild(pos)] < self.queue[self.rightChild(pos)]:
self.swap(pos, self.leftChild(pos))
minHeapify(self.leftChild(pos))
else:
self.swap(pos, self.rightChild(pos))
minHeapify(self.rightChild(pos))
def buildMinHeap(self):
"""Loop through all nodes in the min heap that are not leaves,
check of the min heap property is satisfied, if not, correct with
minHeapify"""
for i in range((self.size-1)//2, -1, -1):
print('size=',self.size)
print('minheapifying at', i)
self.minHeapify(i)
def __str__(self):
return str(self.queue)
def Print(self):
for i in range(1, (self.size//2)):
print(" PARENT : "+ str(self.queue[i])+" LEFT CHILD : "+
str(self.queue[2 * i])+" RIGHT CHILD : "+
str(self.queue[2 * i + 1]))
test = MinHeap()
for i in range(10, 0, -1):
print('inserting {}'.format(i))
test.insert(i)
test.buildMinHeap()
#print(test)
|
e71cb442dc1388eb31774665a3db80578dcded3f | Kvn12/MC102 | /Lab09.py | 1,267 | 4.03125 | 4 | def intersecao(m, n):
'''Recebe duas matrizes cujas linhas sao conjuntos e compara cada linha em busca de intersecoes, as quais se existirem\
sao colocadas como linhas de uma nova matriz, a qual e retornada.
Parametros:
m --- matriz a ser comparada
n --- matriz a ser comparada
'''
matriz_intersecao = []
for i in range(len(m)):
for j in range(len(n)):
intersecao = m[i].intersection(n[j])
if len(intersecao) != 0:
matriz_intersecao.append(intersecao)
return matriz_intersecao
while True:
linha_1 = input().split()
if linha_1[0] != '0':
m = []
n = []
for i in range(int(linha_1[0])):
linha = input().split()
s = set()
m.append(s)
for j in range(len(linha)):
m[i].add(int(linha[j]))
for i in range(int(linha_1[1])):
linha = input().split()
s = set()
n.append(s)
for j in range(len(linha)):
n[i].add(int(linha[j]))
matriz_intersecao = intersecao(m, n)
print(len(m)+len(n)-len(matriz_intersecao), "x", len(m)+len(n)-len(matriz_intersecao[0]))
else:
break
|
c260c9db895e6c7dcaaf475a655d3722b4d99663 | deepeshkumarsoni/Python-Basic | /numconverfunct.py | 376 | 3.71875 | 4 | #1.Conversion into Binary Form
print('Conversion into Binary Form')
print(bin(15345))
print(bin(0o7625))
print(bin(0xface34))
print('\nConversion into Octal Form')
#2.Conversion into Octal form
print(oct(34765))
print(oct(0b1101110001))
print(oct(0xafc4f))
print('\nConversion into Hexadecimal Form')
print(hex(84579))
print(hex(0b101011110))
print(hex(0o7467))
|
078120fd81a0a8068d2ac958c340b3562bb10da1 | Brian-Mascitello/Advent-of-Code | /Advent of Code 2015/Day 3 2015/Day3Q2.py | 3,927 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Author: Brian Mascitello
Date: 12/20/2015
School: Arizona State University
Websites: http://adventofcode.com/day/3
http://adventofcode.com/day/3/input
Info: --- Part Two ---
The next year, to speed up the process, Santa creates a robot version of
himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to
the same starting house), then take turns moving based on instructions from
the elf, who is eggnoggedly reading from the same script as the previous
year.
This year, how many houses receive at least one present?
For example:
- ^v delivers presents to 3 houses, because Santa goes north, and then
Robo-Santa goes south.
- ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa end up
back where they started.
- ^v^v^v^v^v now delivers presents to 11 houses, with Santa going one
direction and Robo-Santa going the other.
"""
import numpy as np
file = open('Day3Q1 Input.txt')
input_string = file.read()
file.close()
north = 0
east = 0
south = 0
west = 0
for i in range(0, len(input_string)):
# Scans the input_string to find the furthest Santa travels in each direction.
# Should be the same since this accounts for max distance in each direction.
if input_string[i] == '^':
north += 1
elif input_string[i] == '>':
east += 1
elif input_string[i] == 'v':
south += 1
elif input_string[i] == '<':
west += 1
# print(north, east, south, west) # Checks final values of the directions.
# horizon_len and vert_len for the size of 2D array Santa will traverse.
# The midpoints will be the starting location in the center of the 2D array
if north > south:
vert_mid = north
vert_len = 2 * north + 1
else:
vert_mid = south
vert_len = 2 * south + 1
if east > west:
horizon_mid = east
horizon_len = 2 * east + 1
else:
horizon_mid = west
horizon_len = 2 * west + 1
# print(vert_mid, vert_len, horizon_mid, horizon_len) # Checks the dimensions of the array.
# Zeros array of type int with dimensions (horizon_len, vert_len)
neighborhood = np.zeros((horizon_len, vert_len), dtype = np.int)
# print(neighborhood) # Checks array is right style.
# Makes two new variables for house locations.
x = horizon_mid
y = vert_mid
x_robot = horizon_mid
y_robot = vert_mid
for i in range(0, len(input_string)):
# Adds presents Santa gives to locations in the array.
if i % 2 == 0:
# If even Santa moves, otherwise the robot moves.
neighborhood[x][y] += 1 # Adds a gift to the house before moving.
# This switch statement moves Santa.
if input_string[i] == '^':
y += 1
elif input_string[i] == '>':
x += 1
elif input_string[i] == 'v':
y -= 1
elif input_string[i] == '<':
x -= 1
neighborhood[x][y] += 1 # Adds a gift to the house after moving.
else:
neighborhood[x_robot][y_robot] += 1 # Adds a gift the robot places.
# This switch statement moves the robot.
if input_string[i] == '^':
y_robot += 1
elif input_string[i] == '>':
x_robot += 1
elif input_string[i] == 'v':
y_robot -= 1
elif input_string[i] == '<':
x_robot -= 1
neighborhood[x_robot][y_robot] += 1
homes_with_gifts = 0 # Will be the number of homes with at least one present.
# Iterates through neighborhood looking for homes with more than 0 presents.
for updown in range(0, vert_len):
for leftright in range(0, horizon_len):
if neighborhood[leftright][updown] > 0:
homes_with_gifts += 1
print(homes_with_gifts) # 2639 homes are marked with at least one gift! |
e6d1f6d318b52a21f1807b615c897c35101b670c | felipeserna/holbertonschool-machine_learning | /unsupervised_learning/0x01-clustering/11-gmm.py | 602 | 3.578125 | 4 | #!/usr/bin/env python3
"""
Calculates a GMM from a dataset
"""
import sklearn.mixture
def gmm(X, k):
"""
Returns: pi, m, S, clss, bic
"""
GMM = sklearn.mixture.GaussianMixture(n_components=k)
# Estimate model parameters with the EM algorithm.
GMM.fit(X)
pi = GMM.weights_
m = GMM.means_
S = GMM.covariances_
# Predict the labels for the data samples in X using trained model.
clss = GMM.predict(X)
# Bayesian information criterion for the current model on the input X.
# The lower the better.
bic = GMM.bic(X)
return pi, m, S, clss, bic
|
ad0d8272be495b8b651186d9330cef3c89a1958c | zhouyang209117/leetcode | /py/l010_regular_expression.py | 427 | 3.84375 | 4 | # coding: utf-8
import re
class Solution:
def isMatch(self, s: str, p: str) -> bool:
r = re.match(p, s)
if r is None:
return False
return r.group() == s
if __name__ == '__main__':
s = Solution()
print(s.isMatch("aa", "a"))
print(s.isMatch("aa", "a*"))
print(s.isMatch("ab", ".*"))
print(s.isMatch("aab", "c*a*b"))
print(s.isMatch("mississippi", "mis*is*p*.")) |
0db338de2b757b7f45eb5c4761a184da0677ae1a | ShineySun/Vanishing-Point-Detection | /v_code/kruskal.py | 3,786 | 4.1875 | 4 | import numpy as np
from operator import itemgetter
# function [w_st, ST, X_st] = kruskal(X, w)
#
# This function finds the minimum spanning tree of the graph where each
# edge has a specified weight using the Kruskal's algorithm.
#
# Assumptions
# -----------
# N: 1x1 scalar - Number of nodes (vertices) of the graph
# Ne: 1x1 scalar - Number of edges of the graph
# Nst: 1x1 scalar - Number of edges of the minimum spanning tree
#
# We further assume that the graph is labeled consecutively. That is, if
# there are N nodes, then nodes will be labeled from 1 to N.
#
# INPUT
#
# X: NxN logical - Adjacency matrix
# matrix If X(i,j)=1, this means there is directed edge
# starting from node i and ending in node j.
# Each element takes values 0 or 1.
# If X symmetric, graph is undirected.
#
# or Nex2 double - Neighbors' matrix
# matrix Each row represents an edge.
# Column 1 indicates the source node, while
# column 2 the target node.
#
# w: NxN double - Weight matrix in adjacency form
# matrix If X symmetric (undirected graph), w has to
# be symmetric.
#
# or Nex1 double - Weight matrix in neighbors' form
# matrix Each element represents the weight of that
# edge.
#
#
# OUTPUT
#
# w_st: 1x1 scalar - Total weight of minimum spanning tree
# ST: Nstx2 double - Neighbors' matrix of minimum spanning tree
# matrix
# X_st: NstxNst logical - Adjacency matrix of minimum spanning tree
# matrix If X_st symmetric, tree is undirected.
#
# EXAMPLES
#
# Undirected graph
# ----------------
# Assume the undirected graph with adjacency matrix X and weights w:
#
# 1
# / \
# 2 3
# / \
# 4 - 5
#
# X = [0 1 1 0 0;
# 1 0 0 1 1;
# 1 0 0 0 0;
# 0 1 0 0 1;
# 0 1 0 1 0];
#
# w = [0 1 2 0 0;
# 1 0 0 2 1;
# 2 0 0 0 0;
# 0 2 0 0 3;
# 0 1 0 3 0];
#
# [w_st, ST, X_st] = kruskal(X, w);
# The above function gives us the minimum spanning tree.
#
#
# Directed graph
# ----------------
# Assume the directed graph with adjacency matrix X and weights w:
#
# 1
# / ^ \
# / / \
# v v
# 2 ---> 3
#
# X = [0 1 1
# 1 0 1
# 0 0 0];
#
# w = [0 1 4;
# 2 0 1;
# 0 0 0];
#
# [w_st, ST, X_st] = kruskal(X, w);
# The above function gives us the minimum directed spanning tree.
#
#
def cnvrtX2ne(X, isUndirGraph):
if isUndirGraph:
ne = np.zeros()
return ne
def cnvrtw2ne(w, ne):
return w
def kruskal(X, w):
print("********************** Kruskal MST **********************")
isUndirGraph = 1
# print((X[:]==0).sum())
# print((X[:]==1).sum())
#print(len(X)*len(X[0]))
#print((X==0).sum())
if X.shape[0] == X.shape[1] and (X[:]==1).sum()==len(X)*len(X[0]):
if (X-X.transpose()).any().any():
isUndirGraph = 0
ne = cnvrtX2ne(X, isUndirGraph)
else:
#size(unique(sort(X,2),'rows'),1)~=size(X,1)
X.sort(axis=1)
for i in range(len(X)):
print(X[i])
X = X.tolist()
#print(X)
tmp = list(set([tuple(ti) for ti in X]))
#print(tmp)
tmp.sort()
#print(tmp)
tmp_len = len(tmp)
#print(len(X))
if tmp_len != len(X):
isUndirGraph = 0
ne = X
return 1,1,1
# print(X.shape[0])
# Convert logical adjacent matrix to neighbors' matrix
return 1,1,1
|
436da6d84c19a4038e7f87c8e7ad9516f9accc68 | tbrodbeck/InspiredByNature | /GA/Makespan_GA_Inga.py | 8,282 | 3.625 | 4 | import numpy as np
from abc import ABC, abstractmethod
''' The problems '''
def get_problem_1():
process_200 = np.random.randint(10, 1001, 200)
process_100 = np.random.randint(100, 301, 100)
processing = np.zeros(300)
processing[:200] = process_200
processing[200:] = process_100
return processing
def get_problem_2():
process_150_1 = np.random.randint(10, 1001, 150)
process_150_2 = np.random.randint(400, 701, 150)
processing = np.zeros(300)
processing[:200] = process_150_1
processing[200:] = process_150_2
return processing
def get_problem_3():
processing = [50, 50, 50]
for i in range(100 - 51):
processing.append(i + 51)
processing.append(i + 51)
return processing
''' Modules '''
class Initializer(ABC):
@abstractmethod
def initialize(self):
pass
class Equal_Initializer(Initializer):
def __init__(self, num_jobs, num_machines, population_size):
self.num_jobs = num_jobs
self.num_machines = num_machines
self.population_size = population_size
def initialize(self):
per_machine = self.num_jobs // self.num_machines
init = []
for i in range(self.num_machines):
init.append([i+1] * per_machine)
init = np.ravel(np.asarray(init))
if len(init) != self.num_jobs:
for i in range(self.num_jobs - len(init)):
init = np.append(init, 1)
return init
class Random_Initializer(Initializer):
def __init__(self, num_jobs, num_machines, population_size):
self.num_jobs = num_jobs
self.num_machines = num_machines
self.population_size = population_size
def initialize(self):
init = np.zeros((self.population_size, self.num_jobs))
for i in range(self.population_size):
init[i] = np.random.randint(1, self.num_machines + 1, self.num_jobs)
return init
class Selector():
def roulette(self):
raise NotImplementedError
def tournament(self, candidates):
return max(candidates)
class Recombiner():
"""
Recombines two parents into two new children with possibly different genes
"""
def __init__(self, chromosomes, cross_probability=.5):
"""
Inits the recombiner with a defined crossover probability, defaulting to .5
"""
self.chromosomes = chromosomes
self.crossover_probability = cross_probability
def crossover_random_num(self):
"""
Generates a random r to check if crossover occurs
"""
return np.random.random()
def get_random_pair(self):
"""
Pulls out two random chromosomes to crossover. If the same pair is pulled, generate another one until
different chromosomes are pulled.
"""
pair = np.random.randint(0, len(self.chromosomes), 2)
while pair[0] == pair[1]:
pair[1] = np.random.randint(0, len(self.chromosomes))
return pair
def one_point_crossover(self):
"""
One point crossover implementation
"""
pair = self.get_random_pair()
# Define the parents
mom = self.chromosomes[pair[0]]
dad = self.chromosomes[pair[1]]
# See if they crossover
cross_chance = self.crossover_random_num()
if cross_chance < self.crossover_probability:
# Cross over occurs, generate crossover point
crossover_point = np.random.randint(1, len(self.chromosomes[1]))
child1, child2 = [], []
from_mom = True
# Step through alleles
for i in range(len(self.chromosomes[1])):
if i == crossover_point: # if hit crossover point, swap allele selection
from_mom = False
if from_mom:
child1.append(mom[i])
child2.append(dad[i])
else:
child1.append(dad[i])
child2.append(mom[i])
return child1, child2
else: # if no crossover, return parents
return mom, dad
def two_point_crossover(self):
"""
Two point crossover implementation
"""
pair = self.get_random_pair()
# Define the parents
mom = self.chromosomes[pair[0]]
dad = self.chromosomes[pair[1]]
# See if they crossover
cross_chance = self.crossover_random_num()
if cross_chance < self.crossover_probability:
# Cross over occurs, generate crossover points
crossover_point1 = np.random.randint(1, len(self.chromosomes[1]))
crossover_point2 = np.random.randint(1, len(self.chromosomes[1]))
if crossover_point2 < crossover_point1: # make sure they are in order
temp = crossover_point2
crossover_point2 = crossover_point1
crossover_point1 = temp
while crossover_point1 == crossover_point2: # make sure they are not the same
crossover_point2 = np.random.randint(1, len(self.chromosomes[1]))
child1, child2 = [], []
from_mom = True
for i in range(len(self.chromosomes[1])):
if i == crossover_point1: # if hit crossover point, swap allele selection
from_mom = False
if i == crossover_point2: # if hit crossover point, swap allele selection
from_mom = True
if from_mom:
child1.append(mom[i])
child2.append(dad[i])
else:
child1.append(dad[i])
child2.append(mom[i])
return child1, child2
else: # if no crossover, return parents
return mom, dad
class Mutator():
#to-do!! (Inga)
def random(self, offspring, num_jobs):
probabilty_m = np.random.random()
if probabilty_m < 0.1:
#randomly choses a position that gets mutated
bit = np.random.randint(0, (len(offspring) - 1))
mutation = np.random.randint(1, num_jobs)
while offspring[bit] == mutation:
mutation = np.random.randint(1, num_jobs)
offspring[bit] = mutation
return offspring
else:
return offspring
def lazy(self, offspring, num_jobs):
probabilty_m = np.random.random()
if probabilty_m < 0.1:
#randomly choses a position that gets mutated
bit = np.random.randint(0, (len(offspring) - 1))
mutation = np.random.randint(1, num_jobs)
while offspring[bit] == mutation:
mutation = np.random.randint(1, num_jobs)
offspring[bit] = mutation
return offspring
else:
return offspring
class Genetic_Algotihm:
def __init__(self, problem, initializer, selector, recombiner, mutator, replacer):
self.problem = problem
self.initializer = initializer
self.selector = selector
self.recombiner = recombiner
self.mutator = mutator
self.replacer = replacer
self.population = self.initializer.initialize()
def evaluate_population(self):
evaluation = []
for chromosome in self.population:
chromosome_eval = []
for index, job in enumerate(chromosome):
chromosome_eval[job] = chromosome_eval[job] + self.problem[index]
evaluation.append(chromosome_eval)
return max(evaluation)
''' hyperparameters '''
population_size = 1
num_jobs = 300
num_machines = 20
''' main script '''
problem_1 = get_problem_1()
#problem_2 = get_problem_2()
#problem_3 = get_problem_3()
#equal_initializer = Equal_Initializer(num_jobs,num_machines,population_size)
random_initializer = Random_Initializer(num_jobs,num_machines,population_size)
#ga_equal = Genetic_Algotihm(equal_initializer, 0,0,0,0)
ga_random = Genetic_Algotihm(problem_1, random_initializer,0,0,0,0)
#print(ga_equal.population)
print(ga_random.population)
print(ga_random.evaluate_population)
|
705fc3b78cbad6655922216d87d8687a5766e489 | spnear/Python-Advanced-Concepts | /decorador_execution_time.py | 841 | 3.765625 | 4 | #Validar eficiencia del programa calculando tiempos de ejecucion
from datetime import datetime
#*args, **kwargs para enviar n cantidad de parametros
def execution_time(func):
def wrapper(*args, **kwargs):
initial_time = datetime.now()
func(*args, **kwargs)
final_time = datetime.now()
time_elapsed = final_time - initial_time
print(f"It took {time_elapsed.total_seconds()} seconds")
return wrapper
#Probando decorador
@execution_time
def random_func():
for _ in range(1,1000000):
pass
@execution_time
def add(a: int,b: int) ->int:
return a+b
@execution_time
def hello(name = 'Juan'):
print(f"Hello {name}")
if __name__ == '__main__':
print("Test 1")
random_func()
print("Test 2")
add(2,10)
print("Test 3")
hello()
hello("Sebastian")
|
ede3c3cac9ddd9701cd07f2b28202e320aed608a | keenhenry/euler | /euler21_30.py | 4,967 | 3.84375 | 4 | #!/usr/bin/python
""" Project Euler Solutions: Problem 21 - 30
"""
import sys
import time
import euler11_20
import euler1_10
import string
#import math
# function to generate fibonacci numbers: a generator
def fib():
a, b, i = 0, 1, 1
while True:
yield b, i
a, b, i = b, a+b, i+1
def ydigits(num=0):
'''A function to extract the digits of an integer.
'''
while num!=0:
d, num = num%10, num/10
yield d
def sigma(n=1):
'''A function to calculate the sum of the proper divisors of a positive integer n.
The idea is to factorize n first, then calculate the sum of proper divisors
'''
# A copy of original value of n
N = n
# initial prime factor
pf = 2
# a dictionary of prime factors -> {k: v} = {prime factor: frequency}
pfs = {}
# find the prime factors of a number
while n != 1:
if n % pf == 0: # n has prime factor pf
n /= pf
pfs[pf] = (pfs[pf]+1) if pfs.has_key(pf) else 1
else: # n has no prime factor pf; update pf to find new prime factor
pf += 1 if (pf < 3) else 2
# The sum of proper divisors
s = 1
for k, v in pfs.items():
s *= (k**(v+1) - 1) / (k - 1)
return (s-N) # sum of proper divisors
def p21(limit=10000):
'''Solution to problem 21
'''
def d(n):
'''d(n)
Calculate the sum of proper divisors of n.
'''
s = 1
facs = euler11_20.factorize(n)
for k in facs: s *= (k**(facs[k]+1) - 1)/(k-1)
return s - n
amicables = [True for x in xrange(limit)]
# prime numbers cannot be amicable numbers
# so we eliminate checking those numbers
for x in euler1_10.sieve(limit):
amicables[x] = False
# cross out non-amicable numbers
for x in xrange(220, limit):
if amicables[x]:
y = d(x)
amicables[x] = False if (d(y) != x or x == y) else True
# calculate the sum of amicable pairs and output
s = 0
for i in xrange(220, limit):
if amicables[i]: s += i
print s
def p22():
'''Solution to problem 22
'''
f = open('names.txt', 'r')
names = sorted([n.strip('"') for n in f.read().split(',')])
f.close()
# calculate total name scores
total, base = 0, ord('A')-1
for i in xrange(len(names)):
total += (i+1)*sum([ord(c)-base for c in names[i]])
print total
def p23(upper=28123):
'''Solution to problem 23
This solution can be further optimized. Think about how.
'''
nums = [True for i in xrange(upper+1)]
abundants = []
# Find abundant numbers first: abundant numbers can be odd and even!
# Watch out. Abundant numbers below 945 are all even! But above that,
# Odd abundants could occur
for i in xrange(12, upper+1):
if sigma(i) > i: abundants.append(i)
# Calculate the final sum
s = ((1+upper)*upper) / 2
for i in xrange(len(abundants)):
for j in xrange(i, len(abundants)):
n = abundants[i]+abundants[j]
if n <= upper and nums[n]:
s -= n
nums[n] = False
print s
def p24(p='0123456789'):
'''Solution to problem 24
I solved it by hand! Not that hard to do it!
'''
print '2783915460'
def p25():
'''Solution to problem 25
'''
for fn, i in fib():
if len(str(fn)) >= 1000:
print i
break
def p26():
'''Solution to problem 26
'''
d = 2
for i in xrange(2, 1000):
print 1.0 / i
print d
def p28(n=1001):
'''Solution to problem 28
'''
s = 0
for i in xrange(1, 501):
s += 4*(4*i*i + i + 1)
print (s+1)
def p29():
'''Solution to problem 29
Let's try brute force method first.
'''
nums = {}
for i in xrange(2, 101):
for j in xrange(2, 101):
num = i**j
if num not in nums: nums[num] = True
print len(nums)
def p30(upper_bound=354294):
'''Solution to problem 30
This solution is brute force. However, the tricky part is to determine
the upper bound for the search (How do you prove that it is the absolute upper bound?).
The upper bound used in this solution is just a simple guess (6 * 9^5 = 354294).
'''
s = 0 # set initial sum to zero
# the lower bound of the loop is also tricky,
# in this solution, this is also a guess, but it's a guess that makes sense.
for i in xrange(upper_bound, 1000, -1):
sum_of_5th_power_of_digits = 0
for j in ydigits(i):
sum_of_5th_power_of_digits += j**5
if i == sum_of_5th_power_of_digits:
#print i
s += i
print s
# A one-liner solution reference:
# print sum([n for n in xrange(1000,354294) if sum(int(i)**5 for i in str(n)) == n])
def main():
'''Main program of module euler21_30
'''
func_list = {
'p21': p21, 'p22': p22, 'p23': p23, 'p24': p24, 'p25': p25,
'p26': p26, 'p28': p28, 'p29': p29, 'p30': p30
}
if func_list.has_key(sys.argv[1]):
func_list[sys.argv[1]]()
else:
print 'No solution to', sys.argv[1]
|
dcd252960a1b08665c15f551c29bd9f9aacd0218 | johannabi/MA-ConceptMining | /MA-ConceptMining/inout/inputoutput.py | 3,476 | 3.6875 | 4 | import sqlite3 as sql
import re
import csv
def read_file_by_line(file):
"""
reads a text file line by line
:param file: path to file
:return: list of all lines
"""
word_list = list()
with open(file, mode='r', encoding='utf-8') as f:
for line in f:
line = line.strip()
word_list.append(line)
return word_list
def read_esco_csv(file, only_unigrams, synsets):
"""
reads a csv file containing esco skills
:param file: path to file
:param only_unigrams: True if you only want to collect unigram skills
:param synsets: True if you want to group skills by synsets
:return: list of skills or list of synsets
"""
if synsets:
synset_list = list()
else:
skills = list()
with open(file, newline='', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
next(reader, None) # skip header
for row in reader:
pref_label = row[4]
alt_labels = row[5]
synset = set()
if only_unigrams:
if ' ' not in pref_label:
synset.add(pref_label)
else:
synset.add(pref_label)
if len(alt_labels) > 0:
label_list = alt_labels.split('\n')
for l in label_list:
if only_unigrams:
if ' ' not in l:
synset.add(l)
else:
synset.add(l)
if synsets:
if len(synset) > 1: # process only synset with more than one member
synset_list.append(synset)
else:
skills.extend(synset)
if synsets:
return synset_list
else:
return skills
def read_ams_synsets(file, only_unigrams, synsets):
"""
:param file:
:param only_unigrams:
:param synsets:
:return:
"""
conn = sql.connect(file)
sql_select = """SELECT Synonyms, Orig_String FROM Categories"""
c = conn.cursor()
c.execute(sql_select)
rows = c.fetchall()
if synsets:
synsets = set()
for r in rows:
syns = r[0]
comp = r[1]
if syns is None:
continue
# collect als synonyms that are single-word-expressions
synset = set([s.lower() for s in syns.split(' | ') if ' ' not in s])
if only_unigrams:
if ' ' not in comp:
synset.add(comp.lower())
else:
synset.add(comp.lower())
if len(synset) > 1:
synsets.add(tuple(synset))
c.close()
return synsets
else:
skills = list()
for r in rows:
comp = r[1]
if only_unigrams:
if ' ' not in comp:
skills.append(comp.lower())
else:
skills.append(comp.lower())
c.close()
return skills
def read_jobads_content(file):
"""
reads all jobads from given sqlite file
:param file: path to file
:return: list of all jobads
"""
conn = sql.connect(file)
sql_select = """SELECT STELLENBESCHREIBUNG FROM jobs_textkernel"""
c = conn.cursor()
c.execute(sql_select)
rows = c.fetchall()
jobs = list()
for r in rows:
jobs.append(r[0])
return jobs
|
fff85242b8b8741f6738b916760a53767cb28f91 | BogdanFi/cmiN | /FII/L3/RN/1/sem/ex.py | 2,833 | 3.5 | 4 | #! /usr/bin/env python
import datetime
import json
import math
import re
import urllib2
import sys
import numpy
def ex1():
name = raw_input("Nume Prenume: ")
age = raw_input("Varsta: ")
chunks = name.split(" ")
if len(chunks) != 2:
print("[x] Doar nume prenume.")
exit()
last, first = [part.capitalize() for part in chunks]
if not age.isdigit() or not int(age):
print("[x] Varsta invalida")
exit()
age = int(age)
with open("out.txt", "w") as fout:
fout.write("{}\n".format(first))
fout.write("{}\n".format(len(last)))
year = datetime.datetime.now().year + (100 - age)
fout.write("{}\n".format(year))
def prime(nr):
if nr < 2:
return False
if nr == 2:
return True
if not nr & 1:
return False
crt = 3
sq = math.sqrt(nr)
while crt <= sq:
if not nr % crt:
return False
crt += 2
return True
def ex2():
nr = int(sys.argv[1])
print("{}".format(prime(nr)))
def ex3():
url = "http://profs.info.uaic.ro/~rbenchea/rn/Latin-Lipsum.txt"
regex = r"\w+"
text = urllib2.urlopen(url).read()
words = re.findall(regex, text, re.I)
words = sorted(words, key=lambda arg: arg.lower())
with open("out.txt", "w") as fout:
for word in words:
fout.write("{}\n".format(word))
def ex4():
m = [
[1, 2, 3, 4],
[11, 12, 13, 14],
[21, 22, 23, 24],
]
v = [
[2],
[-5],
[7],
[10]
]
md = (len(m), len(m[0]))
vd = (len(v), len(v[0]))
res = []
for _ in range(md[0]):
res.append([0] * vd[1])
for i in range(md[0]):
for j in range(vd[1]):
cell = 0
for k in range(md[1]):
print(m[i][k], v[k][j]) ####
cell += m[i][k] * v[k][j]
print(i, j, cell)
res[i][j] = cell
print(json.dumps(res, indent=4))
def ex5():
# 1
m = [
[1, 2, 3, 4],
[11, 12, 13, 14],
[21, 22, 23, 24],
]
v = [
[2],
[-5],
[7],
[10]
]
m = numpy.array(m)
v = numpy.array(v)
print(m.dot(v))
print(m[:2, -2:])
print(v[-2:])
# 2
dim = (1, 4)
v1 = numpy.random.random(dim)
v2 = numpy.random.random(dim)
print(v1, v2)
s1 = numpy.sum(v1)
s2 = numpy.sum(v2)
print("Sum", (v1 if s1 > s2 else v2))
print("Add", v1 + v2)
print("Mul", v1 * v2)
print("Sqrt", numpy.sqrt(v1))
print("Sqrt", numpy.sqrt(v2))
# 3
dim = (5, 5)
m = numpy.random.random(dim)
print(m)
print(m.T)
print(numpy.linalg.inv(m))
print(numpy.linalg.det(m))
# 4
v = numpy.random.random((5, 1))
print(m.dot(v))
ex1()
ex2()
ex3()
ex4()
ex5()
|
72a5e589104c67da59eea40c758dd9dc0bcd591c | ulyssesorz/data-structures | /oj/是否是二叉搜索树.py | 2,059 | 3.84375 | 4 | """
按照层次遍历给出一颗二叉搜索树,例如:3 1 4 # # 2 #,以空格分开,其中#号代表对应的节点处为空
"""
class Node:
def __init__(self,val):
self.left=None
self.right=None
self.val=val
def level_insert(root,val): #按照题目所给还原该树
if root is None: #空树,生成根节点
root=Node(val)
else: #层次遍历的思想,利用队列
queue=[]
queue.append(root)
while queue:
current=queue.pop(0)
if current.left is None:
if val=='#':
current.left = Node(None)
else:
current.left = Node(val)
break #插入后break,否则同层其他左节点也会被插入data
elif current.right is None:
if val == '#':
current.right = Node(None)
else:
current.right = Node(val)
break
else:
queue.append(current.left)
queue.append(current.right)
return root
def isBst(root,min,max):
if root is None or root.val is None: #遍历到叶节点还未出现矛盾,返回True
return True
if int(root.val)<min or int(root.val)>max:
return False
return isBst(root.left,min,int(root.val)-1) and isBst(root.right,int(root.val)+1,max) #递归地比较每一个节点,注意最大、小值的变化
#确保每个左节点不大于父节点,每个右节点不小于父节点
if __name__=='__main__':
list=input().split()
root=None
for i in list:
root=level_insert(root,i)
list=[int(i) for i in list if i!='#'] #除去#
max_val=max(list)+1
min_val=min(list)-1
if isBst(root,min_val,max_val):
print('True')
else:
print('False')
|
11377403f75dcfce2ef674afe462854b158b8c30 | globalghost1/Secure_ERP_Python_project | /view/terminal.py | 4,966 | 3.765625 | 4 | import os
import datetime
from copy import deepcopy
def clean():
os.system("cls || clear")
show_now = datetime.datetime.now().strftime("%A, %d-%m-%Y\nTime: %H:%M:%S ")
print('Today is:', show_now)
print("\n")
def print_menu(title, list_options):
"""Prints options in standard menu format like this:
Main menu:
(1) Store manager
(2) Human resources manager
(3) Inventory manager
(0) Exit program
Args:
title (str): the title of the menu (first row)
list_options (list): list of the menu options (listed starting from 1, 0th element goes to the end)
"""
print(title)
for number, element in enumerate(list_options):
print(f"{number}) {element}")
print()
def print_message(message):
"""Prints a single message to the terminal.
Args:
message: str - the message
"""
print(message)
def print_general_results(result, label):
"""Prints out any type of non-tabular data.
It should print numbers (like "@label: @value", floats with 2 digits after the decimal),
lists/tuples (like "@label: \n @item1; @item2"), and dictionaries
(like "@label \n @key1: @value1; @key2: @value2")
"""
if type(result) == float:
formatted_float = "{:.2f}".format(result)
print(f'{label}: {formatted_float}')
elif type(result) == int:
print(f'{label}: {result} ')
elif type(result) == list or type(result) == tuple:
print(f'{label}: ')
k = 1
for i in result:
print(f'{i} ', end="")
if k != len(result):
print(f'; ', end="")
k += 1
print()
elif type(result) == dict:
print(label)
k = 1
for elem in result:
print(f'{elem}: {result[elem]}', end="")
if k != len(result):
print(f'; ', end="")
k += 1
print()
print()
else:
print(f"{label}: {result}")
# /--------------------------------\
# | id | product | type |
# |--------|------------|----------|
# | 0 | Bazooka | portable |
# |--------|------------|----------|
# | 1 | Sidewinder | missile |
# \-----------------------------------/
def print_table(headers, table):
"""Prints tabular data like above.
Args:
headers: list of headers - headers to print out on top of table
table: list of lists - the table to print out
"""
table = populate_index_rows(headers, table)
column_widths = count_column_widths(table)
table_width = count_table_width(column_widths)
for index, rows in enumerate(table):
if index == 0:
print(f"/" + "-" * (table_width - 1), end="\\\n")
else:
print(f"|", end="")
for col_index, column in enumerate(rows):
print("-" * (column_widths[col_index] + 1) + "|", end="")
print()
if index == 0:
print("|", end="")
for col_index, column in enumerate(rows):
print(f"{column.center(column_widths[col_index])}", end=" |")
print()
else:
print("|", end="")
for col_index, column in enumerate(rows):
print(f"{column.center(column_widths[col_index])}", end=" |")
print()
if index == len(table) - 1:
print(f"\\" + "-" * (table_width - 1), end="/\n")
def get_input(label):
"""Gets single string input from the user.
Args:
label: str - the label before the user prompt
"""
return input(label)
def get_inputs(labels):
"""Gets a list of string inputs from the user.
Args:
labels: list - the list of the labels to be displayed before each prompt
"""
answer_list = []
for label in labels:
answer = input(label)
answer_list.append(answer)
return answer_list
def print_error_message(message):
"""Prints an error message to the terminal.
Args:
message: str - the error message
"""
print(message)
def count_column_widths(table):
columns_max_width = []
for row_index, rows in enumerate(table):
for index, column in enumerate(rows):
if row_index == 0:
columns_max_width.append(len(rows) + 1)
if len(column) >= columns_max_width[index]:
columns_max_width[index] = len(column) + 1
return columns_max_width
def count_table_width(columns_max_width):
return sum(columns_max_width) + (len(columns_max_width) * 2)
def populate_index_rows(headers, table):
indexed_table_with_headers = deepcopy(table)
copied_headers = deepcopy(headers)
indexed_table_with_headers.insert(0, copied_headers)
for index, row in enumerate(indexed_table_with_headers):
if index == 0:
row.insert(0, "#")
else:
row.insert(0, str(index))
return indexed_table_with_headers
|
943aae59bfd26bfb27efddb3971066109da2a003 | taras16/Python_learn | /ATV/Numbers.py | 147 | 4 | 4 | num1 = 30
num2 = 45
num3 = num1 + 10
print(num3)
print(num1 + num2 )
print(num1 * num2 +10)
print(num2/3)
# float
x1 = 6
x2 = 4
print(x1/x2)
|
18137f736b9bc8cc477d8742d7e9c1d48b8bbb0f | BALURAAM/sc | /6.py | 123 | 3.671875 | 4 | def bala(a,b):
if(b==0):
return a
else:
return bala(b,a%b)
a = int(input())
b= int(input())
print (bala(a,b))
|
cf80cb9a836d8dc7b75ab622b02a92367e4eab4f | jingong171/jingong-homework | /刘恺诚/2017310423第四次作业金工17-1刘恺诚/骰子.py | 309 | 3.640625 | 4 | class Die():
"""A small Die"""
def __init__(self,sides=6):
self.sides=sides
def roll_die(self):
print(int(randint(1,self.sides)))
from random import randint
sides=int(input("请输入骰子的面数"))
myDie=Die(sides)
for i in range(1,11):
myDie.roll_die()
|
d7a89f675a7df26559f92547984848f7dd11d50f | i3ef0xh4ck/mylearn | /Python基础/day015/08 random模块.py | 1,664 | 3.640625 | 4 | # random随机数
import random
# print(random.random()) #0~1之间的小数
# print(int(random.random() * 10))
# print(random.randint(1,5)) #随机范围整数,包含边界
# print(random.randrange(0,10,2)) #随机偶数
# print(random.randrange(1,11,2)) #随机奇数
# print(random.choice([1,2,"ww",22,33])) #从可迭代对象随机一个元素
# print(random.choice("12345")) #从可迭代对象随机一个元素
# print(random.choices([1,2,"ww",22,33],k=2)) #随机多个,会出现重复元素
# print(random.sample([1,2,3,4,5,6,7],k=2)) #随机多个不重复,不会出现重复元素
# lst = [1,2,3,4,5,6,7,8,3]
# lst.sort()
# print(lst)
# random.shuffle(lst) #打乱顺序
# print(lst)
# 使用随机数实现一个5位数的验证码(字母,数字)
# 1.ASCII码表
# 65-90是大写字母,通过chr()获取对应的内容
# 97-122是小写字母,通过chr()获取对应的内容
# 2.使用for循环执行5圈,将获取的内容累加起来,最后输出
# a = chr(random.randint(65,90))
# b = chr(random.randint(97,122))
# c = random.randint(0,9)
# # d = random.choice([chr(random.randint(65,90)),chr(random.randint(97,122)),random.randint(0,9)])
# import random
# s = ""
# for i in range(5):
# s += str(random.choice([chr(random.randint(65,90)),chr(random.randint(97,122)),random.randint(0,9)]))
# print(s)
# lst = list()
# lst.extend(list(range(65, 91)))
# lst.extend(list(range(48, 58)))
# lst.extend(list(range(97, 123)))
# s = ""
# for i in range(5):
# s = s + str(chr(random.choice(lst)))
# print(s)
# import random
# print("".join(random.choices([chr(i) for i in range(122) if chr(i).isalnum()],k=5))) |
3b492dd41354983b222c219debde58ce0f0e5168 | Gayatri424/Assignment-supportgenie | /Supportgenie/Selected_Agents.py | 1,530 | 3.84375 | 4 | import random
from Agent_data import Agent
n=int(input("Enter Number Of Agents :")) #Enter No of Agents
selection_mode=int(input("Enter Number Of Selection mode :")) #Selectionmode 1.All available 2.Leastbusy 3.Random
j=0
agents=[] #Enter Agent Data here
while j<n:
agent=Agent(eval(input()),input(),[item for item in input("Enter the list items : ").split()])
agents.append(agent)
j=j+1
def Agent_selection(agents,selection_mode): # Agent Selection function
selected_agents=[]
issue="sales" #issues
i=0
sm=selection_mode
max=agents[0].available_since
if sm==1: # All available
while i<n:
if agents[i].is_available=="True":
print(agents[i].is_available)
selected_agents.append("agent"+str(i+1))
i=i+1
return selected_agents
elif sm==2: #Least busy mode
i=0
least_busy_agent=''
while i<n:
if agents[i].is_available==True and issue in agents[i].roles:
selected_agents.append("agent"+str(i+1))
if agents[i].available_since<=max:
max=agents[i].available_since
least_busy_agent="agent"+str(i+1)
i=i+1
return least_busy_agent
elif sm==3: #Random mode
print("sm==3")
while i<n:
if agents[i].is_available=="True" and issue in agents[i].roles:
selected_agents.append("agent"+str(i+1))
i=i+1
return random.choice(selected_agents)
else:
print("Please enter a valid Selection Mode ")
sa=Agent_selection(agents,selection_mode) #calling Agent selection function
print(sa) |
22df2a801d292cf1efa815cc1786ae25ee45c9d7 | shalinichaturvedi20/moreExercise | /question5.py | 434 | 4.21875 | 4 | # fact=int(input("enter the number"))
# i=0
# while i<fact:
# if fact < 0:
# print("it is factorial number")
# elif fact == 0:
# print("The factorial of 0 is 1")
# else:
# for i in range(1,fact + 1):
# fact = fact*i
# print("The fact of",fact,"is",fact)
num = int(input("enter a number: "))
fac = 1.
for i in range(1, num + 1):
fac = fac * i
print("factorial of ", num, " is ", fac) |
fc37caa5d7f3f89f3dbff1c7d9ba9a5131c4593c | redixhumayun/ctci | /RADP/Robot.py | 1,290 | 4.03125 | 4 | #! /usr/bin/env python3
import pdb
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def findPath(grid, row, column, pathArray, failedPoints):
'''
findPath is a function to help a robot move through a grid
Return type: grid of path
'''
# pdb.set_trace()
try:
current = grid[row][column]
except IndexError:
return False#robot has stepped out of bounds
point = Point(row, column) #creating point object here
if point in failedPoints:
return False
if current == 2:
#robot reached end
return True
if current == 0:
#robot cannot go on this path
failedPoints.append(point)
return False
pathArray.append(point)
result = findPath(grid, row, column+1, pathArray, failedPoints) or \
findPath(grid, row+1, column, pathArray, failedPoints)
return result
if __name__ == "__main__":
grid = [[1,1,0,1],[1,1,1,0],[1,0,1,1],[0,1,1,0], [1,1,1,0], [1,0,1,2]]
#0 - robot cannot go on
#1 - robot can go on
#2 - end point
pathArray = []
failedPoints = []
result = findPath(grid, 0, 0, pathArray, failedPoints)
if result is True:
print("Found path")
else:
print("Could not find path")
|
7021403de9813d4c888e02045dec85a3f8556f7b | Yobretaw/AlgorithmProblems | /EPI/Python/Recursion/16_1_tower_of_hanoi_problem.py | 1,148 | 4.03125 | 4 | import sys
import os
import math
"""
You are given n rings. The i-th ring has diamter i. The rings are initially
in sorted order on a peg(P1), with the largest ring at the bottom. You are
to transfer these rings to another peg(P2), which is initially empty. You
have a third peg(P3), which is initially empty. The only operation you can
do is taking a single ring from the top of one peg and placing it on the top
of another peg; you must never place a bigger ring above a smaller ring.
Exactly n rings on P1 peg need to be transferred to P2, possibly using P3
as an intermediate, subject to the stacking constraint. Write a function
that prints a sequence of operations that transfers all rings from P1 to
P3.
"""
def transfer(n):
transfer_help(n, 0, 1, 2)
def transfer_help(n, from_peg, to_peg, intermediate_peg):
if n <= 0:
return
transfer_help(n - 1, from_peg, intermediate_peg, to_peg)
print 'Move ring %s from peg %s to peg %s' % (str(n), str(from_peg), str(to_peg))
transfer_help(n - 1, intermediate_peg, to_peg, from_peg)
if __name__ == '__main__':
transfer(5)
|
357636e66c64e3d53f47291fb9bf593d735ec2c1 | rrssantos/Python | /Python39/teste ro.py | 309 | 4.125 | 4 | print("Exercicio 13")
h13 = float(input("Digite sua altura: "))
s13 = input("Você é homem ou mulher? (m/h")
if s13 == "m" or s13 == "M" :
print(f"Se voce for homem seu peso ídeal é de: {(72.7*h13)-58:6.2f}")
else :
print(f"Se voce for mulher seu peso ídeal é de: {(62.7*h13)-44.7:6.2f}")
|
6f81993c484b04f440943cdd0acdf3a988de6fde | ZeroxZhang/pylearning | /inheritance&override.py | 583 | 3.90625 | 4 | class Father:
def eat(self):
surname = "zhang"
print("Father can eat")
class Mother:
def cook(self):
print("mom can cook food")
#son继承father的属性,在类括号中写入要继承属性的类名
class Son(Father,Mother):#继承的时候用逗号隔开多个类
def eat(self):
print("这句话重载了father eat的方法")
def cook(self):
print("mom does not like cook")
#如果继承类之后,这个类有相同的方法,那么则会重载父类的方法
littlezerox = Son()
littlezerox.eat()
littlezerox.cook()
|
83421b5edaa402adc3a5eaaba85edf6d8cbb8406 | abhishek-jana/Leetcode-Solutions | /dynamic_programming/300-Longest-Increasing-Subsequence.py | 3,136 | 3.875 | 4 | '''
Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
Note:
There may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n^2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
'''
class Solution:
# Time O(n^2)
# Space O(n)
def lengthOfLIS(self,nums):
max_count = 0
LIS = []
for i in range(len(nums)-1):
LIS.append(nums[i])
for j in range(i+1,len(nums)):
if LIS[-1]<nums[j]:
LIS.append(nums[j])
max_count = max(max_count,len(LIS))
LIS = []
return max_count
# Using Dynamic Programming
# Time O(n^2)
# Space O(n)
def lengthOfLIS2(self,nums):
dp = [1]*len(nums)
for i in range(len(nums)):
for j in range(i):
if nums[i]>nums[j] and dp[i]<dp[j]+1:
dp[i] = dp[j]+1
max_length = 0
for i in range(len(nums)):
max_length = max(max_length,dp[i])
return max_length
# lis returns length of the longest increasing subsequence
# in arr of size n
def lis(arr):
n = len(arr)
# Declare the list (array) for LIS and initialize LIS
# values for all indexes
lis = [1]*n
# Compute optimized LIS values in bottom up manner
for i in range (1 , n):
for j in range(0 , i):
if arr[i] > arr[j] and lis[i]< lis[j] + 1 :
lis[i] = lis[j]+1
# Initialize maximum to 0 to get the maximum of all
# LIS
maximum = 0
# Pick maximum of all LIS values
for i in range(n):
maximum = max(maximum , lis[i])
return maximum
# end of lis function
def lengthOfLIS(nums):
max_count = 0
LIS = []
for i in range(len(nums)-1):
LIS.append(nums[i])
for j in range(i+1,len(nums)):
if LIS[-1]<nums[j]:
LIS.append(nums[j])
max_count = max(max_count,len(LIS))
LIS = []
return max_count
array = [10,22,9,33,21,50,41,60,80]
import timeit
from timeit import Timer
t1 = Timer("lis([3,10,2,1,20])", "from __main__ import lis")
print (t1.timeit(number=100000),"milliseconds")
t2 = Timer("lengthOfLIS([3,10,2,1,20])", "from __main__ import lengthOfLIS")
print (t2.timeit(number=100000),"milliseconds")
#print (Solution().lengthOfLIS2([3,10,2,1,20] ))
# Binary Search
def lengthOfLIS(self, nums):
tails = [0] * len(nums)
size = 0
for x in nums:
i, j = 0, size
while i != j:
m = (i + j) / 2
if tails[m] < x:
i = m + 1
else:
j = m
tails[i] = x
size = max(i + 1, size)
return size
# Taken from https://leetcode.com/problems/longest-increasing-subsequence/discuss/74824/JavaPython-Binary-search-O(nlogn)-time-with-explanation
|
44db98b01565aaa9ce17491282490483d9968528 | Jackelyneg/Python-challenge | /budget.py | 1,853 | 3.921875 | 4 | # read csv
import os
import csv
budget_csv = os.path.join("..", "Resources", "budget_data.csv")
total_months = []
total_profit = []
Average_change = []
Monthly_profit = []
with open(budget_csv) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=",")
#skips column name
skip_header = next(csv_reader)
#end here
#Iterates through rows
for row in csv_reader:
total_months.append(row[0])
total_profit.append(int(row[1]))
#end here
#Iterates through total profits
for i in range(len(total_profit)-1):
#Difference between months and appends montly prfot change
Average_change.append(total_profit[i+1]-total_profit[i])
#end here
#Calculates the min and max
Month_max = max(Average_change)
Month_min = min(Average_change)
#Assigning max and min to appropriate month, adding 1 to asscoiate with changing months
max_formonth = Average_change.index(max(Average_change))+1#
min_formonth = Average_change.index(min(Average_change))+1
print(f"total months:{len(total_months)}")
print(f"total profit:{sum(total_profit)}")
print(f"Average Change:{round(sum(Average_change)/len(Average_change),2)}")
print(f"Greatest Increase in profits:{total_months[ max_formonth]},(${Month_max})")
print(f"Greatest Increase in profits:{total_months[ min_formonth]},(${Month_min})")
#end code
#resources:
#https://www.w3schools.com/python/ref_list_index.asp
#https://blog.finxter.com/python-indexerror-list-index-out-of-range/#:~:text=The%20error%20%E2%80%9Clist%20index%20out,index%20is%20out%20of%20range.
#https://careerkarma.com/blog/python-typeerror-list-object-cannot-be-interpreted-as-an-integer/
#https://evanhahn.com/python-skip-header-csv-reader/
|
c916098a8b0247d4966841b39855da45d6448319 | Prasan92/mywork | /python_AtoZ/decorator.py | 579 | 3.765625 | 4 |
def deco(f):
#check no. of arguments
def inner(*args):
try:
if len(args) != 2:
raise Exception ("cannot pass more then two arguments")
a,b=args
if not (type(a) in [int,float] and type(b) in [int,float]):
raise Exception ("pass either int or float")
if b==0:
raise Exception ("divisible value shouldn't be zero")
return f(*args)
except Exception as e:
return e
return inner
@deco
def div(a,b):
return (a/b)
print(div(1,"3"))
|
5647eed9b4a815e17b5b7fc7ed9c57d794ceee3f | OvchinnikovaNadya/coursePython1 | /Example_5_2_compare.py | 251 | 3.515625 | 4 | def compare(S1, S2):
ngrams = [
S1[i:i + 3] for i in range(len(S1))
]
count = 0
for ngram in ngrams:
count += S2.count(ngram)
return count / max(len(S1), len(S2))
a = compare('стол', 'стул')
print(str(a))
|
32fb7abd131562a992181b0fb4984e32e3b56fbe | crisdata/Proyecto-Agenda | /contacts.py | 6,704 | 3.6875 | 4 | # -*- coding: utf-8 -*-
import os
import csv
# Clases
class Contacto:
def __init__(self, nombre, telefono, email):
# variables inicializadas en publicas
self.nombre = nombre
self.telefono = telefono
self.email = email
class Agenda:
def __init__(self):
# Guarda una variable privada
self._contactos = []
# Metodo para Agregar
def add(self, nombre, telefono, email):
contacto = Contacto(nombre, telefono, email)
# append agrega datos al final de la lista
self._contactos.append(contacto)
self._save()
# Metodo para actualizar
def update(self, nombre):
for idx, contacto in enumerate(self._contactos):
if contacto.nombre.lower() == nombre.lower():
command = str(raw_input('''
--------------------------------
* ¿Qué Vamos a Actualizar? *
* *
* [an] = Nombre *
* [at] = Telefono *
* [ae] = E-mail *
* [to] = Todo *
* [xx] = Salir *
---------------------------------
'''))
if command == 'an':
newName = str(raw_input('Ingresa el nuevo nombre: '))
newContact = Contacto(newName, contacto.telefono, contacto.email)
self._contactos[idx] = newContact
self._save()
print('*** NOMBRE ACTUALIZADO ***')
break
elif command == 'at':
newPhone = str(raw_input('Ingresa el nuevo numero de telefono: '))
newContact = Contacto(contacto.nombre, newPhone, contacto.email)
self._contactos[idx] = newContact
self._save()
print('*** TELEFONO ACTUALIZADO ***')
break
elif command == 'ae':
newEmail = str(raw_input('Ingresa el nuevo E-mail: '))
newContact = Contacto(contacto.nombre, contacto.telefono, newEmail)
self._contactos[idx] = newContact
self._save()
print('*** E-MAIL ACTUALIZADO ***')
break
elif command == 'to':
newName = str(raw_input('Ingresa el nuevo nombre: '))
newPhone = str(raw_input('Ingresa el nuevo numero de telefono: '))
newEmail = str(raw_input('Ingresa el nuevo E-mail: '))
newContact = Contacto(newName, newPhone, newEmail)
self._contactos[idx] = newContact
self._save()
print('*** CONTACTO ACTUALIZADO ***')
break
elif command == 'xx':
print('SALIENDO...')
break
else:
print('Comando no encontrado')
break
else:
self._not_found()
# Metodo para eliminar por nombre
def delete(self, nombre):
for idx, contacto in enumerate(self._contactos):
# Comparamos nombre del contacto en minuscula y mayuscula
if contacto.nombre.lower() == nombre.lower():
del self._contactos[idx]
self._save()
break
# Metodo para buscar
def search(self, nombre):
for contacto in self._contactos:
# Comparamos nombre del contacto en minuscula y mayuscula
if contacto.nombre.lower() == nombre.lower():
self._print_contact(contacto)
break
# Este else pertenece al for
else:
self._not_found()
# Metodo para mostrar
def show_all(self):
for contacto in self._contactos:
self._print_contact(contacto)
# Escribir a disco (exportar)
def _save(self):
with open('contactos.csv', 'w') as f:
writer = csv.writer(f)
# primera columna de valores
writer.writerow( ('nombre', 'telefono', 'email'))
for contacto in self._contactos:
writer.writerow( (contacto.nombre, contacto.telefono, contacto.email))
# Metodo para mostrar contactos creados
def _print_contact(self, contacto):
print('*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-')
print('Nombre: {}'.format(contacto.nombre))
print('Telefono: {}'.format(contacto.telefono))
print('Email: {}'.format(contacto.email))
print('*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-')
def _not_found(self):
print('*********************')
print('* ¡ No Encontrado ! *')
print('*********************')
# Interfaz
def main():
# Instancias
agenda = Agenda()
# importar CSV
with open('contactos.csv', 'r') as f:
reader = csv.reader(f)
for idx, row in enumerate(reader):
if idx == 0:
continue
agenda.add(row[0], row[1], row[2])
while True:
command = str(raw_input('''
*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.
* ¿Me diras que hacer? *
* *
* [a] Agregar Contacto *
* [b] Modificar Contacto *
* [c] Buscar un Contacto *
* [d] Eliminar Contacto *
* [e] Mostrar Contactos *
* [x] Cerrar *
* *
*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.
'''))
if command == 'a':
nombre = str(raw_input('Digita el nombre: '))
telefono = str(raw_input('Digita el Telefono: '))
email = str(raw_input('Digita el Email: '))
# Metodos
agenda.add(nombre, telefono, email)
elif command == 'b':
nombre = str(raw_input('Digita el nombre: '))
# Metodo
agenda.update(nombre)
elif command == 'c':
nombre = str(raw_input('Digita el nombre: '))
# Metodo
agenda.search(nombre)
elif command == 'd':
nombre = str(raw_input('Digita el nombre: '))
# Metodo
agenda.delete(nombre)
elif command == 'e':
agenda.show_all()
elif command == 'x':
break
else:
print('Comando no encontrado')
if __name__ == '__main__':
os.system('clear')
print('B I E N V E N I D O A L A A G E N D A V 0.1')
main()
|
ef0a97be6c731097640016f271ec139fdb565087 | chenxy3791/leetcode | /No0543-diameter-of-binary-tree.py | 3,584 | 4.28125 | 4 | """
Given a binary tree, you need to compute the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two
nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/diameter-of-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
"""
解题思路1:
从root来看,存在最长路径经过自己(case1)和不经过自己(case2)两种情况
case1: 左子树深度+右子树深度+1
case2: max(左子树 diameter, 右子树 diameter)
Hence, the final result is max{左子树深度+右子树深度+1, 左子树 diameter, 右子树 diameter}
Can be solved with recursive method, but seems too costly.
解题思路2:
很显然,最长的路径的一端必定是树的最深的叶子节点--不仅限于一个。
可以先正向地从root出发找到最深的某个叶子结点,
然后以该叶子节点作为树的根节点逆向搜索求该树的深度。
但是这样要求重构这颗树--因为要以该叶子节点为新的root?这个是不是会比较麻烦。
解题思路3:
"""
import math
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# Two slow. Win only 6% python3 delivery!
def getdepth(self, root: TreeNode):
# Not exactly the depth of tree, the number of edges from the root to
# the deepest leaf
if root == None:
return 0
if root.left == None:
depleft = 0
else:
depleft = 1 + self.getdepth(root.left)
if root.right == None:
depright = 0
else:
depright = 1 + self.getdepth(root.right)
return max(depleft,depright)
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if root == None:
return 0
d0 = 0
if root.left != None:
d0 = d0 + self.getdepth(root.left) + 1
if root.right != None:
d0 = d0 + self.getdepth(root.right) + 1
dleft = self.diameterOfBinaryTree(root.left)
dright= self.diameterOfBinaryTree(root.right)
#print(d0, dleft, dright)
return max(d0,max(dleft,dright))
if __name__ == '__main__':
import time
import numpy as np
sln = Solution()
# # testcase1
# print('\ntestcase1 ...')
# prices = [7,1,5,3,6,4]
# tStart= time.time()
# print(sln.maxProfit(prices))
# tStop = time.time()
# print('tStart={0}, tStop={1}, tElapsed={2}(sec)'.format(tStart, tStop, tStop-tStart))
# # testcase2
# print('\ntestcase2 ...')
# prices = [7,6,4,3,1]
# tStart= time.time()
# print(sln.maxProfit(prices))
# tStop = time.time()
# print('tStart={0}, tStop={1}, tElapsed={2}(sec)'.format(tStart, tStop, tStop-tStart))
# # testcase3
# print('\ntestcase3 ...')
# n = 100000
# a = np.random.randint(0,1000,(n,))
# prices = a.tolist()
# tStart= time.time()
# print(sln.maxProfit(prices))
# tStop = time.time()
# print('tStart={0}, tStop={1}, tElapsed={2}(sec)'.format(tStart, tStop, tStop-tStart))
|
441b927481354faf54b2a7b163e49c9ccd7e756b | pnkumar9/linkedinQuestions | /smallestMissingInt.py | 358 | 3.671875 | 4 | #!/usr/local/bin/python3
#Given an array of ints,
#return the smallest positive integer that doesn't appear in the list
#A = [ 1, 13, 3, 4, 7 ]
A = [ 1, 2, 3 ]
#A = [ -1, -3 ]
#A = [ 1, 3, 6, 4, 1, 2 ]
A.sort()
i=1
false=0
true=1
while (i <= len(A)+1):
found=false
for val in A:
if(i==val):
found=true
if (found == false):
print(i)
i = i + 1
|
6ba69e65d6a2f5fdb6f081b0f0f26957e786289d | plzprayme/study-python-algorithm-interview | /ch7_sequential/q1.py | 501 | 3.671875 | 4 | test_cases = [
dict(nums=[2,7,11,15], target=9),
]
def main(test_case):
nums = test_case["nums"]
target = test_case["target"]
for idx, num in enumerate(nums):
for idx2, num2 in enumerate(nums[idx+1:]):
if num + num2 == target:
return idx, idx + idx2 + 1
return False
# return is_palindrome(char_num_list)
def start(test_cases):
for idx, case in enumerate(test_cases):
print(f"case {idx}: {main(case)}")
start(test_cases)
|
d2b0faddef8801724de6bc9aace4bdea074ce16b | rakaar/algo-ds-notes | /insertion_sort.py | 1,092 | 4.03125 | 4 | arr = [5,2,4,6,1,3]
# insert sort
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
# the idea is to keep pushing the key inside the sorted array till it finds it proper place
while j >=0 and arr[j] > key:
arr[j], arr[j+1] = key, arr[j]
j -= 1
print(arr)
# optimised insertion
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
# the idea is to keep pushing the key inside the sorted array till it finds it proper place
# but u can take advantage of the fact that u have to push the number inside a sorted array
# so basically u look to insert at the middle, if fail then go to the left half or the right half accordingly
# hence reducing half the places
## but the problem with inserting by binary search is that it requires shifting all the elements to the right,
# which is an expensive job in sense that it again leads to n^2, because in worst u shift all the elements to right
while j >=0 and arr[j] > key:
arr[j], arr[j+1] = key, arr[j]
j -= 1
print(arr)
print(arr) |
7580f441c2898f9de3b492b8a3ef0e2900eca26c | ivenpoker/Python-Projects | /Projects/Project 0/Strings/string-validators.py | 1,442 | 4.34375 | 4 | #!/usr/bin/env python3
"""
Program purpose: Validates characters in the string.
Program Author : Happi Yvan
Author email : [email protected]
"""
def process(_str):
print("\n\tIs there any alphanumeric character: ", end="")
if any(c.isalnum() for c in _str):
print("True")
else:
print("False")
print("\tIs there any alphabetic character: ", end="")
if any(c.isalpha() for c in _str):
print("True")
else:
print("False")
print("\tIs there any digit: ", end="")
if any(c.isdigit() for c in _str):
print("True")
else:
print("False")
print("\tIs there is any lower character: ", end="")
if any(c.islower() for c in _str):
print("True")
else:
print("False")
print("\tIs there any upper character: ", end="")
if any(c.isupper() for c in _str):
print("True")
else:
print("False")
# print(any(c.isalnum() for c in _str))
# print(any(c.isalpha() for c in _str))
# print(any(c.isdigit() for c in _str))
# print(any(c.islower() for c in _str))
# print(any(c.isupper() for c in _str))
def main():
user_str = input("\n\tEnter a string: ")
process(user_str)
if __name__ == "__main__":
print("\n\t==========[ PROGRAM: Validate string ]========")
main() |
6e4fd97f950e1e19d04cdbbfc11a04adc119a098 | DHRUVSAHARAN/python- | /ch 5/practice_6.py | 327 | 3.5 | 4 | favlang = {}
a = input("enter your favorite lang srishti :\n")
b = input("enter your favorite lang shivan :\n")
c = input("enter your favorite lang aarav :\n")
d = input("enter your favorite lang dawik :\n")
favlang [ "srishti"] = a
favlang [ "shivan"] =b
favlang [ "aarav"]=c
favlang [ "dawik "]=d
print (favlang)
|
a30685ea83282f07eb0047349e1fad35d3253298 | salaschen/ACM | /Leetcode/2144_MinCostBuyCandies/sol.py | 582 | 3.921875 | 4 | '''
Prob: 2144 - Easy
Author: Ruowei Chen
Date: 26/Feb/2022
'''
class Solution:
def minimumCost(self, cost: [int]) -> int:
cost = sorted(cost, reverse=True)
result = 0
clen = len(cost)
i = 0
# at least three candies left in the loop
while i < (clen-2):
result += (cost[i] + cost[i+1])
i += 3
result += sum(cost[i:])
return result
### test ###
s = Solution()
cost = [1,2,3]
print(s.minimumCost(cost))
cost = [6,5,7,9,2,2]
print(s.minimumCost(cost))
cost = [5,5]
print(s.minimumCost(cost))
|
9bf429830641604a4fc1706980b3fe92f9a8dc24 | alexandraback/datacollection | /solutions_2645486_0/Python/rishig/b.py | 825 | 3.59375 | 4 | from library import *
from itertools import *
# given pairs return the key corresponding to the greatest value
def argmax(pairs):
return max(pairs, key= lambda x: x[1])[0]
# given values return the index of the greatest value
def argmax_index(values):
return argmax(enumerate(values))
def recstep(start, end, E, R, V):
assert end >= R
l = len(V)
assert end-start <= l*R
if end-start == l*R:
return 0
ind = argmax_index(V)
endl = min(E, start+R*ind)
startr = max(0, end-R*(l-ind))
return (endl-startr)*V[ind] + recstep(start, endl, E, R, V[:ind]) + recstep(min(startr+R,E), end, E, R, V[ind+1:])
f = file('b.in1','r')
T = readint(f)
for case in range(1,T+1):
E,R,N = readints(f)
V = readints(f)
ans = recstep(E, R, E, R, V)
print 'Case #%d: %d' % (case, ans)
|
446db15c854e44602a5aa9f0964f99be20fe5d25 | IvanWoo/coding-interview-questions | /puzzles/number_of_boomerangs.py | 1,450 | 3.890625 | 4 | # https://leetcode.com/problems/number-of-boomerangs/
"""
You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).
Return the number of boomerangs.
Example 1:
Input: points = [[0,0],[1,0],[2,0]]
Output: 2
Explanation: The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]].
Example 2:
Input: points = [[1,1],[2,2],[3,3]]
Output: 2
Example 3:
Input: points = [[1,1]]
Output: 0
Constraints:
n == points.length
1 <= n <= 500
points[i].length == 2
-104 <= xi, yi <= 104
All the points are unique.
"""
from collections import defaultdict
from typing import List
def number_of_boomerangs(points: List[List[int]]) -> int:
def distance(p1, p2):
x1, y1 = p1
x2, y2 = p2
return (x1 - x2) ** 2 + (y1 - y2) ** 2
n = len(points)
if n < 3:
return 0
hashmap = defaultdict(lambda: defaultdict(int))
res = 0
for i in range(n):
for j in range(n):
if j == i:
continue
d = distance(points[i], points[j])
hashmap[i][d] += 1
res = 0
for i in range(n):
for d, l in hashmap[i].items():
if l >= 2:
res += l * (l - 1)
return res
if __name__ == "__main__":
number_of_boomerangs([[0, 0], [1, 0], [2, 0]])
|
27fa308137938aeea83c4d6a35579083a37e07d9 | kanglicheng/CodeBreakersCode | /mixed bag/day3/81. Search in Rotated Sorted Array II (can't move left or right when a[l] == a[mid] or a[r] == a[mid]).py | 2,060 | 3.53125 | 4 | # can't make decision when a[l] == a[mid] or a[r] == a[mid]
class Solution:
def search(self, a: List[int], tgt: int) -> bool:
def bSearch(a, tgt, l, r):
if l == r:
return a[l] == tgt
if l == r - 1:
return a[l] == tgt or a[r] == tgt
mid = (l + r) // 2
if a[mid] == tgt:
return True
if a[mid] > tgt:
return bSearch(a, tgt, l , mid - 1)
if a[mid] < tgt:
return bSearch(a, tgt, mid + 1, r)
def bSearchInRotatedArray(a, tgt, l, r):
if l == r:
return a[l] == tgt
if l == r - 1:
return a[l] == tgt or a[r] == tgt
mid = (l + r) // 2
# this is the key
if a[mid] == a[l]:
return bSearchInRotatedArray(a, tgt, l + 1, r)
# this is the key
if a[mid] == a[r]:
return bSearchInRotatedArray(a, tgt, l, r - 1)
if a[mid] > a[l]:
if tgt <= a[mid] and tgt >= a[l]:
return bSearch(a, tgt, l , mid)
else:
return bSearchInRotatedArray(a, tgt, mid , r)
if a[mid] < a[r]:
if tgt >= a[mid] and tgt <= a[r]:
return bSearch(a, tgt, mid , r)
else:
return bSearchInRotatedArray(a, tgt, l, mid)
n = len(a)
if n == 0:
return False
l, r = 0, n - 1
if a[l] < a[r]:
return bSearch(a, tgt, l, r)
else:
return bSearchInRotatedArray(a, tgt, l, r)
|
2d82271d0d48bc98dd6e0478c7c128c107dd44eb | tgandor/meats | /toys/math/geometry.py | 1,971 | 3.625 | 4 |
from math import *
# conventions:
# 2D point: (x, y) tuple
# 2D line: (A, B, C) tuple, Ax + By + C == 0
# 2D circle: (x0, y0, R), hypot(x-x0, y-y0) == R
def bisector(a, b):
"""2D line equidistant to points 'a' and 'b'."""
return (2*(b[0]-a[0]), 2*(b[1]-a[1]), a[0]*a[0] + a[1]*a[1] - b[0]*b[0] - b[1]*b[1])
def line_intersection(l1, l2):
"""Return common point in two lines or None if parallel."""
(A1, B1, C1), (A2, B2, C2) = l1, l2
W = A1 * B2 - B1 * A2
if abs(W) < 1e-6:
return None
Wx = C1 * B2 - B1 * C2
Wy = A1 * C2 - C1 * A2
return (Wx/W, Wy/W)
def points_distance(a, b):
"""Euclidian."""
return hypot(a[0]-b[0], a[1]-b[1])
def circle_through_points(a, b, c):
"""Circle through 'a', 'b' and 'c' or None if colinear."""
center = line_intersection(bisector(a, b), bisector(b, c))
if center is None:
return None
return center + (points_distance(a, center),)
def circular_segment_radius_theta(chord, sagitta):
"""Return radius and inner angle theta for given arc chord and sagitta."""
c = circle_through_points((0, 0), (0.5*chord, sagitta), (chord, 0))
if c is None:
return None, None
R = c[2]
theta = 2*asin(0.5*chord/R)
return R, theta
def circular_segment_area(chord, sagitta):
"""Compute area of segment sector given chord and sagitta lengths."""
R, theta = circular_segment_radius_theta(chord, sagitta)
if R is None:
return None
return 0.5 * R * R * (theta - sin(theta))
if __name__ == '__main__':
print "Examples of circular segments:"
for c, s in [(90, 10), (110, 20)]:
print "Chord = %3d, Sagitta = %d:" % (c, s)
A = circular_segment_area(c, s)
R, th = circular_segment_radius_theta(c, s)
print "\tArea: %7.2f (avg. h: %5.2f), R=%6.2f, th=%.2f(%.1f deg), arc length: %5.1f" % (
A, A/c, R, th, th*180/pi, th*R
)
|
982d4ee3e3ff25862deee3a0ec7b7da4e7d6e9b1 | Aasthaengg/IBMdataset | /Python_codes/p00005/s277840971.py | 225 | 3.65625 | 4 | def gcd(a, b):
if b == 0: return a
else: return gcd(b, a % b)
def lcm(a, b):
return a * b / gcd(a, b)
while True:
try:
a, b = map(int, input().split())
print(int(gcd(a, b)), int(lcm(a, b)))
except EOFError:
break |
37c071adff0c60b9dfe3e7d35012a1fb1d628214 | sxlongwork/pythonPro | /if-for-while/for.py | 676 | 4.28125 | 4 | # for 使用
# for循环遍历一个对象(比如数据序列,字符串,列表,元组等),根据遍历的个数来确定循环次数。
for i in range(5):
print(i, end=" ")
print()
for i in range(3, 10):
print(i,end=" ")
print()
for i in range(1, 20, 2):
print(i, end=" ")
print()
for i in range(20, 0, -2):
print(i, end=" ")
print()
name = input("pls type your name:")
for i in name:
print(i, end=" ")
print()
lists = [1, 3, 5, 7, 9]
# 注意,变量名不能使用python的关键字,虽然可以使用该变量,但是会覆盖该关键字在python中的原有含义
for i in lists:
print(i, end=" ")
li = list(lists)
print(li)
|
2192fead97f4c769321bf8efe2c5cdba09ece4c4 | hellux/tddd86-kattis | /bachetsgame/bach_test.py | 361 | 3.5 | 4 | def show_wins(stones, M):
wins = [False for _ in range(stones)]
for i in range(1, stones):
for m in M:
index = i - m
if index >= 0 and not wins[index]:
wins[i] = True
break
for i in range(1, stones):
print("+" if wins[i] else "_", end="")
print()
show_wins(124, [1, 8])
|
df929df7785e84a2c93cce38c0c250b005d6bfdd | Dorkond/stepik-python-course | /Module 1/1.12.2.py | 524 | 4.125 | 4 | '''
Задача 2
Напишите программу, принимающую на вход целое число, которая выводит True, если переданное значение попадает в интервал
(−15,12]∪(14,17)∪[19,+∞) и False в противном случае (регистр символов имеет значение).
'''
num = int(input())
if -15 < num <= 12 or 14 < num < 17:
print('True')
elif num >= 19:
print('True')
else:
print('False') |
a17852f89fa1db2689547ec90e67428118a63289 | rasel06/python | /sorting.py | 222 | 4.1875 | 4 | #Input like
# mango,banana,lichi,malta,grape,orrange,coconut
input_string = input("Enter enter fruits list (, seperated value)= ")
words = input_string.split(",")
words.sort()
for item in reversed(words):
print(item) |
62643bdba2ca151c771ba3f790909c54ca6babff | tomjingang/data-science | /Chapter 2 custom visualization hard.py | 4,914 | 3.84375 | 4 | # A challenge that users face is that, for a given y-axis value (e.g. 42,000),
# it is difficult to know which x-axis values are most likely to be representative,
# because the confidence levels overlap and their distributions are different
# (the lengths of the confidence interval bars are unequal). One of the solutions the authors propose
# for this problem (Figure 2c) is to allow users to indicate the y-axis value of interest (e.g. 42,000)
# and then draw a horizontal line and color bars based on this value. So bars might be colored red if
# they are definitely above this value
# (given the confidence interval), blue if they are definitely below this value, or white if they contain this value.
import pandas as pd
import numpy as np
import scipy.stats as st
np.random.seed(12345)
df = pd.DataFrame([np.random.normal(33500,150000,3650),
np.random.normal(41000,90000,3650),
np.random.normal(41000,120000,3650),
np.random.normal(48000,55000,3650)],
index=[1992,1993,1994,1995])
df['mean']=df.mean(axis=1)
df['std']=df.std(axis=1)
#this is approximate method for interval
df['sem']=df.sem(axis=1) # 误差
df['i_min']=df['mean']-df['sem']*4
df['i_max']=df['mean']+df['sem']*4
df['yerr']=df['sem']*4
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
cl_max_color='red'
cl_min_color='blue'
cl_neitral_color='grey'
class Cursor(object):
_df=None
_bl=None
def __init__(self, ax, data_F, bars):
self._df=data_F
self._bl=bars
self.ax = ax
self.lx = ax.axhline(color='b')
def mouse_move(self, event):
if not event.inaxes:
return
x, y = event.xdata, event.ydata
self.lx.set_ydata(y)
for index, row in self._df.iterrows():
if row['i_max']<y:
self._bl[self._df.index.get_loc(index)].set_color(cl_min_color)
continue
if row['i_min']>y:
self._bl[self._df.index.get_loc(index)].set_color(cl_max_color)
continue
self._bl[self._df.index.get_loc(index)].set_color(cl_neitral_color)
plt.draw()
def plot_base(fix_x, fig_y, fig_title, c_alpha=0.5):
ax=df['mean'].plot.bar(yerr=df['yerr'],
title =fig_title, figsize=(fix_x, fig_y),
legend=False, fontsize=10, alpha=c_alpha, width=0.95,
rot=0, position=0, style='-', color=cl_neitral_color)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
majors = [0.5,1.5,2.5, 3.5]
ax.xaxis.set_major_locator(ticker.FixedLocator(majors))
plt.tight_layout()
return (ax, ax.get_children()[1:5])
ax, barlist=plot_base(5, 5, "Easiest option")
cursor = Cursor(ax, df, barlist)
plt.connect('motion_notify_event', cursor.mouse_move)
from matplotlib.patches import Rectangle
import matplotlib.pyplot as plt
from collections import OrderedDict
dct=OrderedDict( [('navy','-100%'), ('blue','-80%'), ('steelblue','-60%'), ('lightblue','-40%'),
('lightcyan','-20%'), ('wheat','20%'), ('sandybrown','40%'),
('salmon','60%'), ('red','80%'), ('brown','100%')] )
com_alpha=0.7
class CursorHard(Cursor):
#_colors=list(dct.keys())
_colors=list(reversed(dct.keys()))
_num_bins=8
def _get_color(self, d_series, val):
s=d_series[['i_min', 'i_max']]
s['val']=val
s=pd.cut(s, bins=self._num_bins, labels=list(range(self._num_bins)), include_lowest=False, right=True)
return self._colors[s['val']+1]
def mouse_move(self, event):
if not event.inaxes:
return
x, y = event.xdata, event.ydata
self.lx.set_ydata(y)
for index, row in self._df.iterrows():
if row['i_max']<y:
self._bl[self._df.index.get_loc(index)].set_color(self._colors[-1])
continue
if row['i_min']>y:
self._bl[self._df.index.get_loc(index)].set_color(self._colors[0])
continue
self._bl[self._df.index.get_loc(index)].set_color(self._get_color(row, y))
plt.draw()
ax1, barlist1=plot_base(6, 6, 'Even Harder option', c_alpha=1)
bars_leg=[]
for k, v in dct.items():
p=Rectangle((0, 0), 1, 1, fc=k, label=v)
bars_leg.append(p)
plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.04),
handles=bars_leg, ncol=len(bars_leg), columnspacing=0.2, handletextpad=0.1, fontsize=7)
plt.tight_layout()
plt.show()
hcursor = CursorHard(ax1, df, barlist1)
plt.connect('motion_notify_event', hcursor.mouse_move) |
0530cad68dc4e62256619ff831f59237787ff524 | chengming-1/python-Basic | /proj01.py | 897 | 4.15625 | 4 | ###########################################################
# Computer Project #1
#
# Algorithm
# input te rod
# convert rod from string to float
# convert the rod to other measurement by divied coefficient
# output the measurement by different cofficient
###########################################################
rod_str=input('Input rods:')
rod_float=float(rod_str)
meter_float=rod_float*5.0292
feet_float=meter_float/0.3048
mile_float=meter_float/1609.34
furlong_float=rod_float/40
MTW_float=(5.0292*rod_float)/(3.1*1609.34/60)
print(' You input',round(rod_float,3),'rods.')
print('Conversions')
print('Meters:',round(meter_float,3))
print('Feet:',round(feet_float,3))
print('Miles:',round(mile_float,3))
print('Furlongs:',round(furlong_float,3))
print('Minutes to walk',round(rod_float,3),'rods:',round(MTW_float,3)) |
4fccc07533869dc9b90fd1036197c4ebd205987e | demo112/1807 | /python/Myself_Note/note/sleep.py | 242 | 3.78125 | 4 | from time import sleep
#
# def myfn(n):
# while n > 0:
# print("hello world")
# sleep(1)
# n -= 1
#
# myfn(6)
def myfn(n):
if n > 0:
print("hello world")
sleep(1)
myfn(n - 1)
myfn(3) |
2a2f38ec62547698a28cff549e06a123dc2590f2 | haha479/Interview_questions | /02-使用nonlocal修改变量.py | 147 | 3.5625 | 4 | def func(*args):
ax = 0
def func_in():
nonlocal ax
for n in args:
ax = ax + n
return ax
return func_in
a = func(1,2,3,4)
print(a()) |
2830233a21c51cbc30dbf8cf35fead7c27ecd69f | Nkaka23dev/data-structure-python | /maricar2.py | 1,233 | 3.75 | 4 |
# # returning a friend when characters are equals to 4
# def friend(arr):
# return [char for char in arr if len(list(char))==4]
# arr=["Ryan", "Kieran", "Jason", "Yous"]
# print(friend(arr))
# # python programm to make a phone number from a list of numbers
# arr=[1,2,3,4,5,6,7,8,9,0]
# str_=[str(n) for n in arr]
# new_arr="".join(str_)
# print(f"({new_arr[0:3]}) {new_arr[3:6]}-{new_arr[6:10]}")
# def fizzBuzz(n):
# if n<0 and n>(2*10**5):
# raise ValueError("Not valid")
# else:
# for i in range(1,n+1):
# if i%3==0 and i%5==0:
# print("FizzBuzz")
# elif i%3==0:
# print("Fizz")
# elif i%5==0:
# print("Buzz")
# else:
# print(f"{i}")
# fizzBuzz(-25)
# def arrSum(number):
# i
# sum=0
# for i in number:
# sum+=i
# return sum
# arr=[3,4,5]
# print(arrSum(arr))
def dnaComplement(s):
word=s.casefold()
new_word=list(reversed(word))
for i in new_word:
if i=="a":
x="t"
i="t"
if i=="t":
temp=i
i=temp
return new_word
print(dnaComplement('ACCGGGTTTT'))
|
97dd767cabef8028704b339edc9454821a912561 | fucci/HelloWorld3 | /fred.py | 164 | 3.84375 | 4 | a = 20
b= 10
for i in range(1, 10,1):
b=b+i
a=a*i
print ('a='+str(a))
print ('b='+str(b))
b=b+i
print ('i='+str(i))
print "this is the end"
|
dba1a9f2aa0f9796e685b5576805d57ddfadfa98 | Hari2019041/Fun-Scripts | /Maths/impossible_squares.py | 499 | 3.828125 | 4 | N = 10**3
SQUARES = {int(i * i) for i in range(N + 1)}
def find_possible(n):
if n in SQUARES:
return f'{n}'
for square in SQUARES:
if n - square in SQUARES:
return f'{square} + {n-square}'
return ''
impossible_squares = []
possible_squares = {}
for i in range(1, N + 1):
temp = find_possible(i)
if temp == '':
impossible_squares.append(i)
else:
possible_squares[i] = temp
print(impossible_squares)
print(possible_squares)
|
0caeca0265e90d0b8742de253da3006e68546f1e | jrbublitz/Aulas-python | /exercicios/4 - ExercicioLoops.py | 1,387 | 3.859375 | 4 | #
# primeiraFase = [5, 9, 3, 5, 2, 1, 6, 3]
# segundaFase = []
# final = []
#
# def CalcularFase(Fase, proximaFase):
# if (len(Fase) != 2):
# for i in range(0, len(Fase), 2):
# if Fase[i] != Fase[i + 1]:
# maior = max(Fase[i], Fase[i + 1])
# proximaFase.append(maior)
# else:
# proximaFase.append(0)
# return proximaFase
# else:
# return max(Fase[0], Fase[1])
#
# print("Primeira Fase: ", primeiraFase)
#
# print("Segunda Fase: ", CalcularFase(primeiraFase, segundaFase))
#
# print("Final: ", CalcularFase(segundaFase, final))
#
# print("Vencedor: ", CalcularFase(final, 0))
#
# print("================== \n")
#
#
# # Questão 2 #
# palavras = ["Banana", "Maçã", "Pepino", "Batata"]
# print("!!!".join(palavras).upper().replace("A", "@"))
#
# # Questão 3 #
# import string
#
# alfabeto = string.ascii_lowercase
# vogais = "aeiou"
#
# palavra = input("Digite a palavra: ")
# nova_palavra = ""
#
# for i in palavra:
# if i.lower() in vogais:
# index = alfabeto.index(i.lower()) - 4
# nova_palavra += alfabeto[index]
# else:
# index = alfabeto.index(i.lower()) + 9
# print(index)
# novo_index = index if index < 26 else index - 26
# nova_palavra += alfabeto[novo_index]
#
# print(nova_palavra)
#
palavra = "bla"
|
4efa06d667375ff7918dcf9cbbdc4220db5acd2a | jaisinghchouhan/Forsks | /Day2/bricks.py | 401 | 4.1875 | 4 | def bricks(small,big,total):
if small+big*5>=total:
if total%5<=small:
return True
else:
return False
else:
return False
small=int(input("enter total number of one intch of brick"))
large=int(input("enter the number of 5 intch of brick"))
total=int(input("enter the total length of brick to be built"))
print(bricks(small,large,total)) |
7023c32df9c562c373ae29dbd799ba736d0ab67f | Elita1114/POS-Tagging-with-Gibbs-Sampling | /non_negative_counter.py | 536 | 3.53125 | 4 | import numpy as _np
from collections import Counter as _Counter
class NonNegativeCounter(_Counter):
"""This class is a Counter sub-class that only accepts non-negative integers as values."""
def __setitem__(self, key, value):
if type(value) not in {int, _np.int}:
raise TypeError("The value to be set is not an integer.")
if value >= 0:
super().__setitem__(key, value)
else:
raise ValueError(f"Tried to set a negative value ({value}) in key '{key}'")
|
03cb02f8a9737407d7889e1ddadbb34d222b80d0 | rockboynton/blind75 | /maxprofit.py | 565 | 3.578125 | 4 | def maxProfit(self, prices: List[int]) -> int:
# min_price = float('inf')
# max_profit = 0
# for price in prices:
# min_price = min(min_price, price)
# profit = price - min_price
# max_profit = max(max_profit, profit)
# return max_profit
min_price = float('inf')
max_profit = 0
for price in prices:
if price < min_price:
min_price = price
elif price - min_price > max_profit:
max_profit = price - min_price
return max_profit |
c72b9bc9e59a50537a3da949e91dacb396ebb91d | hoomanvhd/inf8007 | /test_text.py | 2,672 | 3.828125 | 4 | from unittest import TestCase, main
from td1 import Text
class TestText(TestCase):
sentences = (
'The cat sat on the mat.',
'This sentence, taken as a reading passage unto itself, is being used to prove a point.',
'The Australian platypus is seemingly a hybrid of a mammal and reptilian creature.'
)
def test_split_syllables(self):
results = [
'The cat sat on the mat.',
'This sen/tence, tak/en as a read/ing pas/sage '
'un/to it/self, is be/ing used to prove a point.',
'The Aus/tralian platy/pus is seem/ing/ly a hy/b'
'rid of a mam/mal and rep/til/ian crea/ture.'
]
for s in self.sentences:
self.assertEqual(results.pop(0), Text(s).split_syllables('en').text)
def test_count_words(self):
t = lambda to_test: Text(to_test).count_words()
self.assertEqual(t("Bon/jour, mon/de!"), 2, "Simple case")
self.assertEqual(t("sau/te-mou/ton"), 2, "Composed word")
self.assertEqual(t("l'arbre"), 2, "Apostrophe separated words")
self.assertEqual(t("àéèâôûùê"), 1, "French stuff")
results = [6, 16, 13]
for s in self.sentences:
result = results.pop(0)
self.assertEqual(result, Text(s).split_syllables('en').count_words())
self.assertEqual(result, Text(s).count_words())
def test_count_sentences(self):
t = lambda to_test: Text(to_test).count_sentences()
self.assertEqual(t("Non."), 1, "Simple case")
self.assertEqual(t("Non... Mais en fait si."), 2, "...")
for s in self.sentences:
self.assertEqual(1, Text(s).split_syllables('en').count_sentences())
self.assertEqual(1, Text(s).count_sentences())
def test_count_syllables(self):
results = [6, 23, 22]
for s in self.sentences:
self.assertEqual(results.pop(0),
Text(s).split_syllables('en').count_syllables(),
"count_syllables for "+s)
def test_count_from_regex(self):
self.assertEqual(Text("abcde")._count_from_regex(r"."), 5, "Simple case is enough")
def test_process_lisibility(self):
t = lambda to_test: Text(to_test).process_lisibility()
self.assertAlmostEqual(t("Tout est dit."), 119.19, msg="Simple case is enough")
results = [116, 69, 50]
for s in self.sentences:
self.assertAlmostEqual(results.pop(0),
Text(s).split_syllables('en').process_lisibility(),
0)
if __name__ == "__main__":
main()
|
a6f40c5d750cefae142fdeae01efc674a5c36d77 | freddywilliam/Python_Intermedio | /list_and_dict.py | 528 | 3.609375 | 4 | def run():
my_list = [1, 'HELLO', True, 4.5]
my_dict = {'firstname' : 'William', 'lastname' : 'Martinez'}
super_list = [
{'firstname' : 'William', 'lastname' : 'Martinez'},
{'firstname' : 'Freddy', 'lastname' : 'Martinez'},
]
super_dict = {
'natural_nums': [1,2,3,4,5,7],
'integer_nums': [-1,-2,-3,-4,-5],
}
for key, value in super_dict.items():
print(key, '-', value)
for i in super_list:
print(i)
if __name__ == '__main__':
run() |
947b94f4a72c11a408e3c76ed88028a6a39672de | v-crn/nlp-100-fungoes | /01_Warming-up/03_count_length_of_each_word.py | 528 | 4.4375 | 4 | import re
def count_length_of_each_word(sentence):
regex = re.compile(r'[a-zA-z]+')
return [len(s) for s in regex.findall(sentence)]
def main():
print('Test 1:')
sentence = 'Now I need a drink, alcoholic of course, \
after the heavy lectures involving quantum mechanics.'
print(count_length_of_each_word(sentence), '\n')
print('Test 2:')
sentence = 'To be, or not to be: that is the question.'
print(count_length_of_each_word(sentence), '\n')
if __name__ == '__main__':
main()
|
bd5acde3ef6424e022cedcae262a1ea2c3ae7138 | qlhai/Algorithms | /程序员面试金典/01.01.py | 705 | 3.828125 | 4 | """"
面试题 01.01. 判定字符是否唯一
实现一个算法,确定一个字符串 s 的所有字符是否全都不同。
示例 1:
输入: s = "leetcode"
输出: false
示例 2:
输入: s = "abc"
输出: true
限制:
0 <= len(s) <= 100
如果你不使用额外的数据结构,会很加分。
"""
class Solution:
def isUnique(self, astr: str) -> bool:
mask = 0
for char in astr:
move_bit = ord(char) - ord('a')
if mask & (1 << move_bit) != 0:
return False
else:
mask |= (1 << move_bit)
return True
if __name__ == '__main__':
obj = Solution()
s = 'abc'
print(obj.isUnique(s)) |
4e2a6bc69cd14dba5becbc658b07f951096ad80b | pangruitao/nt_py | /day08/exercise.py | 707 | 3.671875 | 4 |
# 购物车功能要求:
# 要求用户输入总资产,例如: 2000
# 显示商品列表,让用户根据序号选择商品,加入购物车
# 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
# goods = [
# {"name":"电脑","price":1999},
# {"name":"鼠标","price":10},
# {"name":"游艇","price":20},
# {"name":"美女","price":98},
a = int(input('请输入总资产:'))
D={}
m=0
c=0
goods=[]
while True:
n=str(input('商品:'))
p=str(input('价格:'))
m=int(p)
c+=m
if c<=a:
D['name']=n
D['price']=p
goods.append(D)
else:
print('余额不足,请充值.')
break
print(goods)
|
42ae0635cdce32c324564a31c8abdb9734546af3 | shireen-nazneen/loops | /prime_num_loop.py | 204 | 4.09375 | 4 | num=int(input("enter your number_--"))
counter=0
i=1
while i<=num:
if num%i==0:
counter+=1
i=i+1
if counter==2:
print(num,"is prime number")
else:
print(num, 'is not prime number') |
cfe3c685c0f032ca26135917ce57e054ce73c77f | Ritvik19/CodeBook | /data/Algorithms/Insertion Sort.py | 353 | 4.1875 | 4 | def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
if __name__ == "__main__":
arr = [64, 34, 25, 12, 22, 11, 90]
insertionSort(arr)
print("Sorted array is:")
print(*arr)
|
15971f6473413a2ead2eab772fc9b8e1b13ab100 | shenqiti/leetcode | /1.Two_sum.py | 877 | 3.921875 | 4 | '''
1.Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
________________________________________
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
_________________________________________
By : shenqiti
2019/7/28
'''
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for i,n in enumerate(nums):
temp = target - n
if temp in d:
return (d[temp],i)
else:
d[n] = i
dd = Solution()
nums = [2,7,11,15]
target = 17
result = dd.twoSum(nums,target)
print(result)
|
b601dc5a216aeb15da23c0c876ec23a9f7b5a4f9 | sebnorth/flask-python-coursera | /app/static/module4_project.py | 5,456 | 3.984375 | 4 | def make_dict(keys, default_value):
"""
Creates a new dictionary with the specified keys and default value.
Arguments:
keys -- A list of keys to be included in the returned dictionary.
default_value -- The initial mapping value for each key.
Returns:
A dictionary where every key is mapped to the given default_value.
"""
result = { }
for key in keys:
result[key] = default_value
return result
def build_scoring_matrix(alphabet, diag_score, off_diag_score, dash_score):
"""
asda
"""
alphabet_dashed = alphabet
alphabet_dashed.add('-')
characters = list(alphabet_dashed)
slownik = make_dict(characters, 0)
dict_list = [make_dict(characters, 0) for dummy in range(len(characters))]
slownik = dict(zip(slownik, dict_list))
for idx in slownik.keys():
for idy in slownik[idx].keys():
if idx == '-' or idy == '-':
slownik[idx][idy] = dash_score
elif idx == idy and not idx == '-':
slownik[idx][idy] = diag_score
else:
slownik[idx][idy] = off_diag_score
return slownik
#build_scoring_matrix(set(['A', 'C', '-', 'T', 'G']), 6, 2, -4)
# print build_scoring_matrix(set(['A', 'C', '-', 'T', 'G']), 6, 2, -4)
def compute_flagtrue(seq_x, seq_y, macierz, scoring_matrix):
"""
asfasa
"""
rows = len(seq_x)
cols = len(seq_y)
for idx in range(1, rows + 1):
macierz[idx][0] = macierz[idx - 1][0] + scoring_matrix[seq_x[idx-1]]['-']
for idy in range(1, cols + 1):
macierz[0][idy] = macierz[0][idy - 1] + scoring_matrix['-'][seq_y[idy - 1]]
for idx in range(1, rows + 1):
for idy in range(1, cols + 1):
macierz[idx][idy] = max( macierz[idx - 1][idy - 1] + scoring_matrix[seq_x[idx-1]][seq_y[idy - 1]] ,macierz[idx - 1][idy] + scoring_matrix[seq_x[idx-1]]['-'], macierz[idx][idy - 1] + scoring_matrix['-'][seq_y[idy - 1]])
def compute_flagfalse(seq_x, seq_y, macierz, scoring_matrix):
"""
asds
"""
rows = len(seq_x)
cols = len(seq_y)
for idx in range(1, rows + 1):
macierz[idx][0] = macierz[idx - 1][0] + scoring_matrix[seq_x[idx-1]]['-']
if macierz[idx][0] < 0:
macierz[idx][0] = 0
for idy in range(1, cols + 1):
macierz[0][idy] = macierz[0][idy - 1] + scoring_matrix['-'][seq_y[idy - 1]]
if macierz[0][idy] < 0:
macierz[0][idy] = 0
for idx in range(1, rows + 1):
for idy in range(1, cols + 1):
macierz[idx][idy] = max( macierz[idx - 1][idy - 1] + scoring_matrix[seq_x[idx-1]][seq_y[idy - 1]] ,macierz[idx - 1][idy] + scoring_matrix[seq_x[idx-1]]['-'], macierz[idx][idy - 1] + scoring_matrix['-'][seq_y[idy - 1]])
if macierz[idx][idy] < 0:
macierz[idx][idy] = 0
def compute_alignment_matrix(seq_x, seq_y, scoring_matrix, global_flag):
"""
asfasa
"""
rows = len(seq_x)
cols = len(seq_y)
macierz = [[0 for dummy_x in range(cols + 1)] for dummy_y in range(rows + 1)]
# print macierz
if global_flag:
compute_flagtrue(seq_x, seq_y, macierz, scoring_matrix)
else:
compute_flagfalse(seq_x, seq_y, macierz, scoring_matrix)
return macierz
# m = compute_alignment_matrix('ACTACT', 'AGCTA', {'A': {'A': 2, 'C': 1, '-': 0, 'T': 1, 'G': 1}, 'C': {'A': 1, 'C': 2, '-': 0, 'T': 1, 'G': 1}, '-': {'A': 0, 'C': 0, '-': 0, 'T': 0, 'G': 0}, 'T': {'A': 1, 'C': 1, '-': 0, 'T': 2, 'G': 1}, 'G': {'A': 1, 'C': 1, '-': 0, 'T': 1, 'G': 2}}, True)
def compute_global_alignment(seq_x, seq_y, scoring_matrix, alignment_matrix):
"""
asdfas
"""
rows = len(seq_x)
cols = len(seq_y)
align_x = ""
align_y = ""
while not rows == 0 and not cols == 0:
if alignment_matrix[rows][cols] == alignment_matrix[rows-1][cols-1] + scoring_matrix[seq_x[rows-1]][seq_y[cols - 1]]:
align_x = seq_x[rows-1]+align_x
align_y = seq_y[cols - 1]+align_y
rows-=1
cols-=1
elif alignment_matrix[rows][cols] == alignment_matrix[rows-1][cols] + scoring_matrix[seq_x[rows-1]]['-']:
align_x = seq_x[rows-1]+align_x
align_y = "-"+align_y
rows-=1
else:
align_x = "-"+align_x
align_y = seq_y[cols - 1]+align_y
cols-=1
while not rows == 0:
align_x = seq_x[rows-1] + align_x
align_y = '-' + align_y
rows-=1
while not cols == 0:
align_x = '-' + align_x
align_y = seq_y[cols-1] + align_y
cols-=1
score = sum([scoring_matrix[align_x[idx]][align_y[idx]] for idx in range(len(align_x)) ])
return (score, align_x, align_y)
def alignment_matrix_maximum(macierz):
"""
fdsfds
"""
rows = len(macierz)
cols = len(macierz[0])
max_value = max([macierz[idx][idy] for idx in range(rows) for idy in range(cols)])
for idx in range(rows):
for idy in range(cols):
if macierz[idx][idy] == max_value:
return (idx, idy)
def compute_local_alignment(seq_x, seq_y, scoring_matrix, alignment_matrix):
"""
saf
"""
largest_x, largest_y = alignment_matrix_maximum(alignment_matrix)
rows = largest_x
cols = largest_y
align_x = ""
align_y = ""
while alignment_matrix[rows][cols]:
if alignment_matrix[rows][cols] == alignment_matrix[rows-1][cols-1] + scoring_matrix[seq_x[rows-1]][seq_y[cols - 1]]:
align_x = seq_x[rows-1]+align_x
align_y = seq_y[cols - 1]+align_y
rows-=1
cols-=1
elif alignment_matrix[rows][cols] == alignment_matrix[rows-1][cols] + scoring_matrix[seq_x[rows-1]]['-']:
align_x = seq_x[rows-1]+align_x
align_y = "-"+align_y
rows-=1
else:
align_x = "-"+align_x
align_y = seq_y[cols - 1]+align_y
cols-=1
score = sum([scoring_matrix[align_x[idx]][align_y[idx]] for idx in range(len(align_x)) ])
return (score, align_x, align_y)
|
0aac3665460994edded34f9e42c4f2329f91ec82 | sametatabasch/Python_Ders | /ders15.py | 352 | 3.765625 | 4 | def selamla():
"""Merhaba mesajını yazdırır"""
print("Merhaba")
#selamla()
def selamla1(isim):
print("Merhaba", isim)
#selamla1("sdfgh")
def selamla2(isim):
return "Merhaba " + isim
def topla(s1,s2):
return s1+s2
print(selamla2("Ahmet"),topla(5,6))
sonuc= 5*2+topla(7,9)
print(sonuc)
print(selamla2("Ahmet").upper())
|
167c6c98c8f7673fe3b1d42918433a35e1c17054 | anishst/Learn | /Programming/Python/functions_practice/lambda_functions.py | 840 | 4.5 | 4 | # lambdas are functions without name
# alwasy used to return values; not for actions
# example 1
def add(x,y):
return x+y
print(add(5,3))
# giving name to lambda
result = lambda x, y: x+y
print(result(5,3))
# example 2
def double(x):
return x *2
# using list comprehension
sequence = [1,5, 3,2]
doubled = [double(x) for x in sequence]
print(doubled)
print(f"Using list comprehension: {doubled} ")
# using map
doubled = map(double, sequence)
print(f"Using map function: {list(doubled)} ")
# lambda
doubled = [(lambda x: x *2)(x) for x in sequence]
print(f"Using lamda: {doubled} ")
# lambda with map function
doubled = map(lambda x: x *2, sequence)
print(f"Using lamda with map function: {list(doubled)} ")
# lambda with filter function
# remove even numbers
nums = range(10)
a = filter(lambda x:x%2 !=0, nums)
print(list(a)) |
77cff494f4f46458f5972d21cc2beb9c979d1468 | landeholt/tilda | /skeleton-code/binary_search_tree.py | 2,378 | 3.984375 | 4 | # Author: John Landeholt [TA]
class Node:
def __init__(self, data):
self.right = None
self.left = None
self.data = data
# "greather than" magic_method
def __gt__(self, other):
"""Dictates whether self or other is greather"""
# YOUR CODE HERE
return None
def find(self, data):
"""Search recursive in left and right node"""
# YOUR CODE HERE
return None
def put(self, node):
"""Find position in left or right node recursively"""
# YOUR CODE HERE
return None
def preorder(self, l):
"""(root, left, right)"""
l.append(self.data)
if self.left: self.left.preorder(l)
if self.right: self.right.preorder(l)
return l
def inorder(self, l):
if self.left: self.left.inorder(l)
l.append(self.data)
if self.right: self.right.inorder(l)
return l
def postorder(self, l):
"""(left, right, root)"""
# YOUR CODE HERE
return l
class Binary_search_tree:
def __init__(self):
self.root = None
@staticmethod
def build(self,l):
""" Builds a tree from a list """
tree = Binary_search_tree()
for data in l:
tree.put(data)
return tree
def put(self, data):
""" Put a Node into the tree """
if self.root:
# YOUR CODE HERE
pass
else:
# YOUR CODE HERE
pass
def __contains__(self, data):
""" Recurses down from the root-node """
if self.root:
# YOUR CODE HERE
pass
return False
@property
def inorder(self):
if self.root:
l = []
return self.root.inorder(l)
@property
def preorder(self):
# YOUR CODE HERE
return None
@property
def postorder(self):
# YOUR CODE HERE
return None
if __name__ == "__main__":
tree = Binary_search_tree.build([6,3,9,1,5,7,11])
if 6 in tree:
print('no.', 6, 'exists in the tree')
if 12 not in tree:
print('no.', 12, 'does not exist in the tree')
if tree.inorder == [1,3,5,6,7,9,11]:
print('inorder works as it should')
if tree.postorder == [1,5,3,7,11,9,6]:
print('postorder works as it should') |
1828a7b827b39231d837ee270353af3d3e347377 | Broadan26/Project-Euler | /Euler3/euler3.py | 2,678 | 3.953125 | 4 | import math
def Euler3BruteForce1(size): #Horribly inefficient brute force
largest_factor = -1
i = 2
while (i < size): #Check all values below the number
if (size % i) == 0: #Found a divisor
is_prime = True
j = 2
while (j < i):
if (i % j) == 0: #Not a prime
isPrime = False
j = i #Break
j = j + 1
if is_prime: #Found new largest factor
largest_factor = i
i = i + 1
print('Largest Factor:', largest_factor)
def Euler3BruteForce2(size): #Less horribly inefficient brute force
largest_factor = -1
i = 2
while (i * i) < size: #Only need to check up to sqrt(num)
if (size % i) == 0: #Check for factor
factors = [i, (size/i)]
k = 0
while (k < 2): #Check both factors
is_prime = True
j = 2
while (j * j) < factors[k]: #Check for prime
if (factors[k] % j) == 0: #Not a prime
is_prime = False
j = factors[k] #Break
j = j + 1
if is_prime and (factors[k] > largest_factor): #Found new largest factor
largest_factor = factors[k]
k = k + 1
i = i + 1
print('Largest Factor:', largest_factor)
def Euler3Optimized1(size): #Optimized Factorization
while(size % 2 == 0): #Remove all multiples of 2
size = (size / 2)
i = 3 #First prime after 2
while( i <= math.sqrt(size)): #Only need to check up to sqrt(num) for primes
while(size % i == 0): #Remove other factors
size = (size / i)
i = i + 2 #Skip evens
if size > 2: #Last prime factor is solution
print('Largest Factor:', int(size))
def Euler3Optimized2(size): #More Optimized Factorization
largest_factor = -1
i = 2
while (i * i) <= size: #Only need to check up to sqrt(num)
if (size % i) == 0: #Check for factor
size = size / i
largest_factor = i #Save it
else:
i = i + 1
if size > largest_factor: #Check which remainder is largest prime
print('Largest Factor:', int(size))
else:
print('Largest Factor:', int(largest_factor))
if __name__ == "__main__": #Driver
size = 600851475143
#Euler3BruteForce1(size) #Don't run this, it's awful
Euler3BruteForce2(size)
Euler3Optimized1(size)
Euler3Optimized2(size) |
12f63a3776cc94f8199d79d28dad90468e89d430 | sreejitaghosh/Travel-Book--Python | /Fetch_Distance.py | 501 | 3.5 | 4 | from math import radians ,sin, cos, sqrt, atan2
def Fetch_Distance(Lat1,Lon1,Lat2,Lon2):
Radius_Of_Earth = 6373
Diff_Lat = radians(Lat2 - Lat1)
Diff_Lon = radians(Lon2 - Lon1)
SubCalculation = (sin(Diff_Lat/2)*sin(Diff_Lat/2)) + cos(radians(Lat1)) * cos(radians(Lat2)) * (sin(Diff_Lon/2)*sin(Diff_Lon/2))
Final_Calculation = 2*Radius_Of_Earth*atan2(sqrt(SubCalculation), sqrt(1-SubCalculation))
# Dist = round(Final_Calculation,2)
Dist = Final_Calculation
return Dist
|
7734bdc1b5ec4f5a5146e80db2970507df245bca | nekoTheShadow/atcoder-answers | /panasonic2020/c.py | 184 | 3.65625 | 4 | import decimal
a, b, c = map(int, input().split())
if decimal.Decimal(a).sqrt() + decimal.Decimal(b).sqrt() < decimal.Decimal(c).sqrt():
print('Yes')
else:
print('No')
|
d74be0cbf4e6db7507b28042678dc0c3ff0e3283 | mohitsharma2/Python | /icccricket_sqlite.py | 2,059 | 3.90625 | 4 | """
Code Challenge
Name:
Webscrapping ICC Cricket Page
Filename:
icccricket.py
Problem Statement:
Write a Python code to Scrap data from ICC Ranking's
page and get the ranking table for ODI's (Men).
Create a DataFrame using pandas to store the information.
Hint:
https://www.icc-cricket.com/rankings/mens/team-rankings/odi
#https://www.icc-cricket.com/rankings/mens/team-rankings/t20i
#https://www.icc-cricket.com/rankings/mens/team-rankings/test
"""
import sqlite3
import pandas as pd
conn = sqlite3.connect("icccricket_sqlite.db")
data = conn.cursor()
data.execute("""CREATE TABLE icccricket(
Pos INTEGER,
Team TEXT,
Weighted Matches INTEGER,
Points INTEGER,
Rating INTEGER
)"""
)
conn.commit()
df= pd.read_csv('C:/Users/mohit/Desktop/Python/odi.csv')
print(df)
df.to_sql('icccricket', conn, if_exists='replace',index=False) # to store in data base
read=data.execute('SELECT * FROM icccricket') # read from data base
read.fetchall() # to read all data from your data base(icccricket_sqlite)
data.execute('DROP TABLE icccricket') # Delete table from data base
conn.commit()
"""
output=============================================================
[(0, 1, 'England', 54, '6,745', 125),
(1, 2, 'India', 64, '7,748', 121),
(2, 3, 'New Zealand', 43, '4,837', 112),
(3, 4, 'South Africa', 47, '5,193', 110),
(4, 5, 'Australia', 53, '5,854', 110),
(5, 6, 'Pakistan', 51, '5,019', 98),
(6, 7, 'Bangladesh', 46, '3,963', 86),
(7, 8, 'Sri Lanka', 56, '4,520', 81),
(8, 9, 'West Indies', 57, '4,573', 80),
(9, 10, 'Afghanistan', 43, '2,440', 57),
(10, 11, 'Ireland', 31, '1,525', 49),
(11, 12, 'Zimbabwe', 35, '1,538', 44),
(12, 13, 'Netherlands', 6, '222', 37),
(13, 14, 'Scotland', 18, '537', 30),
(14, 15, 'United States', 12, '299', 25),
(15, 16, 'Oman', 10, '199', 20),
(16, 17, 'Nepal', 8, '152', 19),
(17, 18, 'Namibia', 11, '177', 16),
(18, 19, 'UAE', 21, '285', 14),
(19, 20, 'Papua New Guinea', 17, '0', 0)]
"""
|
c0046dd18609db4215dabfae58829937ce33b296 | arxrean/ML-Algorithm-Implementation | /knn.py | 1,764 | 3.53125 | 4 | # https://towardsdatascience.com/machine-learning-basics-with-the-k-nearest-neighbors-algorithm-6a6e71d01761
from collections import Counter
import math
reg_data = [
[65.75, 112.99],
[71.52, 136.49],
[69.40, 153.03],
[68.22, 142.34],
[67.79, 144.30],
[68.70, 123.30],
[69.80, 141.49],
[70.01, 136.46],
[67.90, 112.37],
[66.49, 127.45],
]
reg_query = [60]
clf_data = [
[22, 1],
[23, 1],
[21, 1],
[18, 1],
[19, 1],
[25, 0],
[27, 0],
[29, 0],
[31, 0],
[45, 0],
]
clf_query = [33]
def mean(labels):
return sum(labels)/len(labels)
def mode(labels):
return Counter(labels).most_common(1)[0][0]
def euclidean_distance(point1, point2):
sum_squared_distance = 0
for i in range(len(point1)):
sum_squared_distance += math.pow(point1[i] - point2[i], 2)
return math.sqrt(sum_squared_distance)
def knn(repo, query, k, distance_fn, choice_fn):
neighbor_distances_and_indices = []
for idx, sample in enumerate(repo):
distance = distance_fn(sample[:-1], query)
neighbor_distances_and_indices.append((distance, idx))
sorted_neighbor_distances_and_indices = sorted(
neighbor_distances_and_indices)
k_sorted_neighbor_distances_and_indices = sorted_neighbor_distances_and_indices[:k]
k_nearest_labels = [repo[i][-1]
for x, i in k_sorted_neighbor_distances_and_indices]
return k_sorted_neighbor_distances_and_indices, k_nearest_labels
reg_k_nearest_neighbors, reg_prediction = knn(
reg_data, reg_query, k=3, distance_fn=euclidean_distance, choice_fn=mean
)
clf_k_nearest_neighbors, clf_prediction = knn(
clf_data, clf_query, k=3, distance_fn=euclidean_distance, choice_fn=mode
)
|
b8c0683e5f1c67ef31794e6db3bd3cb20a7e207a | Vicklan/Classes | /animals.py | 487 | 3.90625 | 4 | class Animals:
def __init__(self, name, weight, height, food):
self.name = name
self.weight = weight
self.height = height
self.food = food
def getFood (self):
return self.__food
def setFood(self,food):
self.__food = food
class Birds(Animals):
def fly(self, speed):
print(self.name,"fly at",speed,"KPH max")
bird1 = Birds("Eagles", 6, 0.45, "mouse")
bird1.setFood("Hare")
print(bird1.getFood())
|
7b4735b11c676f6bdca78d41f809c51200b7a7c5 | FabianoJanisch/CursoEmVideo-Python | /Exercício 096.py | 240 | 3.765625 | 4 | def área(l, c):
a = l*c
print (f'A área do seu terreno {l}x{c} = {a}m²')
print (30*'-')
print ('Calculador da área'.center(30))
print (30*'-')
l = float(input('Largura (m): '))
c = float(input('Comprimento (m): '))
área(l, c) |
3b5455234bcb3a3f38785d65b5d00c0f073d0d58 | RaymondZano/Initial-programs | /Mastermind version 2.py | 3,612 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 23 23:38:43 2019
Version 2 of the Mastermind game
This is a transition program to the final version.
I used loop thru the dataframe to check the number of correct guess.
Determining the currect color but incorrect place is challenging.
Increased color to be guess to four.
@author: raymondzano
"""
import random
import pandas as pd
colors = ["black", "white", "red", "blue", "yellow"] #possible colors to guess
colorRightCount = [0, 0, 0, 0, 0] #initializing the values of the soon-to-be dataframe
colorRightGuess = [0, 0, 0, 0, 0] #initializing the values of the soon-to-be dataframe
colorGuessCount = [0, 0, 0, 0, 0] #initializing the values of the soon-to-be dataframe
colorWrongPosCount = [0, 0, 0, 0, 0] #initializing the values of the soon-to-be dataframe
labels = ['Colors', 'Actual Count', 'Right Guess Count','Guess Count', 'Wrong Position Count'] #different labels to be used in the dataframe
list_cols = [colors, colorRightCount, colorRightGuess, colorGuessCount, colorWrongPosCount] #
zipped = list(zip(labels, list_cols))
data = dict(zipped)
colorListCount = pd.DataFrame(data)
color1 = random.choice(colors) #choosing the four colors to be guess
color2 = random.choice(colors)
color3 = random.choice(colors)
color4 = random.choice(colors)
tobeguess = [color1, color2, color3, color4] #puts the guessed color to a list
for i in range(len(tobeguess)): #updates the Actual Count column of the colorListCount table
for j in range(len(colorListCount)):
if str(tobeguess[i]) == str(colorListCount.iloc[j,0]):
colorListCount.iloc[j,1] += 1
print("""
1. Guess the correct four colors AND its correct position.
2. There are five possible colors: black, blue, red, white, and yellow.
3. You have twelve chances to guess.
4. At the end of each guess, there will be two hints:
number of color/s in correct position/s
number of correct color but in wrong position
""") #mechanics
guessesTaken = 0 #initializing the guess taken by the player
maxGuess = 2
while guessesTaken < maxGuess:
RightPosition = 0
userGuessColor1 = input(f"""
Number of guess/es made : {guessesTaken} out of {maxguess}.
Possible colors: black, blue, red, white, yellow
First color: """)
userGuessColor2 = input("""
Second color: """)
userGuessColor3 = input("""
Third color: """)
userGuessColor4 = input("""
Fourth color: """)
userGuessColor = [userGuessColor1, userGuessColor2, userGuessColor3, userGuessColor4]
for i in range(len(userGuessColor)): #for correct color in correct place
if str(userGuessColor[i]) == str(tobeguess[i]):
RightPosition += 1 #counts the right positions
guessesTaken = guessesTaken + 1
if RightPosition != 4:
print(f"""
Sorry! You did not guess both colors correctly.
HINT: You have {RightPosition} color in right position """)
colorListCount.iloc[:,2] = 0 #to do: reset the guess count to 0
elif RightPosition == 4:
print(f"""
Wow! You guess the correct colors in their correct positions.
As you guessed, they are {color1} as first,
{color2} as second,
{color3} as third, and
{color4} as the fourth one.
You did it in {guessesTaken} guesses only.""")
guessesTaken = maxGuess * 20 #forcing exit after guessing the puzzle
|
97e57f74a57c5d2f610120ae0a593eacb081478e | JontySinai/hackerrank | /10_Days_Stats/day4_geom_dist_1.py | 356 | 4.0625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import sys
# inp = raw_input()
inp = '1 3\n 5'
inp = inp.split(' ')
inp[1] = inp[1].replace('\n' ,'')
num = float(inp[0])
den = float(inp[1])
p_def = num/den
inspection = int(inp[2])
def geom_dist(n,p):
return ((p-1)**(n-1))*p
print round(geom_dist(inspection,p_def),3)
|
56436e45be8c7486f58a5640f7ae2acb4c1ce5d1 | devansh20la/Algorithms | /topinterview/flatten-nested-list-iterator.py | 1,635 | 4.09375 | 4 | # """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger:
# def isInteger(self) -> bool:
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# """
#
# def getInteger(self) -> int:
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# """
#
# def getList(self) -> [NestedInteger]:
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# """
class NestedIterator:
def __init__(self, nestedList: [NestedInteger]):
self.nestedlist = []
def flatten(nestedList):
for vals in nestedList:
if vals.isInteger():
self.nestedlist += [vals.getInteger()]
else:
flatten(vals.getList())
flatten(nestedList)
self.len = len(self.nestedlist)
self.index = 0
def next(self) -> int:
val = self.nestedlist[self.index]
self.index += 1
return val
def hasNext(self) -> bool:
if self.index == self.len:
return False
else:
return True
# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next()) |
05de53faace4960e88f76fbe9c3d7020a1a1f737 | yarduoc/L-Systems | /Environment-sensitive/Growth_Modifier.py | 4,337 | 3.578125 | 4 | ## Growth_Modifier_Volume Objects
"""
Defines volumes in a 3D space, associated with a function on Euclidian_Space_Vectors.
"""
import os
os.chdir("C:\\GitHub\\L-Systems\\Environment-sensitive")
from Euclidian_Space_Vector import *
## Abstract Volume
class Growth_Modifier_Volume :
"""
Growth_Modifier_Volume( influence)
Returns a Growth_Modifier_Volume. This class is not made to be instanciated,
but rather to serve as a base to create custom influence volumes
Parameters
----------
influence : Eucilidian_Space_Vector -> Eucilidian_Space_Vector function
This function represents the influence this volume will have on vectors
"""
influence = None
def __init__( self, influence = None):
if influence is not None :
self.influence = influence
else :
self.influence = Growth_Modifier_Volume.Default_Influence
def is_in( self):
pass
## Default influence
def Default_Influence( vector):
return vector
def Double_Length_Influence( vector):
copy = vector.get_copy()
copy.homothety(2)
return copy
def Halve_Length_Influence( vector):
copy = vector.get_copy()
copy.homothety(1/2)
return copy
## Real Volumes inheriting from Growth_Modifier_Volumes
class GM_Sphere (Growth_Modifier_Volume):
"""
GM_Sphere( center_vector, radius, influence)
Returns a GM_Sphere. GM_Sphere represent a volumic influence bounded inside
a sphere.
Parameters
----------
center_vector : Euclidian_Space_Vector
This vector determines where the center of the influence sphere will be
radius : float or int
This value determines the radius of the influence sphere
influence : Eucilidian_Space_Vector -> Eucilidian_Space_Vector function
This function represents the influence this volume will have on vectors
"""
center = Euclidian_Space_Vector((0,0,0))
radius = 1
def __init__( self, center_vector, radius, influence):
super().__init__(influence)
self.center = center_vector
self.radius = radius
def is_in( self, vector):
return (self.center - vector).get_norm() < self.radius
class GM_Parallelepiped (Growth_Modifier_Volume):
"""
GM_Parallelepiped( origin_vector, x_vect, y_vect, z_vect, influence)
Returns a GM_Parallelepiped. GM_Sphere represent a volumic influence bounded
inside a parallelepiped
Parameters
----------
origin_vector : Euclidian_Space_Vector
This vector determines where the origin corner of the parallelepiped will
be located
x_vect : Euclidian_Space_Vector
This vector represents the first edge of the parallelepiped connected to the
origin point
y_vect : Euclidian_Space_Vector
This vector represents the second edge of the parallelepiped connected to the
origin point
z_vect : Euclidian_Space_Vector
This vector represents the third edge of the parallelepiped connected to the
origin point
influence : Eucilidian_Space_Vector -> Eucilidian_Space_Vector function
This function represents the influence this volume will have on vectors
"""
origin = Euclidian_Space_Vector((0,0,0))
x = Euclidian_Space_Vector((1,0,0))
y = Euclidian_Space_Vector((0,1,0))
z = Euclidian_Space_Vector((0,0,1))
def __init__( self, origin_vector, x_vect, y_vect, z_vect, influence):
super().__init__(influence)
self.origin = origin_vector
self.x = x_vect
self.y = y_vect
self.z = z_vect
def is_in( self, vector):
new_vector = vector - self.origin
valid_x = 0 <= (new_vector * self.x) <= (self.x.get_norm())**2
valid_y = 0 <= (new_vector * self.y) <= (self.y.get_norm())**2
valid_z = 0 <= (new_vector * self.z) <= (self.z.get_norm())**2
return valid_x and valid_y and valid_z
|
fbb6bb45204d87e29b99e91aa82128a49b000444 | RoanPaulS/Whileloop_Python | /num_divby_3.py | 262 | 4.09375 | 4 | first = 1;
last = 100;
while(first <= last):
if(first%3==0):
print(first);
first = first+1;
"""
without using if condition
first = 3;
last = 100;
while(first <= last):
print(first);
first = first +3;
"""
|
0b5d47eec4174325920c9454a19996b7e18537dd | AshDagot/python_lessons | /lesson1.py | 4,368 | 3.953125 | 4 | # 1. Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько
# чисел и строк и сохраните в переменные, выведите на экран.
# 2. Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды и выведите в формате
# чч:мм:сс. Используйте форматирование строк.
time_sec = int(input('Введите число: '))
hours = time_sec//3600
hours_res = (hours) if hours > 10 else ('0' + str(hours))
minutes = (time_sec % 3600)//60
minutes_res = (minutes) if minutes > 10 else ('0' + str(minutes))
seconds = (time_sec % 3600) % 60
seconds_res = (seconds) if seconds > 10 else ('0' + str(seconds))
if hours > 24:
print('Количество полученных часов превышает количество часов в сутка, скоректируйте ввод.')
else:
print(f'Московское время: {hours_res}:{minutes_res}:{seconds_res}')
# 3. Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn. Например, пользователь ввёл число
# 3. Считаем 3 + 33 + 333 = 369.
# n = input('Введите число: ')
# nn = int(n+n)
# nnn = int(n+n+n)
# n = int(n)
# result = n+nn+nnn
# print(result)
# 4. Пользователь вводит целое положительное число. Найдите самую большую цифру в числе.
# Для решения используйте цикл while и арифметические операции.
# number = int(input(''))
# 5. Запросите у пользователя значения выручки и издержек фирмы. Определите,
# с каким финансовым результатом работает фирма (прибыль — выручка больше
# издержек, или убыток — издержки больше выручки). Выведите соответствующее сообщение.
# Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке).
# Далее запросите численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника.
# plus = int(input('Введите значение прибыли: '))
# minus = int(input('Введите значение издержек: '))
# people = int(input('Ввдите количество работников: '))
# if plus > minus:
# print('Выручка больше издержек')
# clear_plus = plus - minus
# rent = clear_plus/plus
# print('Рентабельность {} выручки {}: {:.2f}' .format('нашей','составила',rent))
# clear_for_person = float(clear_plus/people)
# print('Прибыль фирмы в расчете на одного сотрудника: %s'%clear_for_person)
# else:
# print('Фирма работает в убыток')
# 6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров.
# Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего.
# Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров.
# Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня.
# Например: a = 2, b = 3.
# Результат:
# 1-й день: 2
# 2-й день: 2,2
# 3-й день: 2,42
# 4-й день: 2,66
# 5-й день: 2,93
# 6-й день: 3,22
#
# Ответ: на 6-й день спортсмен достиг результата — не менее 3 км. |
e560e1a1f6f4797e6cffa979cc66b6879c740bf0 | shubhangsrikoti/lab1-python | /main.py | 582 | 4.28125 | 4 | ## Author Shubhang Srikoti [email protected]
## Collaborator Zihan Xia [email protected]
## Collaborator Xinyi Yang [email protected]
## Collaborator Lynn Francis [email protected]
temp = float(input("Enter temperature: "))
unit = input("Enter unit in F/f or C/c: ")
if unit == "F" or unit == "f":
newCelsius = ((temp - 32) * 5)/9
print(f"{temp}° in Fahrenheit is equivalent to {newCelsius}° Celsius.")
elif unit == "C" or unit == "c":
##print("Converting Celsius to Fahrenheit.")
newFahrenheit = (temp * 1.8) + 32
print(f"{temp}° in Celsius is equivalent to {newFahrenheit}° Fahrenheit.")
else:
print(f"Invalid unit({unit}).") |
eef0aeff189ebfda11809665b38a64f59e084612 | 0neir0s/ctci | /1-arrays-strings/1.3.py | 181 | 3.875 | 4 | def permutation(s1,s2):
"""Given two strings, decide if one is a permutation of the other"""
if len(s1) != len(s2):
return False
return sorted(s1) == sorted(s2)
|
062663954a0689537bfd4b0671ddd17d260375c8 | Lazy-coder-Hemlock/Leet_Code-Solutions | /988. Smallest String Starting From Leaf.py | 723 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def smallestFromLeaf(self, root: TreeNode) -> str:
if root is None:
return ""
def paths(root,path,big_path):
if root is None:
return
path+=chr(root.val+97)
if root.left is None and root.right is None:
big_path.append(path[::-1])
paths(root.left,path,big_path)
paths(root.right,path,big_path)
path=""
big_path=[]
paths(root,path,big_path)
return min(big_path)
|
50b346c924470dda87b5ae62c36488361b4d2a61 | Manis99803/advance_calendar | /calendar/month_calendar.py | 1,964 | 4.1875 | 4 | """
file which deals with generating month calendar
"""
import calendar
class MonthCalendar:
"""
displays the full calendar
"""
def __init__(self, today_date):
"""
constructor for initializng the necessary items for full calendar class
"""
self.today_date = today_date
def highlight_current_date(self, month_calendar):
"""
highlights the current date
"""
row_index = 3
cal_len = len(month_calendar)
date_str_length = int()
date_row_index = int()
date_col_index = int()
for j in range(2, cal_len):
dates = month_calendar[j]
dates_len = len(dates)
column_index = 1
for i in range(dates_len):
if dates[i] == str(self.today_date.curr_date):
return row_index, column_index, 1
elif (i + 1) < dates_len and \
((dates[i] + dates[i + 1]) == str(self.today_date.curr_date)):
return row_index, column_index + 1, 2
column_index += 1
row_index += 1
return date_row_index, date_col_index, date_str_length
def get_month_calendar(self, month):
"""
returns full month calendar for the given month
"""
calendar_date_info = dict()
month_calendar = calendar.month(self.today_date.curr_year, month)
month_calendar = month_calendar.split("\n")
row_index, column_index, date_len = self.highlight_current_date(month_calendar)
month_calendar_str = str()
for row in month_calendar:
month_calendar_str += (row + "\n")
calendar_date_info["month_calendar"] = month_calendar_str
calendar_date_info["row_index"] = row_index
calendar_date_info["column_index"] = column_index
calendar_date_info["date_len"] = date_len
return calendar_date_info
|
61e65e37b64a6ab8f3de8202d7ca61a7d857e812 | agyen/glcd | /advanced_python/fold.py | 150 | 3.890625 | 4 | def join_string():
words = ["hey", "how", "are", "you", "doing"]
return ("" + words)
words_joined = join_string()
print( " " + words_joined) |
238f75b271d0b78f7e3a989ca33a7f0b4ea0eb6a | coreyarch1234/leetcode-problems | /leetcode/random_pick_index.py | 443 | 4.0625 | 4 |
import random
def pick(target, nums):
"""
:type target: int
:rtype: int
"""
len_nums = len(nums)
found = False
while found == False:
random_indices = []
for num in nums:
random_indices.append(random.randint(0, len_nums - 1))
for index in random_indices:
if nums[index] == target:
found = True
return index
print pick(3, [1,2,3,3,3])
|
f65971306c8f0fe9407ea30d50065bf23fdcca36 | mne-tools/mne-tools.github.io | /0.21/_downloads/b8b52271197f52c0aa9d972bdb70f36c/plot_3d_to_2d.py | 4,910 | 3.65625 | 4 | """
.. _ex-electrode-pos-2d:
====================================================
How to convert 3D electrode positions to a 2D image.
====================================================
Sometimes we want to convert a 3D representation of electrodes into a 2D
image. For example, if we are using electrocorticography it is common to
create scatterplots on top of a brain, with each point representing an
electrode.
In this example, we'll show two ways of doing this in MNE-Python. First,
if we have the 3D locations of each electrode then we can use Mayavi to
take a snapshot of a view of the brain. If we do not have these 3D locations,
and only have a 2D image of the electrodes on the brain, we can use the
:class:`mne.viz.ClickableImage` class to choose our own electrode positions
on the image.
"""
# Authors: Christopher Holdgraf <[email protected]>
#
# License: BSD (3-clause)
from scipy.io import loadmat
import numpy as np
from matplotlib import pyplot as plt
from os import path as op
import mne
from mne.viz import ClickableImage # noqa
from mne.viz import (plot_alignment, snapshot_brain_montage,
set_3d_view)
print(__doc__)
subjects_dir = mne.datasets.sample.data_path() + '/subjects'
path_data = mne.datasets.misc.data_path() + '/ecog/sample_ecog.mat'
# We've already clicked and exported
layout_path = op.join(op.dirname(mne.__file__), 'data', 'image')
layout_name = 'custom_layout.lout'
###############################################################################
# Load data
# ---------
#
# First we'll load a sample ECoG dataset which we'll use for generating
# a 2D snapshot.
mat = loadmat(path_data)
ch_names = mat['ch_names'].tolist()
elec = mat['elec'] # electrode coordinates in meters
# Now we make a montage stating that the sEEG contacts are in head
# coordinate system (although they are in MRI). This is compensated
# by the fact that below we do not specicty a trans file so the Head<->MRI
# transform is the identity.
montage = mne.channels.make_dig_montage(ch_pos=dict(zip(ch_names, elec)),
coord_frame='head')
info = mne.create_info(ch_names, 1000., 'ecog').set_montage(montage)
print('Created %s channel positions' % len(ch_names))
###############################################################################
# Project 3D electrodes to a 2D snapshot
# --------------------------------------
#
# Because we have the 3D location of each electrode, we can use the
# :func:`mne.viz.snapshot_brain_montage` function to return a 2D image along
# with the electrode positions on that image. We use this in conjunction with
# :func:`mne.viz.plot_alignment`, which visualizes electrode positions.
fig = plot_alignment(info, subject='sample', subjects_dir=subjects_dir,
surfaces=['pial'], meg=False)
set_3d_view(figure=fig, azimuth=200, elevation=70)
xy, im = snapshot_brain_montage(fig, montage)
# Convert from a dictionary to array to plot
xy_pts = np.vstack([xy[ch] for ch in info['ch_names']])
# Define an arbitrary "activity" pattern for viz
activity = np.linspace(100, 200, xy_pts.shape[0])
# This allows us to use matplotlib to create arbitrary 2d scatterplots
fig2, ax = plt.subplots(figsize=(10, 10))
ax.imshow(im)
ax.scatter(*xy_pts.T, c=activity, s=200, cmap='coolwarm')
ax.set_axis_off()
# fig2.savefig('./brain.png', bbox_inches='tight') # For ClickableImage
###############################################################################
# Manually creating 2D electrode positions
# ----------------------------------------
#
# If we don't have the 3D electrode positions then we can still create a
# 2D representation of the electrodes. Assuming that you can see the electrodes
# on the 2D image, we can use :class:`mne.viz.ClickableImage` to open the image
# interactively. You can click points on the image and the x/y coordinate will
# be stored.
#
# We'll open an image file, then use ClickableImage to
# return 2D locations of mouse clicks (or load a file already created).
# Then, we'll return these xy positions as a layout for use with plotting topo
# maps.
# This code opens the image so you can click on it. Commented out
# because we've stored the clicks as a layout file already.
# # The click coordinates are stored as a list of tuples
# im = plt.imread('./brain.png')
# click = ClickableImage(im)
# click.plot_clicks()
# # Generate a layout from our clicks and normalize by the image
# print('Generating and saving layout...')
# lt = click.to_layout()
# lt.save(op.join(layout_path, layout_name)) # To save if we want
# # We've already got the layout, load it
lt = mne.channels.read_layout(layout_name, path=layout_path, scale=False)
x = lt.pos[:, 0] * float(im.shape[1])
y = (1 - lt.pos[:, 1]) * float(im.shape[0]) # Flip the y-position
fig, ax = plt.subplots()
ax.imshow(im)
ax.scatter(x, y, s=120, color='r')
plt.autoscale(tight=True)
ax.set_axis_off()
plt.show()
|
d74f515852e4146e324f4d719476f8c2e6a2af3e | Azerlund6214/Python-Semantic-Analysis-for-NNetwork | /FUNC/TEXT/_3_get_list_words_no_small.py | 421 | 4.15625 | 4 | # 01.dec.17 20.29
def GET_LIST_WORDS_NO_SMALL( list_of_words , MAX_LEN_OF_SMALL_WORD ):
# MAX_LEN_OF_SMALL_WORD = 3
final_list_lists = []
for one_word in list_of_words:
if len(one_word) <= MAX_LEN_OF_SMALL_WORD:
continue
final_list_lists.append(one_word)
return final_list_lists
### |
b74ee0c8f0c7ab909600d8f15cb104351a9a0aaf | Monzillaa/practices-python | /lists.py | 1,280 | 4.21875 | 4 | demo_list = [1, 'hello', 1.34, True, [1,2,3]]
colors = ['red', 'red', 'red', 'green', 'blue']
##Definimos las listas a travez de un constroctor o funcion llamado list
numbers_list = list((1,2,3,4))
print(numbers_list)
#print(type(numbers_list))
#r = list(range(1, 10))
#print(r)
#print(dir(colors))
#print(len(demo_list))
#print(colors[2])
#print("green" in colors)
# print(colors)
# colors[1] = 'yellow'
# print(colors)
#print(dir(colors))
##agregar elementos a una lista
#colors.append('violet')
##extiende los elementos en la lista
#colors.extend(['violet', 'yellow'])
#colors.extend(['pink', 'black'])
#colors.insert(-1, 'violet')
##cuenta la longitud y coloca al final de la lista el elementp
# colors.insert(len(colors),'violet')
# print(colors)
##elimina el ultimo elemento de la lista si no especifico el indice
# colors.pop()
#colors.pop(1)
#print(colors)
##remueve un elemento en especifico
#colors.remove('green')
#print(colors)
##limpiar toda la lista
#colors.clear()
##ordena la lista alfabeticamente si se deja vacio
#si colocas reverse en los parentesis lo hace de forma inversa
#colors.sort(reverse=True)
##imprimir el indice del valor
#print(colors.index('blue'))
##imprime cuantas veces esta almacenado un elemento
print(colors)
print(colors.count('red')) |
47f0e2d3a7ccbdf4ee7d765c3761e0d29912bf74 | sirvolt/Avaliacao1 | /questao14.py | 315 | 3.578125 | 4 | def contaEV():
frase=str(input('Frase: '))
i=0
x=0
while i<len(frase):
if frase[i]==' ':
x=x+1
i=i+1
print('Espacos: %d'%(x))
i=0
x=0
while i<len(frase):
if frase[i]=='a' or frase[i]=='e' or frase[i]=='i' or frase[i]=='o' or frase[i]=='u':
x=x+1
i=i+1
print('Vogais: %d'%(x))
|
edff72b178255bcd926cab683a257610bd70ca56 | eugenepark1/py2 | /interview/basic/palin.py | 1,435 | 4 | 4 | '''
Created on Aug 31, 2017
@author: eugene
when there is an inner and outer loop, ask if you need to shoten the inner loop (i.e. possible palins)
'''
# 1st inner-outer loop
# 2nd is have all the palins in dictionary and search against it o(1)
# cigar tragic
# palin means reveserd is the same
def is_palin(first_word, second_word):
concat_word = first_word + second_word
if concat_word == concat_word.reversed():
return True
return False
def give_possible_palins(word):
'tragic'
return
# 1) store english_dict in Dictionary
# * lookup will be O(1))
# runtime is O(N*K*1) where N is the number of words in english_dict, K is the number of possible palins and lookup
# Pseudo
# for word in english_dict:
# for possible in give_possible_palins(word)
# if possible in english_dict:
# add possible
def check_palin(word):
for i in xrange(len(word)/2):
if word[i] != word[-1*(i+1)]:
return False
return True
def all_palindromes(string):
left,right=0,len(string)
j=right
results=[]
while left < right-1:
temp = string[left:j] #Time complexity O(k)
j-=1
if check_palin(temp):
results.append(temp)
if j<left+2:
left+=1
j=right
return list(set(results))
print all_palindromes("racecarenterelephantmalayalam") |
dbeed1ea7490ee00fa842ca55d7caa757f61bf69 | zchaoking/gsplinets | /gsplinets_tf/group/SE2.py | 7,335 | 3.65625 | 4 | # Class implementation of the Lie group SE(2)
import tensorflow as tf
import numpy as np
# Rules for setting up a group class:
# A group element is always stored as a 1D vector, even if the elements consist
# only of a scalar (in which case the element is a list of length 1). Here we
# also assume that you can parameterize your group with a set of n parameters,
# with n the dimension of the group. The group elements are thus always lists of
# length n.
#
# This file requires the definition of the base/normal sub-group R^n and the
# sub-group H. Together they will define G = R^n \rtimes H.
#
# In order to derive G (it's product and inverse) we need for the group H to be
# known the group product, inverse and left action on R^n.
#
# In the B-Spline networks we also need to know a distance between two elements
# g_1 and g_2 in H. This can be defined by computing the length (l2 norm) of the
# vector that brings your from element g_1 to g_2 via the exponential map. This
# vector can be obtained by taking the logarithmic map of (g_1^{-1} g_2).
#
# Finally we need a way to sample the group. Therefore also a function "grid" is
# defined which samples the group as uniform as possible given a specified
# number of elements N. Not all groups allow a uniform sampling given an
# aribitrary N, in which case the sampling can be made approximately uniform by
# maximizing the distance between all sampled elements in H (e.g. via a
# repulsion model).
## The normal sub-group R^n:
# This is just the vector space R^n with the group product and inverse defined
# via the + and -.
class Rn:
# Label for the group
name = 'R^2'
# Dimension of the base manifold N=R^n
n = 2
# The identity element
e = tf.constant(np.array([0.,0.]), dtype=tf.float32)
## The sub-group H:
class H:
# Label for the group
name = 'SO(2)'
# Dimension of the sub-group H
n = 1 # Each element consists of 1 parameter
# The identify element
e = tf.constant(np.array([0.]), dtype=tf.float32)
## Essential definitions of the group
# Group product
def prod( h_1, h_2 ):
return h_1 + h_2
# Group inverse
def inv( h ):
return -h
## Essential for computing the distance between two group elements
# Logarithmic map
def log( h ):
return tf.math.mod(h + np.pi, 2*np.pi) - np.pi
def exp( c ):
return c
# Distance between two group elements
def dist( h_1, h_2):
# The logarithmic distance ||log(inv(h1).h2)||
# dist = tf.abs(tf.mod(h2 - h1 + np.pi, 2*np.pi) - np.pi)
dist = ( H.log( H.prod( H.inv(h_1), h_2)))[...,0] # Since each h is a list of length 1 we can do [...,0]
return dist
## Essential for constructing the group G = R^n \rtimes H
# Define how H acts transitively on R^n
def left_action_on_Rn( h, xx ):
x = xx[...,0]
y = xx[...,1]
th = h[0]
x_new = x * tf.cos(th) - y * tf.sin(th)
y_new = x * tf.sin(th) + y * tf.cos(th)
# Reformat c
xx_new = tf.stack([x_new,y_new],axis=-1)
# Return the result
return xx_new
## Essential in the group convolutions
# Define the determinant (of the matrix representation) of the group element
def det( h ):
return 1.
## Grid class
class grid_global: # For a global grid
# Should a least contain:
# N - specifies the number of grid points
# scale - specifies the (approximate) distance between points, this will be used to scale the B-splines
# grid - the actual grid
# args - such that we always know how the grid was construted
# Construct the grid
def __init__(self, N ):
# This rembembers the arguments used to construct the grid (this is to make it a bit more future proof, you may want to define a grid using specific parameters and later in the code construct a similar grid with the same parameters, but with N changed for example)
self.args = locals().copy()
self.args.pop('self')
# Store N
self.N = N
# Define the scale (the spacing between points)
self.scale = [2*np.pi/N]
# Generate the grid
if self.N==0:
h_list = tf.constant(np.array([]),dtype=tf.float32)
else:
h_list = tf.constant(np.array([np.linspace(0, 2*np.pi - 2*np.pi/N,N)]).transpose(),dtype=tf.float32)
self.grid = h_list
## Grid class
class grid_local: # For a global grid
# Should a least contain:
# N - specifies the number of grid points
# scale - specifies the (approximate) distance between points, this will be used to scale the B-splines
# grid - the actual grid
# args - such that we always know how the grid was construted
# Construct the grid
def __init__(self, N, scale ):
# This rembembers the arguments used to construct the grid (this is to make it a bit more future proof, you may want to define a grid using specific parameters and later in the code construct a similar grid with the same parameters, but with N changed for example)
self.args = locals().copy()
self.args.pop('self')
# Store N
self.N = N
# Define the scale (the spacing between points)
# dc should be a list of length H.n. Let's turn it into a numpy array:
scale_np = np.array(scale)
self.scale = scale_np
# Generate the grid
# Create an array of uniformly spaced exp. coordinates (step size is 1):
# The indices always include 0. When N = odd, the grid is symmetric. E.g. N=3 -> [-1,0,1].
# When N = even the grid is moved a bit to the right. E.g. N=2 -> [0,1], N=3 -> [-1,0,1,2]
grid_start = -((N-1)//2)
c_index_array = np.moveaxis(np.mgrid[tuple([slice(grid_start,grid_start + N)]*H.n)],0,-1).astype(np.float32)
# Scale the grid with dc
c_array = scale_np*c_index_array
# Flatten it to a list of exp coordinates as a tensorflow constant
c_list = tf.constant(np.reshape(c_array,[-1,H.n]), dtype = tf.float32 )
# Turn it into group elements via the exponential map
h_list = H.exp(c_list)
# Save the generated grid
self.grid = h_list
## The derived group G = R^n \rtimes H.
# The above translation group and the defined group H together define the group G
# The following is automatically constructed and should not be changed unless
# you may have some speed improvements, or you may want to add some functions such
# as the logarithmic and exponential map.
# A group element in G should always be a vector of length Rn.n + H.n
class G:
# Label for the group G
name = 'SE(2)'
# Dimension of the group G
n = Rn.n + H.n
# The identity element
e= tf.concat([Rn.e,H.e],axis=-1)
# Function for splitting a group element g in G in to its xx and h component
def xx_h(g):
xx = g[...,0:Rn.n]
h = g[...,Rn.n:]
return xx, h
# Function that returns the classes for R^n and H
def Rn_H():
return Rn, H
# The derived group product
def prod( g_1, g_2 ): # Input g_1 is a single group element, input g_2 can be an array of group elements
# (xx_1, h_1)
xx_1 = g_1[0:Rn.n]
h_1 = g_1[Rn.n:]
# (xx_2, h_2)
xx_2 = g_2[...,0:Rn.n]
h_2 = g_2[...,Rn.n:]
# (xx_new, h_new)
xx_new = H.left_action_on_Rn( h_1, xx_2) + xx_1
h_new = H.prod(h_1,h_2)
g_new = tf.concat([xx_new,h_new],axis=-1)
# Return the result
return g_new
# The derived group inverse
def inv( g ):
# (xx, h)
xx = g[0:Rn.n]
h = g[Rn.n:]
# Compute the inverse
h_inv = H.inv(h)
xx_inv = H.left_action_on_Rn( H.inv(h), -xx)
# Reformat g3
g_inv = tf.concat([xx_inv,h_inv],axis=-1)
# Return the result
return g_inv |
820e8fbea5b01f6fa436d83cbe969973bfbd5751 | hefengxian/python-playground | /learn/slice/advanced_slice.py | 3,628 | 4 | 4 | """
深入理解 slice 切片操作
"""
lst = list(range(10))
# X >= len(list) 时如下的切片都表示完整的 list(没有截取)
X = len(lst)
print(lst == lst[0:X]) # True
print(lst == lst[0:]) # True
print(lst == lst[:X]) # True
print(lst == lst[:]) # True
print(lst == lst[::]) # True
print(lst == lst[-X:X]) # True
print(lst == lst[-X:]) # True
print(lst[1:5]) # [1, 2, 3, 4]
print(lst[1:5:2]) # [1, 3]
print(lst[-1:]) # [9]
print(lst[-4:-2]) # [6, 7]
print(lst[:-2] == lst[-len(lst):-2] == [0, 1, 2, 3, 4, 5, 6, 7]) # True
# 步长为负时,其实并不是翻转列表,这个地方的表示如下
# 0 1 2 3 4 5 6 7 8 9
# ^ 到这里结束 <-- ^ 从这里开始
print(lst[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# 表示如下的截取方法
# 0 1 2 3 4 5 6 7 8 9
# ^ <-- ^
print(lst[4::-1]) # [4, 3, 2, 1, 0]
# 0 1 2 3 4 5 6 7 8 9
# - ^ <-- ^ 注意这里 -9 的位置是开区间,所以取不到
print(lst[-3:-9:-1]) # [7, 6, 5, 4, 3, 2]
# 0 1 2 3 4 5 6 7 8 9
# ^ ^ ^ ^ ^
print(lst[::-2]) # [9, 7, 5, 3, 1]
# 0 1 2 3 4 5 6 7 8 9
# - ^ ^
print(lst[-2:-6:-2]) # [8, 6]
lst = [1, 2, 3, 4]
my_lst = lst[::]
print(lst == my_lst)
# id() 方法, CPython 的实现返回的是内存地址
print(id(lst) == id(my_lst))
lst.append(['A', 'B'])
my_lst.extend([5, 6])
print(lst) # [1, 2, 3, 4, ['A', 'B']]
print(my_lst) # [1, 2, 3, 4, 5, 6]
# 一点没有用的操作,直接使用 len(lst) > 8 更好理解,效率更高
if lst[8:]:
print('Length > 8')
else:
print('Length <= 8')
# 切片只是浅拷贝
lst = [1, 2, [3, 4], 6]
my_lst = lst[:3]
print(my_lst) # [1, 2, [3, 4]]
# 更新数据
lst[2].append('A')
print(my_lst) # [1, 2, [3, 4, 'A']]
# 给切片赋值,注意:值必须是可迭代对象
lst = [1, 2, 3, 4]
# 头部添加
lst[:0] = [-1, 0]
print(lst) # [-1, 0, 1, 2, 3, 4]
# 尾部添加
lst[len(lst):] = [6, 7]
print(lst) # [-1, 0, 1, 2, 3, 4, 6, 7]
# 中间添加
lst[6:6] = [5] # [-1, 0, 1, 2, 3, 4, 5, 6, 7]
print(lst)
# 必须是可迭代对象
# lst[:0] = 3 # TypeError: can only assign an iterable
lst[:0] = (-3, -2)
print(lst) # [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7]
# 前面我们操作的都是:切片后列表是空的
# 那么切片后的列表不为空,复制后之后会发生什么?—— 替换
lst = [0, 1, 2, 5]
lst[3:] = (3, 4, 5)
print(lst) # [0, 1, 2, 3, 4, 5]
lst[2:4] = ['A', 'B']
print(lst) # [0, 1, 'A', 'B', 4, 5]
# 不等长的替换
lst[2:4] = ['x'] * 4
print(lst) # [0, 1, 'x', 'x', 'x', 'x', 4, 5]
# 删除
del lst[2:6]
print(lst) # [0, 1, 4, 5]
# 使用自定义步长的替换,注意:带步长的只能等长替换
lst = [0, 1, 2, 3, 4, 5]
lst[::2] = ['A', 'B', 'C']
print(lst) # ['A', 1, 'B', 3, 'C', 5]
lst[::2] = ['X'] * 3
print(lst) # ['X', 1, 'X', 3, 'X', 5]
# lst[::2] = ['W'] # ValueError: attempt to assign sequence of size 1 to extended slice of size 3
del lst[::2]
print(lst) # [1, 3, 5]
# 自定义切片对象
class MyList:
def __init__(self, data):
self.data = data
def __getitem__(self, key):
print(f"Key is: {key}")
if isinstance(key, slice):
return self.data[key]
elif isinstance(key, int):
return self.data[key]
else:
msg = f"{MyList.__name__} indices must be integers"
raise TypeError(msg)
ml = MyList([1, 2, 3, 4])
print(ml[1])
print(ml[:2])
print(ml['key'])
# 输出如下:
# Key is: 1
# 2
# Key is: slice(None, 2, None)
# [1, 2]
# Key is: key
# Traceback (most recent call last):
# ...
# TypeError: MyList indices must be integers
|
7c9dcb84f33118685cab06a8878af486422bbc78 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4008/codes/1745_3088.py | 174 | 3.9375 | 4 | num = (int(input("digite um nume: ")))
par = 0
impar = 0
cont = 0
while(num!=0):
if(num%2):
par = par + 1
cont = num + 1
else:(num%1):
impar = impar + 1
cont = num |
7311ac2d265d2256cafb99b7bc96cb3ec0001e36 | thierrydecker/ipi-pyt010 | /files-manipulation.py | 2,333 | 3.875 | 4 | #!/usr/bin/python
# -*- coding= utf-8 -*-
# Imports de la biblithèque standard
#
#
# Imports des bibliothèques tierces
#
#
# Internal functions
#
#
# main() function
#
#
# Open a file
#
def file_open(file_name, rights):
# Rights : 'r' -> read
# 'w' -> write
# 'a' -> append
file_descriptor = open(file_name, rights)
return file_descriptor
#
# Close a file
#
def file_close(file_descriptor):
file_descriptor.close()
#
# Read a file in one big string
#
def file_read(file_descritor):
file = file_descritor.read()
return file
#
# Read a file in one big list (each line in an element of the list
#
def file_read_lines(file_descritor):
file_list = file_descritor.readlines()
return file_list
#
# Read a file in one string per line at a time
#
def file_read_next_line(file_descritor):
line = file_descritor.readline()
return line
#
# Write a string into a file
#
def write_file_line(file_descriptor, text):
file_descriptor.write(text)
#
# Write a list of strings into a file
#
def write_file_lines(file_descritor, text):
file_descritor.writelines(text)
#
# Main function
#
def main():
file_name = 'test.txt'
rights = 'w'
file_descriptor = file_open(file_name, rights)
text = 'abc\n'
write_file_line(file_descriptor, text)
text = 'def\n'
write_file_line(file_descriptor, text)
text = [
'This is an exemple 1\n',
'This is an exemple 2\n',
'This is an exemple 3\n',
]
write_file_lines(file_descriptor, text)
file_close(file_descriptor)
file_name = 'test.txt'
rights = 'r'
file_descriptor = file_open(file_name, rights)
text = file_read(file_descriptor)
print(text)
file_close(file_descriptor)
file_name = 'test.txt'
rights = 'r'
file_descriptor = file_open(file_name, rights)
text = file_read_lines(file_descriptor)
print(text)
file_close(file_descriptor)
file_name = 'test.txt'
rights = 'r'
file_descriptor = file_open(file_name, rights)
text, line_number = None, 1
while text != "":
text = file_read_next_line(file_descriptor)
print(line_number, " -> ", text, end="")
line_number += 1
file_close(file_descriptor)
if __name__ == '__main__':
main()
|
126a550d60ea0e596d741ffbf5be43e1928dba71 | guipw2/python_exercicios | /ex050.py | 282 | 3.640625 | 4 | soma = 0
cont = 0
conta = 0
for c in range(1, 7):
num = int(input('Digite um valor:'))
conta += 1
if num % 2 == 0:
soma += num
cont += 1
print('Você me informou {} números dos quais {} era(m) par(es) e a soma dele(s) foi {}'.format(conta, cont, soma))
|
ab5da6baa1da81b80bd60684eb1bf0d978f40285 | nadeendames96/Web-Application-By-Python | /partical_assignments/PA1_NadeenDames/prob3.py | 628 | 3.84375 | 4 | # # Prob 3
# # Mars Rover
x=0
y=0
# Define Tuple and add x,y to position variable
position=()
print("Enter dicoration and value of dicoration : ")
dic=" "
dic_value=" "
for i in range(1,7):
dic,dic_value=input().split()
#dic_value=int(input())
if(dic=="U"):
y+=int(dic_value)
position=(x,y)
if(dic=="R"):
x+=int(dic_value)
position=(x,y)
if(dic=="L"):
x=abs(x-int(dic_value))
position=(x,y)
if(dic=="lo"):
y=abs(y-int(dic_value))
position=(x,y)
print(f"Current position: {position}"),
|
fb911ac3d63e60b1dc186b01bd32542366040642 | WasimAlgahlani/Instagram-Followers-Game | /main.py | 1,003 | 4 | 4 | """Guess the number program"""
import random
from game_data import data
def check(guess_f, account_a_f, account_b_f):
if account_a_f['follower_count'] > account_b_f['follower_count']:
return "a"
else:
return "b"
con = True
score = 0
account_a = random.choice(data)
while con:
account_b = random.choice(data)
while account_a == account_b:
account_b = random.choice(data)
print(f"Compare A: {account_a['name']}, a {account_a['description']}, from {account_a['country']}.\n")
print(f"Compare B: {account_b['name']}, a {account_b['description']}, from {account_b['country']}.\n")
guess = input("Who has more followers? Type 'A' or 'B': ").lower()
print()
if check(guess, account_a, account_b) == guess:
score += 1
print(f"You're right! Current score: {score}.\n")
else:
con = False
print(f"You're Wrong! Current score: {score}.\n")
account_a = account_b
print("\n\n")
|
439ab46484d99efb052575eb9be269d32a5eabf7 | janak11111/Data-Structure-With-Python | /Searching/BinarySearch.py | 473 | 3.640625 | 4 | pos = -1
def Search(list,n):
l = 0
u = len(list)-1
while l <= u:
mid = (l+u)//2
if list[mid] == n:
globals()['pos'] = mid
return True
else:
if list[mid] < n:
l = mid+1
else:
u = mid-1
return False
list = [1,3,7,9,23,65,88,453,2290,767654]
n = 453
if Search(list,n):
print("found at",pos+1)
else:
print("not found") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.