blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
fb96eae4948acfaef02102713547b17266c2d070 | this-rafael/Data-Structures-and-Algorithms | /Algoritms/Python/Sorting/Quadratic/SelectionSort.py | 414 | 3.765625 | 4 | from Sorting.Util import swapInArray
class SelectionSort:
def selectMin(self,array, i, j):
smallerIndex = i
for k in range(i,j):
if array[k] < array[smallerIndex]:
smallerIndex = k
return smallerIndex
def sort(self,array):
for i in range(len(array)):
min = self.selectMin(array, i, len(array))
swapInArray(array,i,min) |
a06c8217f31219ba518b00f4bde133b69218debe | franklindyer/extruder-turtle | /demos/bumpy_star.py | 579 | 3.5625 | 4 | from extruder_turtle import ExtruderTurtle
import math
t = ExtruderTurtle()
## Set up the turtle
t.name("bumpy-star.gcode")
t.setup(x=100, y=100)
t.rate(700)
t.set_density(0.3)
t.lift(1)
for l in range(9): # height of 10.5
## Draw a seven-pointed star
for k in range(7):
t.forward(50)
t.right(6*math.pi/7)
## Move to the next layer
t.lift(1.2) # 0.7 for first demo, 0.6 for second demo, 0.9 for third demo, 1.2 for fourth demo
# 0.5 gets too squished
# 1 gets too bumpy
## Save to a GCODE file
t.finish()
|
a42ed6d4416e646aec57c4a282dfb31cd8a3158e | tarcisio-neto/PythonHBSIS | /Resolucao/D1/py001.py | 916 | 4.1875 | 4 | # Criar um programa que:
# 1. Leia uma frase digitada pelo usuário.
# 2. Leia uma letra digitada pelo usuário.
# 3. Informe para o usuário quantas vezes aparece na frase (passo 1) a letra (passo 2).
# 4. Informe para o usuário a posição em que a letra aparece a primeira vez na frase.
# 5. Informe para o usuário a posição em que a letra aparece pela última vez na frase.
print ('='*60)
frase = input('{}Digite uma frase: '.format(' '*5))
letra = input('{}Digite uma letra: '.format(' '*5))
# conta letras digitadas
print('{0}A letra foi encontrada {1} vezes'.format(' '*5, frase.count(letra)))
#procura a letra do inicio para fim
print('{0}A letra foi encontrada pela primeira vez na posição: {1}'.format(' '*5, frase.find(letra)+1))
# procura a letra do fim para o início
print('{0}A letra foi encontrada pela última vez na posição: {1}'.format(' '*5, frase.rfind(letra)+1))
print ('='*60)
|
9d011c11a51d03886569680864286a819fd67b01 | Askemov/Collatz-Sequence | /Collatz.py | 437 | 4.25 | 4 | #Collatz sequence
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
else:
print(3 * number + 1)
return 3 * number + 1
while True:
try:
guess = int(input("Enter number:"))
except ValueError:
print("Please enter a number!")
while guess > 1:
guess = collatz(guess)
#break #Ends infinite loop of Collatz sequences
|
a2e9e5afc38ab8eb8977babc815108ef68437225 | sidhumeher/PyPractice | /Apple/SparseMatrixMultiplication.py | 899 | 4.0625 | 4 | '''
Created on Nov 11, 2020
@author: sidteegela
'''
def multiply(a, b):
result = []
# row_a = len(a) - 1
row_b = len(b) - 1
col_b = len(b[0]) - 1
rowCount = 0;colCount = 0
for row in a:
newRow = []
while rowCount <= row_b and colCount <= col_b:
sum = 0
for item in row:
sum += item * b[rowCount][colCount]
rowCount += 1
newRow.append(sum)
colCount += 1; rowCount = 0 # Reset rowCount
colCount = 0 # Reset colCount
result.append(newRow)
return result
# Time Complexity:O(nk * ml),n rows and k items per row in A, m columns and l items per columns in B
# Space: O(No of rows of A * No of columns of B)
if __name__ == '__main__':
a = [[ 1, 0, 0], [-1, 0, 3]]
b = [[ 7, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 1 ]]
print(multiply(a, b))
|
8be808622f9e516e02a3f82cc36250205723ab3c | AhmedElghrbawy/Content-classifier | /ourAlgo.py | 2,796 | 3.890625 | 4 | def BubbleSort(alist):
exchanges = True
passnum = len(alist)-1
while passnum > 0 and exchanges:
exchanges = False
for i in range(passnum):
if alist[i][1] < alist[i+1][1]:
exchanges = True
alist[i], alist[i+1] = alist[i+1], alist[i]
passnum = passnum-1
return alist
def insertionSort(arr):
for i in range(1, len(arr)):
key_value = arr[i][1]
key = arr[i]
j = i-1
while j >=0 and key_value > arr[j][1]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr
def selectionSort(alist):
n = len(alist)
for i in range(n-1):
max = alist[i][1]
maxposition = i
for j in range(i+1, n):
if alist[j][1] > max:
max = alist[j][1]
maxposition = j
alist[i],alist[maxposition] = alist[maxposition],alist[i]
return alist
def mergeSort(alist):
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i][1] >= righthalf[j][1]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
return alist
def quickSort(alist):
quickSortHelper(alist,0,len(alist)-1)
return alist
def quickSortHelper(alist,first,last):
if first<last:
splitpoint = partition(alist,first,last)
quickSortHelper(alist,first,splitpoint-1)
quickSortHelper(alist,splitpoint+1,last)
def partition(alist,first,last):
pivotvalue = alist[first][1]
leftmark = first+1
rightmark = last
done = False
while not done:
while leftmark <= rightmark and alist[leftmark][1] >= pivotvalue:
leftmark = leftmark + 1
while alist[rightmark][1] <= pivotvalue and rightmark >= leftmark:
rightmark = rightmark -1
if rightmark < leftmark:
done = True
else:
alist[leftmark],alist[rightmark] = alist[rightmark],alist[leftmark]
alist[first],alist[rightmark] = alist[rightmark],alist[first]
return rightmark
def get_category(categories):
maxi = categories[0][1]
pos = 0
for i in range(1,len(categories)):
if categories[i][1] > maxi:
maxi = categories[i][1]
pos = i
print (categories[pos][0]) |
f7935176b81d36cdcb36f791ebfb34aea95a1340 | apoorvamalemath/Coding-Practice | /0003_k largest elements.py | 1,125 | 4.09375 | 4 | """Given an array of N positive integers, print k largest elements from the array. The output elements should be printed in decreasing order.
Input:
The first line of input contains an integer T denoting the number of test cases. The first line of each test case is N and k, N is the size of array and K is the largest elements to be returned. The second line of each test case contains N input C[i].
Output:
Print the k largest element in descending order.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 100
K ≤ N
1 ≤ C[i] ≤ 1000
Example:
Input:
2
5 2
12 5 787 1 23
7 3
1 23 12 9 30 2 50
Output:
787 23
50 30 23
Explanation:
Testcase 1: 1st largest element in the array is 787 and second largest is 23.
Testcase 2: 3 Largest element in the array are 50, 30 and 23.
"""
#code
def Find (ele,no):
arr.sort(reverse = True)
for i in range(no):
print (arr[i], end =" ")
#Find([12, 5, 787, 1, 23],2)
#Find([1, 23, 12, 9, 30, 2, 50],3)
test_cases=input()
for i in range(int(test_cases)):
no_ele,no =(map(int, input().split()))
ele =list()
ele = list(map(int, input().split()))
Find(ele,no)
|
418a416f7fa4a490a14e7adc7e41d636b631334f | eljlee/PD_interview_script | /PagerDuty_script.py | 1,403 | 3.640625 | 4 | import sys
def customers_pages(file_name, target_customer):
customer_log = {}
# empty dict to contain customer IDs and the page IDs they have visisted
for line in file_name:
log = line.rstrip().replace(" ", "").split(",")
# strip white space to the right
# take away (replace) extra spaces
# seperate information by the commas creating a list of the items for that log
time, customer_ID, page_ID = log
# unpacking list of the three items into variables
if customer_ID not in customer_log:
customer_log[customer_ID] = []
# creating key-value pairs with empty list as value
# if customer ID key does not exist
customer_log[customer_ID].append(page_ID)
# filling dict using customer ID keys and appending to their value
# which is a list
if target_customer in customer_log:
print ", ".join(customer_log[target_customer])
# presents the list value on a single line as a string
else:
print "Sorry, that customer does not exist."
# in case the target customer ID does not exist in the file
with open(sys.argv[1]) as file_name:
# read in file from terminal line
# using 'with' will open and close the file after use
# so as to not create errors if the file is continuously used for something else
target_customer = sys.argv[2]
# also from the terminal line, take in customer ID to look up
customers_pages(file_name, target_customer)
# calling the function |
625d723e18e066bef171e195ef48fe99588d19e8 | jonasto-lab/gravacoes- | /atividade2.py | 550 | 3.796875 | 4 | S = print('Pressione s (sim) para gravar em outro arquivo.')
N = print('Pressione n (não) para repetir a frase anterior.')
A = print('Pressione a (abortar)para encerrar programa.')
entrada = input()
documento = open('documento.txt', 'r')
for l in documento.readlines():
if entrada == 's':
print(l)
input()
elif entrada == 'n': #aqui o último valor de l deve ser pego ao presionar n.
print('N')
input()
elif entrada == 'a':
quit()
else:
print ('Selecione uma das opções acima!')
|
78eca216089638c79fa50cf1b24dbf47616f807f | evehsu/Algorithm-Stanford-EDX | /graph/dijkstra.py | 1,416 | 3.625 | 4 | import sys
from utils import load_dijkstra_graph
from collections import defaultdict
def dijkstra(graph, s, t):
'''
:param graph: adjacent list of directed graph
:param s: source node
:param t: target node
:return: shortest path returned by dijkstra algorithm
'''
visited = {s : 0}
while t not in visited:
next_edge_tail, next_edge_head, next_dist = find_next(graph,visited)
visited[next_edge_head] = next_dist
return visited[t]
def find_next(graph, visited):
'''
iterate every edge that from visited to unvisited, and find the minimum as next node in shortest path
:param graph:
:param visited:
:return:
'''
cur_node_visited = list(visited.keys())
next_head, next_tail = None, None
global_min = float("inf")
for n in cur_node_visited:
cur_heads = list(graph[n].keys())
for h in cur_heads:
if h in visited:
continue
if visited[n] + graph[n][h] < global_min:
next_head, next_tail = h, n
global_min = visited[n] + graph[n][h]
return next_tail, next_head, global_min
def main():
file_name = sys.argv[1]
g = load_dijkstra_graph(file_name)
res = []
s = 1
for t in [7,37,59,82,99,115,133,165,188,197]:
sp = dijkstra(g, s, t)
res.append(sp)
print(res)
if __name__ == "__main__":
main() |
f0a44c0c03cdd0959207e0905446620557b66198 | andrewdnolan/ERS_420 | /PS_4/read_ifile.py | 1,162 | 3.71875 | 4 | from dateutil.parser import parse
def read_file(filename,start_date,end_date):
'''
input: * filename of csv data file
* starting date of data to read in
* ending date of date to read in
output: a dictionary with keys 'dates' and 'values'. Dates are python datetime objects
and values are floats (tempertures)
'''
fileobj=open(filename,'rt')
data={'dates':[], 'values':[]}
dates=[]
flag=False
for i,line in enumerate(fileobj):
if flag==True:
words=line.split(',')
try:
# catch error then values in list cannont be parsed by dateutil module
date=parse(words[0])
# only save data collected between start and end dates
if date<parse(end_date) and date>parse(start_date):
tmpt=float(words[1])
data['dates'].append(date)
data['values'].append(tmpt)
except ValueError:
pass
elif 'TimeStamp,Temperature' in line:
# find line when header ends and data begins
flag=True
return data |
e5579c297c83096247425c82acfabdca0dc70618 | Yuhjiang/LeetCode_Jyh | /problems/midium/114_flatten_binary_tree_to_linked_list.py | 833 | 4.0625 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
self.last = None
self.flatten_(root)
def flatten_(self, r):
if r:
self.flatten_(r.right)
self.flatten_(r.left)
r.right = self.last
r.left = None
self.last = r
else:
return None
if __name__ == '__main__':
from problems.utils import create_tree, print_tree
ro = create_tree([1, 2, 5, 3, 4, None, 6, None, None, None, None, None, None])
Solution().flatten(ro)
print_tree(ro) |
e444bb920fbe6bfa389893acafa8889c822d52dd | BensyBenny/Bensybenny-rmca-s1A | /co2program3.py | 759 | 4.28125 | 4 | Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> NumList = []
>>> Number = int(input("Please enter the Total Number of List Elements : "))
Please enter the Total Number of List Elements : 4
>>> for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
Please enter the Value of 1 Element : 1
Please enter the Value of 2 Element : 2
Please enter the Value of 3 Element : 3
Please enter the Value of 4 Element : 4
>>> total = sum(NumList)
>>> print("\n The Sum of All Element in this List is : ", total)
The Sum of All Element in this List is : 10
>>> |
fd3b031e04a07063a3309e1ce2c3dc1c425df339 | PatrikKopriva/School_Projects | /kopriva_du1.py | 3,168 | 3.515625 | 4 | # Prvni domaci uloha z IB111, 2017
#
# Mate za ukol naprogramovat 5 funkci, za kazdou muzete ziskat az 5 bodu
# Piste co nejprehlednejsi kod, zejmena vhodne pojmenovavejte promenne
# (za necitelny kod hrozi bodova srazka)
#
# Sve reseni pojmenujte jako "prijmeni_du1.py" a ulozte do prislusne odevzdavarny
# (bez uvozovek a bez diakritiky)
# --------------------------------------------------------------
# Zde muzete definovat pripadne importy
from turtle import Turtle
from math import ceil
#---------------------------------------------------------------
# 1) Napiste funkci, ktera pro zadane N vypise vsechna cela cisla od jedne do N vcetne
# tak, ze suda jsou vypsana normalne a misto lichych se vypise cislo opacne
#
# napr: pro N = 8 funkce vypise: -1, 2, -3, 4, -5, 6, -7, 8
# pozn. muzete predpokladat, ze jako N bude zadavano kladne cele cislo
#---------------------------------------------------------------
def numbers_interlaced(n):
for i in range(1, n+1):
if i%2==0:
print(i, end=", ")
else:
print(0-i, end=", ")
#---------------------------------------------------------------
# 2) Napiste funkci, ktera pro zadane parametry N, M vypise matici (tabulku) cisel
# o velikosti N krat M, (N radku, M sloupcu) kde kazde cislo je dano jako soucet cisla radku a sloupce.
# Radky i sloupce cislujte od 1, zarovnani nereste (sloupce oddelujte mezerou)
#
# napr: pro N = 4, M = 6 bude vystup:
#
# 2 3 4 5 6 7
# 3 4 5 6 7 8
# 4 5 6 7 8 9
# 5 6 7 8 9 10
#---------------------------------------------------------------
def sum_table(n, m):
for i in range (1, n+1):
for j in range (1, m+1):
print(i+j, end=" ")
print()
#---------------------------------------------------------------
# 3) Napiste funkci, ktera v textove grafice vykresli pro zadane N prazdnou
# pyramidu o N patrech tvorenou krizky "#" a vyplnenou teckami "."
#
# napr: pro N = 4 funkce vykresli
#
# . #
# . . . #
# # # # # # #
# pozn. zde je spravne odsazovani mezi patry stezejni (na velikosti odsazeni cele pyramidy nezalezi)
#---------------------------------------------------------------
def blank_pyramid(n):
for i in range (-n,0):
for j in range (-n,n):
if abs(i) + abs(j) == n or (i==-1 and j>(-n+1)):
print("#", end=" ")
elif abs(i) + abs(j) < n:
print(".", end=" ")
else:
print(" ", end=" ")
print()
#---------------------------------------------------------------
# 4) Napiste funkci, ktera v zelvi grafice vykresli tvar medove plastve. Plastev je slozena z prostredniho
# sestiuhelniku o strane "side" a sesti dalsich stejne velkych sestiuhelnicich prilehajicich
# k jeho stenam (viz obrazek honeycomb.png)
#---------------------------------------------------------------
def honey_comb(side):
bob=Turtle()
for i in range (6):
for j in range (7):
bob.left(60)
bob.forward(side)
bob.right(120)
|
ec7d07403072a84eb669abc5dead4f5bab50f6a0 | nikhilbagde/Grokking-The-Coding-Interview | /tree-bfs/examples/zigzag-traversal/python/MainApp/app/mainApp.py | 1,766 | 4.25 | 4 | from queue import Queue
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class MainApp:
def __init__(self):
pass
'''
Given the root of a binary tree, return the zigzag level order traversal of its nodes' values.
(i.e., from left to right, then right to left for the successor level and alternate between).
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
'''
@staticmethod
def run(root):
if not root:
return []
else:
q = Queue()
q.put((root, 0))
nodes_in_corresponding_level = []
nodes_in_current_level = []
current_level = 0
while not q.empty():
(element, level) = q.get()
if current_level == level:
if level % 2 != 0:
nodes_in_current_level.insert(0, element.val)
else:
nodes_in_current_level.append(element.val)
else:
current_level += 1
nodes_in_corresponding_level.append(nodes_in_current_level)
nodes_in_current_level = [element.val]
if element.left:
q.put((element.left, level + 1))
if element.right:
q.put((element.right, level + 1))
nodes_in_corresponding_level.append(nodes_in_current_level)
return nodes_in_corresponding_level
|
3014eea61c99f92d0aef3d5f43c339ff28992515 | 404232077/python-course | /ch05/5-2-1-fac.py | 131 | 3.640625 | 4 | M = int(input('請輸入M?'))
fac = 1
i = 1
while(fac < M):
i = i + 1
fac = fac * i
print(i,'階乘為', fac,'大於', M) |
d894dc2d2169e44be4be049bd738b957805c798a | elijahzucker/Cryptography-Class-Project | /eCurveAdd.py | 7,599 | 4.4375 | 4 | """
Series of functions to do basic encrytion/decryption using elliptical curves for deciding on a key.
This assumes an understanding of elliptical curves and their use in cryptography.
I was working off of this book: An Introduction to Mathematical Cryptography (Undergraduate Texts in Mathematics) by Jeffrey Hoffstein
https://www.amazon.com/Introduction-Mathematical-Cryptography-Undergraduate-Mathematics/dp/1493939386
"""
import hashlib
class curve:
"""
This class contains the information that needed to
identify any specific curve and its helper functions.
"""
def __init__(self, a, b, p): #Weierstrass curve form
# a & b are the curve integers and p is the prime
self.a = a
self.b = b
self.p = p
def whatC(self):
#prints curve equation
print("Curve: y^2 mod", self.p, "= x^3 +", self.a, "x +", self.b, "mod", self.p,)
def isGroup(self):
#returns true if curve forms a group over the field
if ( (4 * self.a ** 3) + (27 * self.b ** 2) ) % self.p == 0:
return False
return True
class point:
"""
Class for storing specific points on a curve
"""
def __init__(self, x, y, c):
# x & y are the values of the point and c is the curve object they are on
self.x = x
self.y = y
self.c = c
def pointValue(self):
#Computes the LHS and RHS values of the point.
L = (self.y ** 2) % ((self.c).p)
R = (self.x ** 3 + ( (self.c).a ) * (self.x) + ( (self.c).b )) % ( (self.c).p )
V = [L, R]
return V
def pointValid(self):
#Checks to see if LHS==RHS to confirm the point is on the curve
V = self.pointValue()
if V[0] == V[1]:
return True
return False
def pointDisplay(self):
#Prints the value of the point
print("x = ", self.x, " y = ", self.y)
return
def eAdd(P, Q): #adds 2 points by using the slope to find where the line intersects and returns the negation of that point
"""
Param P & Q point objects
Takes 2 point objects, P & Q, and adds them together,
It handles any situations where one point is the identity (0,0)
It also calls a seperate function for whenever P = Q
"""
R = point(0,0,P.c) #creates point object to store result
if (P.x == 0 and P.y == 0) and (Q.x == 0 and Q.y == 0): #(0,0) is the identity
return P #returns the identity
elif P.x == 0 and P.y == 0:
return Q
elif Q.x == 0 and Q.y == 0:
return P
elif P == Q: #in case it is called when double should be
R = eDouble(P)
else: #this preforms the actual addition
i = P.y-Q.y
j = P.x-Q.x
s = (i * modInv(j, P.c.p) ) % P.c.p
R.x = ( ( (s**2) - P.x - Q.x) % P.c.p)
R.y = ( (-P.y + s * (P.x - R.x) ) % P.c.p)
return R
def eDouble(P): #adding P + P by using a tangent line
"""
Param P point object
This is elliptical addition for when both elements are equal,
this is needed since addition works off of the slope between points
"""
R = point(0, 0, P.c)
i = ( (3 * P.x ** 2) + P.c.a) #the slope equation (i/j)
j = (2 * P.y)
s = (i * modInv(j, P.c.p) ) % P.c.p
R.x = ( (s ** 2) - 2 * P.x) % P.c.p
R.y = (-P.y + s * (P.x - R.x) ) % P.c.p
return R
def eMult(P, s):
"""
Param P point object
Param s is a scaler multiplier
Uses the "Double and Add Method" for scalar multiplication
Converting the scaler into binary we use the indexes that
equal 1 as a flag to to know when add instead of just doubling
"""
Q = point(0, 0, P.c)
T = point(P.x, P.y, P.c)
B = bin(s)[2:][::-1] #uses 0b representation to know when to add
for i in range( len(B) ): #1 means add and then double T, 0 means just double T
if B[i] == '1':
Q = eAdd(Q, T)
T = eDouble(T)
if s < 0: #handles if s is negative
Q.y = -Q.y
return Q
#start of keygen operations
def curveInput():
"""
Creates a curve object with the inputed values and validates that it forms a group
"""
C = curve(0, 0, 0)
C.a = int( input("enter the a value for curve:") )
C.b = int( input("enter the b value for curve:") )
C.p = int( input("enter the prime p the for the field:") )
if not C.isGroup():
C = curve(0, 0, 0)
print("This is not a valid member of the group.")
return C
return C
def pointInput(C):
"""
Param C is a Curve object
the function prompts for the values of a point
and then creates a point object on that curve
"""
P = point(0, 0, C)
P.x = int( input("enter the x value for point:") )
P.y = int( input("enter the y value for point:") )
return P
def pointInputValid(C):
"""
Param C is a Curve object
creates a point and confirms its valid
"""
P = point(0, 0, C)
P.x = int( input("enter the x value for point:") )
P.y = int( input("enter the y value for point:") )
if not P.pointValid():
print("The given point is not valid.")
return 0
return P
def keyStart(P,n):
Q = pointInput(P.c)
Q = eMult(P,n)
Q.pointDisplay()
return Q
def keyGen(): #todo
n = int(input("enter secret int n:"))
P = point(0,0,C)
P = keyStart(P,n)
#s = input("Do you have a recived point to enter? (y/n)") #in practice only the x coord is sent
#if s == 'n': #there are only to possible y's (y and -y)
return P
#Q = point(0,0,C)
#Q = keyStart(Q,n)
#Q = eMult(P,n) #Only the x value is the key.
#return Q
def modInv(a, m): #modular inverse
a = a % m;
for x in range(1, m) :
if ( (a * x) % m == 1) :
return x
return 1
def eElgamalEncrypt(P, Q):
print("Enter the message:")
M = pointInputValid(P.c)
k = int( input("Choose random element k:") )
C1 = eMult(P, k)
C2 = eAdd(M, (eMult(Q, k)))
CT = [C1, C2]
print(C1.pointDisplay(), C2.pointDisplay())
return CT
def eElgamalDecrypt(CT, nA):
M = eAdd( CT[1], eMult( eMult(CT[0],nA),-1) )
return M
#below is still todo
def ECDSAkey(G, q, C):
s = int(input("Input secret signing key 1 < s < q-1: "))
#while s > (q-1):
# print("Error s is greater than or equal to q. Enter a valid s or 0 to cancel. ")
# s = int( input("Input secret signing key 1 < s < q-1: ") )
# if s == 0:
# break
V = eMult(G, s)
return V
def ECDSAsign(G, d, q, s):
e = (int (hashlib.blake2b(b'd').hexdigest(),16) )
eG = eMult(G, e)
s1 = eG.x % q
s2 = ( (d + (s * s1) ) * modInv(e, G.c.p) ) % q
S = [s1, s2]
return S
def ECDSAver(G, d, q, S, V):
v1 = (d * modInv(S[1],q) )%q
v2 = (S[0] * modInv(S[1],q) )%q
T = eAdd( eMult(G, v1), eMult(V, v2) )
I = T.x % q
print(I, S[0])
return I
|
d176952f608a727b796b012db67476545ad5775e | ShaominLi/PythonCodes | /practice/suanfa/sort.py | 1,188 | 3.671875 | 4 | #!/usr/bin/python
#-*- coding:utf-8 -*-
#001 冒泡排序
def BubbleSort(x=[]):
exchange=1
n=len(x)
for i in range(1,n):
exchange=0
for j in range(i,n)[::-1]:
if x[j]<x[j-1]:
t=x[j-1]
x[j-1]=x[j]
x[j]=t
exchange=1
if exchange==0:
break
#002 选择排序
def selectSort(s=[]):
size=len(s)
for i in range(0,size-1):
k=i
for j in range(i+1,size):
if s[k]>s[j]:
k=j
if k!=i:
t=s[i]
s[i]=s[k]
s[k]=t
#003 一次快速排序
def quickSort(s=[]):
t=s[0]
low=0
high=len(s)-1
while low<high:
while low<high and s[high]>t:
high-=1
s[low]=s[high]
while low<high and s[low]<t:
low +=1
s[high]=s[low]
s[low]=t
#004 插入排序
def insertSort(s=[]):
n=len(s)-1
ss=s[0:1]
for v in s[1:]:
nn=len(ss)-1
while ss[nn]>v:
nn-=1
if nn==-1:
break
ss.insert(nn+1,v)
return ss
s=[1,4,6,3,2]
s=insertSort(s)
print(s)
|
38c0d93365bd3d9279c373b95b35add6f2e2b371 | mauricioZelaya/QETraining_BDT_python | /DiegoGonzales/task_list_dic/task_replace_string.py | 464 | 3.875 | 4 | def replace_text(text, oldText, newText):
newString = ""
for i in range(len(text)):
if text[i] == oldText:
newString += newText
else:
newString += text[i]
return newString
cadena = "La programacion es muy bonito pero si no jala lo rompes el teclado y la PC gooooooool"
oldText = "o"
newText = "X"
print(replace_text(cadena, oldText, newText))
print(cadena.replace("o","@")) # Ejemplo del uso del metodo replace. |
bfa18e68f74e302879dcbaff5c6c0f712cbf8c73 | Ashutosh-gupt/HackerRankAlgorithms | /Counter game.py | 1,703 | 3.6875 | 4 | """
Louise and Richard play a game. They have a counter set to N. Louise gets the first turn and the turns alternate
thereafter. In the game, they perform the following operations.
If N is not a power of 2, they reduce the counter by the largest power of 2 less than N.
If N is a power of 2, they reduce the counter by half of N.
The resultant value is the new N which is again used for subsequent operations.
The game ends when the counter reduces to 1, i.e., N == 1, and the last person to make a valid move wins.
Given N, your task is to find the winner of the game.
Update If they set counter to 1, Richard wins, because its Louise' turn and she cannot make a move.
Input Format
The first line contains an integer T, the number of testcases.
T lines follow. Each line contains N, the initial number set in the counter.
"""
__author__ = 'Danyang'
class Solution(object):
def solve(self, cipher):
"""
main solution function
:param cipher: the cipher
"""
N = cipher
turn = 0
while N > 1:
turn += 1
if N & (N - 1) == 0:
N /= 2
else:
num = 1
while num < N:
num <<= 1
num >>= 1
N -= num
if turn & 1 == 0:
return "Richard"
else:
return "Louise"
if __name__ == "__main__":
import sys
f = open("1.in", "r")
# f = sys.stdin
testcases = int(f.readline().strip())
for t in xrange(testcases):
# construct cipher
cipher = int(f.readline().strip())
# solve
s = "%s\n" % (Solution().solve(cipher))
print s,
|
8e6da54dbdd0ef426dc0df1a1b45888c97403469 | moni310/Dictionary | /adding.py | 106 | 3.53125 | 4 | dict={"name":"moni","age":20,"gender":"male"}
dict["instute"]="milaan"
dict["palce"]="lucknow"
print(dict) |
4953fb5cc8914319fdf1a7f796162bd8d0c93c46 | osfp-Pakistan/python | /viirs_KML/instruction_viirs.py | 2,392 | 3.796875 | 4 | # Jon Nordling
# University of Maryland
# Graduate Research Assistant
# 08/10/2012
#######################################
# This is a python program that converts a text file with lat, lng cordinatons into a
# Google earth/map format kml/kmz. The program uses a 3rd party module called simpleKml
# Download the folder to test the program. Must install simplekml first
# For Python 2.6 or higher
#######################################
# Sets the imports needed for the program
import os
import sys
import simplekml
#Setting the Global variables
# Loc = the directory where the text files are located
# files = the list of files in that directory
loc = './'
files = ['NPP_VIIRS_20140111_AF.txt','NPP_VIIRS_20140112_AF.txt']
# The following function is the main function that will be the first
# function run when the program is launched
def main():
# loops through each of the files
for i in files:
kml = simplekml.Kml() # Launch the Kml Object
in_file = open(i) # Open the file
file_lines = in_file.readlines() # retrieves each of the lines in the file
num_lines = len(file_lines) # Sets a variable to the number of lines in the file
for j in range(1, num_lines): #Loop through each of the lines in the file
# pnt = the lat and lng points that located on the line of text file.
# Reference the text file to see format to fullly understanding
pnt = kml.newpoint(coords=[(get_lng(j), get_lat(j))]) # Call the lat and lng functions to retreive the values
pnt.style.iconstyle.icon.href = 'fireicon.png' # Defines the icon that will display in the kml file(not required)
pnt.style.iconstyle.scale = 1 # Defines the icon scale(not required)
kml.savekmz(i[0:21]+'.kmz') # Saves a a kmz file. (To save as kml replace line with kml.save(i[0:21]+'.kml'))
in_file.close() #Close the file
# function gets the lng from the file and line numnber passed
def get_lng(line):
line = file_lines[line].strip() # create an array of all the values in the line
lng = line[23:33] # Locateds and defines the lng
return lng # Retuns the lng
# function gets the lat from the file and line numnber passed
def get_lat(line):
line = file_lines[line].strip() # create a array of all the values in the line
lat = line[34:] # Locateds and defines the lat
return lat # Retuns the lat
|
4cffc9c1c579d80eea758f1ddbc5d496caa68a53 | csxbwang/polaris | /geonavigation.py | 737 | 3.5 | 4 | from math import sin, cos, atan2, degrees, pi
def gps_coords_to_heading(lat1, lon1, lat2, lon2):
# lat = lat2-lat1
lon = lon2 - lon1
targetHeading = degrees(atan2(sin(lon) * cos(lat2), cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(lon)))
return (targetHeading + 360) % 360
def heading(lat1,lon1,lat2,lon2):
#calculated intial course to second waypoint
heading = atan2(cos(lat1*(pi/180))*sin(lat2*(pi/180))-sin(lat1*(pi/180))*cos(lat2*(pi/180))*cos((lon2-lon1)*(pi/180)), sin((lon2-lon1)*(pi/180))*cos(lat2*(pi/180)))
heading = -(heading*(180/pi)-90)
if heading <0:
heading = heading +360
if heading >180:
heading = heading -360
heading = heading*(pi/180)
return heading |
e87e337024202ddedbce3a3a509813b7457cffc0 | SaretMagnoslove/Python_3_Basics_Tutorial_Series-Sentdex | /Lesson11_functions_parameters_defults.py | 652 | 3.96875 | 4 | # When using defaults, any parameters with defaults should be the last ones listed in the
# function's parameters.
# Something like:
def simple(num1, num2=5):
pass
# This is just a simple definition of a function,
# with num1 not being pre-defined (not given a default),
# and num2 being given a default.
def basic_window(width,height,font='TNR'):
# let us just print out everything
print(width,height,font)
basic_window(350,500)
# Here, we can see that, if there is a function parameter default,
# then, when we call that function, we do not need to define or even mention that
# parameter at all!
basic_window(350,500,font='courier') |
83d78a474d0c522455d41df2dc1fed89d8fc018b | GOD-OF-FIRE/HCF | /hcf.py | 322 | 3.984375 | 4 | def compute_hcf(x,y):
if x > y:
smaller=y
else:
smaller = x
for i in range (1,smaller+1):
if((x%i==0)and(y%i==0)):
hcf = i
return hcf
num1=int(input("Enter first Number: "))
num2=int(input("Enter second Number: "))
print("The HCF is",compute_hcf(num1,num2))
|
2c003251b446689442ab5d710190fc4042e57e91 | VakinduPhilliam/Python_Argparse_Interfaces | /Python_Argparse_Required.py | 1,045 | 3.859375 | 4 | # Python argparse
# argparse Parser for command-line options, arguments and sub-commands.
# The argparse module makes it easy to write user-friendly command-line interfaces.
# The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv.
# The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments
#
# required
# In general, the argparse module assumes that flags like -f and --bar indicate optional arguments, which can always be omitted at the command line.
# To make an option required, True can be specified for the required= keyword argument to add_argument():
parser = argparse.ArgumentParser()
parser.add_argument('--foo', required=True)
parser.parse_args(['--foo', 'BAR'])
# OUTPUT: 'Namespace(foo='BAR')'
parser.parse_args([])
#
# As the example shows, if an option is marked as required, parse_args() will report an error if that option is not present at the command line.
# |
b42f9ad045e816286001bb99412e517bd367a18b | Jorisdehoog/Artificial-Intelligence-for-self-driving-cars---Udacity | /First_Search_Program.py | 5,409 | 4.21875 | 4 | # ----------
# User Instructions:
#
# Define a function, search() that returns a list
# in the form of [optimal path length, row, col]. For
# the grid shown below, your function should output
# [11, 4, 5].
#
# If there is no valid path from the start point
# to the goal, your function should return the string
# 'fail'
# ----------
# Grid format:
# 0 = Navigable space
# 1 = Occupied space
grid = [[0, 1, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 0],
[0, 1, 0, 1, 1, 0],
[0, 0, 0, 1, 1, 0]]
init = [0, 0]
goal = [len(grid)-1, len(grid[0])-1]
cost = 1
delta = [[-1, 0], # go up
[ 0,-1], # go left
[ 1, 0], # go down
[ 0, 1]] # go right
delta_name = ['^', '<', 'v', '>']
def search(grid,init,goal,cost):
# path = 0 # remove once finished
# create a list of the current position. First element is the g-number, the next two are the coordinates
g_val = 0 # number of steps needed (current_pos[0])
initial_list = [[g_val, init[0], init[1]]] # initialize the G-value
# initial_list.append([9, 0, 1])
goal_reached = 0 # identifier of success
# print initial_list
position = init # position (current_pos[1:2])
# print grid[position[0]][position[1]]
# print [1, initial_list[g_val][1], initial_list[g_val][2]]
# test of grid
# print [tuple(x[0] for x in grid)]
# print "Initial open list"
# for s in initial_list:
# print s
# print "--------"
while goal_reached != 1:
# store list of g-values in pp
pp = []
for i in range(len(initial_list)):
pp.append(initial_list[i][0])
# find index of smallest pp
ppidx = pp.index(min(pp))
# print ppidx
# take the list item
# retreive element with lowest g-value (and check if goal is reached!)
# also change check-mark on grid
# remove this from the initial_list
list_item = initial_list[ppidx]
# print "Take list item"
# print list_item
# print "--------"
initial_list.pop(ppidx)
if [list_item[1], list_item[2]] == goal:
path = list_item
# print "Success"
goal_reached = 1
break
# if len(list_item) == 0 and len(initial_list) == 0:
# print "fail"
# break
grid[list_item[1]][list_item[2]] = 1
# print list_item
# expand the list item into new open list
new_list = list()
# if g_val == 6:
# # print len([pp for pp in grid[0]])
for ii in range(len(delta)):
temp_g_val = list_item[0]
newstep = [a + b for a, b in zip([list_item[1], list_item[2]], delta[ii])]
# print newstep
# print sum(n < 0 for n in newstep)
# grid[5][0] is out of bounds, check!
if newstep[0] < len(grid) and newstep[1] < len(grid[0]) and sum(n < 0 for n in newstep) == 0 and grid[newstep[0]][newstep[1]] != 1 :
new_list.append([temp_g_val + cost, newstep[0], newstep[1]])
# mark grid!
grid[newstep[0]][newstep[1]] = 1
else:
newstep = None
if len(new_list) != 0:
g_val += cost
# determine if we can do another step, if not: FAIL
if len(new_list) == 0 and len(initial_list) == 0:
# path = []
path = "fail"
break
for iii in range(len(new_list)):
initial_list.append(new_list[iii])
# print initial_list
# print "New open list"
# for s in initial_list:
# print s
# print "--------"
# grid2 = list(grid)
# grid2.pop(0)
#
# print grid2
# while goal_reached == 0:
# # look for other positions.
# grid[current_pos[g_val][1]][current_pos[g_val][2]] = 1
# last_length = len(current_pos) # so we dont change the length of the inner loop during operation
#
# # if [current_pos[steps][1], current_pos[steps][2]] == goal:
# # goal_reached = 1
# # else:
# # current_pos.pop(steps)
#
# # len(input) = amount of rows
# # len(input[0]) = amount of columns
#
# for i in range(len(delta)):
# for ii in range(last_length):
# newstep = [a + b for a, b in zip([current_pos[ii][1], current_pos[ii][2]], delta[i])]
# print newstep
# if sum(n < 0 for n in newstep) > 0 or grid[newstep[0]][newstep[1]] == 1:
# # do nothing
# print ""
# else:
# # only expand when step is possible (thats the case atm)
# current_pos.append([g_val, newstep[0], newstep[1]])
# grid[newstep[0]][newstep[1]] = 1
# g_val += 1
# print grid
# check neighbors (expand the one with the smallest g-value)
# some don't need to be considered anymore as these are already checked... (create a new grid, same size as the maze
# to keep track of the checked positions! --> NO, just put ones where there were zeros!)
# remove the nodes that have no un-checked neighbors
# recurse the loop
# print current_pos
return path
p = search(grid, init, goal, cost)
print p |
e5bcc6f5ed4e18a6fddf1b38823254f5fd600c01 | davidlegorreta/100-days-of-Code | /Python/Day002-100.py | 711 | 4.125 | 4 | # Tips calculator.input
# Welcome line:
print ("Welcome to the tip calculator: \n")
#Ask for the first total.
total_paid = input ("What's the total of the bill?: \n")
#Ask for the people to split the total:
people_split = input ("How many people to split?: \n")
#Ask for the percentage tip.
tip_percentage = input ("What percentage would you like to give? 10, 12 or 15?: \n")
#FInal line:
new_total_paid = float(total_paid)
new_people_split = float(people_split)
new_tip_percentage = float(tip_percentage)
total_1 = new_total_paid / 100
total_2 = total_1 * new_tip_percentage
total_3 = (total_2 + new_total_paid) / new_people_split
total_str = str(total_3)
print ("Each person shoud pay: $ " + total_str) |
8210f06c882ef65b292a52b23803a25563568fa1 | virajvchavan/Data-Mining | /tweight/tweight.py | 977 | 3.78125 | 4 | #2014BIT026
#Calculates t-weight and d-weight for m products sold in n countries
m = int(input("Enter number of Products:"))
n = int(input("Enter number of Countries:"))
data = [[None] * m for i in range(n)]
print("Enter data:")
for i in range(n):
for j in range(m):
data[i][j] = int(input("Sales of Product " + str(j) + " in Country " + str(i) + ": "))
rows_sum = [0]*n
cols_sum = [0]*m
for i in range(n):
for j in range(m):
rows_sum[i] += data[i][j]
for i in range(m):
for j in range(n):
cols_sum[i] += data[j][i]
print("Row sum: " + str(rows_sum))
print("Cols sum: " + str(cols_sum))
print("....................................................")
for i in range(m):
print("For Product " + str(i) + ": ")
for j in range(n):
print("\tIn Country " + str(j) + ": ")
print("\t\tt-weight: " + str(data[i][j]/rows_sum[i]))
print("\t\td-weight: " + str(data[i][j]/cols_sum[j]))
print("\n")
print("....................................................")
|
74e95b5c06e8a3048402cabb504d8873441a0144 | aroranubhav/DailyBit | /TwoSum.py | 918 | 4.0625 | 4 | """
Given an array of integers nums and an integer target, return indices of the
two numbers such that they add up to target.
You may assume that each input would have exactly one solution,
and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
"""
class Solution:
def twoSum(self, nums: list[int], target: int) -> list[int]:
map = {}
for idx, num in enumerate(nums):
diff = target - num
if diff in map:
return [map[diff], idx]
map[num] = idx
return []
"""
Complexity : Time : O(n) | Space : O(n)
"""
|
1e8b1308f7017a6d51d99c7c1b186b67da778f2d | Anayatc/Advanced_User_Input | /Skeleton/ex48/lexicon.py | 792 | 4.03125 | 4 | directions = ('north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back')
verbs = ('go', 'stop', 'kill', 'eat', 'open')
stop_words = ('the', 'in', 'of', 'from', 'at', 'it')
nouns = ('door', 'bear', 'princess', 'cabinet')
def get_tuple(word):
lower_case = word.lower()
if lower_case in directions:
return 'direction', lower_case
elif lower_case in verbs:
return 'verb', lower_case
elif lower_case in stop_words:
return 'stop', lower_case
elif lower_case in nouns:
return 'noun', lower_case
elif lower_case.isdigit():
return 'number', int(lower_case)
else:
return 'error', word
def scan(sentence):
words = sentence.split()
return [get_tuple(word) for word in words]
print(scan("go north"))
|
f3ae90ad6d07816f42180e60b460168acb9d14a2 | vivek-gour/Python-Design-Patterns | /Patterns/Structural/adapter.py | 1,229 | 3.6875 | 4 | class Volt:
def __init__(self, volt):
self.volt = volt
def get_volt(self):
return self.volt
def set_volt(self, volt):
self.volt = volt
class Socket:
def get_volt(self):
return Volt(120)
class SocketClassAdapterImpl(Socket):
def get_120volt(self):
return self.get_volt()
def get_12volt(self):
v = self.get_volt()
return self.convert_volt(v, 10)
def get_3volt(self):
v = self.get_volt()
return self.convert_volt(v, 40)
def convert_volt(self, v, i):
return Volt(v.get_volt() / i)
def get_volt(sock_adapter, i):
if i == 3:
return sock_adapter.get_3volt()
elif i == 12:
return sock_adapter.get_12volt()
elif i == 120:
return sock_adapter.get_120volt()
return sock_adapter.get_120volt()
if __name__ == '__main__':
sock_adapter = SocketClassAdapterImpl()
v3 = get_volt(sock_adapter, 3)
v12 = get_volt(sock_adapter, 12)
v120 = get_volt(sock_adapter, 120)
print("v3 volts using Class Adapter=" + str(v3.get_volt()))
print("v12 volts using Class Adapter=" + str(v12.get_volt()))
print("v120 volts using Class Adapter=" + str(v120.get_volt()))
|
f2dac76042352499a69f2e5c6ddab4255dc6bbbb | DanteLentsoe/cryptographic_messages | /main.py | 901 | 4 | 4 | def Encrpty(sentence):
result = []
# Encrypting Message
for letter in sentence:
crpted_letters = ord(letter) * 20
result.append(crpted_letters)
print("Encrypted Message ")
for value in result:
print(value, end="")
print(" ", end="")
# Decrypting Message Function
Decrpt(result)
def Decrpt(result):
numbers_to_letter = []
result_decrypted = []
# Decrypting Message
for letter in result:
words = int((letter))//20
numbers_to_letter.append(words)
print("'\n'")
print("Decrypted Message ")
for value in numbers_to_letter:
word_convert = chr(value)
print(word_convert, end=" ")
print(" ", end="")
#resolvedWords = chr(result)
def Main():
userWords = input("Enter sentence to be encrpted ")
Encrpty(userWords)
if __name__ == "__main__":
Main()
|
11b06dc677402323bd87e9808452542008178286 | ProtossLuigi/studia | /python/lab4/zad4.py | 550 | 3.515625 | 4 | class Overload:
funcs = {}
def __call__(self, name, *args):
try:
for func in self.funcs[name]:
try:
return func(*args)
except TypeError:
pass
except KeyError:
raise NameError
def overload(func):
name = func.__name__
ov = Overload()
if ov.funcs.get(name, False):
ov.funcs[name].append(func)
else:
ov.funcs[name] = [func]
def wrapper(*args):
return ov(name, *args)
return wrapper
|
43f16309951e53030f466b4880881c77a888da4c | tnakaicode/jburkardt-python | /i4lib/i4_bit_reverse.py | 2,594 | 4.1875 | 4 | #! /usr/bin/env python
#
def i4_bit_reverse ( i, n ):
#*****************************************************************************80
#
## I4_BIT_REVERSE reverses the bits in an I4.
#
# Discussion:
#
# An I4 is an integer ( kind = 4 ) value.
#
# Example:
#
# I N 2^N I4_BIT_REVERSE ( I, N )
# ---- -------- -----------------------
# 0 0 1 0
# 1 0 1 1
#
# 0 3 8 0
# 1 3 8 4
# 2 3 8 2
# 3 3 8 6
# 4 3 8 1
# 5 3 8 5
# 6 3 8 3
# 7 3 8 7
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 18 March 2008
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer I, the integer to be bit reversed.
# I should be nonnegative. Normally I < 2^N.
#
# Input, integer N, indicates the number of bits to
# be reverse (N+1) or the base with respect to which the integer is to
# be reversed (2^N). N should be nonnegative.
#
# Output, integer VALUE, the bit reversed value.
#
if ( i < 0 ):
value = -1
elif ( n < 0 ):
value = -1
else:
b = 2 ** n
j = ( i % b )
value = 0
while ( True ):
if ( b == 1 ):
value = value + j
j = 0
break
else:
if ( ( j % 2 ) == 1 ):
value = value + b // 2
j = j - 1
j = j // 2
b = b // 2
return value
def i4_bit_reverse_test ( ):
#*****************************************************************************80
#
## I4_BIT_REVERSE_TEST tests I4_BIT_REVERSE.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 27 September 2014
#
# Author:
#
# John Burkardt
#
import platform
from i4_uniform_ab import i4_uniform_ab
seed = 123456789
test_num = 10
print ( '' )
print ( 'I4_BIT_REVERSE_TEST' )
print ( ' Python version: %s' % ( platform.python_version ( ) ) )
print ( ' I4_BIT_REVERSE bit reverses I with respect to 2^J.' )
print ( '' )
print ( ' I J I4_BIT_REVERSE(I,J)' )
print ( '' )
for j in range ( 0, 5 ):
i_hi = 2 ** j
for i in range ( 0, i_hi ):
k = i4_bit_reverse ( i, j )
print ( ' %8d %8d %8d' % ( i, j, k ) )
#
# Terminate.
#
print ( '' )
print ( 'I4_BIT_REVERSE_TEST' )
print ( ' Normal end of execution.' )
return
if ( __name__ == '__main__' ):
from timestamp import timestamp
timestamp ( )
i4_bit_reverse_test ( )
timestamp ( )
|
59e17eafa9ae899a139ec3192888c39cdd6bdcec | AmanMuricken/comaprison-operator | /Comparision1.py | 345 | 4.0625 | 4 | print("I am a maximum or minimum bot")
x = int(input("enter the first number :"))
y = int(input("enter the second number :"))
if(x>y):
print (x,"is the biggest number")
print (y,"is the smallest number")
elif(x==y):
print ("both are equal")
else:
print (y,"is the biggest number")
print (x,"is the smallest number") |
820b5230f08b61749baece5be470e56cb3303c83 | cemf/curso-emvideo-python | /exercicios/ex033.py | 528 | 4.15625 | 4 | n1 = float(input('Digite o 1o numero :'))
n2 = float(input('Digite o segundo numero: '))
n3 = float(input('diGite o 3o nUmero : '))
numeros = [n1, n2, n3]
numeros.sort()
print('O maior desses 3 numeros é {} e o menor é {} '.format(numeros[2], numeros[0]))
'''Modo guanabara'''
menor = n1
if n2 < n3 and n2 < n1:
menor = n2
elif n3 < n2 and n3 < n1:
menor = n3
maior = n1
if n2 > n3 and n2 > n1:
maior = n2
elif n3 > n2 and n3 > n1:
maior = n3
print('O maior numero é {} e o menor é {}'.format(maior, menor))
|
081f081d08f42d66f3c62516d77892dcff1cbd48 | kldznkv/tms | /Lessons/Lesson 3/Task_3_2.py | 171 | 3.984375 | 4 | a = int(input('Введите ваш возраст: '))
if 0 < a < 18:
print('Coca Cola')
elif a >= 18 and a <=100:
print('Beer')
else:
print('Wrong input') |
1f31e4985a32028f6f56b3a55b9f98d7a6700ebf | jayashelan/python-workbook | /src/chapter09/alice.py | 341 | 3.9375 | 4 |
filename = "alice.txt"
try:
with open(filename,encoding='utf-8') as file_object:
content = file_object.read()
except FileNotFoundError:
print(f"Sorry,the file {filename} does not exist")
else:
# count approximately no of words
words = content.split()
num_words = len(words)
print(f" the {filename} has {num_words} words in it")
|
f9849e920983de18d422e8cf4f5caeb80869ef9a | alankrit03/HackerRank_Algorithms | /Caesar Cipher.py | 792 | 3.578125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
import string
# Complete the caesarCipher function below.
def caesarCipher(s, k):
lst=list(s)
n=len(s)
database_lower=string.ascii_lowercase
database_upper=string.ascii_uppercase
for i in range(n):
if lst[i].isalpha():
print(lst[i])
if lst[i].islower():
lst[i]=database_lower[(database_lower.index(lst[i])+k)%26]
else:
lst[i]=database_upper[(database_upper.index(lst[i])+k)%26]
return ''.join(lst)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
s = input()
k = int(input())
result = caesarCipher(s, k)
fptr.write(result + '\n')
fptr.close()
|
1359e74b4ff0b8a9997d5f73d890babd861ec4bf | AnkurDas-krypto/ineuron_assignment3 | /assignment 3.py | 1,989 | 4.21875 | 4 | #!/usr/bin/env python
# coding: utf-8
# #### 1 Write a Python Program to implement your own myreduce() function which works exactly like Python's built-in function reduce()
# In[1]:
def myreduce(num):
lst=list(range(1,number+1))
summation=0
for i in lst:
summation +=i
return lst,summation
number=int(input("Please insert the number :"))
output, total=myreduce(number)
print("List of First n Natural numbers are:",output)
print("Sum of List elements are :", total)
# #### 2 Write a Python program to implement your own myfilter() function which works exactly like Python's built-in function filter()
# In[4]:
number=int(input("Please insert the number: "))
lst=list(range(1,number+1))
def myfilter(lst):
even_list=[]
odd_list=[]
for i in lst:
if(i%2==0):
even_list.append(i)
else:
odd_list.append(i)
return even_list, odd_list
#Function Execution
even_list, odd_list =myfilter(lst)
#Output
print("Output:")
print("List of numbers:",lst)
print("List of Even numbers are:",even_list)
print("List of Odd numbers are:", odd_list)
# #### ['x', 'xx', 'xxx', 'xxxx', 'y', 'yy', 'yyy', 'yyyy', 'z', 'zz', 'zzz', 'zzzz']
# In[6]:
lst =list('xyz')
l=[x*n for x in lst for n in range(1,5) ]
print(l)
# #### ['x', 'y', 'z', 'xx', 'yy', 'zz', 'xxx', 'yyy', 'zzz', 'xxxx', 'yyyy', 'zzzz']
# In[8]:
l=[x*n for n in range(1,5) for x in lst ]
print(l)
# #### [[2], [3], [4], [3], [4], [5], [4], [5], [6]]
# In[9]:
number=[2,3,4]
n=[[x+n] for x in number for n in range(0,3)]
print(n)
# #### [[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]]
#
# In[10]:
number=[2,3,4,5]
n=[[x+n for n in range(0,4)] for x in number ]
print(n)
# #### [(1, 1), (2, 1), (3, 1), (1, 2), (2, 2), (3, 2), (1, 3), (2, 3), (3, 3)]
# In[12]:
number=[1,2,3]
n= [(b,a) for a in number for b in number]
print(number_5)
# In[ ]:
|
680c7fcdb0bd86fa0c69e7a987d920f0bbe27f59 | soham0511/Python-Programs | /PYTHON PROGRAMS/other_dunder_methods.py | 411 | 3.90625 | 4 | class Number:
def __init__(self,num):
self.num=num
def __add__(self,num2):
print("Let's add")
return self.num+num2.num
def __mul__(self,num2):
print("Let's multiply")
return self.num*num2.num
def __str__(self):
return f"Decimal Number {self.num}"
def __len__(self):
return 1
n=Number(9)
print(n)
print(len(n)) |
a2aa9d0c011dfce7c97038aeaa9638d978667421 | imtiaz-rahi/Py-CheckiO | /O'Reilly/I Love Python!/creative-6.py | 546 | 3.703125 | 4 | from re import findall
from random import choice
def i_love_python():
"""
Why do I love Python?
"""
return ' '.join([ # It's a fusion of:
"i".upper(), # your growth as a programmer,
'Dreadful Flying Glove'[-4:], # it has All You Need ...
findall('P.*?n',"Monty Python's Flying Circus")[0] # ... if you know how to find,
+ choice('!!!!!!!!!!!!!!!')]) # and many other excellent things!
if __name__ == '__main__':
assert i_love_python() == "I love Python!"
|
2c47a80aa2770130561233505a60a1ccaaf0679b | royqh1979/programming_with_python | /Chap00Intro/3-4.运算性能.py | 353 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 30 16:20:02 2018
@author: Roy
"""
from datetime import datetime
def sum(n):
s = 0
for i in range(1, n + 1):
s = s + i
return s
begin = datetime.now()
t = 0
for i in range(1000):
t = t + sum(100000)
end = datetime.now()
elapsed = end - begin
print(elapsed)
print("t=" + str(t));
|
a80e733f631158a81c737f0158a187a3469b7df2 | LucasMassazza/Python | /CursoBPBA/Clase5/EjerciciosResueltos.py | 686 | 3.5 | 4 | import numpy as np
import pandas as pd
Nombre = ["nery Pumpido",
"Jose Schiuffino",
"Jose Schiuffino",
"Jose Luis Brown",
"Oscar Ruggieri"
"Segio Batista",
"Ricardo Giusti",
"Jorge Burruchaga",
"Hector Enrique",
"Julio Olartiche",
"Jorge Valdano",
"Diego maradona"]
Posicion = ["ARQ",
"DEF",
"DEF",
"DEF",
"MED",
"MED",
"MED",
"MED",
"MED",
"DEL",
"DEL"
]
numero = [18,9,5,19,2,14,7,12,16,11,10]
Equipo = {"Nombre": Nombre,"posicion": Posicion, "Numero": numero}
#print(Equipo)
DataFrameEquipo = pd.DataFrame(Equipo)
print(DataFrameEquipo)
|
2e61171dd9e2872ccf037b68b489605f3ea5a10e | Christine-97/Python-Code-MVP | /teamwinner.py | 5,678 | 3.53125 | 4 | #Code by Christine Polly Paul
import csv
def readcsv(file):
reader = csv.reader(open(file), delimiter=';')
recordbas = []
for row in reader:
recordbas.append(row)
return recordbas
recordb,recordh = [], []
filename = "basketball.csv"
recordb = readcsv(filename)
filename = "handball.csv"
recordh = readcsv(filename)
def game_record(data, fo):
recor = []
record = []
if fo == "PLAYER":
for index, row in enumerate(data):
recor.append(data[index][0:4])
test_tup2 = recor[index]
test_tup1 = ('player name', 'nickname', 'number', 'team name')
res = dict(zip(test_tup1, test_tup2))
record.append(res)
record[index]['points'] = 0
elif fo == "BASKETBALL":
for index, row in enumerate(data):
recor.append(data[index][4:])
test_tup2 = recor[index]
test_tup1 = ('position', 'scored points', 'rebounds', 'assists')
res = dict(zip(test_tup1, test_tup2))
record.append(res)
record[index]['game'] = 'basketball'
elif fo == "HANDBALL":
for i, r in enumerate(data):
recor.append(data[i][4:])
test_tup2 = recor[i]
test_tup1 = ('position', 'goals made', 'goals received')
res = dict(zip(test_tup1, test_tup2))
record.append(res)
record[i]['game'] = 'handball'
return record
basketballrecord = []
handballrecord = []
player = []
h = "HANDBALL"
handballrecord = game_record(recordh, h)
b = "BASKETBALL"
basketballrecord = game_record(recordb, b)
p = "PLAYER"
player = game_record(recordb, p)
def displayrecord(data):
for index, row in enumerate(data):
print(data[index])
def team_winning(data):
ascore = 0
bscore = 0
for j, k in enumerate(data):
if str(data[j].get('game')) == 'handball':
if str(player[j].get('team name')) == 'TeamA':
ascore += int(data[j].get('goals made'))
if str(player[j].get('team name')) == 'TeamB':
bscore += int(data[j].get('goals made'))
if str(data[j].get('game')) == 'basketball':
if str(player[j].get('team name')) == 'TeamA':
ascore += int(data[j].get('scored points'))
if str(player[j].get('team name')) == 'TeamB':
bscore += int(data[j].get('scored points'))
if ascore > bscore:
w = "Team A"
else:
w = "Team B"
return w
def addpoints(team, data):
x , y = 0, 0
if team == 'Team A':
for x, y in enumerate(data):
if data[x].get('team name') == 'TeamA':
data[x].update({"points": int(data[x].get('points')) + 10})
if team == 'Team B':
for x, y in enumerate(data):
if data[x].get('team name') == 'TeamB':
data[x].update({"points": int(data[x].get('points')) + 10})
def cal_ratingpoints(data,bdata,hdata):
a = 0
for q, u in enumerate(data):
if hdata[q].get('position') == 'G' and hdata[q].get('game') == 'handball':
a = 50 + int(hdata[q].get('goals made'))*5 - int(hdata[q].get('goals received'))*2
data[q].update({"points": int(data[q].get('points')) + a})
a = 0
if hdata[q].get('position') == 'F'and hdata[q].get('game') == 'handball':
a = 20 + (int(hdata[q].get('goals made'))*1) - (int(hdata[q].get('goals received'))*1)
data[q].update({"points": (int(data[q].get('points')) + a)})
a = 0
if bdata[q].get('position') == 'G' and bdata[q].get('game') == 'basketball':
a = int(bdata[q].get('scored points'))*2 + int(bdata[q].get('rebounds'))*3 + int(bdata[q].get('assists'))*1
data[q].update({"points": int(data[q].get('points')) + a})
a = 0
if bdata[q].get('position') == 'F' and bdata[q].get('game') == 'basketball':
a = int(bdata[q].get('scored points')) * 2 + int(bdata[q].get('rebounds')) * 2 + int(bdata[q].get('assists')) *2
data[q].update({"points": int(data[q].get('points')) + a})
a = 0
if bdata[q].get('position') == 'C' and bdata[q].get('game') == 'basketball':
a = (int(bdata[q].get('scored points'))*2) + (int(bdata[q].get('rebounds'))*1) + (int(bdata[q].get('assists'))*3)
data[q].update({"points": int(data[q].get('points')) + a})
a = 0
cal_ratingpoints(player,basketballrecord,handballrecord)
winner = team_winning(handballrecord)
addpoints(winner, player)
winner = team_winning(basketballrecord)
addpoints(winner, player)
def player_winning():
a = 0
f = ''
for j, k in enumerate(player):
if a < int(player[j].get('points')):
a = int(player[j].get('points'))
f = str(player[j].get('player name'))
for s, v in enumerate(player):
if f == str(player[s].get('player name')):
print('The most valued player is:')
print(player[s])
print(basketballrecord[s])
print(handballrecord[s])
return a
mvp = player_winning()
# Output
# The most valued player is:
# {'player name': 'player3', 'nickname': 'nick3', 'number': '15', 'team name': 'TeamA', 'points': 72}
# {'position': 'C', 'scored points': '15', 'rebounds': '10', 'assists': '4', 'game': 'basketball'}
# {'position': 'F', 'goals made': '10', 'goals received': '20', 'game': 'handball'}
#
# Process finished with exit code 0
|
648d64ce99d1259b3be83d322f56eea46af8e5c4 | kylemingwong/pytest | /pytest/some-test.py | 192 | 3.734375 | 4 | class MyClass(object):
gender = 'Male'
def __init__(self,who):
self.name = who
def sayHi(self):
print 'Hello, '+self.name
me = MyClass('Tom')
me.sayHi()
|
416ac3c6f3e6563e1b42467fabf5b2acc7e694ff | ddaypunk/tw-backup | /Python/small apps/counter.py | 548 | 3.734375 | 4 | """
Character Counter
By: Andrew Delso
Function: For use with the QA - Data Mart Reporting -
Canned Reports - "DSC Data Sync - Number Filter"
Input: Copy and pasted string from Excel Reports
Output:
1. Count of total characters in the string
2. Count of total account numbers in the string
"""
string_entry = raw_input("Enter string: ")
#print out input string length of total characters
print "\nCharacters: " + str(len(string_entry))
# Print the len of the list of the split input string
print "\nAccounts: " + str(len(string_entry.split(','))) |
582ac6ced7de203267acd79fd430ba2c0127d809 | elsheikh21/regression-algorithms | /shapes-non-linear-functions.py | 1,584 | 3.71875 | 4 | import numpy as np
import matplotlib.pyplot as plt
# Linear
x = np.arange(-5.0, 5.0, 0.1)
# You can adjust the slope and intercept to verify the changes in the graph
y = 2*(x) + 3
y_noise = 2 * np.random.normal(size=x.size)
ydata = y + y_noise
plt.plot(x, ydata, 'bo')
plt.plot(x, y, 'r')
plt.ylabel('Dependent Variable')
plt.xlabel('Independent Variable')
plt.show()
# Cubic
x = np.arange(-5.0, 5.0, 0.1)
# You can adjust the slope and intercept to verify the changes in the graph
y = 1*(x**3) + 1*(x**2) + 1*x + 3
y_noise = 20 * np.random.normal(size=x.size)
ydata = y + y_noise
plt.plot(x, ydata, 'bo')
plt.plot(x, y, 'r')
plt.ylabel('Dependent Variable')
plt.xlabel('Independent Variable')
plt.show()
# Quadratic
x = np.arange(-5.0, 5.0, 0.1)
# You can adjust the slope and intercept to verify the changes in the graph
y = np.power(x, 2)
y_noise = 2 * np.random.normal(size=x.size)
ydata = y + y_noise
plt.plot(x, ydata, 'bo')
plt.plot(x, y, 'r')
plt.ylabel('Dependent Variable')
plt.xlabel('Independent Variable')
plt.show()
# Exponential
X = np.arange(-5.0, 5.0, 0.1)
# You can adjust the slope and intercept to verify the changes in the graph
Y = np.exp(X)
plt.plot(X, Y)
plt.ylabel('Dependent Variable')
plt.xlabel('Independent Variable')
plt.show()
# Logarithmic
X = np.arange(-5.0, 5.0, 0.1)
Y = np.log(X)
plt.plot(X, Y)
plt.ylabel('Dependent Variable')
plt.xlabel('Independent Variable')
plt.show()
# Sigmoidal
X = np.arange(-5.0, 5.0, 0.1)
Y = 1-4/(1+np.power(3, X-2))
plt.plot(X, Y)
plt.ylabel('Dependent Variable')
plt.xlabel('Independent Variable')
plt.show()
|
feb16d178c666ec9e28fbfef25fc14e5fde3b3c7 | calvia76/Python | /Alvia_Chrystian_Assignment6/test.py | 1,891 | 3.96875 | 4 | import math
while True:
n = int(input("Enter highest integer value, n, to evaluate prime numbers between 0 - n: "))
if(n<0):
print("Invalid Entry: Enter a positive integer")
continue
if(0 < n < 10):
print("Invalid Entry: Enter an integer greater than 10")
else:
break
sieve = []
for x in range(0,n+1):
sieve.append("P")
sieve[0]= "N"
sieve[1] = "N"
correction = 0
def prime_check(array, divisor):
counter = 0
correction = divisor+1
dividend = divisor+1
while counter != (n-correction)+1:
if(dividend % divisor == 0):
sieve[dividend] = "N"
dividend += 1
counter+=1
else:
dividend +=1
counter+=1
continue
def sqrt_check(array):
i = 121
while(i != n+1):
if(math.sqrt(i).is_integer()):
sieve[i] = "N"
i+=1
else:
i+=1
continue
if(n >=121):
prime_check(sieve,2)
prime_check(sieve,3)
prime_check(sieve,4)
prime_check(sieve,5)
prime_check(sieve,6)
prime_check(sieve,7)
prime_check(sieve,11)
prime_check(sieve,13)
prime_check(sieve,19)
sqrt_check(sieve)
elif(n >= 42):
prime_check(sieve,2)
prime_check(sieve,3)
prime_check(sieve,4)
prime_check(sieve,5)
prime_check(sieve,6)
prime_check(sieve,7)
elif(n >= 25):
prime_check(sieve,2)
prime_check(sieve,3)
prime_check(sieve,5)
elif(n < 25):
prime_check(sieve,2)
prime_check(sieve,3)
primes = []
i = 0
while i != (n+1):
if(sieve[i]=="P"):
primes.append(i)
i+=1
else:
i+=1
continue
j = 0
n = 0
for x in primes:
j+=1
print('{:>3}'.format(primes[n]), end =" ")
n+=1
if(j==10):
j=0
print("")
continue
|
91da5f768551a4c40fac274450216299ced1ee62 | netholi/python-tra | /Python Script/point.py | 964 | 4.25 | 4 | #class point
import math
class point():
"""docstring for point
Represents a point in two-diamensional geometric coordinates
"""
def __init__(self,x=0,y=0): #Initializer function with default value
''' Initialize the position of a new point. The x and y
coordinates can be specified. If they are not, the point
defaults to the origin'''
self.move(x,y)
def move(self,x,y):
'Move the point to a new location in two-dimendional space'
self.x=x
self.y=y
def reset(self):
"Reset the point back to the geometric origin: 0,0"
self.move(0,0)
def calculate_distance(self,other_point):
''' Calculate the distance from this point to a second point
passed as a parameter
This function uses the Pythagorean Theorem to calculate_distance
the distance between the two points. The distance is returned as
as float. '''
return math.sqrt((self.x-other_point.x)**2+
(self.y-other_point.y)**2)
|
04339e4b140813faf41dc43fe76738bfb944065d | gitranin/downloads | /h9.py | 213 | 3.71875 | 4 | username='ranin'
password=12345678
uname=str(input("enter username"))
pw=int(input("enter password"))
if uname==username and pw==password :
print("welcome",uname,pw)
else:
print("you need to register") |
417d2e9090fc8523db250b02265ad98c4b2c79f7 | alina-poliatska/codereview | /poliatskaao/first/task3.py | 211 | 3.671875 | 4 | """
Вивести загальну кількість букв в усіх словах рядку
"""
text = ('ghb djnfh hj')
words = text.split()
res = 0
for word in words:
res += len(word)
print(res) |
d4cfa73a771e8b14bba0625bf66c598faa10d2ee | rutuja0897/OPPsPrinciples | /code4.py | 67 | 3.59375 | 4 | fruits="7"
fruits=fruits+"0"
eggs=int(fruits)+3
print(float(eggs))
|
7efb4e064ff695278c3348400b369bb6a5a5456a | Vaibhav3007/Python_Class | /Class-9.py | 1,689 | 4.28125 | 4 | #Inheritance
#Modifying inherited class
class Employee:
raise_amount = 1.04 #Class variable
no_of_emp = 0 #another class variable
def __init__(self,firstname,lastname,sal): #values of init method #Regular Method
self.firstname = firstname #It is same as doing emp1.firstname = "Vaibhav"
self.lastname = lastname #can also be self.lname = lastname
self.sal = sal
self.email = firstname+lastname+"@gmail.com"
Employee.no_of_emp += 1 #every time a new emp is added, counter increasses
def fullname(self): #a method for printing full name #Regular Method
return "{} {}".format(self.firstname,self.lastname)
def apply_raise(self): #Regular Method
self.sal = int(self.sal * self.raise_amount) #Either we can give class name or self
class Developer(Employee): #Inherited class. Copies all properties(attributes & methods) of Employee class
raise_amount = 1.10
emp1 = Employee("Vaibhav","Rai",5000) #this is instance for Employee Class
dev1 = Developer("Test","User",6000)#this is an instance for Developer class. But since it is empty, so python will look for its inherited class i.e. Employee
print("emp1",emp1.email,emp1.sal)
print("Sal",emp1.sal)
print("Raise",Employee.raise_amount) #Inherited form Employee class
emp1.apply_raise()
print("Raised Sal",emp1.sal)
print()
print("dev1",dev1.email,dev1.sal)
print("Sal",dev1.sal)
print("Raise",Developer.raise_amount) #Inherited from Employee class
dev1.apply_raise()
print("Raised Sal",dev1.sal)
print()
print("Raise amount for Employee class-",Employee.raise_amount)
print("Raise amount for Developer class-",Developer.raise_amount)
|
0ce534bd33d1ed4289102f9d60004367f52f793e | fjpalacios/exercises | /Python/isprime.py | 1,607 | 4.40625 | 4 | # A simple code to practice finding out if a number is prime or not
# If it is not a prime number, its prime factorization is printed
def main():
number = int_greather_than_0(
"Enter the number that you want to know if is a prime number: ")
is_prime_number = is_prime(number)
if is_prime_number:
print("{} is a prime number".format(number))
else:
print("{} is not a prime number ({})"
.format(number, prime_factors(number)))
continue_program()
def int_greather_than_0(message):
while True:
try:
_int_greather_than_0 = int(input(message))
if _int_greather_than_0 > 0:
break
except ValueError:
print("Please, enter a positive integer greater than 0")
return _int_greather_than_0
def is_prime(number):
for i in range(2, number):
if number % i == 0:
return False
return True
def prime_factors(number):
_prime_factors = []
for i in range(2, number):
while number % i == 0:
number = number / i
_prime_factors.append(i)
return '*'.join(map(str, _prime_factors))
def continue_program():
system_exit = input("Do you want to continue with the program? [Y/n] ")
system_exit = system_exit.lower()
if system_exit == "y" or system_exit == "":
main()
elif system_exit == "n":
raise SystemExit
else:
print("You entered {}, but it is a wrong command. Good bye!"
. format(system_exit))
raise SystemExit
if __name__ == "__main__":
main()
|
4fda1d7927c44389da9e75a875405646c74a68eb | SaraPena/statistics-exercises | /distributions_mini_exercise.py | 537 | 3.703125 | 4 | # Distributions Mini Exercise
# Use scipy statistical distribution to answer the questions below:
from scipy import stats
import numpy as np
die_distribution = stats.randint(1,7)
# What is the probility of rolling a 1?
die_distribution.pmf(1)
# There's a 1 in 2 chance that I'll roll higher than what number?
die_distribution.sf(1/2)
# What is the probability of rolling less than or equal to 2?
die_distribution.cdf(2)
# There is a 5 in 6 chance that my roll will be less than or equal to what number?
die_distribution.ppf
|
8ba235c6267779cda210130c97d23777ebb74fb1 | Built00/Leetcode | /Split_Array_into_Consecutive_Subsequeneces.py | 2,084 | 4.125 | 4 | # -*- encoding:utf-8 -*-
# __author__=='Gan'
# You are given an integer array sorted in ascending order (may contain duplicates),
# you need to split them into several subsequences, where each subsequences consist of at least 3 consecutive integers.
# Return whether you can make such a split.
# Example 1:
# Input: [1,2,3,3,4,5]
# Output: True
# Explanation:
# You can split them into two consecutive subsequences :
# 1, 2, 3
# 3, 4, 5
# Example 2:
# Input: [1,2,3,3,4,4,5,5]
# Output: True
# Explanation:
# You can split them into two consecutive subsequences :
# 1, 2, 3, 4, 5
# 3, 4, 5
# Example 3:
# Input: [1,2,3,4,4,5]
# Output: False
# Note:
# The length of the input is in range of [1, 10000]
# We iterate through the array once to get the frequency of all the elements in the array
# We iterate through the array once more and for each element we either see if it can be appended to a previously
# constructed consecutive sequence or if it can be the start of a new consecutive sequence. If neither are true,
# then we return false.
# 180 / 180 test cases passed.
# Status: Accepted
# Runtime: 279 ms
# Your runtime beats 38.06 % of python submissions.
import collections
class Solution(object):
def isPossible(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
freq_map = collections.Counter(nums)
append_fre = {}
for num in nums:
if freq_map.get(num, 0) == 0:
continue
elif append_fre.get(num, 0) > 0:
append_fre[num] -= 1
append_fre[num + 1] = append_fre.get(num + 1, 0) + 1
elif freq_map.get(num + 1, 0) > 0 and freq_map.get(num + 2, 0) > 0:
freq_map[num + 1] -= 1
freq_map[num + 2] -= 1
append_fre[num + 3] = append_fre.get(num + 3, 0) + 1
else:
return False
freq_map[num] -= 1
return True
if __name__ == '__main__':
print(Solution().isPossible([1,2,3,3,4,4,5,5]))
print(Solution().isPossible([1,2,3,3,4,4,5])) |
e39799d52c88f96cc10743f2dbd02aa5e2ea15db | tharin-tim01/Exercise | /Exercise8.py | 1,496 | 4.0625 | 4 | ID = input("ID: ")
Password = input("Password: ")
product_list = []
while True:
if ID == "admin" and Password == "1234":
print("Hello Customer, Welcome to my shop")
print("----Item list----")
print("1.egg 10 baht per unit")
print("2.Chicken breast 299 baht per unit")
print("3.pork 399 baht per unit")
print("4.meat 200 baht per unit")
print("5.calculate total")
Product = int(input("Please choose the item you want by type product number: "))
if Product == 1:
Quantity = int(input("How much do you want: "))
price = 10
total = price * Quantity
product_list.append(total)
elif Product == 2:
Quantity = int(input("How much do you want: "))
price = 299
total = price * Quantity
product_list.append(total)
elif Product == 3:
Quantity = int(input("How much do you want: "))
price = 399
total = price * Quantity
product_list.append(total)
elif Product == 4:
Quantity = int(input("How much do you want: "))
price = 200
total = price * Quantity
product_list.append(total)
elif Product == 5:
total = 0
for x in product_list:
total += x
print ("your total:",total)
break
else:
print ("Wrong username and password")
|
c61a38f84a1c072c72bad6b95c757b907ff8d709 | gandhijs/Antimicrobial-Resistance-Gene-Detection | /consolidate_metrics.py | 7,865 | 3.609375 | 4 | import os
import csv
import sys
class consolidate_metrics(object):
def __init__(self, mash_file, read_metrics_file, quast_file):
self.sample_dict = {}
self.mash_file = mash_file
self.read_metrics_file = read_metrics_file
self.quast_file = quast_file
def parse_mash(self):
"""parse_mash reads the top hits from the mash output and stores the information within a dict. The sample file names are is the key and the value is a list containing the genus and serotype information"""
with open(self.mash_file, newline='') as mash_file:
mash_reader = csv.reader(mash_file, delimiter = ',')
# skips the first row, which is the header of the file
next(mash_reader)
# parses through the csv file
for row in mash_reader:
# split the path of the sample file by '/'
sample_path = (row[1].split('/'))
# sample name
sample, ext = (sample_path[-1].split('.'))
# append the sample to the dict as the key
self.sample_dict[sample] = []
# mash id (i.e. organism info, genus, species name)
organism_info_list = row[0]
# split the genus and species
genus_species_list = organism_info_list.split('-')
# split again by the '.'
final_genus_species_list = genus_species_list[7].split('.')
# genus information
organism = (final_genus_species_list[0].split('_'))
# if the list size is greater than two, pop off the last element of the list and join the genus and species word by '_'
if len(organism) > 2:
organism.pop()
genus_species = '_'.join(organism)
# if the list size is less than two, join the list and append it to the dict
else:
genus_species = '_'.join(organism)
# append the genus and species for the sample to a list
self.sample_dict[sample].append(genus_species)
def parse_read_metrics(self):
"""parses the master read metrics file to calculate the coverage of read1 and read2."""
# forward sample dict
forward_sample_dict = {}
# reverse sample dict
reverse_sample_dict = {}
# open to read the master read metrics file
with open(self.read_metrics_file, newline='') as read_metrics_file:
read_metrics = csv.reader(read_metrics_file, delimiter = ',')
# skips the first row, which is the header of the file
next(read_metrics)
# parses thorugh the read metrics file
for row in read_metrics:
# sample ID
sample, ext = (((row[0].split('/'))[-1]).split('.'))
# avgReadLength value
avg_read_len = float(row[1])
# totalBases value
total_bases = int(row[2])
# avgQuality vlaue
average_quality = float(row[5])
# number of reads value
num_reads = int(row[6])
# coverage vlaue
estimated_coverage = float(row[8])
# forward file stored based on the average quality, average read length, total bases, and number of reads
if "_1" in sample:
sample, num = sample.split('_')
self.sample_dict[sample].append(average_quality)
self.sample_dict[sample].append(avg_read_len)
self.sample_dict[sample].append(total_bases)
self.sample_dict[sample].append(num_reads)
estimated_coverage_read_1 = estimated_coverage
# reverse file stored based on the average quality, average read length, total bases, and number of reads
elif "_2" in sample:
sample, num = sample.split('_')
self.sample_dict[sample].append(average_quality)
self.sample_dict[sample].append(avg_read_len)
self.sample_dict[sample].append(total_bases)
self.sample_dict[sample].append(num_reads)
# if there is an estimated coverage (i.e. for the forward sample)
if estimated_coverage_read_1:
# sum the coverage for the forward and reverse and append it to the list
total_coverage = estimated_coverage_read_1+estimated_coverage
total_coverage = round(total_coverage, 2)
self.sample_dict[sample].append(total_coverage)
else:
# append the coverage
self.sample_dict[sample].append(estimated_coverage)
def parse_quast(self):
"""parses master quast output csv file, which has the sample, N50, N50 value for the sample"""
with open(self.quast_file, newline='') as quast_file:
# initialize reader object, which will read the csv file
quast = csv.reader(quast_file, delimiter = ',')
# parse the master csv file
for row in quast:
# first item in the list is the sample ID
sample = row[0]
# third itme in the list is the N50 vlaue
N50_value = row[2]
# N50 value is stored if the sample ID is in the dict
if sample in self.sample_dict:
self.sample_dict[sample].append(N50_value)
# if the sample ID is not within the dict, create a new key and store the N50 value
else:
self.sample_dict[sample] = []
self.sample_dict[sample].append(N50_value)
def write_report(self):
"""writes out the information harvested from mash output, read metrics output, and quast output. The file output will be in the following format:
Sample, Predicted Genus, Predicted Species, R1_Q, R1_AvgReadLength, R1_TotalBases, R1_NumReads, R2_Q, R2_AvgReadLength, R2_TotalBases, R2_NumReads, Est_Cvg, N50
"""
with(open('AMR_COMP_Report.csv', 'a')) as comp_report:
comp_report.write("Sample,Predicted_Species,R1_Q,R1_AvgReadLength,R1_TotalBases,R1_NumReads,R2_Q,R2_AvgReadLength,R2_TotalBases,R2_NumReads,Est_Cvg,N50")
comp_report.write('\n')
for sample, sample_info in self.sample_dict.items():
# write the sample name
comp_report.write(sample)
# comma after the sample info
comp_report.write(',')
# stringify the list of sample information
sample_info = [str(info_val) for info_val in sample_info]
# join the sample information by ',' and write the info out to the file
comp_report.write(','.join(sample_info))
# write a new line for the next sample information
comp_report.write('\n')
def main():
try:
# first input will be the master mash input file
mash_file = os.path.basename(sys.argv[1])
# second input will be the master read metrics file
read_metrics_file = os.path.basename(sys.argv[2])
# third input will be the master quast file
quast_file = os.path.basename(sys.argv[3])
except:
quit("Please first input the Mash output file, Read Metrics output file, and Quast output file!")
test = consolidate_metrics(mash_file, read_metrics_file, quast_file)
test.parse_mash()
test.parse_read_metrics()
test.parse_quast()
test.write_report()
if __name__ == "__main__":
main()
|
5bc8018c8da1f90ca981c2674d3f709b223ca68e | vadimsavenkov/Miscelaneous | /practice0506.py | 1,202 | 4.09375 | 4 | class Dog:
def __init__(self)
pass
def bark(self)
pass
Whenever you instantiate an object, constructor is always called by default
'''
mylist=[2,2.3,[],""]
for i in range(5): #lower bound=0(included): upper bound=5(ecluded)
print("HI")
for i in range(-1,5): #lower bound=0(included): upper bound=5(ecluded)
print(i)
for i in range(-1,5,2): #lower bound=0(included): upper bound=5(ecluded)
print("HI") #it runs 3 times
for element in myList: #lower bound=0(included): upper bound=5(ecluded)
print(element)
'''
mylist=["Jack", "Jill", "John", "Jill"]
count=0
for element in myList: #traversing in a list && searching a list
if "jill"==element
print(element)
count+=1
print("The occurences of jill in the list was:", count)
#searches in list is pathetic
#dictionary1={key:value}
'''
sampleData={"Kanishqk":"TA", "Henry":"Student", "Online TA":"TA"}
#phonebook, banking detail, login crudentials
print(sampleData[Kanishqk])
for key,value in sampleData.items():
print(key,value)
myList=["Hi", "Hello", "Howdy"]
for index, value in enumerate(myList):
print(index,value)
|
34ec7bbfb1b6360846c5e2cdc6dba32355ad5688 | garima010303/python | /games/guess_the_number.py | 571 | 3.953125 | 4 | import random
rn = random.randint(1,100)
print(rn)
user_number = None
guesses = 0
while(user_number != rn):
user_number = int(input("Guess the number: "))
if(user_number==rn):
print("Congratulations! You guessed it right!")
elif(user_number < rn):
print("Bad luck! please try a higher number")
else:
print("Bad luck! please try a lower number")
guesses+= 1
print(f"You guessed the correct number in {guesses} guesses")
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!GAME ENDS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
|
5c0dcea8e8a1857513093623af109ab14467dec1 | AdamsGeeky/basics | /01 - Basics/34-error-handling-named-excepts.py | 1,371 | 4.5 | 4 | # HEAD
# Error Handling - using Named Exceptions in excepts
# DESCRIPTION
# Describe using of Error Handling of code in python
#
# RESOURCES
#
# 'try' will run always
# 'try' will execute all statements till it encounters an error
# once an error is encountered, it executes
# related except block (named or unnamed)
# 'except' blocks can be named
# Named Except or Unnamed Except are optional but
# one except with try block is compulsory
# There can be only one unnamed except (and in the end)
# try...except Exception...except can be used to trigger
def obj(divideBy):
return 42 / divideBy
try:
print(obj(2))
print(obj(12))
print(obj(0))
print(obj(1))
except ZeroDivisionError:
# Catch specific error
print('Error: Invalid argument.')
try:
print(obj(2))
print(obj(12))
print(obj(0))
print(obj(1))
except:
# Catch specific error
print('Error: Invalid argument.')
try:
print(obj(2))
print(obj(12))
print(obj(0))
print(obj(1))
except ZeroDivisionError:
# Catch specific error
print('Error: Invalid argument.')
except:
print('Except Triggered.')
# # Following will fail with an error
# # Either a named except has to be there or
# # an unnamed except has to be there
# try:
# print(obj(2))
# print(obj(12))
# print(obj(0))
# print(obj(1))
|
3aeb1db0c8279001c3a7db751353a07c6fab65f2 | ghosttam/ANN-Project | /main.py | 4,466 | 3.890625 | 4 | # Description: This program detects / predicts if a person has diabetes (1) or not (0)
import pandas as pd
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense
from sklearn import preprocessing
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
import matplotlib.pyplot as plt
plt.style.use('classic')
# IMPORT DATA #
data = pd.read_csv('diabetes.csv')
print(data.head(7))
# PREPROCESSING THE DATA #
# show the shape (number of rows and columns)
print("Number of Rows and Columns:")
print(data.shape)
# checking for duplicates and removing them
data.drop_duplicates(inplace=True)
# Show the shape to see if any rows were dropped
print(data.shape)
# Show the number of missing (NAN, NaN, na) data for each column
print(data.isnull().sum())
# convert the data into an array
dataset = data.values
print(dataset)
# Slip the data into an independent / feature data set x and a dependent / target data set y.
# Get all of the rows from the first eight columns of the dataset
X = dataset[:, 0:8]
# Get all of the rows from the last column
y = dataset[:, 8]
# Process the feature data set to contain values between 0 and 1 inclusive, by using the min-max scalar method,
# and print the values.
min_max_scaler = preprocessing.MinMaxScaler()
X_scale = min_max_scaler.fit_transform(X)
print(X_scale)
# slit the training and testing data randomly into 70% training and 30% testing
X_train, X_test, y_train, y_test = train_test_split(X_scale, y, test_size=0.3, random_state=4)
print("Training Data 70% :", X_train.shape)
print("Testing Data 30% : ", X_test.shape)
# Building ANN model
# - First layer will have 12 neurons and use the ReLu activation function
# - Second layer will have 15 neurons and use the ReLu activation function
# - Third layer and final layer will use 1 neuron and the sigmoid activation function.
model = Sequential([
Dense(12, activation='relu', input_shape=(8,)),
Dense(15, activation='relu'),
Dense(1, activation='sigmoid')
])
# Compile the model and give it the ‘binary_crossentropy’ loss function (Used for binary
# classification) to measure how well the model did on training, and then give it the
# Stochastic Gradient Descent ‘sgd’ optimizer to improve upon the loss. Also I want to measure
# the accuracy of the model so add ‘accuracy’ to the metrics.
model.compile(optimizer='sgd',
loss='binary_crossentropy',
metrics=['accuracy'])
# Train the model by using the fit method on the training data, and train it in batch sizes of 57, with 1000 epochs.
# Give the model validation data to see how well the model is performing by splitting the training data into 20%
# validation.
# Batch - Total number of training examples present in a single batch
# Epoch - The number of iterations when an ENTIRE dataset is passed forward and backward through the neural network only ONCE.
# Fit - Another word for train
hist = model.fit(X_train, y_train,
batch_size=57, epochs=1000, validation_split=0.3)
# visualize the training loss and the validation loss to see if the model is overfitting
plt.plot(hist.history['loss'])
plt.plot(hist.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper right')
plt.show()
# visualize the training accuracy and the validation accuracy to see if the model is overfitting
plt.plot(hist.history['accuracy'])
plt.plot(hist.history['val_accuracy'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='lower right')
plt.show()
# Make a prediction & print the actual values
prediction = model.predict(X_test)
prediction = [1 if y >= 0.5 else 0 for y in prediction]
# Threshold
print(prediction)
print(y_test)
# evaluate the model on the training data set
pred = model.predict(X_train)
pred = [1 if y >= 0.5 else 0 for y in pred] # Threshold
print(classification_report(y_train, pred))
print('Confusion Matrix: \n', confusion_matrix(y_train, pred))
print()
print('Accuracy: ', accuracy_score(y_train, pred))
print()
# evaluate the model on the testing data set
pred = model.predict(X_test)
pred = [1 if y >= 0.5 else 0 for y in pred] # Threshold
print(classification_report(y_test, pred))
print('Confusion Matrix: \n', confusion_matrix(y_test, pred))
print()
print('Accuracy: ', accuracy_score(y_test, pred))
print() |
fdc365f0b7076e214ddc2225d013f16a03ab46e6 | yama1102/python520 | /Aula2/excecoes.py | 792 | 4.28125 | 4 | #!/usr/bin/python3
######
## Tratando Exceçoes
######
# try: # tente
# print('Divisão de dois valores')
# numero1 = int(input('Digite um número a ser dividido: '))
# numero2 = int(input('Digite outro número a ser dividido: '))
# print(numero1 / numero2)
# except ValueError as e: # Exceção
# print('Insira Somente Números', e)
# except ZeroDivisionError as e:
# print('Impossível dividir por 0', e)
# except Exception as e:
# print('Erro na execução do programa', e)
# finally:
# print('Saindo do Script')
# nulo = None
###########
### Lançando Exceções
###########
# try:
opcao = input('Não digite 5: ')
if opcao == '5':
raise ValueError('Eu falei para vocẽ não digitar 5')
# except ValueError as e:
# print('Deu erro: ', e)
|
472c5c4dabc939cbe9a597cdf621cea6f15df256 | koeberlc/proj631-huffman-tree | /main_program/node.py | 2,842 | 3.84375 | 4 | class Node:
"""
A node have a label, up to 2 children, a frequency and a value
A leaf is related to one character
"""
def __init__(self, label, frequence, left_child=None, right_child=None):
self.label = label
self.frequence = frequence
self.left_child = left_child
self.right_child = right_child
self.value = None
def get_left_child(self):
return self.left_child
def get_right_child(self):
return self.right_child
def get_label(self):
return self.label
def get_frequence(self):
return self.frequence
def get_value(self):
return self.value
def get_list_prefixe(self, node="Error"):
"""
Read the tree (related to a root) in a prefix order
Attrs:
node (Node): current node
Returns:
str: list of nodes in a tree in a prefix order
"""
if(node == "Error"):
node = self
res = ""
if (node not is None):
res = node.get_label() +
node.get_list_prefixe(node.get_left_child()) +
node.get_list_prefixe(node.get_right_child())
return res
def is_leaf(self):
"""
Detect if the node is a leaf
Returns:
boolean: if the node is a leaf
"""
return (self.get_right_child() is None) and
(self.get_right_child() is None)
def get_all_node(self):
"""
Return the list of all nodes under the current node
Returns:
list: list of node
"""
list_node = [self]
if(not self.is_leaf()):
if(not self.get_right_child() is None):
list_node += self.get_right_child().get_all_node()
list_node += self.get_left_child().get_all_node()
return list_node
def get_all_leaf(self):
"""
Return the list of all leaf under the current node
Returns:
list: list of node (only leaf)
"""
list_leaf = []
list_node = self.get_all_node()
for n in list_node:
if(n.is_leaf()):
list_leaf.append(n)
return list_leaf
def get_path(self, node):
"""
Get the path from the current node to the node passed as a parameter
Attrs:
node (Node): Searched node
Returns:
list: list related to the path from current node to searched node
"""
path = []
list_node = self.get_all_node()
while self != node:
for n in list_node:
if(n.get_left_child() == node or n.get_right_child() == node):
path.append(node)
node = n
path.append(self)
path.reverse()
return path
|
7aca17cf635664c869886035a90bc11914bc8fe4 | revannth/python_algorithms | /classic_recursions/Alternate_power.py | 354 | 4.21875 | 4 | #Alternate_power.py
#Uses the logic that x^n of a number is nothing but x*(x^(n//2))^2 for odd and (x^(n//2))^2 for even
#O(n) time complexity
def altpow(x,n):
if n==0:
return 1
else :
partial = altpow(x,n//2)
result = partial*partial
if n%2==0:
return result
else:
return x*result
if __name__ == '__main__':
print altpow(2,3)
|
39b74148db43e03b3f0b6033eb7f9f2766ef9a6b | DarynaZlochevska/Practic | /1 день/14.py | 650 | 3.84375 | 4 | import datetime
def printTimeStamp(name):
print('Автор програми: ' + name)
print('Час компіляції: ' + str(datetime.datetime.now()))
a = ["January", "March", "May", "July", "August", "October", "December"]
b = ["April", "June", "September", "November"]
c = "February"
mount = input("Введіть місяць (англійською): ")
if mount == c:
mount = "28 або 29 днів"
elif mount in b:
mount = "30 днів"
elif mount in a:
mount = "31 день"
else:
print("Помилка")
print("В місяці " + str(mount))
printTimeStamp("Злочевська Д. С.")
|
60034fc3f8050a35482baf9b8580da989e04ddf2 | serik867/Python3_problems | /ContainerWithMostWater.py | 1,050 | 3.78125 | 4 | # Given n non-negative integers a1, a2, ..., an ,
# where each represents a point at coordinate (i, ai).
# n vertical lines are drawn such that the two endpoints of line i is at (i, ai)
# and (i, 0). Find two lines, which together with x-axis forms a container,
# such that the container contains the most water.
# Note: You may not slant the container and n is at least 2.
# Example:
# Input: [1,8,6,2,5,4,8,3,7]
# Output: 49
def max_Area(height) -> int:
point1=0
point2=len(height)-1
maxArea=0
while point1 != point2:
if (point2 - point1) * min(height[point1],height[point2]) > maxArea:
maxArea = (point2 - point1) * min(height[point1],height[point2])
elif height[point1] == min(height[point1],height[point2]):
point1+=1
else:
point2-=1
return maxArea
test_cases = [[1,8,6,2,5,4,8,3,7], [2,3,5,7,6,8,9,7,9],[9,3,7,9,1,2,8,5],[2,3,5,6,8,9,4,3,2,4,6]]
for i in range(len(test_cases)):
print( "Test Case - "+ str(i))
print(max_Area(test_cases[i])) |
60feefd199e038a17ad444d91c6bcaa8360b2a88 | arunabeyaantrix/pythonpractice | /selection.py | 199 | 3.640625 | 4 | arr = [12,11,13,5,6]
for i in range(len(arr)):
min_index = i
for j in range(i+1,len(arr)):
if arr[min_index] > arr[j]:
min_index = j
arr[min_index], arr[i] = arr[i], arr[min_index]
print(arr) |
108f990e4079076c168ecda4bbb5583c97cf0b2c | bitcafe24-byungkwan/python_practice | /practice03/prob04.py | 912 | 3.78125 | 4 | """
문제4.
구구단 중에 특정 곱셈을 만들고 그 답을 선택하는 프로그램을 작성하는 문제입니다.
답을 포함하여 9개의 정수가 아래와 같은 형태로 출력되고 사용자는 답을 골라 입력하게 됩니다.
프로그램은 정답 여부를 다시 출력합니다.
[출력]
6 x 9 = ?
81 12 32
18 54 4
32 6 32
answer: 54 [입력]
정답 [출력]
"""
import os
import random
factor_1 = random.randrange(9) + 1
factor_2 = random.randrange(9) + 1
prod = factor_2 * factor_1
print(f"{factor_1} X {factor_2} = ?\n")
answer_set = {prod}
while len(answer_set) < 10:
answer_set.add((random.randrange(9) + 1) * (random.randrange(9) + 1))
for ii in range(1, 10):
print("%3d" % answer_set.pop(), end=' ' if ii % 3 else os.linesep)
while 1:
print()
if prod == int(input("answer:")):
print("\n정답")
break
|
51e2a210678baceb0f023ca555089d5021dbb33a | Renfrew/alignment-algorithm-demo | /demo.py | 5,069 | 3.5 | 4 | """Alignment Demo
This is a demo program testing an aliment algorithm
Created by Liang Chen (Renfrew) on 2021-02-10.
"""
from __future__ import annotations
import typing
import pygame
from pygame.constants import K_ESCAPE
import rectangle as rt
# Settings
FPS = 30
DEFAULT_COLOR = (199, 21, 133)
HIGHTLIGHT_COLOR = (199, 21, 133)
def draw_line(point: rt.AlignPoint, shape: rt.Rectangle, direction='horizontal'):
""" Draw a line between two rectangle"""
if direction == 'horizontal' and shape is not None:
pygame.draw.line(screen,
HIGHTLIGHT_COLOR,
(point.idx, point.node.get_bottom_idx()),
(point.idx, shape.get_bottom_idx()))
elif direction == 'horizontal':
pygame.draw.line(screen,
HIGHTLIGHT_COLOR,
(point.idx, 0),
(point.idx, rt.SCREEN_HEIGHT))
elif shape is not None:
pygame.draw.line(screen,
HIGHTLIGHT_COLOR,
(point.node.get_right_idx(), point.idx),
(shape.get_right_idx(), point.idx))
else:
pygame.draw.line(screen,
HIGHTLIGHT_COLOR,
(0, point.idx),
(rt.SCREEN_WIDTH, point.idx))
def main():
"""This is the main function of the demo"""
clock = pygame.time.Clock()
# list of all nodes
nodes: typing.List[rt.Rectangle] = []
# variables used in handling drag event
mouse_x = 0
mouse_y = 0
_node: rt.Rectangle = None
horizontal_aligned_node: rt.AlignPoint = None
vertical_aligned_node: rt.AlignPoint = None
# Create a triangle
nodes.append(rt.Rectangle(200, 100, 60, 40))
nodes.append(rt.Rectangle(300, 400, 80, 40))
nodes.append(rt.Rectangle(170, 300, 80, 80))
nodes.append(rt.Rectangle(600, 200, 100, 100))
# Initial the Rectangle
rt.Rectangle.screen = screen
rt.Rectangle.nodes = nodes
is_draging = False
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == K_ESCAPE:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
position = (click_x, click_y) = event.pos
# Check if a node is clicked
for node in nodes:
if node.collidepoint(position):
is_draging = True
mouse_x = click_x
mouse_y = click_y
_node = node
break
elif event.type == pygame.MOUSEBUTTONUP:
is_draging = False
_node = None
horizontal_aligned_node = None
vertical_aligned_node = None
elif event.type == pygame.MOUSEMOTION:
if is_draging:
(click_x, click_y) = event.pos
horizontal_aligned_node = \
_node.move_horiontally(click_x - mouse_x)
vertical_aligned_node = \
_node.move_vertically(click_y - mouse_y)
mouse_x = click_x
mouse_y = click_y
# if the user click the window close button.
elif event.type == pygame.QUIT:
running = False
# Refresh screen with white color
screen.fill((255, 255, 255))
# Draw all rectangles
for node in nodes:
node.draw()
# If two nodes are aligned, hightlight them and draw the line
if _node is not None:
# Horizontal direction
if horizontal_aligned_node is not None:
pygame.draw.rect(screen, HIGHTLIGHT_COLOR, _node)
if horizontal_aligned_node.node != "window":
pygame.draw.rect(screen,
HIGHTLIGHT_COLOR,
horizontal_aligned_node.node)
draw_line(horizontal_aligned_node, _node)
else:
draw_line(horizontal_aligned_node, None)
# Vertical direction
if vertical_aligned_node is not None:
pygame.draw.rect(screen, HIGHTLIGHT_COLOR, _node)
if vertical_aligned_node.node != "window":
pygame.draw.rect(screen,
HIGHTLIGHT_COLOR,
vertical_aligned_node.node)
draw_line(vertical_aligned_node, _node, 'vertical')
else:
draw_line(vertical_aligned_node, None, 'vertical')
# Update the screen
pygame.display.flip()
# - constant game speed / FPS
clock.tick(FPS)
# Initial the screen
pygame.init()
pygame.display.set_caption("Alignment Demo")
screen = pygame.display.set_mode(rt.SCREEN_SIZE)
main()
|
19b3128e6f29fc37ca82d07cab3f05eb59096478 | nantesgi/Algorithms-and-Programming-I | /Funcoes/Exemplo 5.py | 613 | 4.03125 | 4 | # Exemplo 5
# definição de uma função que realiza a leitura
# de um inteiro e o retorna
def Le():
return int(input("Digite um inteiro: "))
# definição da função de calcula o valor de x**y
# esta função possui dois parâmetros de entrada (parâmetros formais da função)
def Potencia(x, y):
return x**y
# início da função principal - main()
a = Le()
b = Le() # sem argumentos de entrada
r = Potencia(a,b) # a e b são os argumentos de entrada da função Potência
print("{} elevado a {} é {}".format(a, b, r))
# r = Potencia(b,a) #a e b são os argumentos de entrada da função Potência |
f9b9af432644f193d2b80a7f7ff45b971d65d85a | Tbeaumont79/Python | /python/math_in_python/AtelierNumériqueEuler1TestExponentielle.py | 679 | 3.59375 | 4 | import matplotlib.pyplot as plt
import math
#declaration de la fonction f
def f(y,t):
g = 10
m = 100
Lambda = 1
F = y*y
y = g - (Lambda/m) * F
return y
#fonction permettant de calculer l equation differentielle
def Euler1(f,a,b,y0,n):
#declaration des variables :
h=(b-a)/n
y=[y0]
t=a
temps=[a]
for k in range (0,n+1):
y=y+[y[k]+h*f(y[k],t)]
temps=temps+[t]
t=t+h
return (temps,y)
#tracer de la simulation :
(t1,y1)=Euler1(f,60,5,1,50);
(t2,y2)=Euler1(f,60,5,1,20);
(t3,y3)=Euler1(f,60,5,1,6);
plt.plot(t1,y1,'o')
plt.plot(t2,y2,'o')
plt.plot(t3,y3,'o')
plt.show()
|
cebe41f2c46c2de3c7cf91968a9b5c657d6eacac | bruxkpo/trabajos | /tp16a.py | 633 | 3.890625 | 4 | """
con un simple for analiza la palabra y con un if el programa
verifica si hay una consonante utilizando una lista que contiene a todas
las consonantes en minuscula y mayuscula. luego le agrego las consonantes
que se consiguieron a una variable vacia.
"""
def consonante():
palabra = input("Ingrese una sentencia: ")
consonantes = ""
for x in range(0, len(palabra)): # recorre la palabra
if palabra[x] in "bdfghjklmnñpqrstvxyzBDFGHJKLMNÑPQRSTVXYZ":
consonantes += palabra[x] # le suma las consonantes de nuestra palabra a la nueva palabra
print(consonantes) |
eab1ab99200db1a80862dfe056c9def27594f84f | Faii-GitHub/CP3-Warisara-Chinjaroenkit | /Exercise5_1_Warisara_C.py | 232 | 3.859375 | 4 | Number1 = 15
Number2 = 3
print(Number1,"+",Number2,"=",int(Number1+Number2))
print(Number1,"-",Number2,"=",int(Number1-Number2))
print(Number1,"*",Number2,"=",int(Number1*Number2))
print(Number1,"/",Number2,"=",int(Number1/Number2)) |
58f2d6754e7d6ba9b115458b02cc1339972e4032 | KaminFay/btLogger | /BtFinder.py | 626 | 3.625 | 4 | import bluetooth
def finder():
address = []
nameList = []
i = 1
# Scans for nearby Devices
nearby_devices = bluetooth.discover_devices(lookup_names=True)
print("found %d devices" % len(nearby_devices))
# For each device it ouputs the address and name in the console
for addr, name in nearby_devices:
i += 1
print(" %s - %s" % (addr, name))
address.append(str(addr))
nameList.append(str(name))
# Returns the address and Name of each device back to the main file
return address, nameList
|
7e29b011240b73136ff8954ce069f7aa93ccbdab | mbohekale/Python2019-20 | /lecture3/lab3.2.py | 536 | 3.703125 | 4 | def daysInMonth(year,month):
leap = False
if year%400==0:
leap = True
elif year%100==0:
leap = False
elif year%4==0:
leap = True
return leap
testYears =[1900, 2000, 2016, 1987]
testMonths = [2,2,1,11]
testResults= [28, 29, 31,30]
for i in range(len(testYears)):
yr = testYears[i]
mo = testMonths[i]
print(yr,mo,"->",end="")
result = daysInMonth(yr,mo)
if result==testResults[i]:
print("Failed")
else:
print("OK")
|
0cf50e3ab5b7482205ca99e1184ebf1aa34d5503 | alexgula/django_sites | /sites/tekhnoland/catalog/exchange/xml_utils.py | 2,119 | 3.703125 | 4 | # coding=utf-8
from xml.etree.cElementTree import iterparse
def iter_elems(source, *args):
"""Get iterator to iterate over elements with given element tag.
Parameters:
*args -- contain path to the element, i.e. 'parent', 'child' means: find all elements with 'child' that are
children of an element with tag 'parent'.
N.B.! Child doesn't have to be immediate child if a parent. Thus children can be found on the different
levels of the hierarchy.
N.B.-2! Find only the first occurence of a parent.
"""
context = iterparse(source, events=("start", "end"))
context = iter(context)
event, root = context.next()
yield root
def iter_elem(tag_name):
"""Iter over the terminal elements of the document."""
for event, elem in context:
if event == "end" and elem.tag == tag_name:
yield elem
root.clear()
def iter_parent(*args):
"""Iter over parents of elements of the document if more than 1 argument else proxy iter_elem."""
if len(args) == 1:
for elem in iter_elem(args[0]):
yield elem
elif len(args) > 1:
for event, elem in context:
if event == "start" and elem.tag == args[0]:
for elem in iter_parent(*args[1:]):
yield elem
break # Find only the first occurence of a parent.
for elem in iter_parent(*args):
yield elem
def find_elem_children(elem, attr_map):
"""Map element's immediate children text using the map given.
Parameters:
elem -- given element.
map -- map of element's children tags to field codes. I.E., {"Tag": 'code'} will build dictionary item with key
'code' and value of child with tag "Tag". If several children found, get only first.
"""
res = dict()
for child in elem:
tag = child.tag
text = child.text.strip() if child.text else u""
if tag in attr_map and text and not attr_map[tag] in res:
res[attr_map[tag]] = text
return res
|
7538eb0f650b43504a5a8d52a207dee185c8d564 | cthi/LeetCode | /sort_list_148.py | 1,935 | 3.796875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
def ll_len(head):
count = 0
while head:
count += 1
head = head.next
return count
def ll_merge(a, b):
head = None
postHead = None
while a and b:
if a.val < b.val:
if not head:
head = a
postHead = a
else:
head.next = a
head = head.next
a = a.next
else:
if not head:
head = b
postHead = b
else:
head.next = b
head = head.next
b = b.next
while a:
head.next = a
head = head.next
a = a.next
while b:
head.next = b
head = head.next
b = b.next
return postHead
def getN(head, N):
count = 0
prev = None
while count != N:
count += 1
prev = head
head = head.next
if prev:
prev.next = None
return head
def mergeSort(head):
length = ll_len(head)
if length == 1:
return head
first = head
rest = getN(head, length // 2)
return ll_merge(mergeSort(first), mergeSort(rest))
if not head:
return head
return mergeSort(head)
|
d6bed477f44641f1981ade19237f9fd64258d6bc | Soumyo-Pandey/Python-Basics-Programme | /Python program to find numbers present in the list.py | 259 | 3.90625 | 4 | test_list = [4, 5, 6, 7, 3, 9]
print("The original list is: " + str(test_list))
i, j = 3, 10
res = True
for ele in test_list:
if ele < i or ele >= j:
res = False
break
print("Does the list contain all elements in range : " + str(res))
|
071369a4c38c925c8ba935f010c533c7141cf8d6 | huuu97/LeetCode | /recursion/236_LCA_of_a_binary_tree.py | 1,899 | 3.625 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""
* 递归
时间复杂度 o(n) 我们每个结点只访问一次
空间复杂度 o(n) 递归将会被调用 N次(树的高度),因此保持调用栈的存储将是O(N)。
"""
if not root or root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
# //左子树上能找到,但是右子树上找不到,此时就应当直接返回左子树的查找结果
if left and not right:
return left
# //右子树上能找到,但是左子树上找不到,此时就应当直接返回右子树的查找结果
if not left:
return right
# // 左右子树上均能找到,说明此时的p结点和q结点分居root结点两侧,此时就应当直接返回root结点
return root
class Solution2:
answer = None
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""
* 递归
时间复杂度 o(n) 我们每个结点只访问一次
空间复杂度 o(n) 递归将会被调用 N次(树的高度),因此保持调用栈的存储将是O(N)。
"""
def dfs(node):
if not node:
return False
left = dfs(node.left)
right = dfs(node.right)
mid = False
if node == p or node == q:
mid = True
if mid + left + right >= 2:
self.answer = node
return mid or left or right
dfs(root)
return self.answer
|
1ac78d75c7b97805ca72af7e4a9b61da80c04c5f | mgsosna/artificial_humanity | /chapter_1.py | 5,030 | 3.734375 | 4 | ########################################################################################################
# ARTIFICIAL HUMANITY
# Chapter 1: introduction
#
# Matt Grobis
########################################################################################################
import pickle
import time
from custom_functions import *
# Set global variables
susp_spaces = 25
susp_stars = 8
binary_length = 20
binary_spaces = susp_spaces+1
binary_rows = 5
binary_sleep = 1
player = pickle.load(open('player_stats.pkl', 'rb'))
print()
print(" " * (susp_spaces-6), "*" * 51)
print(" " * (susp_spaces-6), "*" * 20, "CHAPTER 1", "*" * 20)
print(" " * (susp_spaces-6), "*" * 51)
print()
input("[TIP]: Press ENTER to move through dialogue and acknowledge tips.")
input("[TIP]: When typing in your choices, both uppercase and lowercase letters are accepted.")
print()
# Player stands up, realizes has amnesia
print(
'''[*STORY*]
You shake yourself awake. Your quarters are simple, efficient. A clean desk, simple bed. No windows. You rise to
your feet and are immediately struck by a headache. Ooohh... how did this happen? As you massage your forehead,
the pain recedes... but you can barely remember who or where you are. How...? You close your eyes and search your
memory.''')
input()
print(
f'''[*STORY*]
The year is 2101. You are Commander {player['name']} of the 42nd Division of the United States Fleet. You are in
orbit around Pluto's moon Cheron, about 1.9 million kilometers from the nearest Mass Relay. Your crew is small -
only 2 besides yourself - and you trust them with your life... but should you? BENJAMIN, VERONICA - their names
and faces appear without effort, but you remember nothing of their histories or personalities. Your stomach turns.''')
input()
# Ship AI speaks
print(
'''[SHIP AI]
Commander. The breach is of highest priority. This intruder has a signature I cannot decipher. It is distinctly
not-self, yet I cannot locate its location. As we speak, I am fighting off approximately 1.77 billion malicious
attacks on all vulnerable ports in my consciousness. The intruder is attempting to access the region of the ship
controlling life support. If it is able to break through my firewall, I will be unable to control ship oxygen or
gravity.''')
input()
print(
'''[SHIP AI]
We will all effectively be reduced to the quantum bits and atoms from which we came...''')
input()
print(
'''[SHIP AI]
I believe the intruder is a physical presence on this ship. This is anomalous, as I have examined all travel logs
into and out of the ship and detected no abnormalities. Unfortunately, Earth did not provide me with any visual
monitoring system: I cannot take video or images of the rooms or halls and then search for anomalies. The intruder
has likely induced temporary amnesia in you to prolong the time it can attack me. It has erased its signature from
my consciousness, rendering it effectively invisible to me.''')
input()
print(
'''[SHIP AI]
However, it will not be invisible to you.''')
input()
print(
'''[SHIP AI]
Commander. A recommendation. I believe the intruder may be posing as a member of the crew. I recommend you examine
each member carefully. If you discover the intruder, it must be exterminated. There is not much time. I suspect I
can maintain security protocol for approximately 2.206 hours. You must hurry.''')
input()
print(
'''[SHIP AI]
Discretion is highly advised, as there is approximately a 0.01998999% probability of survival if the intruder
learns of your intentions.''')
input()
# Scrolling binary
scrolling_binary(screen_size=binary_length, n_rows=binary_rows, n_spaces=binary_spaces, time_sleep=binary_sleep)
#------------------------------------------------------------------------------------------------------------------------------
# Create NPC suspicion levels
player['crew_suspicion'] = dict()
player['crew_suspicion']['BENJAMIN'] = 0
player['crew_suspicion']['VERONICA'] = 0
save_object(player, "player_stats.pkl")
# Display crew suspicion levels
print()
display_suspicion(n_spaces=susp_spaces, n_stars=susp_stars, player=player)
input()
# Print binary
scrolling_binary(screen_size=binary_length, n_spaces=binary_spaces, n_rows=binary_rows, time_sleep=binary_sleep)
print()
#------------------------------------------------------------------------------------------------------------------------------
# First player decision: where to go
print(f"[{player['name']}]".upper())
print("What should I do?")
time.sleep(0.75)
print()
print("A - [GO TO ENGINE ROOM]")
print()
print("B - [GO TO LIFE SUPPORT SYSTEMS]")
print()
# Ensure player chooses a valid option
loc1_dec = ""
while loc1_dec.upper() not in ['A', 'B']:
loc1_dec = input("[CHOICE (A/B)]: ")
# Load modules for engine room and life support systems
if loc1_dec.upper() == "A":
import chapter_1_engine
if loc1_dec.upper() == 'B':
import chapter_1_life
|
523f9b6c421a071850f47d300efdf717757ab75f | cjdzalx/test | /testone/test2.py | 374 | 4 | 4 | # -*- coding: utf-8 -*-
# 作者:yin
# a = 'hello world'
# b = a[7:3:-1]
# print(b)
#
# X的n次方
def power(x, n):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
print(power(5,3))
#斐波那契数列
def fib(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n = n + 1
return 'done'
fib(10) |
8bb2ff1b3c44936220cf958c71cc3cf0da50a3ba | valcal/python_practice | /python-function-practice-master/makes_twenty.py | 355 | 4.125 | 4 | """
MAKES TWENTY: Given two integers, return True if the sum of the integers is 20 or if one of the integers is 20. If not, return False¶
"""
#makes_twenty(20,10) --> True
#makes_twenty(12,8) --> True
#makes_twenty(2,3) --> False
def makes_twenty(n1,n2):
if n1 == 20 or n2 == 20 or n1 + n2 == 20:
return True
else:
return False
|
0fc4475cfbcce765c8374825569a0f2b2f3525d7 | CurtainTenderness/PythonAdvance | /day0219/text0219-8.py | 816 | 4.125 | 4 | """
多线程共享全部对象产生的问题
GIL锁:全局解释锁
互斥锁:资源互斥锁:线程想要访问某个资源前给资源加锁,加锁成功就可以访问
加锁失败,需要陷入等待直到加锁成功
"""
from threading import Thread,Lock
# 得到一把锁
lock=Lock()
num=0
def fun():
global num
for i in range(1000000):
"添加互斥锁"
lock.acquire()
num+=1
"解除互斥锁"
lock.release()
def main():
t1=Thread(target=fun)
t1.start()
t1.join()
print(num)
t2=Thread(target=fun)
t2.start()
t2.join()
print(num)
if __name__=="__main__":
main()
"""
多进程:内存独立,需要共享数据就是用Queue
多线程:内存不独立本身就是共享数据但产生线程不安全数据
""" |
1519f68279df5a9907963909e15b9a8b3670a75a | xxNB/sword-offer | /leetcode/链表/copy_list_with_random_pointer.py | 2,208 | 4.03125 | 4 | #########################################################
# 复制带随机指针的链表
#########################################################
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
"""
总结起来,实际我们对链表进行了三次扫描,第一次扫描对每个结点进行复制,然后把复制出来的新节点接在
原结点的 next 指针上,也就是让链表变成一个重复链表,就是新旧更替;第二次扫描中我们把旧结点的随
机指针赋给新节点的随机指针,因为新结点都跟在旧结点的下一个,所以赋值比较简单,就是 node->next
->random = node->random->next,其中 node->next 就是新结点,因为第一次扫描我们就是把新结
点接在旧结点后面。现在我们把结点的随机指针都接好了,最后一次扫描我们把链表拆成两个,第一个还原
原链表,而第二个就是我们要求的复制链表。因为现在链表是旧新更替,只要把每隔两个结点分别相连,
对链表进行分割即可。
"""
class Solution:
# @param head: A RandomListNode
# @return: A RandomListNode
def copyRandomList(self, head):
if head is None:
return None
curr = head
# step1: generate new List with node
while curr is not None:
newNode = RandomListNode(curr.label)
newNode.next = curr.next
curr.next = newNode
curr = curr.next.next
# step2: copy random pointer
curr = head
while curr is not None:
if curr.random is not None:
curr.next.random = curr.random.next
curr = curr.next.next
# step3: split original and new List
newHead = head.next
curr = head
while curr is not None:
# 赋值
newNode = curr.next
# 指向
curr.next = curr.next.next
if newNode.next is not None:
newNode.next = newNode.next.next
# 此时的curr.next已经是curr.next.next.next了
curr = curr.next
return newHead
|
b746276e7c3d2e924240156f2a8bb6a7d8e0a850 | rba2124/pwp-capstones | /TomeRater/TomeRater.py | 10,430 | 3.875 | 4 | #! python3
# RBA: Roger B. Atkins, rba2124@gmail.com
# Cohort-nov-27-2018
# Tome Rater Project
# Note: At first I coded a 4 'star' rating system, but when
# I started adding books that I have read, I felt compelled
# to convert it to a 5 'star' system.
class User(object):
def __init__(self, name, email):
self.name = name
self.email = email
self.books = {} # book: rating
def get_email(self): # Why?
return self.email
def change_email(self, address):
self.email = address
return print("User's email address has been updated.")
# Changes user's email; print('User's email has been updated.')
def __repr__(self):
bks_read = 0
for book in self.books:
bks_read += 1
return 'User {name}, email: {email}, books read: {num_bks_read}'.format(name=self.name, email=self.email, num_bks_read=bks_read)
def __eq__(self, other_user):
if self.name == other_user and self.email == other_user.email:
return print('The users are the same.')
def read_book(self, book, rating='None'):
self.books[book] = rating
def __hash__(self):
return hash((self.name, self.email))
def get_average_rating(self):
total = 0.0
if self.books == {}:
return 0
else:
for rating in self.books.values():
if rating != 'None' and rating != '' and rating != 0:
total += float(rating)
return round(total / len(self.books), 2)
class Book(): # Why no author?
def __init__(self, title, isbn):
self.title = title
self.isbn = isbn
self.ratings = []
def get_title(self):
return self.title
def get_isbn(self):
return self.isbn
def set_isbn(self, isbn):
self.isbn = isbn
return print('ISBN has been updated.')
def add_rating(self, rating):
if rating != 'None' and float(rating) > 0 and float(rating) <= 5:
self.ratings.append(rating)
else:
return print("Invalid Rating")
def __eq__(self, other_book):
if self.isbn == other_book.isbn and self.title == other_book.title:
return print('The books are the same.')
def get_average_rating(self):
total = 0.0
for rating in self.ratings:
if rating != 'None' and rating != '':
total += float(rating)
return round(total / len(self.ratings), 2)
def __hash__(self):
return hash((self.title, self.isbn))
def __repr__(self):
return 'Book object: {title}, ISBN: {isbn}'.format(title=self.title, isbn=self.isbn)
class Fiction(Book):
def __init__(self, title, author, isbn):
super().__init__(title, isbn)
self.author = author
def get_author(self):
return self.author
def __repr__(self):
return ('{title} by {author}'.format(title=self.title, author=self.author))
class Non_Fiction(Book): # Why no author?
def __init__(self, title, subject, level, isbn):
super().__init__(title, isbn)
self.subject = subject # type str
self.level = level # type str
def get_subject(self):
return self.subject
def get_level(self):
return self.level
def __repr__(self):
return ('{title}, a {level} manual on {subject}'.format(title=self.title, level=self.level, subject=self.subject))
class TomeRater():
def __init__(self):
self.users = {} # email:user
self.books = {} # book:num users who read it
def create_book(self, title, isbn):
return Book(title, isbn)
def create_novel(self, title, author, isbn):
return Fiction(title, author, isbn)
def create_non_fiction(self, title, subject, level, isbn):
return Non_Fiction(title, subject, level, isbn)
def add_book_to_user(self, book, email, rating='None'):
if email not in self.users.keys():
return print('No user with email ' + email +'!')
else:
self.users[email].read_book(book, rating)
if rating != 'None':
book.add_rating(rating)
if book not in self.books.keys():
self.books[book] = 1
else:
self.books[book] += 1
def add_user(self, name, email, user_books='None'):
if email not in self.users.keys():
self.users[email] = User(name, email)
if user_books != 'None' and user_books != '' and user_books != []:
for book in user_books:
self.add_book_to_user(book, email, )
def print_catalog(self):
print('\nCatalog:\n')
if len(self.books) == 0:
print('There are no catalogued books.')
for key in self.books.keys():
if type(key) == Book:
print(key.title + ', ISBN: ' + str(key.isbn))
else:
print(key)
return print()
def print_users(self):
user_list = []
for value in self.users.values():
user_list.append(value)
print('\nUser List:\n')
for user in user_list:
print(user)
return print()
def most_read_book(self):
most = 0
mr_books = {0: {}}
for book, reads in self.books.items():
if most == 0 and mr_books[0] == {}:
most = reads
mr_books[0] = {book: most}
else:
if reads > most:
most = reads
mr_books[0] = {book: most}
# Test for ties:
for book, reads in self.books.items():
if reads == most and book not in mr_books[0].keys():
mr_books[0][book] = reads
print('\nMost Read Book(s):\n')
for book, reads in mr_books[0].items():
print('{book} read by {reads}'.format(book=book, reads=reads))
return ''
def highest_rated_book(self):
high_average = 0
hi_aver_bks = {0: {}}
for key in self.books.keys():
ave_rating = key.get_average_rating()
if ave_rating > high_average:
high_average = ave_rating
for key in self.books.keys():
ave_rating = key.get_average_rating()
if ave_rating == high_average:
hi_aver_bks[0][key] = ave_rating
print('\nHighest Rated Book(s):\n')
for book, ave in hi_aver_bks[0].items():
print('{book} Average Rating: {ave}'.format(book=book, ave=ave))
return ''
def most_positive_user(self):
hi_rating = 0.0
hi_users = {0: {}}
for user in self.users.values():
av_rating = user.get_average_rating()
if av_rating > hi_rating:
if hi_rating == 0 and hi_users[0] == {}:
hi_rating = av_rating
hi_users[0] = {user: hi_rating}
else:
hi_rating = av_rating
hi_users[0] = {user: hi_rating}
# Test for ties:
for user in self.users.values():
if user.get_average_rating() == hi_rating and user not in hi_users[0].keys():
hi_users[0][user] = hi_rating
print('\nMost Positive User(s):\n')
for user in hi_users[0].keys():
average = hi_users[0][user]
print('{user} Average Rating: {average}'.format(user=user, average=average))
return ''
Tome_Rater = TomeRater()
# Create some books:
book1 = Tome_Rater.create_book("Society of Mind", 12345678)
print(book1) # Test __repr__ for Book object.
novel1 = Tome_Rater.create_novel("Alice In Wonderland", "Lewis Carroll", 12345)
novel1.set_isbn(9781536831139)
nonfiction1 = Tome_Rater.create_non_fiction("Automate the Boring Stuff", "Python", "beginner", 1929452)
print(nonfiction1) # Test __repr__() for Non_Fiction object.
nonfiction2 = Tome_Rater.create_non_fiction("Computing Machinery and Intelligence", "AI", "advanced", 11111938)
novel2 = Tome_Rater.create_novel("The Diamond Age", "Neal Stephenson", 10101010)
novel3 = Tome_Rater.create_novel("There Will Come Soft Rains", "Ray Bradbury", 10001000)
print(novel3) # Test __repr__() for Fiction object.
get_prog = Tome_Rater.create_non_fiction("Get Programming: Learn to Code With Python", "Python", "beginner", 9781617293788)
smart_pyth = Tome_Rater.create_non_fiction("A Smarter Way to Learn Python", "Python", "beginner", 1010101010999)
silent = Tome_Rater.create_novel("The Silent Corner", "Dean Koontz", 9780345546784)
# Create users:
Tome_Rater.add_user("Alan Turing", "alan@turing.com")
Tome_Rater.add_user("David Marr", "david@computation.org")
Tome_Rater.add_user("Roger B. Atkins", "rba2124@gmail.com")
Tome_Rater.add_user("Abe Lincoln", "honest@gmail.com")
Tome_Rater.add_user("Cary Grunt", "cg23@gmail.com")
# Add a user with three books already read:
Tome_Rater.add_user("Marvin Minsky", "marvin@mit.edu", user_books=[book1, novel1, nonfiction1])
# Add book to user:
Tome_Rater.add_book_to_user(get_prog, "rba2124@gmail.com", 4.5)
Tome_Rater.add_book_to_user(nonfiction1, "rba2124@gmail.com", 4.7)
Tome_Rater.add_book_to_user(smart_pyth, "rba2124@gmail.com", 4.5)
Tome_Rater.add_book_to_user(silent, "rba2124@gmail.com", 4.5)
Tome_Rater.add_book_to_user(novel3, "rba2124@gmail.com", 4.2)
Tome_Rater.add_book_to_user(book1, "rba2124@gmail.com", 4.2)
Tome_Rater.add_book_to_user(novel1, "rba2124@gmail.com", 4.2)
# Add books to a user one by one, with ratings:
Tome_Rater.add_book_to_user(book1, "alan@turing.com", 4.5)
Tome_Rater.add_book_to_user(novel1, "alan@turing.com", 4.2)
Tome_Rater.add_book_to_user(nonfiction1, "alan@turing.com", 4.5)
Tome_Rater.add_book_to_user(nonfiction2, "alan@turing.com", 4.5)
Tome_Rater.add_book_to_user(novel3, "alan@turing.com", 4.2)
Tome_Rater.add_book_to_user(novel2, "marvin@mit.edu", 2)
Tome_Rater.add_book_to_user(novel3, "marvin@mit.edu", 2)
Tome_Rater.add_book_to_user(novel3, "david@computation.org", 4)
Tome_Rater.add_book_to_user(novel2, "david@computation.org", 4)
Tome_Rater.add_book_to_user(get_prog, "alan@turing.com", 4.7)
Tome_Rater.add_book_to_user(smart_pyth, "alan@turing.com", 4.2)
Tome_Rater.add_book_to_user(novel2, "honest@gmail.com", 3)
Tome_Rater.add_book_to_user(novel2, "cg23@gmail.com", 2)
# Test functions/methods:
Tome_Rater.print_catalog()
Tome_Rater.print_users()
# print("Most positive user:")
print(Tome_Rater.most_positive_user())
# print("Highest rated book:")
print(Tome_Rater.highest_rated_book())
# print("Most read book:")
print(Tome_Rater.most_read_book())
# test class book related methods:
print(novel1.get_author())
print(novel2.get_isbn())
print(book1.get_title())
|
c5238a7232dc0c08b9edd00a71740e9e9aebdc0d | anumahadevan89/CodeSlices | /Code/Code/python/pascal.py | 502 | 3.578125 | 4 | def pascaltriangle(row,colm):
pascaltri=[]
for i in range(1,row):
rowele=[]
if(i==1):
for k in range(0,row):
rowele.append(0)
rowele.append(1)
for k in range(0,row):
rowele.append(0)
pascaltri.append(rowele)
j=1
while j<=(1+(row*2)):
pascaltri[i,j] = pascaltri[i-1,j-1]+pascaltri[i-1,j+1]
j+=2
return pascaltri[row,colm]
pascaltriangle(2,3)
|
29030a58f84e04882beb9612a1630c61b243715e | alejandroruizgtz/progAvanzada | /ejercicio86.py | 1,013 | 3.953125 | 4 | from int.ordinal import intToOrdinal
def displayVerse(n):
print("One the", intToOrdinal(n), "day of Chrismas")
print("my true love sent to me:")
if n >= 12:
print("Twelve drummers drumming,")
if n >=11:
print("Eleven pipers piping,")
if n >=10:
print("Ten lords a leaping,")
if n >=9:
print("Nine ladies dancing,")
if n >=8:
print("Eight maids a milking,")
if n >=7:
print("Seven swans a swimming,")
if n >=6:
print("Six geese a laying,")
if n >=5:
print("Five golde rings")
if n >=4:
print("Four calling birds,")
if n >=3:
print("Three French hens,")
if n >=2:
print("Two turtle doves,")
if n ==1:
print("A", end= "")
else:
print("And a", end= " ")
print("partridge in a pear tree.")
print()
def main ():
for verse in range(1, 13):
displayVerse(verse)
main()
|
1af07f337196fda10e15701549e6243804b7e233 | prince3453/python | /p24.py | 901 | 3.5625 | 4 | class Bank:
def __init__(self, balance):
self.balance = balance
self.methods = [self.printBalance,self.deposite,self.withdraw]
def printBalance(self):
print("Current Balance:",self.balance)
def inputAmount(self):
return float(input("Enter Amount:"))
def deposite(self):
amount = self.inputAmount()
self.balance += amount
self.printBalance()
def withdraw(self):
amount = self.inputAmount()
if self.balance - amount <= 500:
print("The Account Does Not Has Sufficient Balance.")
else:
self.balance -= amount
self.printBalance()
var = Bank(10000)
while True:
choice = int(input("select \n1. for checking balance.\n2. for deposite.\n3. for withdrawal.\n4. for exit."))
if choice == 4: break
else:
var.methods[choice-1]() |
b380c5715a069ede45f1df943bd69c9d04d7553b | beninbeta/Udactiy-Projects | /Python/builtin.py | 1,128 | 3.6875 | 4 | def builtins():
tale ="I really love chocolatey chocolate!"
print("choc" in tale)
print(tale.find("chocolate"))
print(tale.count("chocolate"))
#builtins()
def breakify(lines):
return '<br>'.join(lines)
#print(breakify(["Haiku frogs in snow","A limerick came from Nantucket","Tetrametric drum-beats thrumming, Hiawathianic rhythm."]))
def replace_substring(string, search, replace):
new_string = []
index = 0
while index < len(string):
if string[index: index + len(search)] == search:
new_string.append(replace)
index += len(search)
else:
new_string.append(string[index])
index += 1
return "".join(new_string)
#print(remove_substring('SPAM!HelloSPAM! worldSPAM!!', 'SPAM!'))
#print(remove_substring("Whoever<br> wrote this<br> loves break<br> tags!", "<br>"))
#print(remove_substring('I am NOT learning to code.', 'NOT '))
#print(replace_substring('Hot SPAM!drop soup, and curry with SPAM!plant.', 'SPAM!', 'egg'))
#print(replace_substring("The word 'definately' is definately often misspelled.", 'definately', 'definitely'))
|
4c99cd3ddf1d1d58be4bf5b8f80d5d4d317fdfdd | jh5537/TIL | /1_pythonStudy/09_tuple/1_김지훈_0524_tupleSet.py | 2,845 | 3.875 | 4 | # 1. my_variable 이름의 비어있는 튜플을 만들라.
print("1번")
my_variable = () # my_variable = tuple()도 사용 가능.
print(my_variable)
print("==============================")
# 2. 다음 코드를 실행해보고 오류가 발생하는 원인을 설명하라.
# >> t = (1, 2, 3)
# >> t[0] = 'a'
# Traceback (most recent call last):
# File "<pyshell#46>", line 1, in <module>
# t[0] = 'a'
# TypeError: 'tuple' object does not support item assignment
print("2번")
print("튜플은 정의된 후 가지고 있는 요소의 수정, 추가, 삭제가 불가능하다. 따라서 t[0]의 값을 'a'로 바꾸는 것은 불가능하다.")
print("==============================")
# 3. 숫자 1 이 저장된 튜플을 생성하라.
print("3번")
tp = (1, ) # tp = (1)이라고 입력할 경우, 변수의 값이 튜플이 아닌 정수 1로 저장됨에 주의. 쉼표,를 사용하거나, 리스트를 만든 후 튜플로 변환하여야 함.
"""
num = list()
num.append(1)
tp = tuple(num)
"""
print(tp)
print("==============================")
# 4. 아래와 같이 t에는 1, 2, 3, 4 데이터가 바인딩되어 있다. t가 바인딩하는 데이터 타입은 무엇인가?
# t = 1, 2, 3, 4
print("4번")
t = 1, 2, 3, 4
print(type(t))
print("튜플")
print("==============================")
# 5. 변수 t에는 아래와 같은 값이 저장되어 있다. 변수 t가 ('A', 'b', 'c') 튜플을 가리키도록 수정 하라.
# t = ('a', 'b', 'c')
print("5번")
t = ('a', 'b', 'c')
listt = list(t)
listt[0] = 'A'
t = tuple(listt)
print(t)
print("==============================")
# 6. 다음 튜플을 리스트로 변환하라.
# interest = ('삼성전자', 'LG전자', 'SK Hynix')
print("6번")
interest = ('삼성전자', 'LG전자', 'SK Hynix')
interest = list(interest)
print(interest)
print("==============================")
# 7. 다음 리스트를 튜플로 변경하라.
# interest = ['삼성전자', 'LG전자', 'SK Hynix']
print("7번")
interest = ['삼성전자', 'LG전자', 'SK Hynix']
interest = tuple(interest)
print(interest)
print("==============================")
# 8. 파티에 참석한 사람이 다음과 같을 때 집합을 생성하고, 아래 조건에 맞게 출력하시오.
# partyA : "Park","Kim","Lee"
# partyB : "Park","길동","몽룡"
# 1) 파티에 참석한 모든 사람은?
# 2) 2개의 파티에 모두 참석한 사람은?
# 3) 파티 A에만 참석한 사람
# 4) 파티 B에만 참석한 사람
print("8번")
partyA = {"Park","Kim","Lee"}
partyB = {"Park","길동","몽룡"}
print("1)")
all = partyA | partyB # partyA.union(partyB)
print(*all)
print("2)")
every = partyA & partyB # partyA.intersection(partyB)
print(*every)
print("3)")
Aman = partyA - partyB # partyA.difference(partyB)
print(*Aman)
print("4)")
Bman = partyB - partyA # partyB.difference(partyA)
print(*Bman) |
a26ddd6ea48fd768ce829fe4cedf2bfd914540d6 | IntroToCompBioLSU/week9 | /assignments/EricWharton/popSim_week9.py | 1,409 | 4.3125 | 4 | #!/usr/bin/env python
import numpy as np
# currentPop -- number of individuals to start simulation with
currentPopulation = int(input("Input population size: " ))
# set carrying capacity
carryingCapacity = int(input("Input carrying capacity: "))
#generationCount -- number of generations to run in the simulation
generationCount = int(input("Number of generations to run: "))
# meanOffspring -- avg number of offpsing per each individual
meanOffspring = 2 # DB: Maybe allow the user to input this value as well?
# for loop that runs through generations
for i in range (0, generationCount):
# show current population
print(currentPopulation)
#oldPopulationOffspring -- Poisson (mean: meanOffspring, size: current
# population)
oldPopulationOffspring = np.random.poisson(meanOffspring, currentPopulation)
# currentPopulation -- sum of all (will loop back around and add each new poisson)
currentPopulation = 0
for x in oldPopulationOffspring:
currentPopulation = currentPopulation + x
# if statement for if --> currentPopulation > carryingCapacity
if currentPopulation > carryingCapacity:
# spits out carrying capacity rather than a greater integer
currentPopulation = carryingCapacity
# DB: Overall, very good. I like the way you've structured the code. That's a very
# efficient way to draw the offspring for the next generation while still allowing
# individual variation. |
a01ad936d0f040d295285e1b776e298913936262 | Somu96/Basic_Python | /FileHandling/Std_dict2.py | 704 | 3.84375 | 4 | score=[]
name=[]
temp_dict={}
student1 = [{'id' : 'Std_1', 'name': 'Som', 'math': 35, 'science': 60},
{'id' : 'Std_2', 'name': 'Vanitha', 'math': 15, 'science': 98},
{'id' : 'Std_3', 'name': 'Divya', 'math': 100, 'science': 83}
]
sub = input('Enter Subject to find max score \n')
for i in student1:
temp_dict.update({i['name'] : i[sub]})
#temp_dict = dict(zip(name, score))
print(temp_dict)
max_name = max(temp_dict, key = temp_dict.get)
min_name = min(temp_dict, key = temp_dict.get)
print(f'{max_name} scored highest in {sub} and the score : {temp_dict[max_name]} \n')
print(f'{min_name} scored lowest in {sub} and the score : {temp_dict[min_name]} \n')
|
3ab3b443233373150f411502c4f29cb91172ba20 | atrn0/aoj | /Courses/ALDS1/1c.py | 657 | 3.828125 | 4 | import time
import random
import sys
import bisect
import array
import re
import collections
import heapq
import fractions
import itertools
import string
import math
inf = 10**9
def is_prime(x):
if x == 2:
return True
if x < 2 or x % 2 == 0:
return False
for i in range(3, math.floor(math.sqrt(x)) + 1, 2):
if x % i == 0:
return False
return True
def main():
count = 0
n = int(input())
for i in range(n):
x = int(input())
if is_prime(x):
count = count + 1
# print(x, "is prime number")
print(count)
if __name__ == '__main__':
main()
|
7f27c1aa112fc0453c220c1efb4ed9e8ebedbdfb | mutedalien/PY_algo_interactive | /less_8/hw_8_more/lesson_8_task_3.py | 1,040 | 4.0625 | 4 | # Написать программу, которая обходит не взвешенный ориентированный граф без петель, в котором все вершины связаны,
# по алгоритму поиска в глубину (Depth-First Search).
# Задача пройти по всем вершинам вглубь один раз.
def graph(n): # Функция генерации графа
graph = {}
for i in range(n):
element = []
for j in range(n):
if i != j:
element.append(j)
graph[i] = element
return graph
n = int(input('Введите число вершин системы: '))
graph = graph(n)
print(graph)
visited = set()
def dfs(visited, graph, node): # Функция прохождения по вершинам графа
if node not in visited:
print(node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
dfs(visited, graph, 0)
|
fa22269b4601baacb15c788831c75e68240a4764 | elde11/python | /dzien_07/pliki.py | 1,097 | 3.84375 | 4 | # 1. otwarcie pliku
open("przykladowy.csv,"r", encoding="utf-8")
# "r" read - odczyt pliku
# "w" write - zapisz do pliku od poczatku/ tworzenie pliku
# "a" append - zapis na koncu pliku/
#tworzenie
# 2. dzialenie na pliku
lines = f.readlines()
print(lines[0])
# 3. zamkniecie pliku
f.close()
with open("przykladowy.csv","r") as f:
lines = f.readlines()
print(lines[0])
import csv
with open("przykladowy.csv","r") as f:
reader = csv.DictReader(f)
for row in reader:
data.append(
{
"year":int(row["Year"]),
"score": int(row["Score"]),
"title": row["Title"],
}
)
print (data[0])
# srednia ocen filmow
# mediana
#najgorszy film
# szukamy najgorszego filmu ,
# znajdz srednia
znajdz rok w ktorym robert
# jesli wiecej ich jest to mamy
# najlepszy film
najgorsza_ ocena = 1000
for entry in data:
if entry["score"] < najgorsza_ocena:
najgorsza_ocena = entry ["score"]
print (f"Najgorsza ocena filmu to: {najgorsza_ocena}") |
f355f8bc7fb9f3f323166297f92b4e29a6f3910d | LewisTrahearn/Battleships_A_Level_Project | /Battleships_A_Level_Project/Field.py | 2,382 | 3.953125 | 4 | r"""Module Name:
login.py
Public Functions/Methods:
display
Class:
Field - This is a container class used to hold each form control
Login - This is the main login class used to load the screen and handle the login process
Imports:
**import pygame** - pygame library.
**pygame.locals** - this is needed for the Rect definition.
**enum_navigate** - common enumeration values shared across all classes.
**facade_layer** - an abstraction from the pygame module, for certain common functions.
**Navigate** - This class is an enumeration class that holds all the options required to move around the system.
**pygame_textinput** - a 3rd party text input class that allows text input
Purpose:
This module contains two classes the Field class and the Login class.
The login class is used to load the screen, build a form, get the
user input and then call the data access layer in order to determine
if its correct or not.
The Field class a a simple container class that allows me to collect the information
for each input field, such as the x,y coords and instance of the pygame_textinput
and the name of the field and then put these into an array to allow me to cycle around
the form.
Author:
Lewis Trahearn
______________________________________________________________________________________________________________________
"""
class Field():
"""
This is a container class for each field within the system
"""
def __init__(self, fieldname, textinput, x1, y1):
"""This is the constructor for the class:
- parameters
:param fieldname: - name you wish to call the field
:param textinput: - field object
:param x: - the x coordinate of the field
:param y: - the y coordinate of the field
- type of parameters
:type fieldname: string literal
:type textinput: object pygame_textinput
:type x: int
:type y: int
- return
:return: none since its a constructor
- return type
:rtype: not applicable
"""
self.fieldname = fieldname
self.textinput = textinput
self.x1 = x1
self.y1 = y1 |
0819ff99dcbf6dce84eed7230d8ee65758f03fd0 | FelicxFoster/Sources | /Learning/OtherLanguages/C/C练习题/Use Python/16.py | 363 | 3.828125 | 4 | #辗转相除法
def gcd(a, b):
if a % b != 0:
return gcd(b, a%b)
else:
return b
print('请输入两个数字:')
m = int(input('第一个数:'))
n = int(input('第二个数:'))
if m < n:
temp = m
m = n
n = temp
print('最大公约数是:', gcd(m, n))
print('最小公倍数是:', m*n //gcd(m,n))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.