blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
b43da9d53ae5e8689a3d6d93c96c45e6551a69a0 | JVorous/ProjectEuler | /problem33.py | 1,453 | 3.765625 | 4 | from fractions import Fraction
def main():
a = 10
b = 10
fract_list = set()
while len(str(a)) < 3:
if a % 10 != 0 and b % 10 != 0 and a /b < 1:
red_a = 0
red_b = 0
#check if a and b are of non-trivial format
str_a = str(a)
str_b = str(b)
#refactor this - could be simpler
if str_a[0] == str_b[0]:
red_a = int(str(a)[1])
red_b = int(str(b)[1])
elif str_a[0] == str_b[1]:
red_a = int(str(a)[1])
red_b = int(str(b)[0])
elif str_a[1] == str_b[0]:
red_a = int(str(a)[0])
red_b = int(str(b)[1])
elif str_a[1] == str_b[1]:
red_a = int(str(a)[0])
red_b = int(str(b)[0])
#check that non-trivial reduced fractions were found
if red_a != 0 and red_b != 0:
if a / b == red_a / red_b:
fract_list.add((red_a, red_b))
#per conditions, both a and b are 2-digit values
if len(str(b)) < 3:
b += 1
else:
b = 10
a += 1
fraction_prod = Fraction(1,1)
for a, b in fract_list:
fraction_prod *= Fraction(a,b)
print('The numerator is {} and the denominator is {}'.format(fraction_prod.numerator, fraction_prod.denominator))
if __name__ == '__main__':
main() |
bd8dce29ec3fed1d6b8cb5b469a529f95b04873d | owenxu10/LeetCode | /sort.py | 723 | 3.984375 | 4 | def selectSort(nums):
for i in range(0, len(nums)):
smallestIndex = i
for j in range(i, len(nums)):
if nums[j] < nums[smallestIndex]:
smallestIndex = j
change(nums, i, smallestIndex)
return nums
def insertSort(nums):
for i in range(1, len(nums)):
j = i - 1
while (j >= 0):
if (nums[i] < nums[j]):
change(nums, i, j)
i = j
j -= 1
return nums
def shellSort(nums):
pass
def change(nums, this, that):
temp = nums[this]
nums[this] = nums[that]
nums[that] = temp
print(selectSort([2, 4, 6, 1, 5, 6, 7, 1, 7, 2]))
print(insertSort([2, 4, 6, 1, 5, 6, 7, 1, 7, 2]))
|
1531336114f6235b88386b10cca46a9d53399d0f | JngHyun/Algorithm | /Inflearn/섹션 6(완전탐색,DFS)/DFS_이진트리순회.py | 802 | 4 | 4 | # DFS : 깊이 우선 탐색 (재귀 이용)
# BFS : 넓이 우선 탐색 (queue 이용)
# 1
# /\
# 2 3
# /\ /\
# 4 5 6 7
#DFS
#전위순회 : (부 왼 오) 1 2 4 5 3 6 7
#중위순회 : (왼 부 오) 4 2 5 1 6 3 7
#후위순회 : (왼 오 부) 4 5 2 6 7 3 1
def DFS(v):
if v>7:
return
else:
#stack 그려서 확인해보기
#print(v,end = ' ') #전위순회 : 함수 본연의 일(출력) - 호출하기 전에 작업을 수행함
DFS(v*2) #왼쪽 노드 호출
#print(v,end = ' ') #중위순회 : 부모가 중간에서 순회
DFS(v*2+1) #오른쪽 노드 호출
print(v,end = ' ') #후위순회 : 왼쪽과 오른쪽 모두 처리하고 수행 "병합정렬"
if __name__ == "__main__":
DFS(1)
|
139a8af9dd11cf28a988ae837ffad9ba54c2acef | Hugocorreaa/Python | /Curso em Vídeo/Desafios/Mundo 1/ex012.py | 327 | 3.640625 | 4 | # Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto.
preçoProduto = float(input("Qual o valor do produto? R$"))
desconto = preçoProduto * 0.05
preçoDesconto = preçoProduto - desconto
print("O preço do produto com 5% de desconto será R${:.2f} reais".format(preçoDesconto))
|
31fe631c72c7f275c3d385b76ac97806f3f3636c | GabrielRomanoo/Python | /Aula 9/ex2.py | 558 | 4.09375 | 4 | # Faça uma função que retorne a quantidade de
# espaços presentes em uma string.
from functools import reduce
x = 'Universidade Catolica de Santos'
espaco = list(filter(lambda s: s==' ', x))
#filter(funcao, sequencia)
#Retorna lista que pode ser de tamanho diferente da
#sequencia original. Retorna na verdade um objeto
#iterator, que deve ser convertido para uma list,
#utilizando o list()
#(lambda x,y : x+y)(1,2)
#Resultado 3
print(espaco)
espaco = len(espaco)
print(espaco)
#SAÍDA:
#[' ', ' ', ' ']
#3
|
e461914fa964bc36bb817fa4454a251d5523d62e | SanjeevkMishra/Generic_Training_Python_INFY | /Fundamental Programming Part 1/Assignment 2/calculate_bill_amount.py | 1,608 | 3.890625 | 4 | '''
Problem Statement
FoodCorner home delivers vegetarian and non-vegetarian combos to its customer based on order.
A vegetarian combo costs Rs.120 per plate and a non-vegetarian combo costs Rs.150 per plate. Their non-veg combo is really famous that
they get more orders for their non-vegetarian combo than the vegetarian combo.
Solution:-
'''
#lex_auth_012693782475948032141
def calculate_bill_amount(food_type,quantity_ordered,distance_in_kms):
bill_amount=0
if(food_type=="N" and quantity_ordered>0 and distance_in_kms>0):
if(distance_in_kms>0 and distance_in_kms<=3):
bill_amount = quantity_ordered*150
elif(distance_in_kms>3 and distance_in_kms<=6):
bill_amount = quantity_ordered*150 + (distance_in_kms-3)*3
elif(distance_in_kms>6):
bill_amount = quantity_ordered*150 + (distance_in_kms-6)*6 +3*3
elif(food_type=="V" and quantity_ordered>0 and distance_in_kms>0):
if(distance_in_kms>0 and distance_in_kms<=3):
bill_amount = quantity_ordered*120
elif(distance_in_kms>3 and distance_in_kms<=6):
bill_amount = quantity_ordered*120 + (distance_in_kms-3)*3
elif(distance_in_kms>6):
bill_amount = quantity_ordered*120 + (distance_in_kms-6)*6 +3*3
else:
bill_amount=-1
return bill_amount
#Provide different values for food_type,quantity_ordered,distance_in_kms and test your program
bill_amount=calculate_bill_amount("N",2,7)
print(bill_amount)
|
3526abc6a3f7eca145116b4491a58af102f171e7 | v3g42/wordsearch | /wordsearch.py | 836 | 3.796875 | 4 | #!/usr/bin/env python
import time
import argparse
from grid import Grid
def get_user_input():
"""
defines argument parser to take dimensions of the grid
"""
parser = argparse.ArgumentParser(
description='Please provide the dimensions of the grid')
parser.add_argument(
'x', metavar='int', type=int, default=10,
help='x dimension')
parser.add_argument(
'y', metavar='int', type=int, default=10,
help='y dimension')
args = parser.parse_args()
return args.x, args.y
if __name__ == '__main__':
curtime = time.time()
x, y = get_user_input()
grid = Grid(x, y)
# prints the grid to console.
print('##### Word Grid #####')
print(grid.to_text())
print('##### Words #####')
results = grid.search_in_dictionary(open('./words.txt'))
print(results)
print("Performed in {0} seconds".format(time.time() - curtime))
|
11c3f1c1c86383ef303f7772a54369609254255e | marciof/tools | /puzzles/uncoupled_integers.py | 918 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Find the only two integers that appear an odd number of times
in a sequence of `integers`.
"""
import unittest
def find(integers):
"""
Time: O(n)
Space: O(1)
https://www.careercup.com/question?id=16306671#commentThread16306671
"""
x_y_xor = 0
for n in integers:
x_y_xor ^= n
bit_mask = 1
while (x_y_xor & bit_mask) == 0:
bit_mask <<= 1
x = 0
y = 0
for n in integers:
if (n & bit_mask) == 0:
x ^= n
else:
y ^= n
return {x, y}
class Test (unittest.TestCase):
def test_only_two(self):
self.assertEqual(
find([3, 0]),
{3, 0})
def test_repeated(self):
self.assertEqual(
find([1, -2, 3, 1, 1, 4, 1, 3, 3, 4]),
{-2, 3})
if __name__ == '__main__':
unittest.main(verbosity = 2)
|
6e3c749c809681b45660258ca362814b0d135a32 | lizetheP/PensamientoC | /CalendarioAgo20L/informacion/autoestudioStrings.py | 366 | 4.34375 | 4 | cadena = "Computacion"
print(cadena[0 : 3])
print(cadena[ : 3])
print(cadena[3])
print(cadena[6: ])
print(cadena[-6: ])
print(cadena.find('o'))
print(cadena.replace('o', 'u'))
print(cadena.upper())
print(cadena.lower())
print(cadena.capitalize())
print('u' in cadena)
"""
print(str[3 : 8])
print(str[ : -3])
print(str[-3 : ])
print(str[5 : ])
print(str[ : 5])"""
|
b00a90327fa7a4e8ea86dc649bf23223fb184eeb | jayceazua/wallbreakers_work | /company/zendesk.py | 2,830 | 4.34375 | 4 | """
Write an `encrypt` and a `decrypt` method. Each should accept a `key` and a `message`.
encrypt(key, message) should reorder the alphabet by moving the key's letters to the front. Then, it should return a string with the message's letters swapped out for their index in the new alphabet. Assume that the key will not contain the same letter more than once.
For example, if your key is "things", the alphabet would transform this way:
Normal Alphabet: abcdefghijklmnopqrstuvwxyz
New Alphabet: thingsabcdefjklmopqruvwxyz
To encrypt your message, find each letter in the normal alphabet, and swap it out for the letter at the same index in the new alphabet.
For example, if your message is "these are some words" the encrypt method would return "rbgqg tpg qljg wlpnq".
encrypt("things", "these are some words")
=> "rbgqg tpg qljg wlpnq"
Decrypt just reverses the process:
decrypt("things", "rbgqg tpg qljg wlpnq")
=> "these are some words"
Use any language you like. Google any documentation you want, but no complete solutions. You're encouraged to ask clarifying questions.
Prioritize a complete solution first. We're most interested in the readability and completeness of your solution, and much less concerned with its performance.
"""
class Cipher:
# class var for alpha
def __init__(self):
# self.new_alpha = self._new_alpha(key)
pass
def _new_alpha(self, key): # build this new alphabet
"""
"things"
"""
cipher = {}
cipher2 = {}
alpha = list("abcdefghijklmnopqrstuvwxyz")
alpha1 = list("abcdefghijklmnopqrstuvwxyz")
new_alpha = []
for char in key:
index = alpha.index(char)
new_alpha.append(alpha.pop(index))
new_alpha = new_alpha + alpha
for char1, char2 in zip(alpha1, new_alpha):
cipher[char1] = char2
cipher2[char2] = char1
return cipher, cipher2
def encrypt(self, key, message):
new_msg = []
key = self._new_alpha(key)[0] # dictionary
for _, char in enumerate(message):
if char.isalpha():
new_msg.append(key[char])
else:
new_msg.append(char)
return "".join(new_msg)
def decrypt(self, key, msg):
new_msg = []
key = self._new_alpha(key)[1] # dictionary
for _, char in enumerate(msg):
if char.isalpha():
new_msg.append(key[char])
else:
new_msg.append(char)
return "".join(new_msg)
c = Cipher()
print(c.encrypt("things", "these are some words") == "rbgqg tpg qljg wlpnq")
print(c.encrypt("", "these are some words") == "these are some words")
print(c.decrypt("things", "rbgqg tpg qljg wlpnq") == "these are some words")
|
0561a11162860bd54e056150645b16daf3e29b48 | mairbek/CS231A-Computer-Vision-From-3D-Reconstruction-to-Recognition | /ps2_code/fundamental_matrix_estimation.py | 6,706 | 3.5 | 4 | import numpy as np
from scipy.misc import imread
import matplotlib.pyplot as plt
import scipy.io as sio
from epipolar_utils import *
'''
LLS_EIGHT_POINT_ALG computes the fundamental matrix from matching points using
linear least squares eight point algorithm
Arguments:
points1 - N points in the first image that match with points2
points2 - N points in the second image that match with points1
Both points1 and points2 are from the get_data_from_txt_file() method
Returns:
F - the fundamental matrix such that (points2)^T * F * points1 = 0
Please see lecture notes and slides to see how the linear least squares eight
point algorithm works
'''
def lls_eight_point_alg(points1, points2):
r = points1.shape[0]
A = np.zeros((r,9))
for i in range(r):
A[i] = np.dot(points2[i].reshape(3,-1),points1[i].reshape(1,-1)).flatten()
u,s,vh = np.linalg.svd(A)
# minimal error solution
F_prime = vh[-1].reshape(3,3)
# force fundamental matrix to rank 2
u,s,vh = np.linalg.svd(F_prime)
s[-1] = 0
F = np.dot(u * s, vh)
return F
'''
NORMALIZED_EIGHT_POINT_ALG computes the fundamental matrix from matching points
using the normalized eight point algorithm
Arguments:
points1 - N points in the first image that match with points2
points2 - N points in the second image that match with points1
Both points1 and points2 are from the get_data_from_txt_file() method
Returns:
F - the fundamental matrix such that (points2)^T * F * points1 = 0
Please see lecture notes and slides to see how the normalized eight
point algorithm works
'''
def normalized_eight_point_alg(points1, points2):
def transform_matrix(pts):
# T = [R 0;-RC 1]
centriod = np.mean(pts,axis=0)
diff = np.sum((pts - centriod)**2,axis=1)
scaling = np.mean(np.sqrt(diff))
R = np.diag([2/scaling,2/scaling])
T = np.diag([2/scaling,2/scaling,1])
T[:-1,-1] = - np.dot(R,centriod[:-1])
return T
T = transform_matrix(points1)
T_prime = transform_matrix(points2)
F_prime = lls_eight_point_alg(np.dot(T, points1.T).T,np.dot(T_prime, points2.T).T)
F = np.dot(T_prime.T,np.dot(F_prime, T))
return F
'''
PLOT_EPIPOLAR_LINES_ON_IMAGES given a pair of images and corresponding points,
draws the epipolar lines on the images
Arguments:
points1 - N points in the first image that match with points2
points2 - N points in the second image that match with points1
im1 - a HxW(xC) matrix that contains pixel values from the first image
im2 - a HxW(xC) matrix that contains pixel values from the second image
F - the fundamental matrix such that (points2)^T * F * points1 = 0
Both points1 and points2 are from the get_data_from_txt_file() method
Returns:
Nothing; instead, plots the two images with the matching points and
their corresponding epipolar lines. See Figure 1 within the problem set
handout for an example
'''
def plot_epipolar_lines_on_images(points1, points2, im1, im2, F):
# # l = F * x_prime
# # l_prime = F.T * x
# l = np.dot(F,points2.T)
# l_prime = np.dot(F.T, points1.T)
# f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
# ax1.imshow(im1,cmap='gray')
# ax1.axis('off')
# ax2.imshow(im2,cmap='gray')
# ax1.axis('off')
pSize=points1.shape
n=pSize[0]
#n=5
#print 'points size :\n',pSize
plt.figure()
plt.imshow(im1, cmap ='gray')
for i in range(n):
plot_epipolar_line(im1,F,points2[i:i+1,:])
plt.plot(points1[i,0],points1[i,1],'o')
#plt.axis('off')
plt.figure()
plt.imshow(im2, cmap ='gray')
for i in range(n):
#plot_epipolar_line(im2,F,points1)
plot_epipolar_line(im2,F.T,points1[i:i+1,:])
plt.plot(points2[i,0],points2[i,1],'o')
def plot_epipolar_line(img,F,points):
m,n=img.shape[:2]
line=F.dot(points.T)
t=np.linspace(0,n,100)
lt=np.array([(line[2]+line[0]*tt)/(-line[1]) for tt in t])
ndx=(lt>=0)&(lt<m)
t=np.reshape(t,(100,1))
#print 't\n',t[ndx]
#print 'lt\n',lt[ndx]
plt.plot(t[ndx],lt[ndx])
'''
COMPUTE_DISTANCE_TO_EPIPOLAR_LINES computes the average distance of a set a
points to their corresponding epipolar lines
Arguments:
points1 - N points in the first image that match with points2
points2 - N points in the second image that match with points1
F - the fundamental matrix such that (points2)^T * F * points1 = 0
Both points1 and points2 are from the get_data_from_txt_file() method
Returns:
average_distance - the average distance of each point to the epipolar line
'''
def compute_distance_to_epipolar_lines(points1, points2, F):
# abs(l.T * x) / sqrt(a**2 + b**2)
l = np.dot(F.T,points2.T)
coff = l[:-1]
distances = np.abs(np.diag(np.dot(l.T,points1.T))) / np.sqrt(np.sum(coff**2,axis=0))
average_distance = np.mean(distances)
return average_distance
if __name__ == '__main__':
for im_set in ['data/set1', 'data/set2']:
print '-'*80
print "Set:", im_set
print '-'*80
# Read in the data
im1 = imread(im_set+'/image1.jpg')
im2 = imread(im_set+'/image2.jpg')
points1 = get_data_from_txt_file(im_set+'/pt_2D_1.txt')
points2 = get_data_from_txt_file(im_set+'/pt_2D_2.txt')
assert (points1.shape == points2.shape)
# Running the linear least squares eight point algorithm
F_lls = lls_eight_point_alg(points1, points2)
print "Fundamental Matrix from LLS 8-point algorithm:\n", F_lls
print "Distance to lines in image 1 for LLS:", \
compute_distance_to_epipolar_lines(points1, points2, F_lls)
print "Distance to lines in image 2 for LLS:", \
compute_distance_to_epipolar_lines(points2, points1, F_lls.T)
# Running the normalized eight point algorithm
F_normalized = normalized_eight_point_alg(points1, points2)
pFp = [points2[i].dot(F_normalized.dot(points1[i]))
for i in xrange(points1.shape[0])]
print "p'^T F p =", np.abs(pFp).max()
print "Fundamental Matrix from normalized 8-point algorithm:\n", \
F_normalized
print "Distance to lines in image 1 for normalized:", \
compute_distance_to_epipolar_lines(points1, points2, F_normalized)
print "Distance to lines in image 2 for normalized:", \
compute_distance_to_epipolar_lines(points2, points1, F_normalized.T)
# Plotting the epipolar lines
plot_epipolar_lines_on_images(points1, points2, im1, im2, F_lls)
plot_epipolar_lines_on_images(points1, points2, im1, im2, F_normalized)
plt.show()
|
a7fb12cac76a371b2c762f7f52346a7ba286e01e | qingyueyang/Algorithms_DataStructure_Questions | /jumpSearch.py | 536 | 3.96875 | 4 | def search(arr, n, key):
# Travers the given array starting
# from leftmost element
i = 0
while (i < n):
# If key is found at index i
if (arr[i] == key):
return i
# Jump the difference between
# current array element and key
i = i + abs(arr[i] - key)
print("key not found!")
return -1
# test
arr = [8 ,7, 6, 7, 6, 5, 4, 3, 2, 3, 4, 3 ]
n = len(arr)
key = 3
print("Found at index ", search(arr,n,key)) |
20c18ea492d988728000eab454351f6a6c9bb31e | dev-juri/FizzBuzz | /FizzBuzz.py | 254 | 4.09375 | 4 | print('Input a number')
num= int(input())
if ((num%3==0) & (num%5==0)):
print('FizzBuzz')
elif (num%3 == 0):
print('Fizz')
elif (num%5 == 0):
print('Buzz')
else:
print('Number is not divisible by 3 and 5')
|
94a4ede627c1c75005d62fe6ca02dfef022a76c7 | Diegooualexandre/PycharmProjects | /pythonProject/desafio056.py | 908 | 3.859375 | 4 | # Programa que mostra o peso das pessoas
# Autor: Diego L. Alexandre | Data: 14/07/2021
soma_idade = 0
media_idade = 0
maior_idade_homem = 0
nome_mais_velho = ''
total_mulher20 = 0
for p in range(1, 5):
print(f'---- {p}ºPESSOA ----')
nome = str(input('Digite nome: ')).strip()
idade = int(input('Digite idade: '))
sexo = str(input('SEXO [M/F]')).strip()
soma_idade += idade
if p == 1 and sexo in 'Mm':
maior_idade_homem = idade
nome_mais_velho = nome
if sexo in 'Mn' and idade > maior_idade_homem:
maior_idade_homem = idade
nome_mais_velho = nome
if sexo in 'Fm' and idade < 20:
total_mulher20 += 1
media_idade = soma_idade / 4
print(f'A média de idade do grupo é {media_idade}')
print(f'O homem mais velho tem {maior_idade_homem} anos e se chama {nome_mais_velho}')
print(f'Ao todo temos {total_mulher20} mulheres com idade menor de 20 anos.')
|
f2d291cd86ff974b9199dc05c36fb33b42b6c079 | singalen/hige_class | /foxcross/foxcross.py | 1,046 | 3.75 | 4 | # -*- coding: utf-8 -*-
def _is_cross_at(a, x, y):
if x <= 0 or x >= len(a)-1:
raise IndexError(x)
if y <= 0 or y >= len(a[0])-1:
raise IndexError(y)
return a[x][y] == '#' and a[x][y-1] == '#' and a[x][y+1] == '#' and a[x-1][y] == '#' and a[x+1][y] == '#'
def is_crosses(a):
n = len(a)
# Предусматриваем случай, когда в a[] сидят str-ы.
for x in range(0, n):
if isinstance(a[x], str):
a[x] = list(a[x])
for x in range(1, n-1):
for y in range(1, n-1):
if _is_cross_at(a, x, y):
a[x][y] = '!'
a[x][y-1] = '!'
a[x][y+1] = '!'
a[x-1][y] = '!'
a[x+1][y] = '!'
hash_count = sum([s.count('#') for s in a])
return hash_count == 0
if __name__ == '__main__':
n = int(input())
a = []
for i in range(0, n):
line = input()
a.append(line)
if is_crosses(a):
print('TRUE')
else:
print('FALSE')
|
09aed5c6da964f91430c50c2202c7430998b0a02 | LeeJiangWei/convex-optimization-assignment | /three_points_interpolation.py | 2,288 | 3.515625 | 4 | import matplotlib.pyplot as plt
import numpy as np
def f(x):
return x ** 3 - 2 * x + 1
def three_points_interpolation(x1, x2, x3, threshold, f):
xs = np.inf
while True:
A = np.array(([x1 ** 2, x1, 1], [x2 ** 2, x2, 1], [x3 ** 2, x3, 1]))
A_inv = np.linalg.inv(A)
b = np.array([f(x1), f(x2), f(x3)])
x = np.matmul(A_inv, b) # x = [a; b; c], Coefficients of parabola y=a^2x+bx+c
xs_new = - x[1] / (2 * x[0]) # x_star = -b/2a
if abs(xs - xs_new) < threshold:
return xs_new
xs = xs_new
if f(xs) < f(x2):
if xs < x2:
x1, x2, x3 = x1, xs, x2
else:
x1, x2, x3 = x2, xs, x3
else:
if xs < x2:
x1, x2, x3 = xs, x2, x3
else:
x1, x2, x3 = x1, x2, xs
def three_points_interpolation_plot(x1, x2, x3, threshold, f):
_x = np.arange(x1, x3, 0.01)
_y = f(_x)
pause_interval = 0.5
plt.ion()
xs = np.inf
while True:
plt.clf()
plt.plot(_x, _y)
plt.plot(x1, f(x1), "rx")
plt.plot(x2, f(x2), "rx")
plt.plot(x3, f(x3), "rx")
plt.pause(pause_interval)
A = np.array(([x1 ** 2, x1, 1], [x2 ** 2, x2, 1], [x3 ** 2, x3, 1]))
A_inv = np.linalg.inv(A)
b = np.array([f(x1), f(x2), f(x3)])
x = np.matmul(A_inv, b) # x = [a; b; c], Coefficients of parabola y=a^2x+bx+c
xs_new = - x[1] / (2 * x[0]) # x_star = -b/2a
_py = x[0] * _x ** 2 + x[1] * _x + x[2]
plt.plot(_x, _py, "r")
plt.pause(pause_interval)
plt.plot(xs_new, f(xs_new), "rx")
plt.axvline(xs_new, color="red")
plt.pause(pause_interval)
# stop condition
if abs(xs - xs_new) < threshold:
plt.pause(1)
plt.ioff()
return xs_new
xs = xs_new
if f(xs) < f(x2):
if xs < x2:
x1, x2, x3 = x1, xs, x2
else:
x1, x2, x3 = x2, xs, x3
else:
if xs < x2:
x1, x2, x3 = xs, x2, x3
else:
x1, x2, x3 = x1, x2, xs
if __name__ == '__main__':
print(three_points_interpolation_plot(0, 1, 3, 0.01, f))
|
f1ac39a76fcb5681eaa810e1cb2ca436492f377c | JitSheng/bt3103 | /solution_template/template_6.py | 885 | 3.5625 | 4 | class Cell():
def __init__(self,cell_size=20,color=(255, 255, 255),x_position=None,y_position=None):
self.cell_size = cell_size
self.x_position = x_position
self.y_position = y_position
self.color = color
class Snake():
def __init__(self, cell_size=20, x_position=0, y_position=0, color=(0, 0, 255), length=3):
self.cell_size = cell_size
self.x_position = x_position
self.y_position = y_position
self.color=color
self.length = length
self.cells = [
Cell(cell_size=self.cell_size, x_position=x_position, y_position=y_position, color=self.color) for i in range(length)]
def add_cell(self):
self.cells.append(
Cell(cell_size=self.cell_size, x_position=self.cells[-1].x_position, y_position=self.cells[-1].y_position, color=self.color))
# START CODE HERE |
687aab6228975e2ac17623e420bcf129d56b2017 | codeWriter9/cautious-python-learner | /Capitalize.py | 247 | 3.578125 | 4 | '''
Created on 20-May-2019
@author: Sanjay Ghosh
'''
def solve(s):
a = s.split(" ");
s = '';
for i in range(len(a)):
s = s + a[i][0:1].upper() + a[i][1:] + " " ;
return s;
if __name__ == '__main__':
print(solve(input())); |
a08c0cfd42c4abbe643e239006e81879c402f6c8 | shareneelie/python-tutorial- | /tebak2.py | 465 | 3.71875 | 4 | """
import random
play = True
while play :
kunci = random.randint(1, 11)
""" """
print(kunci)
"""
guess = int(input('please enter your guess (1-10) : '))
if guess == kunci:
print('selamat!')
coba = input('mau main lagi? (y/n) :')
if coba == 'y' :
continue
else :
break
elif guess<kunci :
print('tambahin lagi!')
elif guess>kunci:
print('kurangin!')
|
aa8ac8559c9046ed6c8dc5f1a5609e8891b61dc4 | shofiulalamshuvo/Python-Projects-by-Shuvo | /Tell a story.py | 697 | 3.8125 | 4 | import random
When = ['A few years ago', 'Yesterday', 'Last night', 'A long time ago','On 30th Sep']
Who = ['a rabbit', 'an elephant', 'a mouse', 'a turtle','a cat']
Name = ['Ali', 'Mariam','Dip', 'Hasan', 'Shuvo']
Place = ['Spain','Antarctica', 'Germany', 'Venice', 'Mars']
Went = ['cinema hall', 'university','seminar', 'school', 'coffee shop']
Situation = ['made a lot of friends','Eats a burger', 'found a secret key', 'solved a mistery', 'wrote a book']
print(random.choice(When) + ', ' + random.choice(Who) + ' that lived in ' + random.choice(Place) + ', went to the ' + random.choice(Went) + ' and ' + random.choice(Situation) + ' -This story is writen by: ' + random.choice(Name)) |
5637f973ef6b3b0acb6b68c336015baa3c7a0e6d | adh2004/Python | /Lab13/DriveCarNew/Car.py | 495 | 3.609375 | 4 | class Car:
def __init__(self, car_make, car_model):
self.__make = car_make
self.__model = car_model
self.__speed = 0
def accelerate(self):
self.__speed += 5
def decelerate(self):
self.__speed -= 5
if self.__speed < 0:
self.__speed = 0
def getSpeed(self):
return self.__speed
def __str__(self):
return 'Car make: ' + self.__make +' Car model: ' + self.__model + ' Car speed: ' + str(self.__speed)
|
6f096143ff669be0e3a3872d2b016ca5880e4947 | Raj-Python/python-training | /ps_functions_demo.py | 1,458 | 3.65625 | 4 | from sys import stderr, exc_info
from traceback import print_tb
print '\n\n'
print '1 -------------- funtion where exception is printed to the error device ---------------------'
def power(x,n=0):
return x ** n
try:
print power(4, 3)
print power(4)
except TypeError as err:
print >>stderr, 'blah blah ....' # prints on the error device
print '\n\n'
print '2 -------------- function to print entire exception stacktrace ---------------------'
def power2(x, n):
return x ** n
try:
print power2(4, 3)
print power2(4)
except TypeError as err:
print err
print_tb(exc_info()[-1]) # prints entire stack trace
print '\n\n'
print '3 -------------- function with multiple args (*args) ---------------------'
def demo(*args): # multiple args will become a tuple
print args
demo()
demo(100)
demo('pete')
demo(1, 2.2, 'iii', 4.4, 5.0)
items = [1, 2, 3, 4, 5]
demo(items) # list will become the first element of the tuple.
a = (1, 2, 3.3, 4.0, 5.0)
b = [1, 2, 3.3, 4.0, 5.0]
demo(a) # passing tuple itself
demo(*a) # passing only contents of a tuple or list or string
demo(*'peter') # passing contents of a string
demo(b)
demo(*b) # passing only contents of a list
print '\n\n'
print '4 -------------- *args should always be the last argument ---------------------'
def demo(a, b, *args):
print a
print b
print args
demo(1,2)
demo(1,2,3,4,5)
|
99287625f93178121348f29be94671668635f2bd | selavy/tables | /tests/stresstest.py | 1,582 | 3.578125 | 4 | #!/usr/bin/env python
import argparse
import random
class Op:
INSERT = 0
ERASE = 1
FIND = 2
MISS = 3
SIZE = 4
MAX = 5
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--nops", type=int, default=100,
help="Number of operations to generate")
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
max_ = (1 << 31) - 1
min_ = -(1 << 31)
d = {}
for i in range(args.nops):
op = random.randint(0, Op.MAX - 1)
if not d and op == Op.FIND:
op = Op.MISS
if op == Op.INSERT:
k = random.randint(min_, max_)
v = random.randint(min_, max_)
if k not in d:
d[k] = v
print(f"INSERT {k} {v} {d[k]}")
elif op == Op.ERASE:
k = random.randint(min_, max_)
try:
del d[k]
r = 1
except KeyError:
r = 0
print(f"ERASE {k} {r}")
elif op == Op.FIND:
i = random.randint(0, len(d) - 1)
for j, k in enumerate(d.keys()):
if j == i:
break
print(f"FIND {k} {d[k]}")
elif op == Op.MISS:
while 1:
k = random.randint(min_, max_)
if k not in d:
break
print(f"MISS {k}")
elif op == Op.SIZE:
print(f"SIZE {len(d)}")
else:
raise ValueError(f"Invalid operation: {op}")
|
b97bc2419e862ed72cd6b015617e28f6c43aa877 | shivasapra/spy_chat-application | /spy_detail.py | 1,887 | 3.984375 | 4 | from spy_details import Spy
# function defined for taking details from spy
def spy_detail():
spy = Spy(" ", " ", 0, 0.0)
# taking name from user if invalid taking name again
temp = 0
while temp == 0:
spy.name = raw_input("\n****************\nEnter Name")
try:
if type(int(spy.name)) == int:
temp = 0
exit(temp == 0)
except:
temp = len(spy.name)
# taking valid salutation
salutation = ' '
while salutation != 'mr.' and salutation != 'ms.':
salutation = raw_input("****************\nwhat should we call (mr.or ms.)")
spy.salutation = salutation
spy.name = spy.salutation + spy.name
# taking age and checking if it is in right format or not
temp = 1
while temp:
spy.age = raw_input("****************\nplease enter age")
try:
if type(int(spy.age)) == int:
temp = 0
spy.age = int(spy.age)
except:
print "\n!!!!!!!!!!!!!!!\nenter carefully\n!!!!!!!!!!!!!!!\n"
temp = 1
# taking spy_rating and checking it
temp = 1
while temp:
spy.rating = raw_input(
"****************\nplease enter spy rating (out of 10)")
print "****************"
try:
if type(float(spy.rating)) == float:
temp = 0
spy.rating = float(spy.rating)
except:
print "\n!!!!!!!!!!!!!!!\nenter carefully\n!!!!!!!!!!!!!!!\n"
temp = 1
spy.is_online = True
if spy.rating >= 9.0:
print " \nyou seems to be excellent"
elif 9.0 > spy.rating >= 7.0:
print "\nyou seems to be good"
elif 7.0 > spy.rating >= 5.0:
print "\nyou seems to be average"
else:
print "\nyou seems to be ok"
# returning details of spy
return spy
|
01ea2e5cbef9fc5f77aaa7571ad5c02f45f7e3eb | metrossb/git-learning-course | /lib/fibonacci.py | 385 | 3.84375 | 4 | class Fibonacci:
def getTerms(self, terms = 10):
if terms < 1:
return []
elif terms == 1:
return [1]
elif terms == 2:
return [1, 1]
else:
# Implement an algorithm
vals = [1, 1]
for i in range(1,terms-1):
vals.append(vals[i] + vals[i-1])
return vals |
26a0de2a5596c453319bf1832d27411ff51c36f6 | karri-sek/craftingPython | /testMultipleFlags.py | 594 | 4.0625 | 4 | x , y , z = 0, 1, 0
if x == 1 or y == 1 or z == 1:
print("passed")
if x == 1 or y ==1 or z == 1:
print("passed")
else:
print("fail")
if 1 in (x, y, z):
print("1 is present in either x , y , z")
if x or y or z:
print('passed')
if any((x, y, z)):
print("passed")
x , y , z = 0, 0, 0
if x == 1 or y == 1 or z == 1:
print("2.passed")
if x == 1 or y ==1 or z == 1:
print("2.passed")
else:
print("2.fail")
if 1 in (x, y, z):
print("2.1 is present in either x , y , z")
if x or y or z:
print('2.passed')
if any((x, y, z)):
print("2.passed") |
2cd47b05a30bec95de86b9ab0c8e458d22cebfd6 | kevinsu628/study-note | /leetcode-notes/easy/array/1_twoSum.py | 1,229 | 3.9375 | 4 | '''
Question:
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.
Approach 1: Brute Force
The brute force approach is simple. Loop through each element xx and find
if there is another value that equals to target - xtarget−x.
'''
def twoSum(nums, target):
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[j] == target - nums[i]:
return [nums[i], nums[j]]
print("no two sum")
'''
Approach 3: One-pass Hash Table
It turns out we can do it in one-pass.
While we iterate and inserting elements into the table,
we also look back to check if current element's complement already exists in the table.
If it exists, we have found a solution and return immediately.
'''
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
h = {}
for i, num in enumerate(nums):
n = target - num
if n not in h:
h[num] = i
else:
return [h[n], i]
print(twoSum([2, 7, 11, 15], 9))
|
51abcf4e3518de95229e2204a77f7b4492733bf2 | hmchen47/Programming | /Python/UoM/book-exercises/purify.py | 557 | 4.28125 | 4 | '''
purify
Define a function called purify that takes in a list of numbers, removes all odd numbers in the list, and returns the result.
For example, purify([1,2,3]) should return [2].
Do not directly modify the list you are given as input; instead, return a new list with only the even numbers.
'''
d = [4, 5, 5, 4]
def purify(x):
tmpx = []
for item in x:
tmpx.append(item)
for item in x:
print item
if (item%2 != 0):
tmpx.remove(item)
print tmpx
return tmpx
print (purify(d)) |
842d81171140c5d97122beeab62daf03f013ea90 | lowrybg/SoftuniPythonFund | /dictionaries/capitals.py | 381 | 3.5 | 4 | line = input().split(', ')
my_dict = {}
counter = 1
country = []
while counter <= 2:
for n in range(len(line)):
if counter ==1:
country.append(line[n])
else:
my_dict[country[n]] = line[n]
counter+=1
if counter >2:
break
line = input(). split(', ')
for key, value in my_dict.items():
print(f'{key} -> {value}') |
3728c0602605c264e70d5e3547ef9af4a33d740f | GeoffVH/Python-Practice | /CCTC python/Chapter 1 questions.py | 3,115 | 4.15625 | 4 | #////////////////////////////////////////#
# Question 1
#Is Unique: Implement an algorithm to determine if a string has all unique characters.
#What if you can't use additional data structures?
def is_Unique(str1):
return len(str1) == len(set(str1))
#No additional data structures
def is_Unique_alt(str1):
str1.sort()
for i in range(len(str1)-1):
if str1[i] != str1[i+1]
return false
return true
#////////////////////////////////////////#
# Question 2
#Given two strings, write a method to decide if one is a permutation of the other.
def isPerm(str1, str2):
return len(str1) == len(str2) and set(str1) == set(str2)
#////////////////////////////////////////#
# Question 3
# Write a method to replace all spaces in a string with '%20:
# You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true"
# length of the string.
def URL1(str1):
listy = ['20%' if char == ' ' else char for char in str1]
return ''.join(listy)
def URL2(str1):
return '20%'.join(str1.split())
def URL3(str1):
return str1.replace(' ', '20%')
#////////////////////////////////////////#
# Question 4
# Palindrome Permutation: Given a string, write a function to check if it is a permutation of
# a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A
# permutation is a rearrangement of letters. The palindrome does not need to be limited to just
# dictionary words.
def is_Permutation(str1):
odd = 0
for char in set(str):
if str.count(char)%2 != 0:
odd+=1
return odd<=1
#////////////////////////////////////////#
# Question 6
# String Compression: Implement a method to perform basic string compression using the counts
# of repeated characters. For example, the string aabcccccaaa would become a2blc5a3 . If the
# "compressed" string would not become smaller than the original string, your method should return
# the original string. You can assume the string has only uppercase and lowercase letters (a - z).
from itertools import groupby
def compress(str1):
ans = ''
for key, group in groupby(str1):
ans += key
rep = str(len(list(group)))
if rep!='1':
ans += rep
return ans
#////////////////////////////////////////#
# Question 8
# String Rotation: Assume you have a method i5Substring which checks if one word is a substring
# of another. Given two strings, S1 and S2, write code to check if S2 is a rotation of S1 using only one
# call to isSubstring (e.g., "waterbottle" is a rotation of "erbottlewat" ).
def isSubstring(s1, s2):
return s1 in s2*2 and len(s1) == len(s2)
# Waterbottle = s1 and erbottleWat = s2
# s2*2 = erbottleWaterbottleWat, which contains Waterbottle so our in operator can function correctly.
# Len() checking makes sure edge cases like s1 being "Wat" won't return a false positive.
|
f6c853249889a207abfce4ae58d2bdd0f6b11b9f | austinmw/Python-code | /super_function.py | 591 | 4.03125 | 4 | # Basic example
class This_is_a_very_long_class_name(object):
def __init__(self):
pass
class Derived(This_is_a_very_long_class_name):
def __init__(self):
super().__init__() #1
This_is_a_very_long_class_name.__init__(self) #2
# Both 1 and 2 do the same thing, but 1 is a lot easier
# Multiple inheritance example
class A(object):
def foo(self):
print('A')
class B(A):
def foo(self):
print('B')
super().foo()
class C(A):
def foo(self):
print('C')
super().foo()
class D(B,C):
def foo(self):
print('D')
super().foo()
d = D()
d.foo() |
7c5e1640f5c76badf1717c88bdcbd02bc54cea2f | saurabhchris1/Algorithm-Pratice-Questions-LeetCode | /Majority_Element.py | 617 | 3.796875 | 4 | # Given an array of size n, find the majority element. The majority
# element is the element that appears more than ⌊ n/2 ⌋ times.
#
# You may assume that the array is non-empty and the majority element always exist in the array.
#
# Example 1:
#
# Input: [3,2,3]
# Output: 3
# Example 2:
#
# Input: [2,2,1,1,1,2,2]
# Output: 2
import collections
class Solution:
# O(n) Time and O(n) space
def majorityElement(self, nums):
count = 0
res = 0
for num in nums:
if count == 0:
res = num
count += 1 if num == res else -1
return res
|
fa28fc36769184c5a38527c8cdf0a5ff0e14fac5 | someMadCoder/mpt | /19.py | 696 | 3.765625 | 4 | import itertools
def getNum():
while type:
num = input('Длина строки = ')
try:
int(num)
except ValueError:
print('"' + num + '"' + ' - не является числом')
else:
break
return int(num)
myList = []
myLen = getNum()
myStr = input("Количество символов = ")
def intersection(str):
for i in range(len(str)):
for j in range(len(myStr)):
if myStr[j] not in str:
return False
return True
for i in itertools.product(myStr, repeat=myLen):
myList.append("".join(i))
for i in myList:
if intersection(i):
print(i, end=" ")
|
25b97010c637525d2345cd95615fc0faf0e01191 | Samitific/Piscine-Python | /day01/ex05/all_in.py | 1,568 | 4.0625 | 4 | #!/usr/bin/env python3
# -*-coding:utf-8 -*
def arg_list(chaine):
"""traite les parametres fournis dans la ligne de commande"""
liste = [item for item in chaine.split(',')]
liste = [item.lstrip().rstrip().title() for item in liste if item != '' and item != '\t']
# print(liste)
return liste
def reverse_dict(dico):
"""prend un dict en argument et le retourne inversé, les clés permuttant avec les valeurs"""
return dict([[v, k] for k, v in dico.items()])
def all_in(argv):
"""Prend une capitale ou un état en argument et renvoie l'état ou la capitale correspondant ou Unknow state"""
import sys
states = {
"Oregon": "OR",
"Alabama": "AL",
"New Jersey": "NJ",
"Colorado": "CO"
}
capital_cities = {
"OR": "Salem",
"AL": "Montgomery",
"NJ": "Trenton",
"CO": "Denver"
}
if len(sys.argv) != 2:
sys.exit(1)
liste = arg_list(sys.argv[1])
states_rev = reverse_dict(states)
capital_cities_rev = reverse_dict(capital_cities)
for item in liste:
if item in states:
print("{0} is the capital of {1} (akr: {2})".format(capital_cities[states[item]], item, states[item]))
elif item in capital_cities_rev:
print("{0} is the capital of {1} (akr: {2})".format(item, states_rev[capital_cities_rev[item]], capital_cities_rev[item]))
else:
print("{0} is neither a capital city nor a state".format(item))
if __name__ == '__main__':
import sys
all_in(sys.argv)
|
a29ed12c6fdecfa537521a683410a1036e363ea1 | bismayan/bigdata_python | /python_misc/angle.py | 143 | 3.953125 | 4 | from math import *
(a,b)=(int(input("Input side {}:".format(_))) for _ in range(2))
print "{}°".format(int(floor((atan2(a,b)*180/pi)+0.5)))
|
bd93606677bdec76d0d37b13dec03abffc157b44 | xdc7/PythonForInformatics | /chp_03/ex_01.py | 281 | 4.15625 | 4 | hours = float(input("Enter the number of hours worked: "))
rate = float(input("Enter the rate per hour: "))
salary = 0
if hours < 40:
salary = hours * rate
else:
salary = (hours * rate) + (hours - 40) * 1.5 * rate
print(("Your salary for the week is {}").format(salary)) |
c8851a5c2dde183b6ce3fbc9452db2e51dc7c08f | satot/project_euler | /solutions/23.py | 680 | 3.609375 | 4 | def is_abundant(n):
divs = set()
for i in range(1, n//2+1):
if n % i == 0:
divs.add(i)
return sum(divs) > n
def find_abundant(n):
abds = set()
for i in range(n):
if is_abundant(i):
abds.add(i)
return abds
def non_abundant_sums(n):
abds = find_abundant(n)
target = set()
for i in range(1, n):
can = False
for j in range(1, i//2+1):
if j in abds and (i-j) in abds:
can = True
break
if not can:
target.add(i)
return target
#print find_abundant(100)
nas = non_abundant_sums(30000)
print nas
print sum(nas)
print max(nas)
|
b75da4bdfc0aaf8f2437b3ea5af3eb8827f1e487 | manjitborah2710/Transposer | /transpose.py | 244 | 3.59375 | 4 | import math
notes=['A','A#','B','C','C#','D','D#','E','F','F#','G','G#']
a=input("From : ")
b=input("To : ")
ind_a=notes.index(a)
ind_b=notes.index(b)
diff=ind_b-ind_a
for i in range(12):
print(notes[i]," --> ",notes[(i+diff)%len(notes)])
|
ad07de80c8a3a426fe6b8121f36d8ce5b1657471 | yebanxinghui/py_program | /py_program/子串出现次数.py | 1,551 | 3.53125 | 4 | def findstr1():
count = j = 0
string = input('请输入目标字符串:')
ch = input('请输入子字符串(两个字符):')
len1=len(string)
len2=len(ch)
for i in range(0,len1):
while i+j<len1 and ch[j] == string[i+j]:
if j == len2 - 1 :
count += 1
j = 0
break
j += 1
print('子字母串在目标字符串中共出现%d次' % count)
findstr1()
'''
def findstr2():
print('请输入目标字符串:',end='')
temp = input()
print('请输入子字符串(两个字符):',end='')
comp = input()
count = 0
i = 0
for i in range(len(temp)):
if temp[i] == comp[0] and temp[i+1] == comp[1]:
count += 1
i += 1
else:
i += 1
count = int(count)
print('子字符串在目标字符串中总共出现 %d 次'%count)
'''
'''
findstr2()
def findStr3(desStr, subStr):
count = 0
length = len(desStr)
if subStr not in desStr:
print('在目标字符串中未找到字符串!')
else:
for each1 in range(length):
if desStr[each1] == subStr[0]:
if desStr[each1+1] == subStr[1]:
count += 1
print('子字符串在目标字符串中共出现 %d 次' % count)
desStr = input('请输入目标字符串:')
subStr = input('请输入子字符串(两个字符):')
findStr3(desStr, subStr)
'''
|
63417e897ad65248967df829fd419127955fb670 | Aasthaengg/IBMdataset | /Python_codes/p02819/s080641923.py | 272 | 3.671875 | 4 | import math
X = int(input())
ans = 0
while ans == 0:
factor = 0
if X % 2 == 0 and X != 2:
X +=1
continue
for divisor in range(2, X // 2):
if X % divisor == 0:
factor += 1
if factor == 0:
ans =X
X +=1
print(ans) |
b6ad725e19b4a7cd64d5741c5bdba99ed3d07709 | alvarogomezmu/dam | /SistemasGestion/Python/1ev/Hoja6/Ejercicio03.py | 295 | 4.28125 | 4 | #_*_coding:utf-8_*_
# Pedimos al usuario que introduzca un string
cadena = raw_input("Introduce una cadena: ")
# Guardamos la cadena al reves en otro string
cadena2 = cadena[::-1]
# Comparamos ambas cadenas
if cadena == cadena2 :
print "Son palindromos"
else :
print "No son palindromos"
|
7249f59a20f7a1c5384d8b53313efff5602460c0 | MrZhangzhg/nsd_2018 | /weekend1/py0102/fib_func.py | 766 | 3.921875 | 4 | # def gen_fib():
# fib = [0, 1]
# n = int(input('length: '))
# for i in range(n - 2):
# fib.append(fib[-1] + fib[-2])
#
# print(fib)
#
# a = gen_fib() # 函数默认返回None
# print(a)
# def gen_fib():
# fib = [0, 1]
# n = int(input('length: '))
# for i in range(n - 2):
# fib.append(fib[-1] + fib[-2])
#
# return fib # 函数的运算结果,通守return进行返回
#
# a = gen_fib()
# print(a)
def gen_fib(n=8): # 定义形参n
fib = [0, 1]
for i in range(n - 2):
fib.append(fib[-1] + fib[-2])
return fib # 函数的运算结果,通守return进行返回
print(gen_fib())
for i in range(5, 16, 2):
a = gen_fib(i)
print(a)
n = int(input('length: '))
print(gen_fib(n))
|
b47ae92e0c82fde8870963c1142737a18acc9678 | nihathalici/Break-The-Ice-With-Python | /Python-Files/Day-11/Question-43.py | 342 | 4.15625 | 4 | """
Question 43
Question:
Write a program which can filter() to make a list whose elements are
even number between 1 and 20 (both included).
Hints:
Use filter() to filter elements of a list.
Use lambda to define anonymous functions.
"""
def even(x):
return x % 2 == 0
evenNumbers = filter(even, range(1, 21))
print(list(evenNumbers))
|
8ac4c3f5abc0c39c09bbc738d98492ff5a815fdb | sunnysunita/stack | /Minimum bracket Reversal.py | 265 | 3.71875 | 4 | list = input()
def fun(list):
s = []
for e in list:
if e is "{":
s.append(e)
elif e is "}":
s.pop()
# print(s)
l = len(s)
if l%2 != 0:
return -1
else:
return l//2
print(fun(list))
|
80e1df15c0f1c427e6823ac78b80bdc598d8d0f4 | impankaj91/Python | /Chepter-7-Loops/exmple-prime_number.py | 255 | 4.125 | 4 | #Check Prime Number.
number=int(input("Enter The Number :"))
prime=True
for i in range(2,number):
if(number%i==0):
prime=False
break
if prime:
print("Number is Prime.")
else:
print("Number is not Prime.")
|
445a15297e05f662726ba2ac89f4d53193aa3b7e | qiblaqi/Stevens-Python-Course-ByQ.Zhao | /810/HW03_Qi_Zhao.py | 7,588 | 3.96875 | 4 | """
this is a program use Class to handle two Fractions plus, minus, mutiply, divide and
check-out if they equals to each other
upgraded with unittest module to build a test suite
Written by Qi Zhao
"""
import unittest as ut
class TestFraction(ut.TestCase):
""" Test class of fraction which includes testing '+-*/ == >= <= != > <' """
def test_init(self):
#test deno cant be 0
with self.assertRaises(ValueError):
Fraction(1,0)
def test_add(self):
#test plus function
testUnit_1 = Fraction(1,3)
testUnit_2 = Fraction(2,5)
self.assertEqual(testUnit_1+testUnit_2,Fraction(11,15))
def test_sub(self):
#test minus function
testUnit_1 = Fraction(1,3)
testUnit_2 = Fraction(2,5)
self.assertEqual(testUnit_1-testUnit_2,Fraction(-1,15))
def test_mul(self):
#test multiply function
testUnit_1 = Fraction(1,3)
testUnit_2 = Fraction(2,5)
self.assertEqual(testUnit_1*testUnit_2,Fraction(2,15))
def test_truediv(self):
#test divide function and vailid new fraction's denominator cant be 0
testUnit_1 = Fraction(1,3)
testUnit_2 = Fraction(2,5)
testUnit_3 = Fraction(0,4)
self.assertEqual(testUnit_1/testUnit_2,Fraction(5,6))
with self.assertRaises(ValueError):
testUnit_1 / testUnit_3
def test_eq(self):
#test the equal function for negative or postive fraction
testUnit_1 = Fraction(1,3)
testUnit_2 = Fraction(2,6)
testUnit_3 = Fraction(-1,-3)
self.assertTrue(testUnit_1==testUnit_2)
self.assertTrue(testUnit_1==testUnit_3)
#special test
self.assertTrue(Fraction(-1,3),Fraction(1,-3))
def test_ne(self):
#test the not equal function
testUnit_1 = Fraction(1,3)
testUnit_2 = Fraction(3,6)
self.assertTrue(testUnit_1!=testUnit_2)
def test_lt(self):
#give two fractions check if self < other
self.assertTrue(Fraction(-1,3)<Fraction(2,4))
self.assertTrue(Fraction(1,-4)<Fraction(1,5))
self.assertFalse(Fraction(1,3)<Fraction(1,-3))
def test_gt(self):
#check the greater than function
self.assertTrue(Fraction(1,2)>Fraction(1,3))
self.assertFalse(Fraction(1,-3)>Fraction(1,2))
def test_ge(self):
#check the greater than or equal to function, two steps 1.test '>' 2. test '='
self.assertTrue(Fraction(1,2)>=Fraction(1,3))
self.assertTrue(Fraction(1,2)>=Fraction(2,4))
self.assertFalse(Fraction(1,4)>=Fraction(1,2))
def test_le(self):
#check the less than or equal to, like test_ge
self.assertTrue(Fraction(1,3)<=Fraction(1,2))
self.assertTrue(Fraction(1,-3)<=Fraction(2,6))
self.assertFalse(Fraction(1,3)<=Fraction(1,4))
class Fraction:
""" Fraction class hold numerator and dorminator with method to do + - * / == with each other """
def __init__(self,numerator, denominator):
# This initiates the fraction's numerator and denominator
if denominator == 0:
raise ValueError("denominator cant be '0' !")
self.numerator = numerator
self.denominator = denominator
def __add__(self,other):
#plus two fraction and return a new fraction
newFractionDeno = self.denominator * other.denominator
newFractionNumer = self.numerator * other.denominator + other.numerator * self.denominator
newFraction = Fraction(newFractionNumer,newFractionDeno)
return newFraction
def __sub__(self,other):
#two fraction minus with each other
newFractionDeno = self.denominator * other.denominator
newFractionNumer = self.numerator * other.denominator - other.numerator * self.denominator
newFraction = Fraction(newFractionNumer,newFractionDeno)
return newFraction
def __mul__(self,other):
#multiply two fractions with one denominator
newFractionDeno = self.denominator * other.denominator
newFractionNumer = self.numerator * other.numerator
newFraction = Fraction(newFractionNumer,newFractionDeno)
return newFraction
def __truediv__(self,other):
#to reverse the fraction and multiply
newFractionDeno = self.denominator * other.numerator
newFractionNumer = self.numerator * other.denominator
newFraction = Fraction(newFractionNumer,newFractionDeno)
return newFraction
def __eq__(self,other):
# check two fractions have the same value or not
newFractionNumer = self.numerator * other.denominator - other.numerator * self.denominator
if newFractionNumer == 0:
return True
else:
return False
def __ne__(self,other):
#check two fractions are not the same by using __eq__ function
return not(self==other)
def __lt__(self,other):
#check self fraction is less than other fraction or not with
if self.denominator*other.denominator>0:
return (self.numerator*other.denominator-self.denominator*other.numerator)<0
elif self.denominator*other.denominator<0:
return (self.numerator*other.denominator-self.denominator*other.numerator)>0
def __gt__(self,other):
#check self fraction is greater than other fraction
if self.denominator*other.denominator>0:
return (self.numerator*other.denominator-self.denominator*other.numerator)>0
elif self.denominator*other.denominator<0:
return (self.numerator*other.denominator-self.denominator*other.numerator)<0
def __ge__(self,other):
#check self >= other with using __lt__ function
return not(self<other)
def __le__(self,other):
#check self <= other with using __gt__ function
return not(self>other)
def __str__(self):
#output the fraction in a mathmetics way like '1/2' for f12
return f"{self.numerator}/{self.denominator}"
def getNumber(yourInputMsg):
# check user's input and make sure it can be converted into an integer
bufferNumber = input(yourInputMsg)
try:
number = int(bufferNumber)
except ValueError:
print(f"{bufferNumber} is not a number, please type a number! ")
number = getNumber(yourInputMsg)
return number
def getCode(yourInputMsg):
#check user's code is legal or not and make sure to get legal code command
bufferCode = input(yourInputMsg)
if bufferCode in ['+','-','*','/','==']:
return bufferCode
else:
print(f"'{bufferCode}' is not a legal code command, please type again! ")
return getCode(yourInputMsg)
def main():
#the main function is to let the user to input their parameters and
f1Numer = getNumber("Fraction 1 numerator: ")
f1Deno = getNumber("Fraction 1 denominator: ")
f1 = Fraction(f1Numer,f1Deno)
code = getCode("Operation (+, -, *, /, ==): ")
f2Numer = getNumber("Fraction 2 numerator: ")
f2Deno = getNumber("Fraction 2 denominator: ")
f2 = Fraction(f2Numer,f2Deno)
if code == '+':
finalF = f1 + f2
elif code == '-':
finalF = f1 - f2
elif code == '*':
finalF = f1 * f2
elif code == '/':
finalF = f1 / f2
elif code == '==':
finalF = f1 == f2
print(f"{f1} {code} {f2} = {finalF}")
if __name__ == '__main__':
#main()
ut.main(exit=False, verbosity=2)
|
8c04f626b6668b00ad18c8b87943505f960b7b51 | hiys/PYTHON | /pythonScripts/PyScripts/PyScripts7/test_if.py | 259 | 4 | 4 | if 10 > 0:
print('yes')
print('ok')
if 10 > 100:
print('yes')
else:
print('no')
if -0.0: print('yes') # 任何值为0的数字都是False
if 100: print('true')
if ' ': print('oooookkkkk') # 任何非空对象都是True,空为False
|
0e92a4abac179ac2b6e9db54c750c790ab401855 | pmkhedikar/python_practicsRepo | /concepts/sample_1.py | 511 | 3.78125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the twoStrings function below.
if __name__ == '__main__':
#fptr = open( os.environ['OUTPUT_PATH'], 'w' )
q = int(input())
for q_itr in range( q ):
s1 = input()
s2 = input()
def twoStrings(s1, s2):
for i in s1:
if i in s2:
return True
else:
return False
twoStrings(a,b)
# fptr.write( result + '\n' )
#
# fptr.close() |
28dd26faeb518328009b5b8609c12616eb6dd775 | 515ek/python-BST | /soln09.py | 704 | 4.125 | 4 | #!/usr/bin/python
## Name: Vivek Babu G R
## Date: 03-10-2018
## Assignment: Implementing the Binary Search Tree DataStructure
## Question: 9. Add method the check whether two BSTs are same. Provide test cases.
#################################################################################################
from soln01 import traversals as bst
def isSame(T1 , T2):
if T1.levelorder() == T2.levelorder():
return True
else:
return False
def seedsameTree(T1):
T1.add(50)
T1.add(30)
T1.add(60)
T1.add(20)
T1.add(25)
if __name__ == '__main__':
T1 = bst()
T2 = bst()
seedsameTree(T1)
seedsameTree(T2)
print(T1.levelorder())
print(isSame(T1,T2)) |
509be3c3904dc8197fcd2a8162d2039a907391b5 | nassarnour/python-datastructures | /pythonDictionaries/count.py | 751 | 4.1875 | 4 | # The following python program utilizes dictionaries to count and keep track of different words in a txt file
# and then prints the most occuring word, and the number of times it appears.
name = input('Enter the files name: ')
handle = open(name)
counts= dict()
for line in handle:
words=line.split()
for word in words:
counts[word]= counts.get(word, 0) +1
# At this point, the program has counted all words, and there is a virtaul histogram
bigcount= None
bigWord = None
for word, count in counts.items():
if bigcount is None or count>bigcount:
bigWord= word
bigcount = count
print(bigWord, bigcount)
# Exanple run- Entering words.txt outputs "to 16" meaning "to" is the most occuring word at a count of 16 |
ed47410a2f58f8076e68b88c77429fe977df4f6e | jasapluscom/PYTHON | /JASAPLUS.COM TRAINING MATERIALS/tkinter/button_sample.py | 519 | 3.921875 | 4 | #!/usr/bin/env python3
'''
button_sample.py
for course material at www.jasaplus.com
'''
from tkinter import Tk, Button, messagebox
def OnClick(num):
messagebox.showinfo("Information","I got clicked at " + str(num))
window = Tk()
window.title("button sample")
window.geometry("600x400+300+10")
btn = Button(window, text="Click Button 1!", command=lambda:OnClick(1))
btn.place(x = 200, y = 50)
btn2 = Button(window, text="Click Button 2 !", command=lambda:OnClick(2))
btn2.place(x = 200, y = 100)
window.mainloop()
|
1efa4d0843cf3ffb43ee8491fdbaf7c25722738b | nsmith0310/Programming-Challenges | /Python 3/LeetCode/lc1171.py | 923 | 3.515625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeZeroSumSublists(self, head: ListNode) -> ListNode:
if head==None:return head
l = []
while head!=None:
l.append(head.val)
head = head.next
i = 0
while i<len(l)-1:
j = len(l)
while j>=i:
if sum(l[i:j])==0:
del l[i:j]
j-=1
i+=1
while 0 in l:
del l[l.index(0)]
if l==[]:
tmp = ListNode()
tmp = tmp.next
return tmp
f = [ListNode(x) for x in l]
i = 0
while i<len(f)-1:
f[i].next = f[i+1]
i+=1
return f[0]
|
5de63b91c4615c16070218e0e86f945fb5b934f8 | wdahl/AI-Uniformed-search | /hw1/scource code/G2_matrix_bfs_queue.py | 1,801 | 3.5 | 4 | def bfs(matrix, start):
states = []
queue = [start]
parents = {}
while queue:
currElement = queue.pop(0)
if currElement not in states:
states += [currElement]
if currElement is 6:
path = [currElement]
while currElement is not 11:
path += [parents[currElement]]
currElement = parents[currElement]
path.reverse()
return states, path
count = 0
for nextElement in matrix[currElement]:
if nextElement == 1:
if count not in states:
queue += [count]
if count not in parents:
parents[count] = currElement
count += 1
return states, path
matrix = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0]]
states, path = bfs(matrix, 11)
letterStates = []
letterPath = []
maps = {0 : 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G', 7: 'H', 8: 'P', 9: 'Q', 10: 'R', 11: 'S'}
for state in states:
letterStates += maps[state]
for elements in path:
letterPath += maps[elements]
print("States Expanded: ", letterStates)
print("Path Returned: ", letterPath) |
73a7fbbd36f8415415564e117b7d58301ad8dc1e | mackenzielarson/SonomaState | /CS115/Lab08/lab08d.py | 2,272 | 3.6875 | 4 | __author__ = 'Mackenzie'
"""
Program: CS 115 Lab 08 (lab08d.py) Extra Credit
Author: Mackenzie Larson
Description: This program uses the graphics package to animate a group of circles to rotate around each other.
"""
from graphics import *
row1_balls = []
row2_balls = []
# Variables
win = GraphWin('Animation', 600, 500, autoflush=False)
radius = 20
diameter = 2 * radius
gap_between_balls = 6
height = 100 # height of the imaginary rectangle.
initial_y = 450
x_left_ball = 70
x_right_ball = x_left_ball + gap_between_balls + diameter
#Row 1
for i in range(5):
row1_center = Point(x_right_ball, initial_y)
row1_circle = Circle(row1_center, radius)
row1_circle.setFill('orange')
row1_balls.append(row1_circle)
row1_circle.draw(win)
x_right_ball = x_right_ball + 2 * diameter + gap_between_balls + 2.5
win.update()
#Row 2
for i in range(5):
row2_center = Point(x_left_ball, initial_y)
row2_circle = Circle(row2_center, radius)
row2_circle.setFill('yellow')
row2_balls.append(row2_circle)
row2_circle.draw(win)
x_left_ball = x_left_ball + 2 * diameter + gap_between_balls + 3
win.update()
win.getMouse()
dx_pixels = 1
dy_pixels = 2
n = 2
# Move row 1 up initially
for i in range(height):
for i in range(len(row1_balls)):
row1_balls[i].move(0, -dy_pixels)
update()
# Movement felt/right for both sets of balls
for j in range(n * 2):
for i in range(gap_between_balls + diameter):
for i in range(len(row1_balls)):
row2_balls[i].move(dx_pixels, 0)
row1_balls[i].move(-dx_pixels, 0)
win.update()
# Movement to bring down last row of balls on last turn
if j == n * 2 - 1:
for i in range(height):
for i in range(len(row1_balls)):
row2_balls[i].move(0, -dy_pixels)
win.update()
break
# Up and down movement for both sets
for i in range(height):
for i in range(len(row1_balls)):
row2_balls[i].move(0, -dy_pixels)
row1_balls[i].move(0, dy_pixels)
win.update()
dx_pixels = -dx_pixels
dy_pixels = -dy_pixels
win.getMouse()
win.close()
|
3009c1c2a4bf306ca500daf5e58b44cd21579435 | caglalogy/Countries-and-Languages | /lang.py | 2,350 | 3.921875 | 4 | import json
# Opening JSON file
with open('country-by-languages.json') as json_file:
data = json.load(json_file)
listOfLists = list()
for sub_dict in data:
listOfLists.append(list(sub_dict.values()))
def list_countries(listOfLists):
i = 1
country_list = list()
for countries in listOfLists:
country_list.append(countries[0])
country_list.sort()
for a in country_list:
print(i ,". ", a )
i+=1
def list_languages(listOfLists):
i = 1
language_list = list()
for languages in listOfLists:
subLanList = languages[1]
for elm in subLanList:
if elm not in language_list:
language_list.append(elm)
language_list.sort()
for a in language_list:
print(i ,". ", a )
i+=1
def search_country_for_languages(listOfLists,targetCountry):
i = 0
for x in listOfLists:
if(x[0] == targetCountry):
for languages in x[1]:
print(i+1 , ". " , languages)
i+=1
def search_language_for_countries(listOfLists, targetLang):
CList = list()
i = 0
for counAndLangs in listOfLists: # [Country , [lan1, lan2, lan3]]
for lang in counAndLangs[1]: # iterate on [lan1, lan2, lan3]
if lang == targetLang:
CList.append(counAndLangs[0])
for a in CList:
print(i+1 ,". ", a )
i+=1
def menu(listOfLists):
choice = int(input('''
1 - list of languages (alphabetically)
2 - list of countries (alphabetically)
3 - search the spoken languages by the country name
4 - search the countries by the given language
What do you want to do: (1,2,3,4):
'''))
if choice == 1:
list_languages(listOfLists)
elif choice == 2:
list_countries(listOfLists)
elif choice == 3:
tar = input("enter the country name you want to learn which languages are spoken: ")
search_country_for_languages(listOfLists,tar)
elif choice == 4:
tar2 = input("enter the language to list all the countries that is spoken on it: ")
search_language_for_countries(listOfLists,tar2)
print("type 1 to load menu again, 2 to quit")
choice2 = int(input())
if choice2 == 1:
menu(listOfLists)
elif choice2 == 2:
return
menu(listOfLists)
|
0a8d337aa61e72ffabae4c435ad2d4c8e481aa09 | YSQC/PythonCode | /H_Model/卷积神经网络/手工实现/Activations.py | 965 | 3.90625 | 4 | import numpy as np
class Relu:
"""Relu层"""
def __init__(self):
self.mask = None
def forward(self, x):
self.mask = (x <= 0)
out = x.copy()
out[self.mask] = 0
return out
def backward(self, dout):
dout[self.mask] = 0
dx = dout
return dx
class Sigmoid:
"""Sigmoid层"""
def __init__(self):
self.out = None
def forward(self, x):
out = 1 / (1 + np.exp(-x))
self.out = out
return out
def backward(self, dout):
dx = dout * (1.0 - self.out) * self.out
return dx
if __name__ == '__main__':
arr_test = np.linspace(-5, 5, 100)
relu = Relu()
sigmoid = Sigmoid()
relu_forward = relu.forward(arr_test)
sigmoid_forward = sigmoid.forward(arr_test)
import matplotlib.pyplot as plt
plt.plot(arr_test, relu_forward, color='red')
plt.plot(arr_test, sigmoid_forward, color='b')
plt.show()
|
812eab134a0cfff4ff776c4b4dd648f6361d9725 | luis-ibanez/Dominion | /src/app/dominion/unitTest/boardTest.py | 2,527 | 3.671875 | 4 | '''
Created on 22/04/2012
@author: ender3
'''
import unittest
import random
from board import Board
from card import Card
class Test(unittest.TestCase):
def setUp(self):
self.board=Board()
self.num_players=4
def test_board_initialization(self):
# make sure the shuffled sequence does not lose any elements
self.assertEqual(len(self.board.action_cards), 25)
self.assertEqual(len(self.board.money_cards), 3)
self.assertEqual(len(self.board.victory_cards), 4)
def test_deal_cards(self):
self.board.deal_cards(self.num_players)
self.assertEqual(self.board.board_cards[Card.GOLD], self.board.NUM_GOLD)
self.assertEqual(self.board.board_cards[Card.SILVER], self.board.NUM_SILVER)
self.assertEqual(self.board.board_cards[Card.COPPER], self.board.NUM_COPPER)
self.assertEqual(self.board.board_cards[Card.ESTATE], self.board.NUM_ESTATE)
self.assertEqual(self.board.board_cards[Card.DUCHY], self.board.NUM_DUCHY)
self.assertEqual(self.board.board_cards[Card.PROVINCE], self.board.NUM_PROVINCE)
self.assertEqual(len(self.board.action_cards), 15)
def test_get_cards(self):
self.board.deal_cards(self.num_players)
self.assertEqual(self.board.get_cards(Card.GOLD, 0), (False, self.board.NUM_GOLD))
self.assertEqual(self.board.get_cards(Card.GOLD, -1), (False, self.board.NUM_GOLD))
self.assertEqual(self.board.get_cards(Card.GOLD, 1),(True,self.board.NUM_GOLD-1))
self.assertEqual(self.board.get_cards(Card.GOLD, 1),(True,self.board.NUM_GOLD-2))
self.assertEqual(self.board.get_cards(Card.GOLD, 1),(True,self.board.NUM_GOLD-3))
self.assertEqual(self.board.get_cards(Card.GOLD, 1),(True,self.board.NUM_GOLD-4))
self.assertEqual(self.board.get_cards(Card.GOLD, 1),(True,self.board.NUM_GOLD-5))
self.assertEqual(self.board.get_cards(Card.GOLD, 5),(True,self.board.NUM_GOLD-10))
self.assertEqual(self.board.get_cards(Card.GOLD, 10),(True,self.board.NUM_GOLD-20))
self.assertEqual(self.board.get_cards(Card.GOLD, 5),(True,self.board.NUM_GOLD-25))
self.assertEqual(self.board.get_cards(Card.GOLD, 6),(False,self.board.NUM_GOLD-25))
self.assertEqual(self.board.get_cards(Card.GOLD, 5),(True,self.board.NUM_GOLD-30))
self.assertEqual(self.board.get_cards(Card.GOLD, 1),(False,self.board.NUM_GOLD-30))
if __name__ == "__main__":
unittest.main()
|
d80b172eff081c4e30e0d49243cdf19bb2bfd162 | moment0517/Foundations_of_Algorithms | /QuickSort.py | 375 | 3.734375 | 4 | def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
arr_p1 = []
arr_p2 = []
for i in range(1, len(arr)):
item = arr[i]
if item <= pivot:
arr_p1.append(item)
else:
arr_p2.append(item)
arr_p1 = quick_sort(arr_p1)
arr_p2 = quick_sort(arr_p2)
return arr_p1 + [pivot] + arr_p2
|
092737312371d79d7222b74716e506716dfbc388 | ridongwang/tsdro | /src/helpers.py | 6,075 | 3.625 | 4 | """
Helper functions used to parse data.
"""
import networkx as nx
import numpy as np
import itertools
from math import sin, cos, asin, radians, sqrt, atan2, degrees
import math
import sys
def gen_shortest_paths(edges, facilities, demandNodes):
"""
Return shortest path lengths from facilities to demandNodes and Graph object
"""
G = nx.Graph()
for a, w in edges.items():
if not G.has_edge(*a):
G.add_edge(a[0], a[1], weight=w)
sp_lengths = {}
for f in facilities:
for d in demandNodes:
if f != d:
sp_lengths[f, d] = nx.shortest_path_length(G, source=f,
target=d,
weight="weight")
return sp_lengths, G
def pairwise_geodesic(coordinates):
""" Return pairwise geodesic (great-circle) distances between coordinates.
Parameters
----------
coordinates : dict
Maps nodes to (latitude, longitude) tuples
Returns
-------
D : dict
Maps node tuple to the geodesic distance between them
"""
R = 6371 # radius of the Earth in km
nodes = list(coordinates.keys())
D = {}
for node1, node2 in itertools.product(nodes, repeat=2):
lon1, lat1 = coordinates[node1]
lon2, lat2 = coordinates[node2]
lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])
dlong = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlong / 2)**2
c = 2 * asin(sqrt(a))
D[node1, node2] = R * c # great circle distance in km
return D
def get_angle(A, B, C):
"""
Return angle between vectors defined by [A, B] and [A, C]
The angle is positive if [A, C] is a counter-clockwise rotation of [A, B],
and negative otherwise.
Parameters
----------
A : tuple, list
coordinates of tail of vector
B : tuple, list
coordinates of head of vector
C : tuple, list
coordinates of C
Returns
-------
angle : float64
angle in radians between vectors AB and AC.
"""
segment = np.subtract(B, A)
A_to_C = np.subtract(C, A)
angle = atan2(np.cross(segment, A_to_C), np.dot(segment, A_to_C))
return angle
def rotate_vector(A, B, angle):
""" Rotate vector by given angle.
Rotation is counterclockwise if angle is positive, and clockwise
if angle is negative.
Parameters
----------
A : tuple, list
coordinates of tail of vector
B : tuple, list
coordinates of head of vector
angle: float64, int
angle in radians between -pi and pi.
Returns
-------
rotated_translated : 1-D array of size 2.
coordinates of point resulting from rotating B, anchored at A
"""
assert angle >= -math.pi and angle <= math.pi
R = np.array([[cos(angle), -sin(angle)], [sin(angle), cos(angle)]])
rotated = np.dot(R, np.subtract(B, A))
rotated_translated = np.add(A, rotated)
return rotated_translated
def get_neighbors(source, coordinates, geodesic_distances, radius,
circle_endpoint, max_neighbors=np.inf):
"""Get neighbors of source given a radius and direction.
Only nodes in the half-circle defined by the radius and direction are
considered as neighbors.
Parameters:
source (tuple) -- landfall node
node (tuple) -- list of all nodes
coordinates (dict) -- dictionary whose keys are nodes and values are
(latitude, longitude) tuples
geodesic_distances (dict) -- pairwise great-circle distances between nodes
radius -- distance within which nodes are considered neighbors
circle_endpoint
Returns
-------
neighborNodes -- list of nodes neighboring source
"""
nodes = list(coordinates.keys())
D = geodesic_distances
neighborNodes = []
for n in nodes:
if n != source:
if len(neighborNodes) < max_neighbors:
a = tuple(np.sort((source, n)))
withinRadius = (D[a] <= radius)
# angle formed by n-source-circle_endpoint
angle = get_angle(coordinates[source], circle_endpoint,
coordinates[n])
withinAngle = degrees(angle) >= -5 or degrees(angle) <= -175
if withinRadius and withinAngle:
neighborNodes.append(n)
return neighborNodes
def normalize(*args):
'''
Normalize each input in args by subtracting the minimum and dividing by
the range.
Input: 1-D lists or dictionaries whose values are array-like.
Output: Normalized data for each input. Lists are returned as a dictionary
mapping the original value to the normalized one. Dictionaries are returned
in the same format with values normalized.
'''
results = []
for i, arg in enumerate(args):
if type(arg) is list:
arg_normalized = {}
min_val = np.min(np.abs(arg))
max_val = np.max(np.abs(arg))
for v in arg:
if len(arg) == 1:
arg_normalized[v] = v
else:
arg_normalized[v] = (v - min_val) / (max_val - min_val)
results.append(arg_normalized)
elif type(arg) is dict:
data = np.array(list(arg.values()))
min_lat, min_lon = np.min(data, axis=0)
max_lat, max_lon = np.max(data, axis=0)
min_coordinates = np.array([min_lat, min_lon])
tmp_denom = np.array([max_lat - min_lat, max_lon - min_lon])
normalized = {k: tuple(np.divide(v - min_coordinates, tmp_denom))
for k, v in arg.items()}
results.append(normalized)
else:
sys.exit("in normalize: Arguments must be lists or dictionaries.")
return tuple(results)
if __name__ == "__main__":
A = [0, 0]
B = [1, 1]
angle = 0
print(rotate_vector(A, B, angle))
|
097c8532fa1598e23df3bc7e695264a6995f1885 | rajatdiptabiswas/competitive-programming | /LeetCode/959 Regions Cut By Slashes.py | 3,604 | 3.578125 | 4 | #!/usr/bin/env python3
from typing import List
class UF:
def __init__(self, n: int) -> None:
self.parent = [i for i in range(n)]
self.size = [1 for _ in range(n)]
def find(self, p: int) -> int:
while p != self.parent[p]:
p = self.parent[self.parent[p]]
return p
def union(self, p: int, q: int) -> None:
root_p = self.find(p)
root_q = self.find(q)
if root_p == root_q:
return
if self.size[root_p] <= self.size[root_q]:
self.parent[root_p] = root_q
self.size[root_q] += self.size[root_p]
else:
self.parent[root_q] = root_p
self.size[root_p] += self.size[root_q]
def connected(self, p: int, q: int) -> bool:
return self.find(p) == self.find(q)
def components(self) -> int:
return len(set([self.find(x) for x in self.parent]))
class Solution:
def _get_root(self, row: int, col: int, n: int) -> int:
return ((n * row) + col) * 4
def _left_index(self, root: int) -> int:
return root
def _up_index(self, root: int) -> int:
return root + 1
def _right_index(self, root: int) -> int:
return root + 2
def _down_index(self, root: int) -> int:
return root + 3
def regionsBySlashes(self, grid: List[str]) -> int:
"""
divide each block in the grid into 4 regions
1
0 2
3
for a 2 x 2 grid
1 5
0 2 4 6
3 7
9 13
8 10 12 14
11 15
for each block
if '/' or ' ' encountered
connect 0,1; 2,3
if '\' or ' ' encountered
connect 1,2; 0,3
connect the grid blocks using
3,9; 2,4; 7,13; 10,12
only connect the right block and the bottom block for each block
(also check if right and bottom block not out of bound)
return the number of components
"""
n = len(grid)
uf = UF(n * n * 4)
for row in range(n):
for col in range(n):
root = self._get_root(row, col, n)
# connect regions inside the grid block
if grid[row][col] == '/' or grid[row][col] == ' ':
uf.union(self._up_index(root), self._left_index(root))
uf.union(self._right_index(root), self._down_index(root))
if grid[row][col] == '\\' or grid[row][col] == ' ':
uf.union(self._up_index(root), self._right_index(root))
uf.union(self._left_index(root), self._down_index(root))
# connect regions of different grid blocks
# (only blocks to the right and bottom)
# check if the block has blocks to the right of it
# i.e. not the right-most row
if col % n != n - 1:
right_root = root + 4
uf.union(self._right_index(root), self._left_index(right_root))
# check if the block has blocks below it
# i.e. not the bottom-most row
if row % n != n - 1:
down_root = root + (4 * n)
uf.union(self._down_index(root), self._up_index(down_root))
return uf.components()
def main():
solve = Solution()
grid = ["\\/", "/\\"]
print(solve.regionsBySlashes(grid))
if __name__ == '__main__':
main()
|
a60ffd69846eb3c404c5367f5c04c29b217d3f9d | middlehuang/CSIE-HW | /Information_Security_Class/hw5/DSA.py | 5,698 | 3.84375 | 4 | import sys
import random
import math
import hashlib
def generateLargePrime(keylength):
while True:
# generate random bits
num = random.getrandbits(int(keylength))
# apply a mask to set MSB and LSB to 1
num |= (1 << int(keylength) - 1) | 1
if isPrime(num):
return num
def isPrime(num):
if (num < 2):
return False
primelist = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241,
251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449,
457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569,
571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661,
673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787,
797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907,
911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
if num in primelist:
return True
for prime in primelist:
if (num % prime == 0):
return False
return millerRabin(40, num)
def millerRabin(times, num):
m = num -1
k = 0
while m % 2 == 0:
m = m // 2
k += 1
for i in range(times):
a = random.randrange(2, num - 1)
b = squareAndMultiply(a, m, num)
if (b != 1) and (b != num - 1):
i = 1
while i < k and b != num - 1:
b = squareAndMultiply(b, b, num)
if b == 1:
return False
i += 1
if b != num - 1:
return False
return True
# y = (x ** h) mod n
def squareAndMultiply(x, h, n):
h = bin(h).lstrip('0b')
h = h[1:]
y = x
for i in h:
y = (y ** 2) % n
if i == '1':
y = (y * x) % n
return y
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modInverse(a, b):
g, x, y = egcd(a, b)
if g == 1:
return x % b
def findOrd(p,q):
for h in range(2, p-1):
a = squareAndMultiply(h, (p-1) // q, p) # a = h ** ((p − 1)/q) % p
if(squareAndMultiply(a, q, p) == 1): # a**q = 1 mod p
return a
def keygen(keylength):
q = generateLargePrime(keylength)
p = q << (1024-160)
while (not (isPrime(p + 1)) and (len(bin(p)[2:]) == 1024)):
p = p + q
p = p + 1
while ((len(bin(p)[2:]) != 1024)):
q = generateLargePrime(keylength)
p = q << (1024-160)
while (not (isPrime(p + 1)) and (len(bin(p)[2:]) == 1024)):
p = p + q
p = p + 1
a = findOrd(p, q)
d = random.randrange(1,q)
b = squareAndMultiply(a, d, p) #(b = a**d % p)
fp = open("publicKey.txt", "w")
flur = str(p) + '\n' + str(q) + '\n' + str(a) + '\n' + str(b)
fp.write(flur)
fp.close()
fp = open("privateKey.txt", "w")
flur = str(d) + '\n'
fp.write(flur)
fp.close()
print('p = ', p)
print('q = ', q)
print('a = ', a)
print('b = ', b)
print('d = ', d)
print('Public key is store in publicKey.txt, and private key is store in privateKey.txt.')
def generation(message):
fp = open("publicKey.txt", "r")
text = fp.readline()
p = int(text)
text = fp.readline()
q = int(text)
text = fp.readline()
a = int(text)
text = fp.readline()
b = int(text)
fp.close()
fp = open("privateKey.txt", "r")
text = fp.read()
d = int(text)
fp.close()
k = random.randrange(1, q)
r = squareAndMultiply(a, k, p) % q # (a^k mod p) mod q
h = int(hashlib.sha1(message.encode("utf8")).hexdigest(), 16)
s = ((h + d * r) * modInverse(k, q)) % q # s ≡ (SHA(x) + d * r) * k^-1 mod q
fp = open("signature.txt", "w")
flur = str(r) + '\n' + str(s)
fp.write(flur)
print('r = ', r)
print('s = ', s)
print('Signature is store in signature.txt.')
def verification(message):
fp = open("publicKey.txt", "r")
text = fp.readline()
p = int(text)
text = fp.readline()
q = int(text)
text = fp.readline()
a = int(text)
text = fp.readline()
b = int(text)
fp.close()
fp = open("signature.txt", "r")
text = fp.readline()
r = int(text)
text = fp.readline()
s = int(text)
fp.close()
w = (modInverse(s, q)) % q # w ≡ s – 1 mod q
h = int(hashlib.sha1(message.encode("utf8")).hexdigest(), 16)
u1 = w * h % q # u1 ≡ w * SHA(x) mod q
u2 = w * r % q # u2 ≡ w * r mod q
v = ((squareAndMultiply(a, u1, p)*squareAndMultiply(b, u2, p)) % p) % q # v ≡ (a^u1 * b^u2 mod p) mod q
if (v == r):
print ('valid')
else:
print ('invalid')
action = sys.argv[1]
if action == '-keygen':
if len(sys.argv) == 3:
keylength = int(sys.argv[2])
else:
keylength = 160
keygen(keylength)
elif action == '-sign':
message = sys.argv[2]
generation(message)
elif action == '-verify':
message = sys.argv[2]
verification(message) |
e661bfabbb699da2641bc9644c7aaf514466058f | Manevle16/PythonUTDDataScienceWorkshop | /October27/DSPython/12_MatPlotLibFunc.py | 813 | 4.375 | 4 | # Plotting Library for Python
# Similar feel to MatLab's graphical Plotting
# Conda Install matplotlib
# Visit matplotlib.org
# important link is gallery
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 11) #Returns 11 evenly spaced numbers from 0 to 5
y = x ** 2
print(x)
print(y)
# FUNCTIONAL method
plt.plot(x, y) #plots x values on x and y values on y axis
#plt.show()
plt.xlabel('X Label') #Gives x axis a label
plt.ylabel('Y Label') #Gives y axis a label
plt.title('Title') #Gives a title to the graph
#plt.show()
# Mutliplot
plt.subplot(1, 2, 1) #Designates number of rows and columns and plots graph in position 1
plt.plot(x, y, 'r')
#plt.show()
plt.subplot(1, 2, 2) #Plots in position 2, if different # of rows and cols, will overwrite previous
plt.plot(y, x, 'b')
plt.show()
|
586f413cb3f08f4cf65eb03c77320b882f601fae | elJuanjoRamos/Curso-Python | /Leccion06-Colecciones/main.py | 3,121 | 4.46875 | 4 | # LISTAS
nombres: str = ['Juan', 'Karla', 'Ricardo', 'Maria']
print(nombres)
# acceder de forma inversa
print(nombres[-1])
# acceder un rango de valores, sin icluir hasta el indice superior
print(nombres[0:2])
# ir del inicio de la lista al indice sin incluirlo
print(nombres[:3])
# ir desde e indice indicado hasta el final, si se incluye el primer indice
print(nombres[1:])
for i in nombres:
print(i)
else:
print('no existen mas nombres en la lista');
print(f'el largo es {len(nombres)}')
##agregar elementos a la lista
nombres.append('Lorena')
print(nombres)
# insertar un elemento en un indice en especifico
nombres.insert(1, 'Octavio')
print(nombres)
# remover un elemento
nombres.remove('Octavio')
print(nombres)
# remover el ultimo elemento
nombres.pop();
print(nombres)
# eliminar un elemento segun un elemento
del nombres[0] # -- del arreglo[index]
print(nombres)
# limpiar lista
nombres.clear()
print(nombres)
# borrar la lista por completo
# del nombres
# print(nombres)
# ////////////////////////////////
# TUPLES
# ////////////////////////////////
print('inicia tuplas')
# definir una tupla
frutas = ('Naranja', 'Manzana', 'Platano')
print(len(frutas))
print(frutas[0])
#recorrer
for i in frutas:
print(i, end=' ')
# convertir tupla a lista
frutasLista = list(frutas)
frutasLista.insert(1, 'Pera')
frutas = tuple(frutasLista)
print(frutas)
tupla = (13, 1, 8, 3, 2, 5, 8)
lista = []
for i in tupla:
if i < 5:
lista.append(i)
else:
print('Ya no hay numeros')
print(lista)
# ////////////////////////////////
# SET
# no tiene indices ni orden, no soporta elementos duplicados
# ////////////////////////////////
print('inicia set')
planetas = { 'Marte', 'Tierra', 'Venus', 'Jupiter' }
print(planetas)
#largo
print(len(planetas))
# revisar si elemento esta presente
print('Marte' in planetas)
# agregar mas elementos
planetas.add('Mercurio')
print(planetas)
# eliminar elementos
planetas.remove('Tierra')
print(planetas)
planetas.discard('Jupiter')
print(planetas)
# limpiar por completo
planetas.clear()
print(planetas)
# eliminar por completo
#del planetas
#print(planetas)
# ////////////////////////////////
# Diccionarios
# esta compuesto por dos elementos, (key, value)
# ////////////////////////////////
print('empieza dicionario')
diccionario = {
'IDE': 'Integrated Development Enviroment',
'OOP': 'Object Oriented Programming',
'DBSM': 'Database Management System'
}
variable: int = 0
print(diccionario)
#largo
print(len(diccionario))
#acceder a los elementos
print(diccionario['IDE'])
#otra forma de acceder
print(diccionario.get('IDE'))
#RECCORRER ELEMENTOS DEL DICCIONARIO
for key, value in diccionario.items():
print(key, value)
#Unicamente recuperar las llaves
for key in diccionario.keys():
print(key)
# Unicamente recuperar los valores
for value in diccionario.values():
print(value)
# agregar un elemento
diccionario['PK'] = 'Primary Key'
print(diccionario)
# remover un elemento
diccionario.pop('IDE')
print(diccionario)
# LIMPIAR
diccionario.clear()
print(diccionario)
|
9c1ba3d9d00cf59c27f66ea481e61f87c278cf8a | ach-orite/leetcode | /leetcode60PermutationSequence.py | 1,726 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/12/14 9:38
# @Author : qkwu
# @File : leetcode60PermutationSequence.py
# 使用老的递归求下一个permutation k次方法 超时,只能通过分析结果来找规律
import math
class Solution:
# @param {integer} n
# @param {integer} k
# @return {string}
def getPermutation(self, n, k):
numbers = [str(i) for i in range(1, n+1)]
print(numbers)
permutation = ''
k -= 1
while n > 0:
n -= 1
# get the index of current digit
index, k = divmod(k, math.factorial(n))
permutation += str(numbers[index])
# remove handled number
numbers.remove(numbers[index])
return permutation
# def getPermutation(self, n, k):
# numbers = [str(i) for i in range(1, n + 1)]
# print(numbers)
# count = 1
# while count < k:
# numbers = self.nextPermutation(numbers)
# count += 1
# return ''.join(numbers)
#
#
#
# def nextPermutation(self, nums):
# """
# :type nums: List[int]
# :rtype: void Do not return anything, modify nums in-place instead.
# """
# length = len(nums)
# for i in range(length - 2, -1, -1):
# if nums[i] < nums[i + 1]:
# for k in range(length - 1, -1, -1):
# if nums[k] > nums[i]:
# nums[i], nums[k] = nums[k], nums[i]
# nums[i+1:] = sorted(nums[i+1:])
# return nums
# return nums
n = 4
k = 9
#Output: "2314"
sl = Solution()
print(sl.getPermutation(4, 9)) |
dfa8c6c55adb576b4ed98be846a14cc1b8536729 | green-fox-academy/FKinga92 | /week-02/day-02/factorio.py | 177 | 4.09375 | 4 | # - Create a function called `factorio`
# that returns it's input's factorial
def factorio(num):
fact = 1
for i in range(1, num+1):
fact *= i
return fact
|
fe73ffe82b8c7bc14f7d0463a077a80516cf95a6 | jiejie168/array_leetCodes | /UniquePaths.py | 1,830 | 3.9375 | 4 | __author__ = 'Jie'
"""
62. Unique Paths
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time.
The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
Constraints:
1 <= m, n <= 100
It's guaranteed that the answer will be less than or equal to 2 * 10 ^ 9.
"""
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
return self.path_recurs(m,n)
def path_recurs(self,m,n):
## recursive method
# first construct the termination condition of recursion
if m<0 or n<0: return 0
if m==1 and n==1: return 1
return self.path_recurs(m-1,n)+self.path_recurs(m,n-1)
def uniquePaths_dp(self,m,n):
# provided the array for data restore
if m<0 or n<0: return 0
result=[]
for i in range(m):
result.append([None for j in range(n)])
# set the initial values in the first column and the first row !
for i in range(n):
result[0][i]=1
for i in range(m):
result[i][0]=1
for i in range(1,m):
# m is the row number, n is the column number
# use the Dp technique
for j in range(1,n):
result[i][j]=result[i-1][j]+result[i][j-1]
return result[m-1][n-1]
m=7
n=3
solution=Solution()
# ans=solution.uniquePaths(m,n)
ans=solution.uniquePaths_dp(m,n)
print (ans) |
05d0585a96c96cf9615fb0fe94b7a7571942d6b3 | Edu93Reis/aulaPoo-Python | /T2/T3/Celular.py | 1,654 | 3.5 | 4 | from Bateria import Bateria
class Celular:
__identificador = 0
def __init__ (self, __nomeUser, __bateria):
#identificador é um elemento estático e precisa do nome da classe antes do elemento para funcionar
Celular.__identificador += 1
self.__nomeUser = __nomeUser
self.__bateria = __bateria
self.__ligado = False
def getId(self):
return self.__identificador
def getUser(self):
return self.__nomeUser
def setBateria(self, __bateria):
if(self.__ligado == True):
self.__ligado = False
self.__bateria = __bateria
def ligaCelular(self):
if(self.__ligado == False):
if(self.__bateria.getCarga()>20):
self.__ligado = True
print("Usuário: ", self.getUser(), ", ID Celular: ", self.getId())
elif(self.__bateria.getCarga() == 0):
pass
else:
self.__ligado = True
self.__bateria.getCarga()
else:
print("Celular já está ligado!")
def desligaCelular(self):
if(self.__ligado == True):
if(self.__bateria.getCarga()>=20):
self.__ligado = False
else:
print("Bye!")
if(self.__bateria.getCarga()>20):
self.__bateria.setCarga(self.__bateria.setCarga()-10)
self.__ligado = False
else:
self.__ligado = False
def tocaSom(self):
if(self.__ligado == True):
if(self.__bateria.getCarga()>10):
print("Baaat-maaan!!") |
b4840b623df06aebf5ce380c444af96574ca9254 | ishikaanugupta/Phone-book | /gui.py | 2,185 | 3.75 | 4 | from tkinter import *
import sqlite3
window=Tk()
window.title("Address Book")
window.geometry('300x350')
def submit():
conn=sqlite3.connect('phone_book.db')
c=conn.cursor()
c.execute("INSERT INTO phone VALUES(:txt1,:txt2,:txt3,:txt4)",
{
'txt1':txt1.get(),
'txt2':txt2.get(),
'txt3':txt3.get(),
'txt4':txt4.get()
})
conn.commit()
conn.close()
txt1.delete(0,END)
txt2.delete(0,END)
txt3.delete(0,END)
txt4.delete(0,END)
def query():
conn=sqlite3.connect('phone_book.db')
c=conn.cursor()
c.execute("SELECT *,oid from phone")
records=c.fetchall()
print_records=' '
for record in records:
print_records+=str(record[0])+" "+"\t"+str(record[4])+"\n"
show=Label(window,text=print_records)
show.grid(row=9,column=1,pady=10)
conn.commit()
conn.close()
def delete():
conn=sqlite3.connect('phone_book.db')
c=conn.cursor()
c.execute("DELETE from phone WHERE oid=" + txt5.get())
txt5.delete(0,END)
conn.commit()
conn.close()
lb1=Label(window,text="Name",font=("Arial Bold",10))
lb1.grid(column=0,row=0)
txt1=Entry(window,width=20)
txt1.grid(column=1,row=0)
lb2=Label(window,text="Address",font=("Arial Bold",10))
lb2.grid(column=0,row=1)
txt2=Entry(window,width=20)
txt2.grid(column=1,row=1)
lb3=Label(window,text="Phone",font=("Arial Bold",10))
lb3.grid(column=0,row=2)
txt3=Entry(window,width=20)
txt3.grid(column=1,row=2)
lb4=Label(window,text="Email",font=("Arial Bold",10))
lb4.grid(column=0,row=3)
txt4=Entry(window,width=20)
txt4.grid(column=1,row=3)
btn4=Button(window,text="Submit",width=15,command=submit,font=("Arial Bold",10))
btn4.grid(column=1,row=4,padx=5,pady=10)
lb5=Label(window,text="Delete ID",font=("Arial Bold",10))
lb5.grid(column=0,row=5)
txt5=Entry(window,width=20)
txt5.grid(column=1,row=5)
btn2=Button(window,text="Delete",width=8,command=delete,font=("Arial Bold",10))
btn2.grid(column=1,row=6,padx=5,pady=10)
btn5=Button(window,text="Show Records",command=query,font=("Arial Bold",10))
btn5.grid(column=1,row=7,pady=10)
window.mainloop()
|
24af02185e7c3320aa614e377e0d3c8e13dfee23 | mentor22/PyTest | /pytest/OOP's/Firstclass.py | 726 | 3.75 | 4 | class First:
def method1(self):
print("Welcome to Method 1 :","Manoj Moolchandani")
print("I have a system with",self.cpu ,"and",self.ram)
def __init__(self,cpu,ram):
self.cpu=cpu
self.ram=ram
def compare(self,other):
if(self.ram==other.ram):
return True
else: return False
met=First('i5',8)
print(id(met))
met1=First('Ryzen 3',16)
print(id(met1))
""" First.method1(met) #not so preferred but one method to call a method of a class
First.method1(met1) """
if(met.compare(met1)):
print("Same")
else: print("Different")
met.method1() #takes met as argument automatically
met1.method1() #takes met1 as argument automatically |
70ca3f70ad593d57d004be0bd533f155a8032dbc | DarthOpto/python_projects | /pig_latin/pig_latin_generator.py | 838 | 4.1875 | 4 | """
A pig latin generator.
Take input of a word or phrase from a user then -
If a word begins with a consonant, then move that consonant to the end and add
"ay".
If the word begins with a vowel, add "way" to the end.
"""
import string
VOWELS = ['a', 'e', 'i', 'o', 'u']
CONSONANTS = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l',
'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x',
'y', 'z']
PIG_LATIN = []
PHRASE = input('What word would you like to turn into Pig Latin: ').lower()
WORD_LIST = list(PHRASE.translate(str.maketrans('', '', string.punctuation))
.split())
for item in WORD_LIST:
if item[0] in VOWELS:
PIG_LATIN.append(item + 'way')
else:
new_word = item.replace(item[0], "")
PIG_LATIN.append(new_word + item[0] + "ay")
print(' '.join(PIG_LATIN))
|
e03aa88c35f324f46f5414c05ce8f736ecfa4675 | heyf/cloaked-octo-adventure | /leetcode/0103_binary-tree-zigzag-level-order-traversal.py | 1,261 | 3.71875 | 4 | #
# @lc app=leetcode id=103 lang=python3
#
# [103] Binary Tree Zigzag Level Order Traversal
#
from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# @lc code=start
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
ret = []
child = [root]
flag = True
while child:
new_child = []
current_layer = []
for node in child:
if node:
current_layer.append(node.val)
if node.left:
new_child.append(node.left)
if node.right:
new_child.append(node.right)
child = new_child
if current_layer:
if flag:
ret.append(current_layer)
else:
ret.append(current_layer[::-1])
flag = not flag
return ret
# @lc code=end
b = [1,2,3,4,None,None,5] # WA1
a = TreeNode(1)
a.left = TreeNode(2)
a.right = TreeNode(3)
a.left.left = TreeNode(4)
a.right.right = TreeNode(5)
s = Solution()
print(s.zigzagLevelOrder(a))
|
d2da69bb9539b9482d17a830bba075003f3934ba | hurricane618/ARTS | /Algorithm/company/vivo_2021_1.py | 925 | 3.890625 | 4 | # 拓扑排序的问题
# 采用优先队列实现
from queue import PriorityQueue
class Solution:
def compileSeq(self , input ):
# write code here
data_list = input.split(",")
l = len(data_list)
pre = []
vis = [False]*l
queue = PriorityQueue(l)
n = 0
result = ""
for data in data_list:
pre.append(int(data))
if data == '-1':
queue.put(n)
n += 1
#print(pre)
#print(queue.queue)
while not queue.empty() :
q = queue.get()
vis[q] = True
result += str(q)
result += ","
n = 0
for p in pre:
if not vis[n] and pre[n] == q:
pre[n] = -1
queue.put(n)
n += 1
return result[:-1]
s = Solution()
print(s.compileSeq("5,0,4,4,5,-1"))
|
97adc09638514e8ea6a73d1c3a54681b1b4fd0c2 | m-hildebrandt/NECTR | /datahelper.py | 20,438 | 3.515625 | 4 | import pandas as pd
import numpy as np
import random
from enum import Enum
from scipy.sparse import csr_matrix
class Sampling(Enum):
"""
Class used to represent the various mechanisms for sampling negative examples
CONSTRAINED_RANDOM: Rather than getting negative examples by randomly corrupting true triples,
we impose the additional constraint that the new tail appears as object in a known triple
with respect to the same relation as the true triple.
DISTANCE: Distance-based sampling where the distances or similarities between items are used to guide the
sampling, with the intuition being that the larger the distance between two items, the more dissimilar they
are and thereby less likely to appear in place of one another.
DISTANCE_IN_CATEGORY: Distance-based sampling within category is an extension of DISTANCE sampling. Instead of
considering all items, we only consider those items that belong to the same category as the item in question
and use the distances to them to guide the sampling.
"""
CONSTRAINED_RANDOM = 1
DISTANCE = 2
DISTANCE_IN_CATEGORY = 3
class DataHelper:
"""
Class responsible for all data-related functionality, such as loading data from files, transforming data into
suitable data structures for optimal access, and sampling negative examples.
"""
categories = None
item2category = None
category2item = None
df_triple2id = None
df_entity2id = None
item_ids = None
solution_ids = None
df_relation2id = None
item_distance = None
data = None
adjacency = None
sampling = Sampling.CONSTRAINED_RANDOM
def __init__(self):
pass
@staticmethod
def setup(data_path, parameters=None):
"""
Loads data from the file system and sets the relevant properties on the DataHelper object.
:param data_path: Path to the folder containing all the data files
:param parameters: Dictionary of parameter keys and values to be set on the DataHelper object
:return: None
"""
DataHelper.categories = pd.read_csv(data_path + 'Categories.csv', sep=';')
temp = DataHelper.categories.apply(lambda x: {int(i): x.name for i in x['entity_id'].split(',')},
axis=1).values.tolist()
DataHelper.item2category = {k: v for i in temp for k, v in i.items()}
temp = DataHelper.categories.apply(lambda x: {x.name: list(map(int, x['entity_id'].split(',')))},
axis=1).values.tolist()
DataHelper.category2item = {k: v for i in temp for k, v in i.items()}
temp = None
DataHelper.df_entity2id = pd.read_table(data_path + 'entity2id.txt', index_col=None, header=0,
names=['entity', 'id', 'type'], encoding='latin1')
DataHelper.item_ids = DataHelper.df_entity2id[DataHelper.df_entity2id['type'] == 'item']['id'].astype(int).tolist()
DataHelper.solution_ids = DataHelper.df_entity2id[DataHelper.df_entity2id['type'] == 'solution']['id'].astype(int).tolist()
DataHelper.df_relation2id = pd.read_table(data_path + 'relation2id.txt', index_col=None, header=0,
names=['relation', 'id'])
try:
DataHelper.df_triple2id = pd.read_table(data_path + 'triple2id.txt', index_col=None, header=0,
names=['h', 't', 'r', 'n'])
except pd.errors.ParserError:
print('No count data found for the triples')
print('Continuing...')
DataHelper.df_triple2id = pd.read_table(data_path + 'triple2id.txt', index_col=None, header=0,
names=['h', 't', 'r'])
DataHelper.set_parameters(parameters)
if DataHelper.sampling == Sampling.DISTANCE or DataHelper.sampling == Sampling.DISTANCE_IN_CATEGORY:
DataHelper.item_distance = np.load(data_path + 'item2item_distance.pickle')
DataHelper.set_data(DataHelper.df_triple2id)
@staticmethod
def setup_prod_data(df_entity2id, df_relation2id):
"""
Sets the specified entity and relation mappings on the DataHelper object.
This method should be used when the data needs to be setup using the passed parameter values
and not loaded from the file system.
:param df_entity2id: DataFrame with the entity to id mapping
:param df_relation2id: DataFrame with the relation to id mapping
:return: None
"""
DataHelper.df_entity2id = df_entity2id
DataHelper.item_ids = DataHelper.df_entity2id[DataHelper.df_entity2id['type'] == 'item']['id'].astype(int).tolist()
DataHelper.solution_ids = DataHelper.df_entity2id[DataHelper.df_entity2id['type'] == 'solution']['id'].astype(int).tolist()
DataHelper.df_relation2id = df_relation2id
@staticmethod
def set_parameters(parameters):
"""
Sets the specified parameters on the DataHelper object
:param parameters: Dictionary of parameter keys and values
:return: None
"""
if parameters:
for p_name, p_value in parameters.items():
setattr(DataHelper, p_name, p_value)
@staticmethod
def has_category(item):
"""
Tells whether or not the specified item has a category
:param item: Id of the item
:return: True if the item has a known category and False otherwise
"""
return item in DataHelper.item2category
@staticmethod
def get_category(item):
"""
Fetches the category of the specified item
:param item: Id of the item
:return: Category of the specified item
"""
return DataHelper.item2category[item]
@staticmethod
def get_category_encoding(item):
"""
Fetches the one-hot encoding of an item based on the categories it belongs to
:param item: Id of the item
:return: One-hot encoded list of categories for the specified item
"""
encoding = [0] * DataHelper.get_category_count()
if DataHelper.has_category(item):
encoding[DataHelper.get_category(item)] = 1
return encoding
@staticmethod
def get_categories():
"""
Fetches all known categories
:param None
:return: A DataFrame of all known categories with category name, item names, and item ids
"""
return DataHelper.categories
@staticmethod
def get_items_in_category(category):
"""
Fetches all items in the specified category
:param category: Id of the category
:return: List of ids of all items in the specified category
"""
return DataHelper.category2item[category]
@staticmethod
def get_items_with_category_count():
"""
Fetches the number of items with a known category
:param None
:return: Integer denoting the number of items with a known category
"""
if DataHelper.item2category is None:
return 0
return len(DataHelper.item2category)
@staticmethod
def get_largest_category():
"""
Fetches the category with the maximum number of items
:param None
:return: Dictionary with the id of the largest category and the number of items in that category
"""
category = max(DataHelper.category2item, key=lambda p: len(DataHelper.category2item[p]))
return {'category': category, 'n_item': len(DataHelper.category2item[category])}
@staticmethod
def get_item_count():
"""
Fetches the number of items
:param None
:return: Integer denoting the number of items
"""
if DataHelper.item_ids is None:
return 0
return len(DataHelper.get_items())
@staticmethod
def get_solution_count():
"""
Fetches the number of solutions
:param None
:return: Integer denoting the number of solutions
"""
return len(DataHelper.solution_ids)
@staticmethod
def get_category_count():
"""
Fetches the number of categories
:param None
:return: Integer denoting the number of categories
"""
if DataHelper.category2item is None:
return 0
return len(DataHelper.category2item)
@staticmethod
def get_entity_id(entity):
"""
Fetches the id of the specified entity
:param entity: Name of the entity
:return: Id of the specified entity
"""
return DataHelper.df_entity2id[DataHelper.df_entity2id['entity'].isin(entity)]['id'].astype(int).tolist()
@staticmethod
def get_items(copy=False):
"""
Fetches all the items
:param copy: Parameter that determines whether the original items or a copy will be returned
:return: If copy=True, a copy of the items is returned. This is useful in cases where the result will be further modified.
Else, the items are directly returned. This should be used for read-only purposes.
"""
if copy:
return DataHelper.item_ids[:]
return DataHelper.item_ids
@staticmethod
def get_entity_count():
"""
Fetches the number of entities
:param None
:return: Integer denoting the number of entities
"""
if DataHelper.df_entity2id is None:
return 0
return len(DataHelper.df_entity2id)
@staticmethod
def get_relation_count():
"""
Fetches the number of relations
:param None
:return: Integer denoting the number of relations
"""
if DataHelper.df_relation2id is None:
return 0
return len(DataHelper.df_relation2id)
@staticmethod
def get_relation_id(relation):
"""
Fetches the id of the specified relation
:param relation: Name of the relation
:return: Id of the specified relation
"""
return DataHelper.df_relation2id[DataHelper.df_relation2id['relation'] == relation]['id'].iloc[0]
@staticmethod
def set_data(data):
"""
Sets the data property on the DataHelper object and also creates an adjacency map
to allow fast access and traversal of linked entities and relations.
:param data: DataFrame containing data in the form of triples
:return: None
"""
DataHelper.data = data
adjacency = {'h': set(), 't': set(), 'r': {}}
for r in DataHelper.df_relation2id['id']:
adjacency['r'][r] = {'h': set(), 't': set(), 'h_map': {}, 't_map': {}}
r_triples = DataHelper.data.loc[DataHelper.data['r'] == r, ['h', 't']]
for triple in r_triples.itertuples():
_, h, t = triple
adjacency['h'].add(h)
adjacency['t'].add(t)
adjacency['r'][r]['h'].add(h)
adjacency['r'][r]['t'].add(t)
adjacency['r'][r]['h_map'].setdefault(h, set()).add(t)
adjacency['r'][r]['t_map'].setdefault(t, set()).add(h)
DataHelper.adjacency = adjacency
@staticmethod
def get_data():
"""
Fetches the data in the form of triples
:param None
:return: DataFrame containing all the triples
"""
return DataHelper.data
@staticmethod
def get_solutions():
"""
Fetches all the solutions
:param None
:return: DataFrame containing all the solutions
"""
return DataHelper.data[DataHelper.data['r'] == 0]
@staticmethod
def get_solution_matrix(solution_ids):
"""
Fetches the matrix of Solutions X Items with the entries corresponding to counts
:param solution_ids: List of solution ids
:return: Tuple consisting of a sparse matrix (Solutions X Items) and a mapping from solution ids to indices.
The entries of the matrix indicate the number of times an item has been configured in the corresponding solution.
"""
temp = DataHelper.data[DataHelper.data['h'].isin(solution_ids)]
solution_id2index = {j: i for i, j in enumerate(solution_ids)}
solution_matrix = csr_matrix((temp['n'], ([solution_id2index[i] for i in temp['h']], temp['t'])),
(len(solution_ids), DataHelper.get_item_count()))
return solution_matrix, solution_id2index
@staticmethod
def sol2triple(solutions):
"""
Converts the solutions to triples
:param solutions: DataFrame containing solutions in the form of a solution id and a tab-separated string of item ids
:return: DataFrame containing the solutions in the form of triples, i.e., solution id, item id, contains relation id
"""
temp = []
for row in solutions.itertuples():
_, h, t = row
temp += [[h, int(i), 0] for i in t.split('\t')]
triples = pd.DataFrame(temp, columns=['h', 't', 'r'])
return triples
@staticmethod
def sol2mat(solutions, sparse=False):
"""
Converts the solutions to a matrix
:param solutions: DataFrame containing solutions in the form of a solution id and a tab-separated string of item ids
:param sparse: Parameter that determines whether a dense or a sparse matrix will be returned
:return: Binary matrix of Solutions X Items where 1 indicates that an item has been configured in the corresponding solution
"""
rows, cols = [], []
for row in solutions.itertuples():
index, h, t = row
if t:
temp = [int(i) for i in t.split('\t')]
rows += [index] * len(temp)
cols += temp
if sparse:
mat = csr_matrix(([1] * len(rows), (rows, cols)), (len(solutions), DataHelper.get_item_count()))
else:
mat = np.zeros((len(solutions), DataHelper.get_item_count()))
mat[rows, cols] = 1
return mat
@staticmethod
def get_item_distance(item_id):
"""
Fetches the distances to all items from the specified item
:param item_id: DataFrame with the entity to id mapping
:return: Numpy array of distances to all items from the specified item
"""
return DataHelper.item_distance[item_id]
@staticmethod
def corrupt_tail(triple, n=1):
"""
Generates a list of corrupt tail entities for the specified triple
:param triple: DataFrame row denoting a triple of the form h, t, r
:param n: Integer denoting the number of corrupt tail entities to generate
:return: List of corrupted tail entities
"""
h, t, r = triple.h, triple.t, triple.r
corrupt_tails = DataHelper.adjacency['r'][r]['t'].difference(DataHelper.adjacency['r'][r]['h_map'][h])
t_corrupt = []
if r == 0:
# Sampling items by distance
if DataHelper.sampling == Sampling.DISTANCE or DataHelper.sampling == Sampling.DISTANCE_IN_CATEGORY:
distances = DataHelper.get_item_distance(t)
if DataHelper.sampling == Sampling.DISTANCE_IN_CATEGORY:
# For items with known category, sample items within the same category
if DataHelper.has_category(t):
corrupt_tails = corrupt_tails.intersection(set(DataHelper.get_items_in_category(DataHelper.get_category(t))))
distances = distances[list(corrupt_tails)]
distances /= distances.sum()
t_corrupt = np.random.choice(range(len(distances)), n, p=distances).tolist()
# Sampling items randomly from the constrained set of corrupted tails
elif DataHelper.sampling == Sampling.CONSTRAINED_RANDOM:
t_corrupt = random.sample(corrupt_tails, min(n, len(corrupt_tails)))
else:
h_primes = DataHelper.adjacency['r'][r]['h'].difference({h})
if not len(h_primes) or not len(corrupt_tails):
t_corrupt = random.sample(DataHelper.adjacency['t'].difference(DataHelper.adjacency['r'][r]['h_map'][h]), n)
else:
t_corrupt = random.sample(corrupt_tails, min(n, len(corrupt_tails)))
return t_corrupt
@staticmethod
def get_batch(data, batch_size, negative2positive_ratio=1, category=False, partial_data=None, complete_data=None):
"""
Fetches a batch of the specified batch size from the data
:param data: DataFrame containing data in the form of triples
:param batch_size: Size of the batch
:param negative2positive_ratio: Ratio of positive to negative samples
:param category: Boolean parameter that determines whether or not category data is included in the response
:param partial_data: Sparse matrix with data corresponding to partial solutions
:param complete_data: Sparse matrix with data corresponding to complete solutions
:return: List of lists or a dictionary consisting of batches of the specified data
"""
batch_index = 0
if category:
columns = ['h', 't', 'r', 'nh', 'nt', 'nr', 't_category', 'nt_category']
else:
columns = ['h', 't', 'r', 'nh', 'nt', 'nr']
while batch_index < len(data.index):
sample = data.iloc[batch_index: batch_index+batch_size]
triples = []
for x in sample.itertuples():
temp = DataHelper.corrupt_tail(x, negative2positive_ratio)
h, t, r = x.h, x.t, x.r
if category:
t_category = DataHelper.get_category_encoding(t)
triples += [[h, t, r, h, i, r, t_category, DataHelper.get_category_encoding(i)] for i in temp]
else:
triples += [[h, t, r, h, i, r] for i in temp]
batch = pd.DataFrame(triples, columns=columns)
if partial_data is not None:
partial_sample = partial_data[batch_index: batch_index + batch_size]
complete_sample = complete_data[batch_index: batch_index + batch_size]
yield {'triple': [list(i) for i in zip(*batch.values)], 'solution': [partial_sample] + [complete_sample]}
else:
yield [list(i) for i in zip(*batch.values)]
batch_index += batch_size
@staticmethod
def get_batch_solution(partial_data, complete_data, batch_size):
"""
Fetches a batch of the specified batch size from the data
:param partial_data: Sparse matrix with data corresponding to partial solutions
:param complete_data: Sparse matrix with data corresponding to complete solutions
:param batch_size: Size of the batch
:return: Dictionary consisting of batches of the specified data
"""
batch_index = 0
while batch_index < partial_data.shape[0]:
partial_sample = partial_data[batch_index: batch_index + batch_size]
complete_sample = complete_data[batch_index: batch_index + batch_size]
yield {'partial_solution': partial_sample, 'complete_solution': complete_sample}
batch_index += batch_size
@staticmethod
def get_test_batch(data_h, batch_size):
"""
Fetches a batch of the specified batch size from the data
:param data_h: List of h entities to extract the batch from
:param batch_size: Size of the batch
:return: List of triples of the form h, t, r where each of h, t, and r is a list of entity/relation ids.
For each h in data_h, combinations with all possible t values, i.e., all items,
and the contains relation (id=0) are returned.
"""
batch_index = 0
while batch_index < len(data_h):
yield [data_h[batch_index: batch_index + batch_size] * DataHelper.get_item_count(),
[i for i in range(DataHelper.get_item_count()) for j in range(batch_size)],
[0] * DataHelper.get_item_count() * batch_size]
batch_index += batch_size
|
c586124dfb2e3772b054a5759c33c1ae73b4cc32 | ethancaballero/myia | /myia/utils/profile.py | 4,356 | 3.546875 | 4 | """Utilities to help support profiling."""
from time import perf_counter as prof_counter # noqa
def _unit(secs):
return "%.3gs" % secs
def print_profile(prof, *, indent=0, sums=None):
"""Print a visualisation of a profile."""
total = prof.pop('__total__')
runtime = 0
ind = " " * indent
if sums is None:
sums = dict()
for v in prof.values():
if isinstance(v, dict):
v = v['__total__']
runtime += v
overhead = total - runtime
print(f"{ind}Total time taken: {_unit(total)}")
print(f"{ind} Overhead: {_unit(overhead)}")
print(f"{ind} Time spent in runtime: {_unit(runtime)}")
for k, v in prof.items():
if isinstance(v, dict):
print(f"{ind} {k}:")
print_profile(v, indent=indent + 4, sums=sums)
else:
sums[k] = sums.setdefault(k, 0) + v
print(f"{ind} {k}: {_unit(v)}")
if indent == 0:
total = sum(sums.values())
print("Sums")
for k, v in sums.items():
print(f" {k:20}: {_unit(v):10}: {(v/total)*100:5.2f}%")
class Profile:
"""Class to collect a hierachical profile of activities.
Every profile is in a context (except the top-level one) and has a
name associated with it in its parent context.
It is expected that the sum of sub-profiles will equal the time
spent in a specific step. Any difference is reported as overhead.
A profile is delimited using the python with statement:
with profile:
# do something
For sub-profiles, use one of the appropriate methods and next the
with statements. The nesting can be through functions calls of
other forms of control flow.
"""
def __init__(self):
"""Create a Profile with its initial context."""
self.ctx = None
self.ctx = ProfContext(None, self)
self.d = dict()
self.ctx.d = self.d
def __enter__(self):
self.ctx.start = prof_counter()
return self.ctx
def __exit__(self, exc_type, exc_value, exc_traceback):
self.ctx.stop = prof_counter()
self.ctx.d['__total__'] = self.ctx.stop - self.ctx.start
return None
def print(self):
"""Print a formatted version of the profile."""
return print_profile(self.d)
def step(self, name):
"""Start a step in the current context with the given name.
Nomes must be unique otherwise the previous record will be
overwritten.
with profile:
with profile.step('start'):
# Start stuff
with profile.step('end'):
# End stuff
"""
self.ctx = ProfContext(name, self)
return self.ctx
def lap(self, count):
"""Creates subcontext for a repeated action.
Count should be monotonically increasing.
with profile:
for i in range(10):
with profile.lap(i):
# loop stuff
"""
self.ctx = ProfContext(f'Cycle {count}', self)
return self.ctx
def _pop(self):
assert self.ctx.name is not None
self.ctx = self.ctx.parent
class ProfContext:
"""Utility class for Profile."""
def __init__(self, name, p):
"""Initialize a subcontext."""
self.name = name
self.p = p
self.parent = p.ctx
self.d = dict()
def __enter__(self):
self.start = prof_counter()
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
self.stop = prof_counter()
self.d['__total__'] = self.stop - self.start
if self.parent:
if len(self.d) > 1:
self.parent.d[self.name] = self.d
else:
self.parent.d[self.name] = self.d['__total__']
self.p._pop()
return None
class NoProf:
"""Class that mimics Profile, but does nothing."""
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
return None
def print(self):
"""Does nothing."""
pass
def step(self, name):
"""Does nothing."""
return self
def lap(self, count):
"""Does nothing."""
return self
no_prof = NoProf()
|
1911212e2e657efe5d82e2c71e19691b915552bd | Adriel-M/HackerRank | /Learn/Artificial Intelligence/Natural Language Processing/From Paragraphs to Sentences/paragraph2sentence.py | 1,775 | 3.9375 | 4 | """
With the assumption that there won't be a quote for the last sentence.
Need to improve abbreviation detection.
Overall, this is not a good implementation as there are too much assumptions
with no basis.
"""
entry = input().strip()
def is_abbreviation(sentence):
"""
Evaluate a word to be an abbreviation if the immediate word before the
period contains a capital letter and not a single word sentence.
"""
sentence_split = sentence.split(" ")
if len(sentence_split) == 1:
return False
elif len(sentence_split[-1]) <= 3 and \
any(x.isupper() for x in sentence_split[-1]):
return True
else:
return False
sentences = []
curr_sentence = ""
sentence_break = "?!."
in_quote = False
quote_chars = ['"', "'"]
curr_quote_char = ""
num_of_chars = len(entry)
for i in range(num_of_chars):
char = entry[i]
if curr_sentence == "" and char == " ":
continue
curr_sentence += char
if not in_quote and char in quote_chars:
if char == "'" and entry[i + 1].isupper():
in_quote = True
curr_quote_char = "'"
elif char == '"':
in_quote = True
curr_quote_char = '"'
elif in_quote:
if char == curr_quote_char:
in_quote = False
curr_quote_char = ""
if entry[i - 1] in sentence_break and \
any(x.isupper() for x in entry[i + 1: i + 3]):
sentences.append(curr_sentence)
curr_sentence = ""
elif char in sentence_break:
if char == "." and is_abbreviation(curr_sentence):
continue
sentences.append(curr_sentence)
curr_sentence = ""
# print out sentences
for sentence in sentences:
print(sentence)
|
cefdfafa0bf5bb6f9a3632b82dcc7a7dad854fdb | egortcevasofia/the_basics_of_programming_in_python | /4_week/Исключающее ИЛИ.py | 205 | 4.09375 | 4 | def xor(x, y):
if (x == 1 and y == 0) or (y == 1 and x == 0):
return 1
elif (x == 0 and y == 0) or (x == 1 and y == 1):
return 0
x = int(input())
y = int(input())
print(xor(x, y))
|
57521e80e0e9ff520c3abc6caf223ed67173b955 | aakashsbhatia2/k-means | /kmeans.py | 6,558 | 3.8125 | 4 | import csv
import math
import random
import sys
import matplotlib.pyplot as plt
from scipy.spatial import distance
def calculate_distance(point1, point2, type):
"""
Here, I am calculating the distance between point 1 and point 2. The distance metric is based on the "type" parameter.
There are 2 types of distances - Manhattan, Euclidean and Minkowski
"""
sum = 0.0
if type == "Euclidean":
for i in range(len(point1)):
sum+=(point1[i] - point2[i])**2
return math.sqrt(sum)
if type == "Manhattan":
for i in range(len(point1)):
sum+= abs(point1[i] - point2[i])
return sum
if type == "Minkowski":
sum = distance.minkowski(point1, point2, p=3)
return sum
def get_clusters(training_data, k, dist):
"""
Step 1:
I initialize the centroids to k random points. The number of centroids depends on the k value defined
Step 2:
For each point, check the distance from the current centroids
map each point to the nearest centroid
STOPPING CONDITION: If the new centroid != current centroid, update the centroids to the mean of the current points mapped to that centroid
If the centroid for 2 consecutive iterations remains the same, the k-means algorithm has converged
"""
centroids = []
for i in range(k):
x = random.choice(training_data)
centroids.append(x[:-1])
for t in range(30):
if t == 0:
for point in range(len(training_data)):
min_dist = float("inf")
temp_centroid = []
for c in range(len(centroids)):
distance = calculate_distance(training_data[point][:-1], centroids[c], dist)
if distance<min_dist:
min_dist=distance
temp_centroid = centroids[c]
training_data[point].append(temp_centroid)
else:
temp_centroids = []
for c in range(len(centroids)):
sum_1 = 0
sum_2 = 0
sum_3 = 0
sum_4 = 0
sum_5 = 0
count = 0
for point in range(len(training_data)):
if training_data[point][-1] == centroids[c]:
count+=1
sum_1 += training_data[point][0]
sum_2 += training_data[point][1]
sum_3 += training_data[point][2]
sum_4 += training_data[point][3]
sum_5 += training_data[point][4]
temp = [sum_1/count, sum_2/count, sum_3/count, sum_4/count, sum_5/count]
temp_centroids.append(temp)
if centroids != temp_centroids:
centroids = temp_centroids
else:
break
for point in range(len(training_data)):
min_dist = float("inf")
temp_centroid = []
for c in range(len(centroids)):
distance = calculate_distance(training_data[point][:-2], centroids[c], dist)
if distance<min_dist:
min_dist=distance
temp_centroid = centroids[c]
training_data[point][-1] = temp_centroid
return training_data, centroids
def create_data(path):
"""
Reading the csv file at the path inputted by the user.
"""
with open(path, newline='') as f:
reader = csv.reader(f)
final_data = list(reader)
final_data.pop(0)
random.shuffle(final_data)
for i in range(len(final_data)):
for j in range(len(final_data[i])):
final_data[i][j] = float(final_data[i][j])
return final_data
def rms(trained_data, dist):
"""
Calculating error to obtain the optimal k-value for the dataset
"""
sum = 0
for i in trained_data:
point = i[:-2]
centroid = i[-1]
distance = (calculate_distance(point,centroid, dist)**2)
sum +=distance
return sum
def plot_error(k_vals, error):
"""
Plotting the line chart to identify the elbow for k-means
"""
plt.plot(k_vals,error)
plt.xlabel('k-value')
plt.ylabel('Cost')
plt.show()
def test_clusters(trained_data, centroids):
"""
Testing the clusters (i.e. Checking the percentage of 0's and 1's in each cluster)
"""
for c in range(len(centroids)):
count_1 = 0
count_0 = 0
for p in range(len(trained_data)):
if trained_data[p][-2] == 0 and trained_data[p][-1] == centroids[c]:
count_0 += 1
if trained_data[p][-2] == 1 and trained_data[p][-1] == centroids[c]:
count_1 += 1
print ("Centroid ", c+1, ":", centroids[c])
print("Number of 1's: ", count_1)
print("Number of 0's: ", count_0)
print("Percent 1's: ", round((count_1/(count_1 + count_0))*100,2))
print("Percent 0's: ", round((count_0 / (count_1 + count_0)) * 100,2))
print("****************")
def main():
"""
The program can be run in command line. 3 parameters can be initialised.
- MANDATORY: Using "--path", you can set the path to the dataset.
- OPTIONAL: Using "--k", you can set the k value. Default value = 2
- OPTIONAL: Using "[--distance Manhattan]", you can run k-means with Manhattan distance. Default is Euclidean Distance
"""
dist = "Euclidean"
path = ""
k_v = 2
error = []
k_vals = []
for i in range(len(sys.argv)):
if sys.argv[i] == "--path":
path = sys.argv[i+1]
if sys.argv[i] == "--k":
k_v = int(sys.argv[i+1])
if sys.argv[i] == "[--distance Manhattan]":
dist = "Manhattan"
if sys.argv[i] == "[--distance Minkowski]":
dist = "Minkowski"
training_data = create_data(path)
for k in range(2,10):
k_vals.append(k)
if k>2:
for i in range(len(training_data)):
training_data[i].remove(training_data[i][-1])
trained_data, centroids = get_clusters(training_data, k, dist)
error.append(rms(trained_data, dist))
plot_error(k_vals, error)
for i in range(len(training_data)):
training_data[i].remove(training_data[i][-1])
trained_data, centroids = get_clusters(training_data, k_v, dist)
test_clusters(trained_data, centroids)
if __name__ == "__main__":
main() |
bc26eaf42883124b997cf6a4a736273724ed7431 | ptsiampas/Exercises_Learning_Python3 | /07_Iteration/Exercise_7.26.11.py | 686 | 4.25 | 4 | # Revisit the drunk pirate problem from the exercises in chapter 3. This time, the drunk pirate makes a turn,
# and then takes some steps forward, and repeats this. Our social science student now records pairs of data:
# the angle of each turn, and the number of steps taken after the turn. Her experimental data is
# [(160, 20), (-43, 10), (270, 8), (-43, 12)].
# Use a turtle to draw the path taken by our drunk friend.
__author__ = 'petert'
import turtle
turtle.setup(600,400)
wn = turtle.Screen() # Set up the window and its attributes
dg=turtle.Turtle()
for (tu , st) in [(160, 20), (-43, 10), (270, 8), (-43, 12)]:
dg.left(tu)
dg.forward(st)
turtle.mainloop() |
6be3bebde1fdd30509f912208c9b278f1f774c85 | msolone/Code_Wars_Katas | /Python/7 Kyu/minimum_steps.py | 1,374 | 3.875 | 4 | # Given an array of N integers, you have to find how many times you have to add up the smallest
# numbers in the array until their Sum becomes greater or equal to K.
# Notes:
# List size is at least 3.
# All numbers will be positive.
# Numbers could occur more than once , (Duplications may exist).
# Threshold K will always be reachable.
# Input >> Output Examples
# 1- minimumSteps({1, 10, 12, 9, 2, 3}, 6) ==> return (2)
# Explanation:
# We add two smallest elements (1 + 2), their sum is 3 .
# Then we add the next smallest number to it (3 + 3) , so the sum becomes 6 .
# Now the result is greater or equal to 6 ,
# Hence the output is (2) i.e (2) operations are required to do this .
# 2- minimumSteps({8 , 9, 4, 2}, 23) ==> return (3)
# Explanation:
# We add two smallest elements (4 + 2), their sum is 6 .
# Then we add the next smallest number to it (6 + 8) , so the sum becomes 14 .
# Now we add the next smallest number (14 + 9) , so the sum becomes 23 .
# Now the result is greater or equal to 23 , Hence the output is (3) i.e (3)
# operations are required to do this .
# 3- minimumSteps({19,98,69,28,75,45,17,98,67}, 464) ==> return (8)
def minimum_steps(numbers, value):
total = 0
operations = 0
for num in sorted(numbers):
if total < value:
total += num
operations += 1
return operations - 1
|
3554146912ba53ad028b1dcb546b3c9120ae1c02 | EduardCosmin/Python | /learn_python/Errors_and_exception_handling_8/errors_and_exception_handling.py | 3,039 | 4.625 | 5 | #Errors and exceptions handling
#We use three keywords for this:
# try: This is the block of code to be attempted (may lead to an error).
# except: Block of code will execute in case there is an error in try block.
# finally: A final block of code to be executed , regardless of an error.
#Example
def add(n1, n2):
print(n1+n2)
add(10,20) #works perfect
#The code below will produce an error (intentionally) if uncomment
# #Now let's imagine the following situation:
# number1 = 10
# number2 = input("Please enter a number") #the number will be a string
# add(number1,number2)
# #Now, after the line above, the code line below(doesn't matter how many) will not execute
# print("Somthing happend! ")
#We can proceed like below:
try:
#want to attemp this code
#may have an error
result = 10 + 10
except:
print("It looks like you aren't adding correctly")
print(result) #output: 20 because the lines are correct
#Now for the same example, but we will insert an error in try block
try:
#want to attemp this code
#may have an error
result2 = 10 + '10'
except:
print("It looks like you aren't adding correctly")
else:
#the code below will execute if there is no error in try block code
print("add function went well")
print(result2)
#Example try except ana finally
try:
f = open('testfile', 'w')
f.write("Write a test file")
except TypeError:
print("There was a type error!")
except OSError: #specific error for opening documents
print("You don't have an OS Error")
finally:
#this block will execute no matter what even if there is an error or not
print("I always run")
#Now let's make some errors
try:
f = open('testfile', 'r') #we change from w to r
f.write("Write a test file")
except TypeError:
print("There was a type error!")
except OSError: #specific error for opening documents
print("You don't have an OS Error")
finally:
#this block will execute no matter what even if there is an error or not
print("I always run")
#try/except/finally in a function
def ask_for_int():
try:
result = int(input("Please provide number"))
except:
print("That is not a number")
finally:
print("End of try/except/finally")
ask_for_int() #will display just finally block of code
#if we will type a word will be displayed block except and finally
print('')
#try/except/finally in a loop
def ask_for_int_2():
while True:
try:
result = int(input("Please provide number: "))
except:
print("That is not a number!")
continue #will continue to ask for an integer until you will type one in case that you type a string for example
else:
print("Yes thank you")
break
finally:
print("End of try/except/finally.")
ask_for_int_2() #display else statement and finally statement
#if we type an string we will have displayed except statement and finally statement
|
7d1b1750caf0e327c092a9a5d23af3a754db163d | jailukanna/Python-Projects-Dojo | /05.More Python - Microsoft/04.inheritance_student.py | 800 | 3.984375 | 4 | class Person():
def __init__(self, name):
self.name = name
def say_hello(self):
print(f'I am Hello {self.name}')
class Student(Person):
def __init__(self, name, school):
super().__init__(name)
self.school = school
def sing_school_song(self):
print(f'Ode to {self.school}')
def say_hello(self):
super().say_hello()
print('and I am a student too.')
def __str__(self):
return f'{self.name} attends {self.school}'
student = Student('Richard', 'NUS')
student.say_hello()
student.sing_school_song()
print(student)
#what are you?
# print(f'Is it a student? {isinstance(student, Student)}')
# print(f'Is is a person? {isinstance(student, Person)}')
# print(f'Is Student a Person? {issubclass(Student, Person)}') |
4c23e316b37181d2d987dc043ee5d1f25df0a3d0 | IsAlbertLiu/Python-basics | /basic/CG平台题目/cg_06_1.py | 548 | 4.0625 | 4 | # 请编写一个程序,实现删除列表重复元素的功能。
# 【输入形式】输入一行数据,以空格作为间隔。
# 【输出形式】输出删除重复元素的一行数字,以空格作为间隔。
# 【样例输入】5 12 9 12 6 23 9 5
# 【样例输出】5 12 9 6 23
arr = input()
new_arr = arr.split(' ')
no_repeat_arr = []
str = ''
# 遍历
for i in new_arr:
if i not in no_repeat_arr:
no_repeat_arr.append(i)
# print(new_arr)
# print(no_repeat_arr)
for i in no_repeat_arr:
str += i+' '
print(str) |
7674cfdda561240673885530dfa356fc20cef58e | unaidelao/python-exercises | /absp/collatz.py | 1,362 | 4.53125 | 5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Practice Projects: The Collatz Sequence.
Write a function named collatz() that has one parameter named number. If number is even, then
collatz() should print number // 2 and return this value.
If number is odd, then collatz() should print and return 3 * number + 1.
Then write a program that lets the user type in an integer and that keeps calling collatz() on
that number until the function returns the value 1. (Amazingly enough, this sequence actually
works for any integer—sooner or later, using this sequence, you’ll arrive at 1! Even
mathematicians aren’t sure why. Your program is exploring what’s called the Collatz sequence,
sometimes called “the simplest impossible math problem.”)
Remember to convert the return value from input() to an integer with the int() function;
otherwise, it will be a string value.
"""
def collatz(number):
"""Collatz Sequence"""
if number != 1:
if number % 2 == 0:
number = number//2
print(number)
collatz(number)
else:
number = 3*number + 1
print(number)
collatz(number)
# Party starts here...
print("Enter an integer, please:")
try:
num = int(input("> "))
except ValueError:
print("ERROR: invalid input literal for integer.")
else:
collatz(num)
|
7c8d4617fe0b4fe1a38e7bb84c0a882a54ff7780 | timelyanswer/python-hafb_KHK | /Day 1/my_list.py | 770 | 3.796875 | 4 | #!/usr/bin/env python3
"""
Author : t11 <me@wsu.com>
Date : 8/9/2021
Purpose:
"""
import argparse
# --------------------------------------------------
def main():
"""Make your noise here"""
r = [4, -2, 10, -18, 22, 55, 2, 77]
# Slicing
print(r[2:6])
print(f'len of linst {len(r)} ')
print(f'last element {r[-1]} ')
#Copy list, by default Python uses Shallow copies
t = r
print(f'1) is t the same as r? {t is r}')
# to make a copy, generate a new list
u = r[:]
print(f'2) is u the same as r? {u is r}')
v = r.copy()_# faster
print(f'2) is v the same as r? {v is r}')
print(f'2) is v the equivalent as r? {v == r}')
# --------------------------------------------------
if __name__ == '__main__':
main()
|
b134907535caa80cea8ee7941263c33d96d78523 | johndoubleday1/Caesar | /Caesar.py | 1,075 | 3.953125 | 4 | import string
import collections
def caesar(rotated_string, number_to_rotate_by):
letters = collections.deque(string.ascii_letters)
letters.rotate(number_to_rotate_by)
letters = ''.join(list(letters))
return rotated_string.translate(str.maketrans(string.ascii_letters, letters))
while True:
rotated_string = input(str('Enter text for Encrypt/Decrypt:'))
n = input('Encrypt or Decrypt (e/d)?')
print(n)
if 'e' == n:
print('Encrypting')
key = input('Select key number:')
key = int(key)
number_to_rotate_by = key
print(caesar(rotated_string, number_to_rotate_by))
else:
print('Decrypting')
key = input('Select key number:')
key = int(key)
number_to_rotate_by = key
print(caesar(rotated_string, -(number_to_rotate_by)))
while True:
answer = input('Run again?(y/n):')
if answer in ('y', 'n'):
break
print('Invalid input.')
if answer == 'y':
continue
else:
print('Goodbye')
break
|
79c233a64d1e8c851691803af698b3bf5987210a | Fabricio-Lopees/computer-science-learning | /exercises/01.python-for-everybody/chapter05/exercise02.py | 431 | 4.125 | 4 | maximum = 0;
minimum = 0;
guard = None;
while guard != "done":
try:
number = input("Enter a number: ").lower()
if number == "done":
print("Highest number entered: ", maximum)
print("Lowest number entered: ", minimum)
guard = number
else:
number = float(number)
if number > maximum:
maximum = number
if number < minimum:
minimum = number
except:
print("Bad input!")
print("Program finished!") |
e8bccfe56389dfbeb3440d0a1c535850ba930477 | Shirmyyy/CS313E | /Work.py | 2,041 | 3.75 | 4 | # File: Work.py
# Description: Assignment8
# Student Name: Shimin Zhang
# Student UT EID: sz6939
# Course Name: CS 313E
# Unique Number: 51350
# Date Created: 10/6/2018
# Date Last Modified: 10/6/2018
#function to find v
def find_v(n,k,hi,lo):
mid = lo + (hi - lo)//2
#if he first writes mid lines of code, he can finish his task, then mid is v
if work_enough(n,mid,k,1,mid)==1:
return mid
#if he first writes mid lines of code, he cannot finish his task
elif work_enough(n,mid,k,1,mid)==0:
#if he first writes mid+1 lines of code, he can finish his task, then mid+1 is v
if work_enough(n,mid+1,k,1,mid+1)==2:
return mid+1
#if he first writes mid+1 lines of code, he cannot finish his task, then look at the other half
else:
return find_v(n,k,hi,mid)
#if he first writes mid lines of code, he cannot finish his task
elif work_enough(n,mid,k,1,mid)==2:
#if he first writes mid-1 lines of code, he cannot finish his task, then mid is v
if work_enough(n,mid-1,k,1,mid-1)==0:
return mid
#if he first writes mid-1 lines of code, he cannot finish his task, then look at the other half
else:
return find_v(n,k,mid,lo)
def work_enough(n,v,k,p,lines):
# the recursion stop when v//k**p==0
if v//k**p==0:
#count the lines to see if he writes enough lines
if n>lines:
return 0
elif n==lines:
return 1
elif n<lines:
return 2
else:
return work_enough(n,v,k,p+1,lines+v//k**p)
def main():
in_file = open("work.txt", 'r')
count = in_file.readline()
for i in range(0, int(count)):
n,k = in_file.readline().strip().split(' ')
n = int(n)
k = int(k)
if not ((1 <= n <= 106) and (2 <= k <= 10)):
print('Invalid input')
else:
print(find_v(n,k,n,1))
main()
|
68b4081f5ffbe467430d67bfedc0afd2c238196e | problems-forked/Dynamic-Programming | /Longest Common Substring/main.py | 1,426 | 3.78125 | 4 | def find_LBS_length(nums):
maxLength = 0
for i in range(len(nums)):
c1 = find_LDS_length(nums, i, -1)
c2 = find_LDS_length_rev(nums, i, -1)
maxLength = max(maxLength, c1 + c2 - 1)
return maxLength
# find the longest decreasing subsequence from currentIndex till the end of the array
def find_LDS_length(nums, currentIndex, previousIndex):
if currentIndex == len(nums):
return 0
# include nums[currentIndex] if it is smaller than the previous number
c1 = 0
if previousIndex == -1 or nums[currentIndex] < nums[previousIndex]:
c1 = 1 + find_LDS_length(nums, currentIndex + 1, currentIndex)
# excluding the number at currentIndex
c2 = find_LDS_length(nums, currentIndex + 1, previousIndex)
return max(c1, c2)
# find the longest decreasing subsequence from currentIndex till the beginning of the array
def find_LDS_length_rev(nums, currentIndex, previousIndex):
if currentIndex < 0:
return 0
# include nums[currentIndex] if it is smaller than the previous number
c1 = 0
if previousIndex == -1 or nums[currentIndex] < nums[previousIndex]:
c1 = 1 + find_LDS_length_rev(nums, currentIndex - 1, currentIndex)
# excluding the number at currentIndex
c2 = find_LDS_length_rev(nums, currentIndex - 1, previousIndex)
return max(c1, c2)
def main():
print(find_LBS_length([4, 2, 3, 6, 10, 1, 12]))
print(find_LBS_length([4, 2, 5, 9, 7, 6, 10, 3, 1]))
main() |
16ebb397f31a29c6cf6667a2c2b6404e99fa1f28 | NileshSavale/Python-3.X | /Pattern2.py | 331 | 3.78125 | 4 | #!/user/bin/python
#Pattern 2:
#***** 1
#****
#**
#*
def pattern2(no):
for i in range(1,no+1):
for j in range (1,no-i+2):
print('*\t',end='')
print ("\n")
def main():
no=eval(input("Enter Number to for pattern2:"))
pattern2(no)
if __name__=='__main__':
main()
|
6ac2d6c9610c9eb2124a09ec108ec2956a2e5c23 | Qiujm/MyPython | /leetCodeAlgorithm/sorts/mergeSort.py | 694 | 3.671875 | 4 | def partition(lyst, left, right):
middle = (left+right) //2
piv = lyst[middle]
lyst[right]=piv
boundary=left
for index in range(left,right):
if lyst[index] <piv:
# lyst[index],lyst[boundary] = lyst[boundary],lyst[index]
swap(lyst,index,boundary)
boundary +=1
swap(lyst,right,boundary)
return boundary
def quickSortHelp(lyst, left, right):
if left<right:
pivLocation = partition(lyst,left,right)
quickSortHelp(lyst,left,pivLocation-1)
quickSortHelp(lyst,pivLocation+1,right)
def quickSort(lyst):
quickSortHelp(lyst,0,len(lyst)-1)
def swap(lyst,a,b):
lyst[a].lyst[b]=lyst[b],lyst[a] |
4639cf59202cdf856e3eb6db5ca25aea8f553ba5 | VagrantXD/Stajirovka | /7kyu/oddoreven.py | 524 | 4.0625 | 4 | #!/bin/python3
#Task:
#Given an array of numbers (a list in groovy), determine whether the sum of all of the numbers is odd or even.
#
#Give your answer in string format as 'odd' or 'even'.
#If the input array is empty consider it as: [0] (array with a zero).
#Example:
#odd_or_even({0}, 1) returns "even"
#odd_or_even({2, 5, 34, 6}, 4) returns "odd"
#odd_or_even({0, -1, -5}, 3) returns "even"
#Have fun!
def OddOrEven( arr ) :
return "even" if sum( arr ) % 2 == 0 else "odd"
print( OddOrEven( [ 5, 7, 88 ] ) );
|
32570dda016cebe08c1256a0a1b89382915ac704 | gprolog/python-for-learn | /GitHub/0002.py | 1,392 | 3.59375 | 4 | #0002,将生成的激活码保存到oracle数据库中
import string
import random
import cx_Oracle
forselect=string.ascii_letters +string.digits
def codes(count,length): #生成激活码
for x in range(count):
Re=''
for y in range(length):
Re+=random.choice (forselect)
yield Re #yield生成器,有返回值
print(Re)
print('激活码数量为:',count)
def insertcode(): #连接数据库
database_user = 'core'
database_pwd = 'core'
database_ip = '127.0.0.1'
database_port = 1521
database_service = 'xe'
database_url = '{}/{}@{}:{}/{}'.format(database_user, database_pwd, database_ip, database_port, database_service)
conn=cx_Oracle.connect(database_url) #建立连接
cursor=conn.cursor() #我们要使用连接对象获得一个cursor对象,接下来,我们会使用cursor提供的方法来进行工作,1.执行命令,2.接受返回值
print('cursor',cursor)
onecode=codes(10,20) #调用激活码生成方法
for mycode in onecode:
cursor.execute ("insert into code (code) values('%s')"%mycode) #插入数据库,注意string类型变量的处理
conn.commit() #提交
print('数据库插入成功')
cursor.close() #关闭cursor
conn.close() #关闭连接
if __name__ =='__main__':
insertcode()
|
5b6449d250a418f1acd5749420b9937499e4a4ed | himichael/LeetCode | /src/1401_1500/1404_number-of-steps-to-reduce-a-number-in-binary-representation-to-one/number-of-steps-to-reduce-a-number-in-binary-representation-to-one.py | 333 | 3.609375 | 4 | class Solution(object):
def numSteps(self, s):
"""
:type s: str
:rtype: int
"""
n = int(s,2)
res = 0
while n!=1:
if n&1==1:
n += 1
res += 1
else:
n //= 2
res += 1
return res
|
3e4f6f4a5cc70efd3a66910c8c3ce14214ed417c | gemapratamaa/codingproblems | /Divide.py | 469 | 4 | 4 | def divide(dividend: int, divisor: int) -> int:
answer = 0
if dividend < 0:
return divide(-dividend, divisor) * -1
if divisor < 0:
divisor *= -1
while dividend - divisor >= 0:
dividend -= divisor
answer += 1
return -answer
elif divisor > 0:
while dividend - divisor >= 0:
dividend -= divisor
answer += 1
return answer |
30d5b7a266e5356f636a49eae169a97245d2eb28 | PierAr/Python_Exercises | /Lists/lists.py | 551 | 4.46875 | 4 | #create and print a list
first_names = ["pier", "allyson", "tony", "kevin", "paolo"]
print(first_names)
#print a specific list item --> list number starts from 0
print(first_names[1].title())
print(first_names[3].title())
#calling for item in -1 position gives bacj the last item
print(first_names[-1].title())
#use item in a list as normal values
print(("\nmy name is ").title() + first_names[0].title())
#change values in a list
cities = ["Berlin", "Budapest", "Roma", "Milano"]
print(cities)
cities[0] = "Reggio Emilia"
print(cities)
|
598dd7d52d4dd0cb4f18630a4f7463858f877691 | AndrewAct/DataCamp_Python | /Analyzing Police Activity with Pandas/Preparing the Data for Analysis/Examining_the_Dataset.py | 276 | 4 | 4 | # 5/11/2020
# Import the pandas library as pd
import pandas as pd
# Read 'police.csv' into a DataFrame named ri
ri = pd.read_csv('police.csv')
# Examine the head of the DataFrame
print(ri.head())
# Count the number of missing values in each column
print(ri.isnull().sum()) |
206f66d416950e685de0f3103a5cfc1c9d915cb3 | yguo18/Zero-Stu-Python | /PygameForKey/randomCircle.py | 686 | 3.5625 | 4 | '''
Created on 2016.11.29
@author: yguo
'''
import pygame
import random
pygame.init()
size = [400, 300]
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
count = 0
red = pygame.Color('#FF8080')
blue = pygame.Color('#8080FF')
white = pygame.Color('#FFFFFF')
black = pygame.Color('#000000')
done = False
while not done:
screen.fill(black)
x = random.randrange(20, size[0]-20)
y = random.randrange(20, size[1]-20)
pygame.draw.circle(screen, red, [x, y], 20)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
clock.tick(200)
count += 1
print(count)
pygame.quit() |
22f8c77fa2d00aff5d82b0a88d148bed36bb7f73 | PedroLSF/PyhtonPydawan | /12a - CHALLENGE_Basic/12a.3_Classes.py | 4,277 | 4.03125 | 4 | ### 1-Setting Up Our Robot
# Define the DriveBot class here!
class DriveBot:
def __init__(self):
self.motor_speed = 0
self.direction = 0
self.sensor_range = 0
robot_1 = DriveBot()
robot_1.motor_speed = 5
robot_1.direction = 90
robot_1.sensor_range = 10
### 2- Adding Robot Logic
class DriveBot:
def __init__(self):
self.motor_speed = 0
self.direction = 0
self.sensor_range = 0
# Add the methods here!
def control_bot(self, new_speed, new_direction):
self.motor_speed = new_speed
self.direction = new_direction
def adjust_sensor(self, new_sensor_range):
self.sensor_range = new_sensor_range
robot_1 = DriveBot()
# Use the methods here!
robot_1.motor_speed = 10
robot_1.direction = 180
robot_1.sensor_range = 20
print(robot_1.motor_speed)
print(robot_1.direction)
print(robot_1.sensor_range)
### 3- Enhanced Constructor
class DriveBot:
# Update this constructor!
def __init__(self,motor_speed =0,direction = 180,sensor_range = 10):
self.motor_speed = motor_speed
self.direction = direction
self.sensor_range = sensor_range
def control_bot(self, new_speed, new_direction):
self.motor_speed = new_speed
self.direction = new_direction
def adjust_sensor(self, new_sensor_range):
self.sensor_range = new_sensor_range
robot_1 = DriveBot()
robot_1.motor_speed = 5
robot_1.direction = 90
robot_1.sensor_range = 10
# Create robot_2 here!
robot_2 = DriveBot(35, 75,25)
print(robot_2.motor_speed)
print(robot_2.direction)
print(robot_2.sensor_range)
### 4- Controlling Them All
class DriveBot:
# Create the class variables!
all_disabled = False
latitude = -999999
longitude = -999999
def __init__(self, motor_speed = 0, direction = 180, sensor_range = 10):
self.motor_speed = motor_speed
self.direction = direction
self.sensor_range = sensor_range
def control_bot(self, new_speed, new_direction):
self.motor_speed = new_speed
self.direction = new_direction
def adjust_sensor(self, new_sensor_range):
self.sensor_range = new_sensor_range
robot_1 = DriveBot()
robot_1.motor_speed = 5
robot_1.direction = 90
robot_1.sensor_range = 10
robot_2 = DriveBot(35, 75, 25)
robot_3 = DriveBot(20, 60, 10)
# Change the latitude, longitude, and all_disabled values for all three robots using only three lines of code!
DriveBot.longitude = 50.0
DriveBot.latitude = -50.0
DriveBot.all_disabled = True
print(robot_1.latitude)
print(robot_2.longitude)
print(robot_3.all_disabled)
#We placed the class variables at the top of the class outside of the constructor. These variables can be accessed within the scope of the entire class.
#This means that the class variables contained within every object from the DriveBot class will change if we modify the class variable directly.
### 5- Identifying Robots
class DriveBot:
# Create a counter to keep track of how many robots were created
all_disabled = False
latitude = -999999
longitude = -999999
robot_count = 0
def __init__(self, motor_speed = 0, direction = 180, sensor_range = 10):
self.motor_speed = motor_speed
self.direction = direction
self.sensor_range = sensor_range
# Assign an `id` to the robot when it is constructed by incrementing the counter and assigning the value to `id`
DriveBot.robot_count +=1
self.id = DriveBot.robot_count
def control_bot(self, new_speed, new_direction):
self.motor_speed = new_speed
self.direction = new_direction
def adjust_sensor(self, new_sensor_range):
self.sensor_range = new_sensor_range
robot_1 = DriveBot()
robot_1.motor_speed = 5
robot_1.direction = 90
robot_1.sensor_range = 10
robot_2 = DriveBot(35, 75, 25)
robot_3 = DriveBot(20, 60, 10)
print(robot_1.id)
print(robot_2.id)
print(robot_3.id)
#The final modifications to this class can be seen at the top of the class and in the constructor. We use a class variable to keep track of the total number of robots.
#This information is shared across all robot objects we create from the class. Every time a robot object is created, the constructor is called and the count is incremented.
|
62ede1f35d72bef8204ca106948614e28ae1d99e | windard/leeeeee | /216.combination-sum-iii.py | 1,415 | 3.703125 | 4 | # coding=utf-8
#
# @lc app=leetcode id=216 lang=python
#
# [216] Combination Sum III
#
# https://leetcode.com/problems/combination-sum-iii/description/
#
# algorithms
# Medium (52.54%)
# Likes: 674
# Dislikes: 34
# Total Accepted: 131.7K
# Total Submissions: 249.9K
# Testcase Example: '3\n7'
#
#
# Find all possible combinations of k numbers that add up to a number n, given
# that only numbers from 1 to 9 can be used and each combination should be a
# unique set of numbers.
#
# Note:
#
#
# All numbers will be positive integers.
# The solution set must not contain duplicate combinations.
#
#
# Example 1:
#
#
# Input: k = 3, n = 7
# Output: [[1,2,4]]
#
#
# Example 2:
#
#
# Input: k = 3, n = 9
# Output: [[1,2,6], [1,3,5], [2,3,4]]
#
#
#
class Solution(object):
def combinationSum3(self, k, n):
"""
:type k: int
:type n: int
:rtype: List[List[int]]
"""
start = 1
length = k
target = n
result = []
def backtrack(s, l, p):
if l == 0:
if sum(p) == target:
result.append(p)
return
for i in range(s, 10):
backtrack(i+1, l-1, p+[i])
backtrack(start, length, [])
return result
# if __name__ == '__main__':
# s = Solution()
# print s.combinationSum3(3,7)
# print s.combinationSum3(3,9)
|
ccfb5c03b8cac3ce160cb137c8b7eb63dca10603 | ljungmanag42/Project-Euler | /PE-007.py | 528 | 3.84375 | 4 | # ProjectEuler 7
'''
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see
that the 6th prime is 13.
What is the 10 001st prime number?
'''
###################
# Answer = 104743
###################
def is_prime(x):
if x==1 or x==2:
return True
for f in xrange(2,int(round(x**0.5))+1):
if x%f==0:
return False
return True
num = 1
primes = []
while len(primes)<=10000:
num += 1
if is_prime(num):
primes.append(num)
print(max(primes)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.