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 |
|---|---|---|---|---|---|---|
4e62eb6514c6a908947234b9471bd81f5a0845f2 | ShunKaiZhang/LeetCode | /merge_k_sorted_lists.py | 762 | 3.96875 | 4 | # python3
# Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
# My solution
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
out = []
while True:
pre = len(out)
for i in range(len(lists)):
if lists[i] != None:
out.append(lists[i].val)
lists[i] = lists[i].next
if pre == len(out):
break
return sorted(out)
|
6d322092f788d4b73d319a78fff74fc14ab3143e | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/557 Reverse Words in a String III.py | 483 | 4.375 | 4 | #!/usr/bin/python3
"""
Given a string, you need to reverse the order of characters in each word within
a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not
be any extra space in the string.
"""
c_ Solution:
___ reverseWords s: s..) __ s..
r.. " ".j.. m..(l.... x: x||-1], s.s..(" ")))
|
db76aba6de2f24272c175dde8a5d9abee914fadd | nurshahjalal/python_exercise | /String_Slicing/Charater.py | 749 | 4.125 | 4 |
parrot = "Norwegian Blue"
print(parrot)
# Print first character
print(parrot[0])
# To print up to 4th character not including 4th character
# By default counting starts from 0
print(parrot[:4])
# this is same as print(parrot[:4])
print(parrot[0:4])
# start and end position
print(parrot[3:7])
# Extract character from end position
print(parrot[-1])
print(parrot[-3])
# start position to end
print(parrot[6:])
# backward start and End
# this is starts from -4 th character and end at up to index character not including the mentioned index
print(parrot[-4:-1])
print(parrot[-4:-2])
print(parrot[-4:-3])
# by default interval is 1 but it can be changed
print(parrot[1:6:2])
print(parrot[1:8:2])
name = 'NurShahjalal'
print(name[::4])
|
ddf374943f6d958cf1dd7a6808b8822bbf9cf7bd | Vishal45-coder/Day3 | /Assignment3_pos or neg or zero by nestedif.py | 280 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 21 15:10:51 2020
@author: vishal
"""
a=int(input("enter a number"))
if(a>0 or a<0):
if(a>0):
print(f"{a} is positive")
else:
print(f"{a} is negative")
else:
print("number is negative") |
e9c1282b93e24549e02cc76f4063f410bd3bc251 | shahkushal38/sudoku-solver-using-dfs-and-graph-coloring | /Sud.py | 10,672 | 3.75 | 4 | import time
# starting time
start = time.time()
class Node :
def __init__(self, idx, data = 0) : # Constructor
self.id = idx
self.data = data
self.connectedTo = dict()
def addNeighbour(self, neighbour , data = 0) :
"""
neighbour : Node Object
weight : Default Value = 0
"""
if neighbour.id not in self.connectedTo.keys() :
self.connectedTo[neighbour.id] = data # adds the neightbour_id : data pair into the dictionary
def setData(self, data) :
self.data = data
def getConnections(self) :
return self.connectedTo.keys()
def getID(self) :
return self.id
def getData(self) :
return self.data
def getWeight(self, neighbour) :
return self.connectedTo[neighbour.id]
class Graph :
totalV = 0 # total vertices in the graph
def __init__(self) :
#Dictionary - idx : Node Object
self.allNodes = dict()
def addNode(self, idx) :
if idx in self.allNodes :
return None
Graph.totalV += 1
node = Node(idx=idx)
self.allNodes[idx] = node
return node
def addNodeData(self, idx, data) :
if idx in self.allNodes :
node = self.allNodes[idx]
node.setData(data)
else :
print("No ID to add the data.")
def addEdge(self, src, dst, wt = 0) :
# Adds edge between 2 nodes
self.allNodes[src].addNeighbour(self.allNodes[dst], wt)
self.allNodes[dst].addNeighbour(self.allNodes[src], wt)
def isNeighbour(self, u, v) :
# check neighbour exists or not
if u >=1 and u <= 81 and v >=1 and v<= 81 and u !=v :
if v in self.allNodes[u].getConnections() :
return True
return False
def getNode(self, idx) :
if idx in self.allNodes :
return self.allNodes[idx]
return None
def getAllNodesIds(self) :
return self.allNodes.keys()
class SudokuConnections :
def __init__(self) : # constructor
self.graph = Graph() # Graph Object
self.rows = 9
self.cols = 9
self.total_blocks = self.rows*self.cols #81
self.__generateGraph() # Generates all the nodes
self.connectEdges() # connects all the nodes acc to sudoku constraints
self.allIds = self.graph.getAllNodesIds() # storing all the ids in a list
def __generateGraph(self) :
"""
Generates nodes with id from 1 to 81.
"""
for idx in range(1, self.total_blocks+1) :
_ = self.graph.addNode(idx)
def connectEdges(self) :
matrix = self.__getGridMatrix()
head_connections = dict() # head : connections
for row in range(9) :
for col in range(9) :
head = matrix[row][col] #id of the node
connections = self.__whatToConnect(matrix, row, col)
head_connections[head] = connections
# connect all the edges
self.__connectThose(head_connections=head_connections)
def __connectThose(self, head_connections) :
for head in head_connections.keys() : #head is the start idx
connections = head_connections[head]
for key in connections : #get list of all the connections
for v in connections[key] :
self.graph.addEdge(src=head, dst=v)
def __whatToConnect(self, matrix, rows, cols) :
connections = dict()
row = []
col = []
block = []
# ROWS
for c in range(cols+1, 9) :
row.append(matrix[rows][c])
connections["rows"] = row
# COLS
for r in range(rows+1, 9):
col.append(matrix[r][cols])
connections["cols"] = col
# BLOCKS
if rows%3 == 0 :
if cols%3 == 0 :
block.append(matrix[rows+1][cols+1])
block.append(matrix[rows+1][cols+2])
block.append(matrix[rows+2][cols+1])
block.append(matrix[rows+2][cols+2])
elif cols%3 == 1 :
block.append(matrix[rows+1][cols-1])
block.append(matrix[rows+1][cols+1])
block.append(matrix[rows+2][cols-1])
block.append(matrix[rows+2][cols+1])
elif cols%3 == 2 :
block.append(matrix[rows+1][cols-2])
block.append(matrix[rows+1][cols-1])
block.append(matrix[rows+2][cols-2])
block.append(matrix[rows+2][cols-1])
elif rows%3 == 1 :
if cols%3 == 0 :
block.append(matrix[rows-1][cols+1])
block.append(matrix[rows-1][cols+2])
block.append(matrix[rows+1][cols+1])
block.append(matrix[rows+1][cols+2])
elif cols%3 == 1 :
block.append(matrix[rows-1][cols-1])
block.append(matrix[rows-1][cols+1])
block.append(matrix[rows+1][cols-1])
block.append(matrix[rows+1][cols+1])
elif cols%3 == 2 :
block.append(matrix[rows-1][cols-2])
block.append(matrix[rows-1][cols-1])
block.append(matrix[rows+1][cols-2])
block.append(matrix[rows+1][cols-1])
elif rows%3 == 2 :
if cols%3 == 0 :
block.append(matrix[rows-2][cols+1])
block.append(matrix[rows-2][cols+2])
block.append(matrix[rows-1][cols+1])
block.append(matrix[rows-1][cols+2])
elif cols%3 == 1 :
block.append(matrix[rows-2][cols-1])
block.append(matrix[rows-2][cols+1])
block.append(matrix[rows-1][cols-1])
block.append(matrix[rows-1][cols+1])
elif cols%3 == 2 :
block.append(matrix[rows-2][cols-2])
block.append(matrix[rows-2][cols-1])
block.append(matrix[rows-1][cols-2])
block.append(matrix[rows-1][cols-1])
connections["blocks"] = block
return connections
def __getGridMatrix(self) :
# Generates the 9x9 grid or matrix consisting of node ids.
matrix = [[0 for cols in range(self.cols)]
for rows in range(self.rows)]
count = 1
for rows in range(9) :
for cols in range(9):
matrix[rows][cols] = count
count+=1
return matrix
class SudokuBoard :
def __init__(self) :
self.board = self.getBoard()
self.sudokuGraph = SudokuConnections()
self.mappedGrid = self.__getMappedMatrix() # Maps all the ids to the position in the matrix
def __getMappedMatrix(self) :
matrix = [[0 for cols in range(9)]
for rows in range(9)]
count = 1
for rows in range(9) :
for cols in range(9):
matrix[rows][cols] = count
count+=1
return matrix
def getBoard(self) :
board = [
[0,0,0,4,0,0,0,0,0],
[4,0,9,0,0,6,8,7,0],
[0,0,0,9,0,0,1,0,0],
[5,0,4,0,2,0,0,0,9],
[0,7,0,8,0,4,0,6,0],
[6,0,0,0,3,0,5,0,2],
[0,0,1,0,0,7,0,0,0],
[0,4,3,2,0,0,6,0,5],
[0,0,0,0,0,5,0,0,0]
]
return board
def printBoard(self) :
print(" 1 2 3 4 5 6 7 8 9")
for i in range(len(self.board)) :
if i%3 == 0 :#and i != 0:
print(" - - - - - - - - - - - - - - ")
for j in range(len(self.board[i])) :
if j %3 == 0 :#and j != 0 :
print(" | ", end = "")
if j == 8 :
print(self.board[i][j]," | ", i+1)
else :
print(f"{ self.board[i][j] } ", end="")
print(" - - - - - - - - - - - - - - ")
def InitializeColor(self):
"""
fill the already given colors
"""
color = [0] * (self.sudokuGraph.graph.totalV+1)
given = [] # list of all the ids whos value is already given. Thus cannot be changed
for row in range(len(self.board)) :
for col in range(len(self.board[row])) :
if self.board[row][col] != 0 :
#first get the idx of the position
idx = self.mappedGrid[row][col]
#update the color
color[idx] = self.board[row][col] # this is the main imp part
given.append(idx)
return color, given
def solveGraphColoring(self, m =9) :
color, given = self.InitializeColor()
if self.__graphColorUtility(m = m, color = color, v =1, given = given) is None :
print(":(")
return False
count = 1
for row in range(9) :
for col in range(9) :
self.board[row][col] = color[count]
count += 1
return color
def __graphColorUtility(self, m, color, v, given) :
if v == self.sudokuGraph.graph.totalV +1 :
return True
#print(color)
for c in range(1, m+1) :
if self.__isSafeToColor(v, color, c, given) == True :
color[v] = c
if self.__graphColorUtility(m, color, v+1, given) :
return True
if v not in given :
color[v] = 0
def __isSafeToColor(self, v, color, c, given) :
if v in given and color[v] == c:
return True
elif v in given :
return False
for i in range(1, self.sudokuGraph.graph.totalV+1) :
if color[i] == c and self.sudokuGraph.graph.isNeighbour(v, i) :
return False
return True
def test() :
s = SudokuBoard()
print("Sudoku Puzzle")
print("\n\n")
s.printBoard()
print("\n\n\nSolution ")
print("\n\n")
s.solveGraphColoring(m=9)
s.printBoard()
test()
# end time
end = time.time()
# total time taken
print(f"Runtime of the program is {end - start}")
|
0b1314ecbe8817d9d77ac9d89922f75f03c13985 | mervesenn/Python-proje | /decoratorler/decorator.py | 809 | 3.734375 | 4 | def ekstra(fonksiyon):
def wrapper(sayilar):
ciftlertoplami = 0
ciftsayilar = 0
teklertoplami = 0
teksayilar = 0
for sayi in sayilar:
if (sayi % 2 == 0):
ciftlertoplami += sayi
ciftsayilar += 1
else:
teklertoplami += sayi
teksayilar += 1
print("Teklerin ortalaması:", teklertoplami / teksayilar)
print("Çiftlerin ortalaması:", ciftlertoplami / ciftsayilar)
fonksiyon(sayilar)
return wrapper
@ekstra
def ortalamabul(sayilar):
toplam = 0
for sayi in sayilar:
toplam += sayi
print("Genel Ortalama:", toplam / len(sayilar))
ortalamabul([1,2,3,4,34,60,63,32,100,105])
|
b8ad500126d1bae548ea97a24db27ac586995765 | rodrigoirm/Simple-GOE | /goe.py | 3,524 | 3.765625 | 4 | import numpy as np
import matplotlib.pyplot as plt
def create_matrices (total, N):
"""Generates an array of square random matrices whose entries are independent gaussian random variables with zero mean and unit std deviation.
Parameters:
total (int): total number of matrices.
N (int): sets the dimension of each matrix as NxN.
Returns:
np.array(matrices_list): an array of length "total" whose entries are NxN gaussian matrices.
"""
matrices_list = []
for k in range(total):
matrices_list.append(np.random.normal(0, 1, size=(N,N)))
return np.array(matrices_list)
def GOE (gens):
"""Turns an ensemble of gaussian random matrices into an Gaussian Orthogonal Ensemble.
Parameters:
ensemble (ndarray): an ndarray of random matrices whose shape is (total # of matrices, N, N)
Returns:
ensemble (ndarray): an ndarray of symmetric gaussian matrices whose shape is (total # of matrices, N, N).
"""
for k in range(gens.shape[0]):
gens[k] = ( gens[k] + np.transpose(gens[k]) )/2
return gens
def eigenval_goe (goe):
"""For each matrix in a Gaussian Orthogonal Ensemble, computes and lists the eigenvalues of said matrix in increasing order.
Parameters:
goe (ndarray): an ndarray of symmetric random matrices whose shape is (total of matrices, N, N).
Returns:
eigenvals: a list whose elements are the lists of eigenvalues of each matrix of goe.
"""
eigenvals = []
for k in range(goe.shape[0]):
eigenval_k = list(np.linalg.eigvals(goe[k])) #unsorted list of eigenvalues of the k-th matrix
sorted_eigvals = sorted(eigenval_k)
eigenvals.append(sorted_eigvals)
return eigenvals
def average (L):
"""Returns the arithmetic average of a non-empty list of floating-point numbers.
Parameters:
L (list): a list non-empty list of floating numbers.
Returns:
average(L) (float): arithmetic average of elements of L.
"""
average = sum(L)/len(L)
return average
def eigendiff (eigenlist, N):
"""Computes the difference between central eigenvalues of matrices of a GOE ensemble, divides these differences by their average and lists the result.
Parameters:
eigenlist (list): a list with the eigenvalues of an even number of gaussian orthogonal matrices.
N (integer): sets the dimension of the matrices.
Returns:
eigendiff (list): a list of the difference between central eigenvalues divided the average difference.
"""
eigendiff = []
for k,l in enumerate(eigenlist):
eigendiff.append(eigenlist[k][N//2] - eigenlist[k][N//2-1]) #Remember: Python starts counting at zero.
eigen_avrg = average(eigendiff)
eigendiff[:] = [diff/eigen_avrg for diff in eigendiff]
return eigendiff
def diffhist (points,farbe):
count, bins, ignored = plt.hist(points, 1000, density=True, color=farbe)
plt.plot(bins, np.pi * (bins/2) *
np.exp( - np.pi * (bins/2)**2 ),
linewidth=2, color='k')
return plt.show()
gens = create_matrices(15000,2)
ensemble = GOE(gens)
eigenvalues = eigenval_goe(ensemble)
goe_diff = eigendiff(eigenvalues, 2)
diffhist(goe_diff,'c')
gens2 = create_matrices(15000,4)
ensemble2 = GOE(gens2)
eigenvalues2 = eigenval_goe(ensemble2)
goe_diff2 = eigendiff(eigenvalues2, 4)
diffhist(goe_diff2,'m')
gens3 = create_matrices(15000,10)
ensemble3 = GOE(gens3)
eigenvalues3 = eigenval_goe(ensemble3)
goe_diff3 = eigendiff(eigenvalues3, 10)
diffhist(goe_diff3,'b') |
eba86c98206de6ac4418cc2d4e2a1021bac27c44 | psukhomlyn/Hillel_PythonAQA | /HW6/HW6-3.py | 499 | 4.15625 | 4 | """
Написать функцию is_prime, принимающую 1 аргумент — число от 2 до 1000,
и возвращающую True, если оно простое, и False - иначе.
"""
def is_prime(x):
if x < 2 or x > 1000:
return f'Number is out of range from 2 to 1000'
else:
for i in range(2, x):
if x % i == 0:
return f'Entered number is not prime'
return f'Entered number is prime'
print(is_prime(7))
|
61e85cc887e8f5a50f6e82f6cb73be7b79fd1957 | prkhrsrvstv1/DSAinPython | /Sorting/QuickSort.py | 535 | 3.84375 | 4 | """ Implements QuickSort """
# Sort A using quicksort
def quick_sort(A):
if len(A) <= 1:
return(A)
pivot = len(A)-1
for i in range(pivot-1, -1, -1):
if A[i] > A[pivot]:
swap(A, pivot, pivot-1)
if i != pivot-1:
swap(A, pivot, i)
pivot -= 1
A[:pivot] = quick_sort(A[:pivot])
A[pivot+1:] = quick_sort(A[pivot+1:])
return(A)
# Swap A[a] and A[b]
def swap(A, a, b):
A[a] = A[a] + A[b]
A[b] = A[a] - A[b]
A[a] = A[a] - A[b]
return
|
2c60a9285a25c4805276d1660791ea9c66dcde35 | shubhomedia/Learn_Python | /control/conditional_operation.py | 341 | 4.21875 | 4 | #This file for Conditional Statement like if then that.
nameinput = input("Enter your name: ")
print("welcome to Learn Python",nameinput)
question1 = input("what is your name ?\n")
if question1 == nameinput:
print("Thanks Acceptable:")
elif question1 == "Other":
print("Wrong Information,but go on")
else:
print("Wrong Answer") |
24f9360e93f580923e1ff5817bc24f09800f5274 | TouailabIlyass/python_sys | /db/dateAndTime.py | 1,707 | 3.84375 | 4 | import time,datetime
from datetime import date, timedelta,time
#exercice 1
print("****** exercice 1 ******")
print("Date et heure actuelles: " , datetime.datetime.now())
print("Année actuelle:", datetime.date.today().strftime("%Y"))
print("Mois de l'année: ", datetime.date.today().strftime("%B"))
print("Numéro de la semaine de l'année: ", datetime.date.today().strftime("%W"))
print("Jour de la semaine: ", datetime.date.today().strftime("%w"))
print("Jour de l'année: ", datetime.date.today().strftime("%j"))
print("Jour du mois: ", datetime.date.today().strftime("%d"))
print("Jour de la semaine: ", datetime.date.today().strftime("%A"))
#exercice 2
print("****** exercice 2 ******")
dt = date.today() - timedelta(5)
print('Date actuelle:',date.today())
print('5 jours avant la date actuelle:',dt)
#exercice 3
print("****** exercice 3 ******")
from datetime import datetime, time
def date_diff_in_seconds(dt2, dt1):
timedelta = dt2 - dt1
return timedelta.days * 24 * 3600 + timedelta.seconds
def dhms_from_seconds(seconds):
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
return (days, hours, minutes, seconds)
#Specified date
date1 = datetime.strptime('2015-01-01 01:00:00', '%Y-%m-%d %H:%M:%S')
#Current date
date2 = datetime.now()
print("\n%d days, %d hours, %d minutes, %d seconds" % dhms_from_seconds(date_diff_in_seconds(date2, date1)))
#exercice 4
print("****** exercice 4 ******")
def leap_year(y):
if y % 400 == 0:
return True
if y % 100 == 0:
return False
if y % 4 == 0:
return True
else:
return False
print(leap_year(2004))
print(leap_year(2018)) |
41159eb6bd04eeaf5593014c6820fcf7e30b5832 | Abhinav-Rajput/CodeWars__KataSolutions | /Python Solutions/spyGames.py | 437 | 3.5625 | 4 | def decrypt(code):
z = {0: ' '}
sum = 0
res = ''
arr = []
for i in range(1, 27):
z[i] = chr(i + 96)
codes = code.split()
for c in codes:
for a in c:
if a.isdigit():
sum += int(a)
if sum > 26:
sum = sum % 27
arr.append(sum)
sum = 0
for r in arr:
res += z[r]
return res
h = decrypt('x20*6<xY y875_r97L')
print(h)
|
7a871c8d1489e3a07de78e5f0fafef4d453eacfd | gerocha/algoritmos | /2/merge.py | 780 | 3.90625 | 4 | def merge(list, begin, middle, end):
n1 = middle - (begin + 1)
n2 = end - middle
list1 = []
list2 = []
for i in range(0, n1):
list1.append(list[begin+i-1])
for j in range(0, n2):
list2.append(list[middle+j])
list1.append('final')
list2.append('final')
i = 0
j = 0
print begin
print end
for k in range(begin, end):
if list1[i] <= list2[j]:
list[k] = list1[i]
i = i + 1
else:
list[k] = list2[j]
j = j + 1
return list
def merge_sort(list, begin, end):
if(begin < end):
q = (begin + end)/2
merge_sort(list, begin, q)
merge_sort(list, q + 1, end)
merge(list, begin, q, end)
merge_sort([0, 3, 8, 2, 1, 9], 0, 5)
|
685837112c9a218ca2e26479ba1ccd40fdde393d | matthew-maya-17/CSCI-1100-Computer-Science-1 | /CS-1100-labs/lab12files/lab12files/Check_1.py | 517 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 10 14:12:36 2019
@author: matth
"""
def add(m,n):
if n == 0:
return m
else:
return add(m,n-1) + 1
def multiply(x,y):
if(y == 0):
return 0
if(y > 0 ):
return (x + multiply(x, y - 1))
if(y < 0 ):
return -multiply(x, -y)
def power(x,n):
if n == 0:
return 1
else:
return power(x,n-1) * x
print(add(5,3))
print(multiply(8, 3))
print(power(6,3)) |
268bf5baa3d0b433c1e7352df3fca24f662bdb26 | yiparkar/Python | /codechef/sublist.py | 443 | 3.9375 | 4 | def is_sublist(f,s):
if s == []:
return True
elif f==s:
return True
elif len(f)<len(s):
return False
flag = False
for i in range(len(s)):
for j in range (len(f)):
if s[i] == f[j]:
flag= True
break
if flag == False:
break
return flag
f= [3,6,4,8]
s1= [5,8]
s2=[4,6]
print ( is_sublist(f,s1))
print ( is_sublist(f,s2))
|
472fca94c8beb8c93efeab8df48d0b536ad4b974 | Cicades/Python | /02-senior/12-元类的使用/02-使用metaclass动态创建类.py | 1,245 | 3.984375 | 4 | """利用元类的特性,将一个类中所有的属性变为大写(__开头的属性除外)"""
class MetaClass(type):
"""定义Metaclass类并继承type,那么该类也拥有创建其他类的对象的能力,所该类也成为元类"""
def __new__(cls, name, parents, attrs):
"""
name --> 类的名字
parents --> 父类(元组)
atts --> 属性(字典)
"""
new_attrs = dict()
for key, value in attrs.items():
if key.startswith('__'):
continue
else:
key = key.upper()
new_attrs[key] = value
else:
return super().__new__(cls, name, parents, new_attrs) # 调用type的__new__的方法类创建对象
# return type(name, parents, new_attrs)
class Test(object, metaclass=MetaClass):
class_name = 'Test'
class_info = '这是测试类'
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def print_intro(self):
print('I am %s, %d, %s' % (self.name, self.age, self.gender))
t = Test()
for key, value in t.__class__.__dict__.items():
print(key, value, sep='---->')
|
8b531810271646f9becc5cf4a6978e96652c0004 | AATopp/AllaT_Portfolio_Data_Scientist | /Python Practice problems/sum of numbs 1 and 10.py | 232 | 3.796875 | 4 | # Accept number from user and calculate the sum of all number between 1 and given number
# For example user given 10 so the output should be 55
summa = 0
n = int(input())
for i in range(1, n + 1):
summa += i
print(summa)
|
aa00cf3db952dbfa32a2240a65e55043f3836df6 | bogdanp05/Benchmark | /caller/config/parser.py | 2,691 | 3.8125 | 4 | import ast
def parse_string(parser, header, arg_name, arg_value):
"""
Parse an argument from the given parser. If the argument is not specified, return the default value
:param parser: the parser to be used for parsing
:param header: name of the header in the configuration file
:param arg_name: name in the configuration file
:param arg_value: default value, if the value is not found
"""
if parser.has_option(header, arg_name):
return parser.get(header, arg_name)
return arg_value
def parse_literal(parser, header, arg_name, arg_value):
"""
Parse an argument from the given parser. If the argument is not specified, return the default value
:param parser: the parser to be used for parsing
:param header: name of the header in the configuration file
:param arg_name: name in the configuration file
:param arg_value: default value, if the value is not found
"""
if parser.has_option(header, arg_name):
return ast.literal_eval(parser.get(header, arg_name))
return arg_value
def parse_list(parser, header, arg_name, arg_value):
"""
Parse an argument from the given parser. If the argument is not specified, return the default value
:param parser: the parser to be used for parsing
:param header: name of the header in the configuration file
:param arg_name: name in the configuration file
:param arg_value: default value, if the value is not found
"""
if parser.has_option(header, arg_name):
val = ast.literal_eval(parser.get(header, arg_name))
t = type(val)
if t == list or t == tuple:
return val
if t == int:
return [val]
return arg_value
def parse_benchmarks(parser, header, default):
"""
Parse an argument from the given parser. If the argument is not specified, return the default value
:param parser: the parser to be used for parsing
:param header: name of the header in the configuration file
:param default: default value, the the value is not found
"""
if parser.has_section(header):
return parser.items(header)
return default
def parse_bool(parser, header, arg_name, arg_value):
"""
Parse an argument from the given parser. If the argument is not specified, return the default value
:param parser: the parser to be used for parsing
:param header: name of the header in the configuration file
:param arg_name: name in the configuration file
:param arg_value: default value, the the value is not found
"""
if parser.has_option(header, arg_name):
return parser.get(header, arg_name) == 'True'
return arg_value
|
725372edf08f235198ae13e54b4016e3091f7e61 | Gabrielatb/Interview-Prep | /elements_of_programming/task_scheduler.py | 726 | 4.0625 | 4 | # Given a char array representing tasks CPU need to do.
# It contains capital letters A to Z where different letters
# represent different tasks.Tasks could be done without original order.
# Each task could be done in one interval. For each interval, CPU could finish
# one task or just be idle.
# However, there is a non-negative cooling interval n that means between two
# same tasks, there must be at least n intervals that CPU are doing different
# tasks or just be idle.
# You need to return the least number of intervals the CPU will take to
# finish all the given tasks.
# Example:
# Input: tasks = ["A","A","A","B","B","B"], n = 2
# Output: 8
# Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
|
b7dd1f8cdd7b110d34b511807f97ef371fc597f9 | upendar245/PCEP | /conditional.py | 97 | 3.859375 | 4 | #!env python3
name = input("what is your name")
if len(name) >= 6:
print("your name is long") |
f915c15cf65fdba868c5a6dc59041b5ac293e61e | RoguedBear/AutomateTheboringStuff | /tictactoe.py | 7,738 | 3.546875 | 4 | import copy
from os import system
board = {'1': '\x1b[2m1\x1b[0m', '2': '\x1b[2m2\x1b[0m', '3': '\x1b[2m3\x1b[0m',
'4': '\x1b[2m4\x1b[0m', '5': '\x1b[2m5\x1b[0m', '6': '\x1b[2m6\x1b[0m',
'7': '\x1b[2m7\x1b[0m', '8': '\x1b[2m8\x1b[0m', '9': '\x1b[2m9\x1b[0m'}
debug_number = board
# Initializing environmental variables. Geez.
X = '\x1b[1;31mX\x1b[0m'
O = '\x1b[1;32mO\x1b[0m'
human = X
computer = O
turn = X
# Prints out the board in a nice sweet format
def printBoard(game_board):
'''
Prints the gameboard
INPUT: game_board: takes the board data structure to print it out
'''
print('\t ' + game_board['1'] + ' | ' + game_board['2'] + ' | ' + game_board['3'])
print('\t-----------')
print('\t ' + game_board['4'] + ' | ' + game_board['5'] + ' | ' + game_board['6'])
print('\t-----------')
print('\t ' + game_board['7'] + ' | ' + game_board['8'] + ' | ' + game_board['9'])
# Checks the winning conditions function
def hasWon(game_board):
'''
Checks if the game board is in a winning state
INPUT: the game board
OUTPUT: winning Player
'''
# Check horizontals.
# Column 1
if game_board['1'] == game_board['4'] == game_board['7'] and game_board['1'] in [X, O]:
return game_board['1']
# Column 2
if game_board['2'] == game_board['5'] == game_board['8'] and game_board['2'] in [X, O]:
return game_board['2']
# Column 3
if game_board['3'] == game_board['6'] == game_board['9'] and game_board['3'] in [X, O]:
return game_board['3']
# Check verticals
# Row 1
if game_board['1'] == game_board['2'] == game_board['3'] and game_board['1'] in [X, O]:
return game_board['1']
# Row 2
if game_board['4'] == game_board['5'] == game_board['6'] and game_board['4'] in [X, O]:
return game_board['4']
# Row 3
if game_board['7'] == game_board['8'] == game_board['9'] and game_board['7'] in [X, O]:
return game_board['7']
# Check Diagonals
# D1
if game_board['1'] == game_board['5'] == game_board['9'] and game_board['1'] in [X, O]:
return game_board['1']
# D2
if game_board['7'] == game_board['5'] == game_board['3'] and game_board['2'] in [X, O]:
return game_board['7']
else:
return None
# Score each game
def Score(game_board):
'''
Returns the score of the board if it is in end stage
human wins: -1
computer wins: 1
tie: 0
INPUT: game_board
OUTPUT: the score
'''
players = {X: 'human', O: 'computer'}
result = hasWon(game_board)
if result is not None:
if players[result] == 'human':
# Human will minimise the computer, so negative.
return -1
elif players[result] == 'computer':
# Maximise computer, so positive
return 1
else:
# CHeck if gameboard is filled since, minmax.
for boardState in game_board.values():
if boardState not in [X, O]:
break
else:
return 'FULL'
return 0
# MINmax
def minimax(game_board, depth, isMaximising):
"""
Does the minimaxing here.
INPUT: game_board: the game board being used
depth: i think it was supposed to ensure recursion limit, but its not
used, and im not gonna remove this parameter for a little
while cuz im lazy.
isMaximising: BOOLEAN; Are we maximising or minimising
OUTPUT: bestScore: ∈ {-1, 0, 1}
"""
# Check if game is in end state:
board_evaluation = Score(game_board)
if board_evaluation == 'FULL': # For minimax to exit, ie the base case
return 0
if board_evaluation != 0: # game is in terminal state
return board_evaluation
# The game is not in end state if execution reaches here.
# Check available moves now.
# Available moves
available_moves = [i if game_board[i] not in [X, O] else 0 for i in game_board.keys()]
while True:
try:
available_moves.remove(0)
except ValueError:
break
# If we are Maximising
if isMaximising:
bestScore = float('-inf')
for move in available_moves:
board_ = copy.copy(game_board)
board_[move] = O
score = minimax(board_, depth + 1, False)
bestScore = max(bestScore, score)
else:
return bestScore
# If we are minimising
else:
bestScore = float('inf')
for move in available_moves:
board__ = copy.copy(game_board)
board__[move] = X
score = minimax(board__, depth + 1, True)
bestScore = min(bestScore, score)
else:
return bestScore
return bestScore
def computerPlays(game_board ):
'''
Computer will decide the best move using MINmax ::sunglasses::
INPUT: game_board: the game board data structure being used
OUTPUT: __optimal__ move
'''
# Available moves
available_moves = [i if game_board[i] not in [X, O] else 0 for i in game_board.keys()]
# Remove the zeroes. feels like, instead of list comprehension,
# I should have done an if/else for available moves. Computional Waste
while True:
try:
available_moves.remove(0)
except ValueError:
break
# Best score for the computer is currently -infinity
bestScore = float('-inf')
# Final/Best Move to play
bestMove = '1'
# Iterate through each move
for move in available_moves:
# Copy the gameboard first, cuz we don't want making changes to the actual gamebaord
copied_board = copy.copy(game_board)
copied_board[move] = O
score = minimax(copied_board, 0, False)
if score > bestScore:
bestScore = score
bestMove = move
print(f"COMPUTER: Best move acquired: {bestMove}\tWith bestScore: {score}")
return bestMove
# MAin game
system('clear')
print ("Welcome to TicTacToe!")
print (f"You are the the first player {X}.")
for i in range(5):
printBoard(board)
# Update Gameboard
## Validates the move entered
while True:
print("Turn for: " + turn + '. You would move on which space?')
move = input('\x1b[0;;40m> ')
print('\r\x1b[0m')
if move in '123456789' and move not in '':
if board[move] not in [X, O, '']:
board[move] = turn
break
else:
print("Place Already taken cheater.")
continue
else:
print("Not a valid move")
continue
# Check if game has ended.
end_game = hasWon(board)
# Check for ties because in the prev. verision, you run into trouble for the
# moveset: 3, 6, 1, 8 and boom you lose. because full board is not checked
# for ties
for j in board.values():
if j not in [X, O]:
break
else:
print("TIE!!")
break
if end_game is not None: #That means we have a victory
if end_game == human:
print("Human WINS!")
break
else:
print("YOU LOSE!!")
break
# Computer plays its part
board[computerPlays(board)] = O
# Now check endstate after computer's move
end_game = hasWon(board)
if end_game is not None: #That means we have a victory
if end_game == human:
print("Human WINS!")
break
else:
print("YOU LOSE!!")
break
# ASSUMING Linux, clearing screen
system('clear')
else:
# GAme is tie
print("TIE!!")
# The final print of the board.
printBoard(board)
|
73eab4b052430c61353b8e1ba3866e6bb2a8ce4c | HusanYariyev/Python_darslari | /46-masala.py | 170 | 3.5625 | 4 | def powerA3(a):
return a**3
A = 1.1
B = 2.2
C = 3.3
D = 1
E = 2
print(powerA3(A))
print(powerA3(B))
print(powerA3(C))
print(powerA3(D))
print(powerA3(E)) |
95775f6f23132f381db022e66b21428a724a79b6 | papatwo/PythonNoob | /basic_py/abs.py | 391 | 4.3125 | 4 | #!/usr/bin/env python
# print abs value of an int
a = 100
if a>= 0:
print a
else:
print -a
b = raw_input('enter an int: ') # raw_input prompt text not int
b = int(b) # convert text to int
if b >=0:
print 'the abs value is',b
else:
print 'the abs value is',-b
c = input('enter an int2: ') # input prompt int
if c >=0:
print 'the abs value is',c
else:
print 'the abs value is',-c
|
739129eda51493304aec63a3a2794d645cc8e7b3 | smithmj/cs123-final-project | /code/alignment.py | 14,544 | 3.71875 | 4 | import numpy as np
# The scoring system for the alignment
# algorithm.
# match between base pairs is +2
MATCH = 2
# a mismatch between base pairs
# is penalize -1
MISMATCH = -1
# a gap between base pairs is
# penalized -1
GAP = -1
class Cell:
# This class is for use in our grid of sequence alignment,
# each piece of information is later utilized in other functions
def __init__(self, val = 0, row = None, col = None, ref_allele = None, read_allele = None, prev = None):
# store the sequence aligment score for the cell
self.val = val
# stores the grid row position of the cell
self.row = row
# stores the grid column position of the cell
self.col = col
# the allele of the reference sequence corresponding to
# the column of the grid
self.ref_allele = ref_allele
# the allele of the read corresponding to the row
# of the grid
self.read_allele = read_allele
# gives the grid coordinates as a tuple for the cell that points
# to the current cell
self.prev = prev
# Returns the cell corresponding to the coordinate self.prev.
# Used in the traceback function to construct the alignment
# from the grid.
def get_prev_cell(self, grid):
if self.prev == None:
return None
prev_row = self.prev[0]
prev_col = self.prev[1]
prev_cell = grid[prev_row, prev_col]
return prev_cell
# The __lt__ and __eq__ methods sort the cell based on the
# value attribute and are used for the purpose of sorting
# in max functions
def __lt__(self, other):
return self.val < other.val
def __eq__(self, other):
if type(other) != Cell:
return False
return self.val == other.val
def __str__(self):
val_str = "val: {}\n".format(self.val)
coor_str = "coor: {}\n".format((self.row, self.col))
ref_allele_str = "ref allele: {}\n".format(self.ref_allele)
read_allele_str = "read allele: {}\n".format(self.read_allele)
prev_str = "prev: {}\n".format(self.prev)
string = val_str + coor_str + ref_allele_str + read_allele_str + prev_str
return string
def __repr__(self):
return self.__str__()
class SNP:
# This class stores information about Single Nucleotide Polymorphisms (SNPs)
def __init__(self, ref_allele, var_allele, ref_pos, coverage, prop):
# The reference allele
self.ref_allele = ref_allele
# The variant allele
self.var_allele = var_allele
# The position of the SNP. Stored as a tuple of (chromosome, base pair)
self.ref_pos = ref_pos
# This stores the number of reads that got mapped to the reference
# position. This can be used as a quality control measure: if the
# coverage is very low, then the alignment was not very reliable
self.coverage = coverage
# This stores the proportion of all the reads that were mapped
# to the reference position that were var_allele. This can be
# used as a quality control measure: if the proportion is low,
# the alignment may not be reliable.
self.prop = prop
def __str__(self):
if type(self.ref_pos[1]) == tuple:
# in this case the SNP is a gap
string = "chr{} {} {} ".format(self.ref_pos[0], self.ref_pos[1][0], self.ref_pos[1][1])
else:
string = "chr{} {} {} ".format(self.ref_pos[0], self.ref_pos[1], self.ref_pos[1])
string += "{} {} {} {}\n".format(self.ref_allele,self.var_allele,
self.coverage,self.prob)
return string
def __lt__(self, other):
if (self.ref_pos[0] > other.ref_pos[0]):
#chrom check
return False
elif (self.ref_pos[0] == other.ref_pos[0]):
return self.ref_pos[1] < other.ref_pos[1] #chrom_pos check if equal
else:
return True
def __repr__(self):
return self.__str__()
# This function takes a reference sequence and a 'read' sequence to compare to.
# If looking for a local sequence alignment the matrix is not allowed to be negative
# Otherwise the grid created is for global match only with negatives allowed
def place_read(ref_seq, read, local = False):
ref_len = len(ref_seq)
read_len = len(read)
grid = np.zeros((read_len + 1, ref_len + 1), dtype = object)
# the grid needs an extra column and row in the case that the alignment starts
# with a gap or multiple gaps
# double for loop sets up the initialization of the alignment matrix
for i in range(grid.shape[0]):
grid[i, 0] = Cell(ref_allele = ref_seq[0], read_allele = read[i-1])
if local:
grid[i, 0].val = max(0, GAP * i)
else:
grid[i, 0].val = GAP * i
grid[i, 0].row = i
grid[i, 0].col = 0
if i != 0:
grid[i, 0].prev = (grid[i-1, 0].row, grid[i-1, 0].col)
for j in range(1, grid.shape[1]):
grid[i, j] = Cell(ref_allele = ref_seq[j - 1], read_allele = read[i - 1])
grid[i, j].row = i
grid[i, j].col = j
if i == 0:
if local:
grid[i,j].val = max(0, GAP * j)
grid[i,j].prev = None
# this prev init sets up terminating condition for traceback (local)
else:
grid[i, j].val = GAP * j
grid[i, j].prev = (grid[i,j-1].row, grid[i,j-1].col)
else:
# This takes into account the three paths from which a value can be determined
# and selects the one with the highest value
ref_nucl = ref_seq[j-1]
read_nucl = read[i-1]
if ref_nucl == read_nucl:
diagonal = MATCH
else:
diagonal = MISMATCH
max_val = diagonal + grid[i-1, j-1].val
grid[i, j].prev = (grid[i-1, j-1].row, grid[i-1, j-1].col)
if GAP + grid[i-1, j].val > max_val:
max_val = GAP + grid[i-1, j].val
grid[i, j].prev = (grid[i-1, j].row, grid[i-1, j].col)
if GAP + grid[i, j-1].val > max_val:
max_val = GAP + grid[i, j-1].val
grid[i, j].prev = (grid[i, j-1].row, grid[i, j-1].col)
if local:
grid[i,j].val = max(0, max_val)
else:
grid[i,j].val = max_val
return grid
def find_start_cell(grid):
max_val = 0
start_cell = None
for i in range(grid.shape[0]):
for j in range(grid.shape[1]):
if grid[i,j].val >= max_val:
max_val = grid[i,j].val
start_cell = grid[i,j]
return start_cell
def find_alignment_score(grid):
start_cell = find_start_cell(grid)
return start_cell.val
# This function is designed to 'walk' through the matrix and give back a list of cells
# corresponding to the best alignment possible. In the case of local alignment we search the
# grid for the highest value and use the 'prev' values to traceback until we reach the top row.
# In a global alignment we start at the bottom right corner and continue until we reach the top left.
def traceback(grid, align_dict, local = False, chrom = None):
if local:
start = find_start_cell(grid[-1:,]) #we need to go over this again to make sure
else:
start = grid[-1,-1]
curr = start
while curr != None and curr.get_prev_cell(grid) != None:
# the grid creation makes sure that this terminating condition is correct
# it is incorrect to call this function with local = True when place_read had
# local = False
ref_seq_pos = curr.col
if chrom != None:
ref_seq_pos = (chrom, ref_seq_pos)
ref_seq_allele = curr.ref_allele
if (ref_seq_allele, ref_seq_pos) not in align_dict:
align_dict[(ref_seq_allele, ref_seq_pos)] = {}
prev_cell = curr.get_prev_cell(grid)
if curr.col == prev_cell.col:
# in this case there is a gap in the reference
insertion = curr.read_allele
curr = prev_cell
prev_cell = curr.get_prev_cell(grid)
while prev_cell != None and curr.col == prev_cell.col:
insertion = curr.read_allele + insertion
curr = prev_cell
prev_cell = curr.get_prev_cell(grid)
insertion = curr.read_allele + insertion
if insertion not in align_dict[(ref_seq_allele, ref_seq_pos)]:
align_dict[(ref_seq_allele, ref_seq_pos)][insertion] = 0
align_dict[(ref_seq_allele, ref_seq_pos)][insertion] += 1
curr = prev_cell
elif curr.row == prev_cell.row:
# in this case there is a gap in the read
nucl = "-"
if nucl not in align_dict[(ref_seq_allele, ref_seq_pos)]:
align_dict[(ref_seq_allele, ref_seq_pos)][nucl] = 0
align_dict[(ref_seq_allele, ref_seq_pos)][nucl] += 1
curr = prev_cell
else:
# in this case there are no gaps
nucl = curr.read_allele
if nucl not in align_dict[(ref_seq_allele, ref_seq_pos)]:
align_dict[(ref_seq_allele, ref_seq_pos)][nucl] = 0
align_dict[(ref_seq_allele, ref_seq_pos)][nucl] += 1
curr = prev_cell
return align_dict
# Givien the alignment dictionary, this function finds the genotype for
# each position in the reference genome.
def genotype(align_dict, save_file = None):
if save_file != None:
f = open(save_file, "w")
f.write("Ref-Position Ref-Allele Var-Allele Read-Coverage Proportion\n")
else:
snps = []
gap_snps = []
for (ref_allele, ref_pos) in align_dict:
max_val = 0
most_probable = None
coverage = 0
for allele in align_dict[(ref_allele, ref_pos)]:
# The genotype is determined by the allele with
# the highest count.
# The coverage identifies how many reads were aligned
# at this position. If the coverage is too low, the
# alignment may not be reliable.
coverage += align_dict[(ref_allele, ref_pos)][allele]
if align_dict[(ref_allele, ref_pos)][allele] >= max_val:
max_val = align_dict[(ref_allele, ref_pos)][allele]
most_probable = allele
# The proportion of the most-probable allele out of all
# the alleles that were aligned to this position of ref_seq.
# If prop is low, the alignment may not be reliable
prop = align_dict[(ref_allele, ref_pos)][most_probable] / coverage
if most_probable == '-':
snp = SNP(ref_allele, allele, ref_pos, coverage, prop)
gap_snps.append(snp)
# "N" is the symbol assigned asigned to alleles during the actual
# DNA sequencing when there is not enough information to determine
# the nucleotide. We are only interested in alleles that are
# "A", "G", "T", or "C" and positions where ref_allele is not the
# same as the ref_allele.
elif most_probable != "N" and ref_allele != "N" and most_probable != ref_allele:
snp = SNP(ref_allele, allele, ref_pos, coverage, prop)
if save_file != None:
f.write(str(snp))
else:
snps.append(snp)
# This command condenses all of the adjacent gap SNPs into a single SNP.
# For example, if there is a gap in the reads at chromosome 1 base at
# base pairs 1, 2, 3, only one SNP will be returned instead of three
# individual SNPs.
combined_gap_snps = gap_handler(gap_snps)
for snp in combined_gap_snps:
if save_file != None:
f.write(str(snp))
else:
snps.append(snp)
if save_file != None:
f.close()
return
else:
return snps
def avg(l):
return sum(l) / len(l)
# This function handles the special case of SNP gaps
def gap_handler(gaps):
gaps.sort()
glen = len(gaps)
i = 0
rv = []
while(i < glen - 1):
start = i
ra = ""
covs = []
props = []
while (gaps[i].ref_pos[0] == gaps[i+1].ref_pos[0] and gaps[i].ref_pos[1] == (gaps[i+1].ref_pos[1] - 1)): #on same chrom and adjacent
ra += gaps[i].ref_allele
covs.append(gaps[i].coverage)
props.append(gaps[i].prop)
i += 1
if (i == start):
rv.append(gaps[i])
else:
ra += gaps[i].ref_allele
covs.append(gaps[i].coverage)
props.append(gaps[i].prop)
print(ra)
print(len(ra))
var_allele = "-" * len(ra)
r = SNP(ra, var_allele,(gaps[i].ref_pos[0],(gaps[start].ref_pos[1],gaps[i].ref_pos[1])),avg(covs),avg(props))
rv.append(r)
i += 1
if (i == glen - 1):
# this checks if the last one was a singleton
rv.append(gaps[i])
return rv
# this function was used for testing purposes so we could visualize
# what an alignment looked like.
def print_alignment(align_dict, ref_seq):
align_list = []
for ref_allele, ref_pos in align_dict:
max_val = 0
most_probable = None
for allele in align_dict[(ref_allele, ref_pos)]:
if align_dict[(ref_allele, ref_pos)][allele] >= max_val:
max_val = align_dict[(ref_allele, ref_pos)][allele]
most_probable = allele
align_list.append((ref_pos, ref_allele, most_probable))
align_list.sort()
# this is the first position of the reference sequence that the
# read has been aligned to. If it is not 1, then there are initial
# gaps in the read sequence
ref_str = ""
read_str = ""
first_ref_pos = align_list[0][0][1]
for i in range(1, first_ref_pos):
ref_str += ref_seq[i - 1]
read_str += "-"
for i in range(len(align_list)):
ref_str += align_list[i][1]
print(ref_str)
for i in range(len(align_list)):
read_str += align_list[i][2]
print(read_str)
return
|
7802e87ce6cd55ee3395d91253baa33258431398 | HimavarshiniKeshoju/AI-Track-ML | /17K41A05F8-ANN-P10-3.py | 5,559 | 3.578125 | 4 | import pandas as pd
import numpy as np
data=pd.read_csv("D:\LoadDatainkW.csv")
data.head()
data.shape
#x=data[0:-1, 2]
#y=data[1:,2]
x = data.iloc[0:-1, 2]
y = data.iloc[1:, 2]
normalized_datax=(x-x.mean())/x.std()
normalized_datax
normalized_datay=(y-y.mean())/y.std()
normalized_datay
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(normalized_datax,normalized_datay,test_size = 0.10, random_state = 42)
def define_structure(X, Y):
input_unit = X.shape[0]
hidden_unit = 2394 # (1.5*1596)
output_unit = Y.shape[0]
return (input_unit, hidden_unit, output_unit)
(input_unit, hidden_unit, output_unit) = define_structure(X_train, y_train)
print("The size of the input layer is: = " + str(input_unit))
print("The size of the hidden layer is: = " + str(hidden_unit))
print("The size of the output layer is: = " + str(output_unit))
def parameters_initialization(input_unit, hidden_unit, output_unit):
np.random.seed(2)
W1 = np.random.randn(hidden_unit, input_unit)*0.01
b1 = np.zeros((hidden_unit, 1))
W2 = np.random.randn(output_unit, hidden_unit)*0.01
b2 = np.zeros((output_unit, 1))
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
return parameters
def sigmoid(z):
return 1/(1+np.exp(-z))
def forward_propagation(X, parameters):
W1 = parameters['W1']
b1 = parameters['b1']
W2 = parameters['W2']
b2 = parameters['b2']
Z1 = np.dot(W1, X) + b1
A1 = np.tanh(Z1)
Z2 = np.dot(W2, A1) + b2
A2 = sigmoid(Z2)
cache = {"Z1": Z1,"A1": A1,"Z2": Z2,"A2": A2}
return A2, cache
def cross_entropy_cost(A2, Y, parameters):
m = Y.shape[1]
logprobs = np.multiply(np.log(A2), Y) + np.multiply((1-Y), np.log(1 - A2))
cost = - np.sum(logprobs) / m
cost = float(np.squeeze(cost))
return cost
def backward_propagation(parameters, cache, X, Y):
#number of training example
m = X.shape[1]
W1 = parameters['W1']
W2 = parameters['W2']
A1 = cache['A1']
A2 = cache['A2']
dZ2 = A2-Y
dW2 = (1/m) * np.dot(dZ2, A1.T)
db2 = (1/m) * np.sum(dZ2, axis=1, keepdims=True)
dZ1 = np.multiply(np.dot(W2.T, dZ2), 1 - np.power(A1, 2))
dW1 = (1/m) * np.dot(dZ1, X.T)
db1 = (1/m)*np.sum(dZ1, axis=1, keepdims=True)
grads = {"dW1": dW1, "db1": db1, "dW2": dW2,"db2": db2}
return grads
def h(a,b,x):
return a*x+b
def mse(a,b,x,y):
return np.mean((h(a,b,x) - y)**2)
def gradient(a,b,x,y):
return np.mean(x*(a*x+b-y), axis=-1), np.mean(a*x+b-y, axis=-1)
def widrow_hoff(y, b, eta, theta, a, color):
k = 0
normalcount = 1
while True:
neweta = eta / normalcount
product = neweta * (b - np.dot(a, y[k]))
newvector = product * y[k]
newvalue = np.linalg.norm(newvector)
# print newvalue
a = a + newvector
if newvalue < theta:
break
normalcount += 1
k = (k + 1) % len(y)
x = np.array([0, 10])
y = (-a[0] - a[1] * x) / a[2]
plt.plot(x, y, color=color)
print a
return normalcount
m = 1 #Initial value of slope
c = -1 #Initial value of intercept
lr = 0.01 #Learning Rate
delta_m = 1 #Initialising Δm
delta_c = 1 #Initialising Δc
max_iters = 1000 #Maximum number of iterations
iters_count = 0 #Counting Iterations
def deriv(m_f, c_f, datax, datay):
m_deriv = 0
c_deriv = 0
for i in range(datax.shape[0]):
x, y = datax[i], datay[i]
m_deriv += (y-m_f*x-c_f)*x
c_deriv += (y-m_f*x-c_f)
m_deriv = -m_deriv/len(datax)
c_deriv = -c_deriv/len(datay)
return m_deriv, c_deriv
while iters_count < max_iters:
delta_m, delta_c = deriv(m, c, x_train, y_train)
delta_m = -lr * delta_m
delta_c = -lr * delta_c
m += delta_m
c += delta_c
iters_count += 1
print(f"Iteration: {iters_count}\tValue of m: {m}, \tValue of c: {c}")
print(f"\nThe local minima occurs at: {m}, {c}")
def neural_network_model(X, Y, hidden_unit, num_iterations = 1000):
np.random.seed(3)
input_unit = define_structure(X, Y)[0]
output_unit = define_structure(X, Y)[2]
parameters = parameters_initialization(input_unit, hidden_unit, output_unit)
W1 = parameters['W1']
b1 = parameters['b1']
W2 = parameters['W2']
b2 = parameters['b2']
for i in range(0, num_iterations):
A2, cache = forward_propagation(X, parameters)
cost = cross_entropy_cost(A2, Y, parameters)
grads = backward_propagation(parameters, cache, X, Y)
parameters =widrow_hoff(parameters, grads)
if i % 5 == 0:
print ("Cost after iteration %i: %f" %(i, cost))
return parameters
parameters = neural_network_model(X_train, y_train, 4, num_iterations=1000)
def prediction(parameters, X):
A2, cache = forward_propagation(X, parameters)
predictions = np.round(A2)
return predictions
predictions = prediction(parameters, X_train)
print ('Accuracy Train: %d' % float((np.dot(y_train, predictions.T) + np.dot(1 - y_train, 1 - predictions.T))/float(y_train.size)*100) + '%')
predictions = prediction(parameters, X_test)
print ('Accuracy Test: %d' % float((np.dot(y_test, predictions.T) + np.dot(1 - y_test, 1 - predictions.T))/float(y_test.size)*100) + '%') |
0313b5a4575c0389f32ab9ee81e9d2ed0d67fb8b | bwkeller/classwork | /phys761/phys761assign2.py | 1,423 | 3.84375 | 4 | #!/usr/bin/python
# Ben Keller
# October 2011
# Solution for Question 2 in Physics 761 Assignment 2
import numpy
import matplotlib.pyplot as plt
#The Lane Emden Equation, reformulated using the subsitution z=Dn' to be
#z' = -Dn^n - 2z/x
def LaneEmden(xi, Dn, z, n):
return -1.0*numpy.power(Dn, n)-(2.0/xi)*z
#This function is simply the Runge-Kutta 4th order method for solving ODEs.
#It solves for y' = func(x, y) at the point x=xf, and returns all the
#intermediate values
def rk4(func, h, x0, y0, z0, xf):
yn = y0
xn = x0
zn = z0
yvals = []
xvals = []
while xn < xf:
k1 = h*func(xn, yn, zn)
k2 = h*func(xn+0.5*h, yn+0.5*k1, zn)
k3 = h*func(xn+0.5*h, yn+0.5*k2, zn)
k4 = h*func(xn+h, yn+k3, zn)
zn += (k1 + k2 + k3 + k4)/6.0
yn += h*zn
xn += h
yvals.append(yn)
xvals.append(xn)
return (xvals, yvals)
if __name__ == "__main__":
#Define the n=1.5 and n=3.0 Lane Emden equations
lane1 = lambda x, y, z: LaneEmden(x, y, z, 1.5)
lane2 = lambda x, y, z: LaneEmden(x, y, z, 3.0)
#Calculate the points for the two solutions
(x1, y1) = rk4(lane1, 1e-5, 1-((1e-10)/6), 1, 0, 5)
(x2, y2) = rk4(lane2, 1e-5, 1-((1e-10)/6), 1, 0, 6)
#Plot the results
plt.plot(x1, y1, 'k-', label="n=1.5")
plt.plot(x2, y2, 'k--', label="n=3")
plt.legend()
plt.ylabel("$D_n$")
plt.xlabel("$\\xi$")
plt.title("Solutions to the Lane-Emden Equation")
plt.ylim((0,1))
plt.savefig("phys761assign2.pdf")
plt.show()
|
be83ebb5b4bf282bcec7a4a18fc61b7a0ad68be9 | aindrila2412/DSA-1 | /Stack/nearest_smaller_to_right.py | 1,298 | 3.859375 | 4 | class Stack:
def __init__(self):
self.stack = []
def is_empty(self):
return len(self.stack) == 0
def pop(self):
if self.is_empty():
raise Exception("Stack is empty.")
return self.stack.pop()
def push(self, elm):
self.stack.append(elm)
def top(self):
if self.is_empty():
return None
return self.stack[-1]
def next_smaller(arr):
arr_size = len(arr)
s = Stack()
result = []
for i in range(arr_size - 1, -1, -1):
if s.is_empty():
result.append(-1)
elif not s.is_empty() and arr[i] > s.top():
result.append(s.top())
elif not s.is_empty() and arr[i] <= s.top():
while not s.is_empty() and arr[i] <= s.top():
s.pop()
if s.is_empty():
result.append(-1)
else:
result.append(s.top())
s.push(arr[i])
result.reverse()
return result
def test_nsr():
a_1 = [4, 8, 5, 2, 25]
r_a_1 = [2, 5, 2, -1, -1]
assert next_smaller(a_1) == r_a_1, "Test case: 1 failed."
a_2 = [1, 6, 4, 10, 2, 5]
r_a_2 = [-1, 4, 2, 2, -1, -1]
assert next_smaller(a_2) == r_a_2, "Test case: 2 failed."
if __name__ == "__main__":
test_nsr()
|
56a90cb7cf3e2ec9ac92f342c8ea52510577ae2f | yuanhawk/Digital-World | /Python Project/Wk 2 In Class Activities + Homework/Largest Number.py | 143 | 3.96875 | 4 | def is_larger(n1, n2):
if n1 > n2:
return True
else:
return False
print(is_larger(2, -1))
print(is_larger(-1, 2))
print(is_larger(2, 2)) |
84948a182ca63d9b0a586f66f2d61acccd32c4ff | saqibzia-dev/DSA | /Practice/8 Oxygen Value.py | 1,291 | 4.34375 | 4 | """
The selection of MPCS exams includes a fitness test which is conducted on the ground.
There will be a batch of 3 trainees, appearing for a running test on track for 3 rounds.
You need to record their oxygen level after every round.
After trainees are finished with all rounds, calculate for each trainee his average oxygen
level over the 3 rounds and select the one with the highest average oxygen level as the fittest trainee.
If more than one trainee attains the same highest average level, they all need to be selected. Display the
fittest trainee(or trainers) and the highest average oxygen level.
"""
T1 = int(0)
T2 = int(0)
T3 = int(0)
count = int(0)
while(count<9):
x=int(input())
if(x>=1 and x<=100):
if(count%3==1):
T1=T1+x
elif(count%3==2):
T2=T2+x
else:
T3=T3+x
count=count+1
else:
print("INVALID INPUT")
exit()
A1 = round(T1/3)
A2 = round(T2/3)
A3 = round(T3/3)
print(A1,A2,A3)
if(A1 <= 70 and A2 <= 70 and A3 <= 70):
print("All trainees are unfit")
exit()
if(A1 >= A2 and A1>= A3):
print("Trainee Number: 1")
if(A2 >= A1 and A2 >= A3):
print("Trainee Number: 2")
if(A3 >= A1 and A3 >= A2):
print("Trainee Number: 3") |
5519187c968157756a35dba6695a090410b5506c | lpawlak1/WDI | /Cwiczenia 7/cw16.py | 1,295 | 3.78125 | 4 | null = None
class Node:
def __init__(self, value=null, next=null):
self.val = value
self.next = next
def __str__(self):
return f"{self.val}-->"
def wypisz(first):
if first == null:
print("List is empty!")
while first != null:
print(first, end='')
first = first.next
print()
# 16. Proszę napisać funkcję, która otrzymując jako parametr wskazujący na
# początek listy jednokierunkowej, przenosi na początek listy te z nich,
# które mają parzystą ilość piątek w zapisie ósemkowym.
def ile_5(num):
ilosc = 0
while num != 0:
if num % 8 == 5:
ilosc += 1
num //= 8
return ilosc
def move(first, cp, cp2):
cp.next = cp2.next
cp2.next = first
return cp2
def check(first):
if first == null:
return null
if first.next == null:
return first
cp, cp2 = first, first.next
while cp2 != null:
if ile_5(cp2.val) % 2 == 0:
first = move(first, cp, cp2)
cp2 = cp.next
else:
cp, cp2 = cp2, cp2.next
return first
first = Node(1)
for i in range(10):
a = Node(5, first)
first = a
wypisz(first)
wypisz(check(first))
|
fc9b28e7aabbb2c099ee32236bce3825865bd1a7 | xiangcao/Leetcode | /python_leetcode_2020/Python_Leetcode_2020/160_intersection_of_two_linked_lists.py | 2,039 | 4.25 | 4 | Write a program to find the node at which the intersection of two singly linked lists begins.
"""
Approach 3: Two Pointers
Maintain two pointers pApA and pBpB initialized at the head of A and B, respectively. Then let them both traverse through the lists, one node at a time.
When pApA reaches the end of a list, then redirect it to the head of B (yes, B, that's right.); similarly when pBpB reaches the end of a list, redirect it the head of A.
If at any point pApA meets pBpB, then pApA/pBpB is the intersection node.
To see why the above trick would work, consider the following two lists: A = {1,3,5,7,9,11} and B = {2,4,9,11}, which are intersected at node '9'. Since B.length (=4) < A.length (=6), pBpB would reach the end of the merged list first, because pBpB traverses exactly 2 nodes less than pApA does. By redirecting pBpB to head A, and pApA to head B, we now ask pBpB to travel exactly 2 more nodes than pApA would. So in the second iteration, they are guaranteed to reach the intersection node at the same time.
If two lists have intersection, then their last nodes must be the same one. So when pApA/pBpB reaches the end of a list, record the last element of A/B respectively. If the two last elements are not the same one, then the two lists have no intersections.
Complexity Analysis
Time complexity : O(m+n)
Space complexity : O(1).
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
#boundary check
if(headA == None or headB == None): return None
a = headA
b = headB
#if a & b have different len, then we will stop the loop after second iteration
while( a != b):
#for the end of first iteration, we just reset the pointer to the head of another linkedlist
a = headB if a is None else a.next
b = headA if b is None else b.next
return a
|
065cc28371581325b72e576aaa632c20fdccd2f2 | GG-Bonds/--- | /rename_catalogue.py | 743 | 3.53125 | 4 | import os
'''
修改图片目录名
'''
def getNumber(mystr: str): # 获取目录的位置 形式为 001 023这类的, 便于排序
length = len(mystr)
zeros = '0' * (3 - length)
mystr = zeros + mystr
return mystr
url = '/Users/jiangchengyin/Downloads/imgs'
catalogue = os.listdir(url)
catalogue.sort()
length_catalogue = len(catalogue)
for i in range(length_catalogue):
dir_name = catalogue[i]
dir_url = os.path.join(url, dir_name)
if os.path.exists(dir_url) and dir_url != '/Users/jiangchengyin/Downloads/imgs/.DS_Store':
new = getNumber(str(i)) + '_' + dir_name.split('_')[-1]
# new = dir_name.split('_')[-1]
newurl = os.path.join(url, new)
os.rename(dir_url, newurl)
|
e90c42f165efee17d4292e248fdafe3fb64bc93a | ShreyaRawal97/data-structures | /Recursion/Palindrome_checker.py | 647 | 4.125 | 4 | def reverse_string(input):
if len(input) == 0:
return ""
first_char = input[0]
the_rest = slice(1, None)
sub_string = input[the_rest]
reversed_substring = reverse_string(sub_string)
return reversed_substring + first_char
def is_palindrome(input):
if input == reverse_string(input):
return True
return False
# Test Cases
print ("Pass" if (is_palindrome("")) else "Fail")
print ("Pass" if (is_palindrome("a")) else "Fail")
print ("Pass" if (is_palindrome("madam")) else "Fail")
print ("Pass" if (is_palindrome("abba")) else "Fail")
print ("Pass" if not (is_palindrome("Udacity")) else "Fail")
|
5256466d4ba0c3f1bf31978d92a9e1c99ecf40c4 | Bhumireddysravani/sravani | /palindrome.py | 153 | 3.5625 | 4 | s=int(input(""))
rev=0
temp=s
while(s>0):
val=s%10
rev=rev*10+val
s=s//10
if(temp==rev):
print("yes")
else:
print("no")
|
ae2a91ae94938a6c656063bcb002793433575c5c | johnnymast/Raspberry-pi-3B | /projects/blinkuserchoice/blinkuserchoice.py | 882 | 3.828125 | 4 | #!/usr/bin/python
import RPi.GPIO as GPIO
import time
import os;
# Set board mode this means real counting the pins
GPIO.setmode(GPIO.BOARD)
GPIO.cleanup()
# Set pin 7 and 11 to accept output
GPIO.setup(7,GPIO.OUT) # Red
GPIO.setup(11,GPIO.OUT) # Green
try:
os.system('clear')
print "Which LED would you like to blink"
print "1: Green?"
print "2: Red?"
led_choice = int(raw_input("Choose your option: "))
times = int(raw_input("How many times: "))
led = 11 # Default green
if led_choice == 2:
print 'red'
led = 7
else:
led = 11
for count in range(0, times):
GPIO.output(led, GPIO.HIGH)
# Wait a half second
time.sleep(0.5)
# Set pin to low meaning power off
GPIO.output(led, GPIO.LOW)
# Wait 1 second
time.sleep(0.5)
finally:
GPIO.cleanup()
|
163751f87293cc0cb4fe19dcec0e477fc26f2714 | whyismefly/learn-python | /100/100-41.py | 455 | 3.90625 | 4 | #!/usr/bin/python
# encoding:utf_8
# 题目:模仿静态变量的用法。
# 程序分析:无。
def varfunc():
var=0
print 'var=%d'%var
var+=1
if __name__=='__main__':
for i in range(3):
varfunc()
# 类的属性
# 作为类的一个属性吧
class Static:
StaticVar=5
def varfunc(self):
self.StaticVar+=1
print self.StaticVar
print Static.StaticVar
a=Static()
for i in range(3):
a.varfunc()
|
2dc273582f4c67aae93ee1d2458b75535df33190 | BAGPALLAB7/HackerRank-Solutions-Python3 | /HackerRank - Problem Solving/making_anagram_hackerrank.py | 695 | 3.703125 | 4 | a='fcrxzwscanmligyxyvym'
b='jxwtrhvujlmrpdoqbisbwhmgpmeoke'
def buildMap(s):
the_map = {}
for char in s:
if char not in the_map:
the_map[char] = 1
else:
the_map[char] +=1
return the_map
def anagram(s1, s2):
map1 = buildMap(s1)
map2 = buildMap(s2)
diff_cnt = 0
for key in map2.keys():
if key not in map1:
diff_cnt += map2[key]
else:
diff_cnt += max(0, map2[key]-map1[key])
for key in map1.keys():
if key not in map2:
diff_cnt += map1[key]
else:
diff_cnt += max(0, map1[key]-map2[key])
return diff_cnt
res=anagram(a,b)
print(res)
|
3cac5e9a8a613943b4b09494a31d90fd51017b18 | Madisonjrc/csci127-assignments | /lab_02/fizzbuzz.py | 509 | 4.125 | 4 | #fizzbuzz
#if number divisible by 3 print fizz
#if number divisible by 5 print buzz
#if both print both
#Madison Chen and Narsima Donuk
def fizzbuzz(max_value):
count=0
while count <= max_value:
if count % 15 == 0 :
print ("FizzBuzz")
elif count % 3 == 0:
print ("Fizz")
elif count % 5 == 0:
print ("Buzz")
else:
print (count)
count = count + 1
return "there are "+ str(max_value // 15) + " FizzBuzz"
print(fizzbuzz(100)) |
d46054d6f12fb1140e5db12b87a461d140910079 | Nayalash/ICS3U-Problem-Sets | /Problem-Set-Three/mohammad_zodiac.py | 1,726 | 4.46875 | 4 | # Author: Nayalash Mohammad
# Date: October 01 2019
# File Name: zodiac.py
# Description: A program that displays your
# zodiac sign based on your birthday
# Ask user for their birthday
try:
day = int(input("Enter Birth Day: "))
month = int(input("Enter Month In Number Format (ex: September = 9) "))
except ValueError:
print("Invalid Input")
# Use Zodiac Algorithm
if month == 12: # December
if (day < 22):
sign = 'Sagittarius'
else:
sign = 'Capricorn'
elif month == 1: # January
if (day < 20):
sign = 'Capricorn'
else:
sign = 'Aquarius'
elif month == 2: # February
if (day < 19):
sign = 'Aquarius'
else:
sign = 'Pisces'
elif month == 3: # March
if (day < 21):
sign = 'Pisces'
else:
sign = 'Aries'
elif month == 4: # April
if (day < 20):
sign = 'Aries'
else:
sign = 'Taurus'
elif month == 5: # May
if (day < 21):
sign = 'Taurus'
else:
sign = 'Gemini'
elif month == 6: # June
if (day < 21):
sign = 'Gemini'
else :
sign = 'Cancer'
elif month == 7: # July
if (day < 23):
sign = 'Cancer'
else:
sign = 'Leo'
elif month == 8: # August
if (day < 23):
sign = 'Leo'
else:
sign = 'Virgo'
elif month == 9: # September
if (day < 23):
sign = 'Virgo'
else:
sign = 'Libra'
elif month == 10: # October
if (day < 23):
sign = 'Libra'
else:
sign = 'Scorpio'
elif month == 11: # November
if (day < 22):
sign = 'Scorpio'
else:
sign = 'Sagittarius'
# Print the result to the console
print("The Astrological sign for your birthday is: " + sign) |
9d27c010eedda0a7a9c9313a35fd108e35392a7f | zdikov/parallel-news | /exceptions.py | 1,304 | 3.796875 | 4 | class BaseApplicationError(Exception):
pass
class RequestError(BaseApplicationError):
"""Raised when request to the website is not successful."""
def __init__(self, url: str, message="Request to the website %s failed"):
self.url = url
self.message = message
super().__init__(self.message)
def __str__(self):
return self.message % self.url
class ParseError(BaseApplicationError):
"""Raised for unsuccessful parsing."""
def __init__(
self,
parser: str,
parser_message: str,
message="Parser %s raised an error with the following message:\n%s",
):
self.parser = parser
self.parser_message = parser_message
self.message = message
super().__init__(self.message)
def __str__(self):
return self.message % (self.parser, self.parser_message)
class WrongNumberOfArguments(BaseApplicationError):
"""Raised when wrong number of arguments passed."""
def __init__(
self, expected: int, got: int, message="Expected %d arguments, but %d got"
):
self.expected = expected
self.got = got
self.message = message
super().__init__(self.message)
def __str__(self):
return self.message % (self.expected, self.got)
|
36eb8354a6abcb60bc316717a5ef9a10fde1358b | janstein123/lrc_rhythm | /test.py | 323 | 3.65625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import threading
from time import sleep
def run(name, sec):
sleep(sec)
print name, ' run'
threads = []
for i in range(10):
t = threading.Thread(target=run, args=("t"+str(i), 2))
t.start()
# t.join()
# for t in threads:
# print 'join'
# t.join()
|
4788d6da6c709911ea5272fdc4ac1f230dd5f766 | zantaclaus/2021s-CodingDaily | /Day023-Kate.py | 216 | 3.734375 | 4 | lst = [1, 2, 3 ,4] # pair 1-2 ---> [2]*1 | pair 3-4 --->[4]*3 ---> output [2, 4, 4, 4]
ans = []
for i in range(0, len(lst), 2):
print("time", i)
for j in range(i+1):
ans.append(lst[i+1])
print(ans) |
7e42647c8e83b9c95b810e89f5c75752ed2454d4 | marekkulesza/Daily-Questions | /Daily question1.py | 156 | 3.703125 | 4 | string = str("Camle Camel Camel")
newstring = string.title()
newnewstring = newstring[0].lower() + newstring[1:]
print(newnewstring.replace(" ", "")) |
86bb3d85014c303a210b851ff86e430fb2cd9ada | odair-pedroso/Nanodegree-Python | /09_funçao_split.py | 448 | 4.03125 | 4 | #-*- coding: utf-8 -*-
#transformando uma variavel contendo uma string em uma variavel contendo a string em elementos lista:
string1 = "Yesterday, PERSON and I went to the PLACE. On our way, we saw a ADJECTIVE NOUN on a bike."
string2 = "PLACE is located on the ADVERB side of Dublin, near the mainly ADJECTIVE areas of PLACE."
list_of_words1 = string1.split()
list_of_words2 = string2.split()
print list_of_words1
print list_of_words2
|
b185571b11752e1f64f028c7c80923e241ffb247 | chintu0019/DCU-CA146-2021 | /CA146-test/markers/add-ten-numbers.py/add-ten-numbers.py | 671 | 4.0625 | 4 | #!/usr/bin/env python3
total = 0
total = total + int(input())
total = total + int(input())
total = total + int(input())
total = total + int(input())
total = total + int(input())
total = total + int(input())
total = total + int(input())
total = total + int(input())
total = total + int(input())
total = total + int(input())
print(total)
# Each assignment, above, reads in a new number and adds it to the existing
# total. We do that ten times.
#
# An alternative would be to begin by reading in ten numbers, and then add
# them up.
#
# However, in my opinion (SB), the approach is above is clearer. (It's also
# easier to write because we can just use cut and paste.)
|
a3ff76063777fa3a89577103c0f0d1d1bc385d15 | adishavit/cvxpy | /cvxpy/utilities/deterministic.py | 287 | 3.875 | 4 | def unique_list(duplicates_list):
"""Return unique list preserving the order.
https://stackoverflow.com/a/58666031/1002277
"""
used = set()
unique = [x for x in duplicates_list
if x not in used and
(used.add(x) or True)]
return unique
|
6a7b441eef66d828a53ec8d48f7ca628631504dc | FlorCorrado/fundamentosInformatica | /trabajoPractico2/tp2Ejercicio3.py | 360 | 3.984375 | 4 | from math import pi
r = int(input("Ingrese la longitud del radio del circulo: "))
print("La superficie del circulo es igual a: ", (pi * r ** 2))
print("El perímetro de la circunferencia es igual a: ", (pi * (r * 2)))
print("La superficie de la esfera es igual a: ", (4 * pi * r ** 2))
print("El volúmen de la esfera es igual a: ", (4/3 * pi * r ** 3))
|
b1897488cbf27d4db10e01c5d2249f30a1f5153d | thomastri/PythonTools | /pw.py | 1,985 | 3.8125 | 4 | __author__ = 'tle'
# pw.py - An insecure password locker. Enter your Username, and it will copy the password to your clipboard.
import sys
import os.path
import pyperclip
import pickle
filepath = "pword.p"
if os.path.exists(filepath) is False:
passwords = {}
with open(filepath, 'wb') as f:
pickle.dump(passwords, f)
passwords = pickle.load(open(filepath, "rb"))
def save(): # saves to file
pickle.dump(passwords, open(filepath, "wb"))
def add_new():
print("Enter new username:")
username = input()
if username in passwords:
print("Username '" + str(username) + "' already exists!\n")
else:
print("Enter password:")
password = input()
passwords[str(username)] = str(password)
print("Account '" + username + "' successfully added.\n")
def remove_account():
print("Enter username to delete:")
delete_username = input()
print("Are you sure you want to delete '" + str(delete_username) + "'? YES / NO.")
agree = str(input()).upper()
if agree == "YES":
del passwords[delete_username]
print("'" + str(delete_username) + "' successfully removed.\n")
elif agree == "NO":
print("'" + str(delete_username) + "' was not removed.\n")
else:
print("Invalid command.")
sys.exit()
def copy_pw():
print("Enter desired username: ")
account = input()
if account in passwords:
pyperclip.copy(passwords[account])
print('Password for ' + account + ' copied to clipboard.\n')
else:
print('There is no account named ' + account + "\n")
def __main__():
print("Select a number:\n1. Retrieve Password\n2. Add Account\n3. Remove Account\n4. Exit\n")
selection = int(input())
if selection is 1:
copy_pw()
elif selection is 2:
add_new()
elif selection is 3:
remove_account()
else:
sys.exit()
save()
__main__() # allows for continuation
__main__()
|
d3056f5cfffef3032985f99ea0a2d07b59f0e79b | danielstaikov/HackerRank | /Text Wrap.py | 227 | 3.6875 | 4 | import textwrap
def wrap(string, max_width):
wraped = textwrap.wrap(string, max_width)
print(*wraped, sep="\n")
return "\n"
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result) |
f88f90abe4da7a9fb2f95832f00113ec4038a8f9 | D-Bits/Python-Practice | /Practice/10-5/math-practice.py | 431 | 4.25 | 4 | #multiplication
num1=5
num2=7
product= num1 * num2
print(product)
#division
quotient = 23 / 3
print (quotient)
#integer division
quotient = 23 // 3
print(quotient)
#remainders
remainder=23 % 3
print(remainder)
#evaluate
number = eval(input("enter a number"))
square = number * number
print(square)
#float
number = float(input("Enter a number"))
#integers
number = int(input("Enter a number"))
|
78955e1f9341569896b60019a254e132a85e43af | Pegasust/Python-Br-fuck-Interpreter | /bf.py | 16,734 | 3.5 | 4 | """
bf.py
Notes:
Each cell holds arbitrary length signed integer because of language
specification.
There is no way to delete a memory of a cell to save memory once it is
initialized.
Logic_God please help with my memory usage from Python. If there is
one way to optimize memory usage and performance overhead from coding
in Python, please tell me.
"""
import time
import logging
from collections import deque
import sys
from typing import *
def bf_init(bf):
# 32 cells of 0 to start with
bf.allocated = 1
bf.cells = [0] * 32
bf.cell_ptr = 0
bf.stdout = ""
bf.stack = deque()
bf.steps = 0
class Brainfork:
def __init__(self, dict_, conversion_func_ptr,
left_right_bracket:tuple, init_ptr = bf_init):
self.dict_char_func_ptr = dict_
self.dict_func_char = dict((v,k) for k,v in dict_.items())
self.symbol_conversion_ptr = conversion_func_ptr
self.init_ptr = init_ptr
self.l_r_tuple = left_right_bracket
def _clean(self, symbol_collection):
cleaned = list(filter(lambda char:char in self.dict_char_func_ptr,
symbol_collection))
return cleaned
def _get_plus(self):
return self.dict_func_char[bf_increment]
def _get_minus(self):
return self.dict_func_char[bf_decrement]
def _clean_op(self, symbol_collection):
cleaned = list()
pos = 0
add_num = 0
adding_sequence_triggered = False
while pos < len(symbol_collection):
if symbol_collection[pos] not in self.dict_char_func_ptr:
pos += 1
continue
while pos < len(symbol_collection):
if symbol_collection[pos] == self.dict_func_char[bf_increment]:
add_num += 1
elif symbol_collection[pos]==self.dict_func_char[bf_decrement]:
add_num -= 1
else:
break
adding_sequence_triggered = True
pos += 1
if adding_sequence_triggered:
if add_num == 0:
continue
if add_num > 0:
cleaned.append(self._get_plus())
else:
cleaned.append(self._get_minus())
cleaned.append(chr(abs(add_num)))
add_num = 0
adding_sequence_triggered = False
continue
cleaned.append(symbol_collection[pos])
pos += 1
return cleaned
def peek_program(self):
cell_str = "cell:["
for i in range(self.allocated):
elem_str=f"{self.cells[i]}"
if i == self.cell_ptr:
elem_str = "<<{}>>".format(elem_str)
cell_str+="{}, ".format(elem_str)
if len(self.cells) > self.allocated:
back_str = f"...({len(self.cells)-self.allocated} more allocated)]"
else:
back_str = "] len = {}".format(len(self.cells))
cell_str+= back_str
std_out = "stdout: \"{}\"".format(self.stdout)
return "{}\n{}".format(cell_str, std_out)
def peek_details(self):
cell_str = "cell:["
for i in range(len(self.cells)):
elem_str=f"{self.cells[i]}\"{chr(self.cells[i])}\""
if i == self.cell_ptr:
elem_str = "<<{}>>".format(elem_str)
cell_str+="{}, ".format(elem_str)
cell_str+="...]"
std_out = "stdout: \"{}\"".format(self.stdout)
steps = "steps: {}".format(self.steps)
return "{}\n{}\n{}".format(cell_str, std_out, steps)
def compare(self, raw_str):
print("==========EXECUTE============")
self.execute(raw_str,False, True)
print("=========EXECUTE_OP==========")
self.execute_op(raw_str, False, True)
def execute(self, raw_string, trace = False, print_immediately = False):
start = time.time()
functional_symbols = self._clean(self.symbol_conversion_ptr(
raw_string))
self.init_ptr(self)
code_position = [0]
while code_position[0] < len(functional_symbols):
exception_msg=(self.dict_char_func_ptr[
functional_symbols[code_position[0]]](
self, code_position, functional_symbols, print_immediately))
if exception_msg is not None:
logging.error(exception_msg)
print(self.peek_details())
print("Code position: {}".format(code_position[0]))
break
if trace:
print(self.peek_program())
self.steps += 1
end = time.time()
print("============== INFO ===============")
# print(self.stdout)
print("clean: {}".format(' '.join(functional_symbols)))
print(self.peek_details())
print("Active commands: {}".format(len(functional_symbols)))
print("Word count: {}".format(len(self.stdout)))
print("Cells allocated: {}".format(self.allocated))
print("Time took: {} secs".format(end-start))
print("============= END INFO =============")
return self.stdout
def execute_op(self, raw_string, trace = False, print_imm = False):
"""
A more optimized execution by grouping many commands into
an iterative and modern-hardware-friendly one
Ex: ++++++++++++++++ -> +"\x16"
Ex: +- -> ''
"""
start = time.time()
# Clean the code and optimize it out
functional_symbols = self._clean_op(self.symbol_conversion_ptr(
raw_string))
# Remap functions
add_chr = self._get_plus()
minus_chr = self._get_minus()
self.op_dict = dict(self.dict_char_func_ptr)
self.op_dict[add_chr] = bf_inc_op
self.op_dict[minus_chr] = bf_dec_op
self.init_ptr(self)
code_position = [0]
while code_position[0] < len(functional_symbols):
# Execute the command, store the exception message
exception_msg=(self.op_dict[
functional_symbols[code_position[0]]](
self, code_position, functional_symbols, print_imm))
# There is an error in the code.
if exception_msg is not None:
logging.error(exception_msg)
print(self.peek_details())
print("Code position: {}".format(code_position[0]))
break
if trace:
print(self.peek_program())
self.steps += 1
end = time.time()
print("============== INFO ===============")
# print(self.stdout)
print("clean: {}".format(' '.join(functional_symbols)))
print(self.peek_details())
print("Active commands: {}".format(len(functional_symbols)))
print("Word count: {}".format(len(self.stdout)))
print("Cells allocated: {}".format(self.allocated))
print("Time took: {} secs".format(end-start))
print("============= END INFO =============")
return self.stdout
# Brainfuck basic functions: ==================================================
def bf_right_ptr_shift(bf:Brainfork, code_position:List[int],
*useless_args):
# Shift it to the right
bf.cell_ptr += 1
if bf.cell_ptr >= bf.allocated:
bf.allocated += 1
if bf.cell_ptr >= len(bf.cells):
# append a new int into the active cells
bf.cells.append(0)
code_position[0] += 1
return None
def bf_left_ptr_shift(bf:Brainfork, code_position:List[int],
*useless_args):
bf.cell_ptr -= 1
if bf.cell_ptr < 0:
return "Attempting to access negative-indexed cell. Undefined behavior."
code_position[0] += 1
return None
def bf_increment_uni(bf:Brainfork, code_position:List[int], functional_symbols,
*u):
bf.cells[bf.cell_ptr] += 1
code_position[0] += 1
return None
def bf_decrement_uni(bf:Brainfork, code_position:List[int], functional_symbols,
*u):
bf.cells[bf.cell_ptr] -= 1
code_position[0] += 1
return None
def bf_increment(bf:Brainfork, code_position:List[int], functional_symbols,
*u):
bf.cells[bf.cell_ptr] += 1
if bf.cells[bf.cell_ptr] == 256:
bf.cells[bf.cell_ptr] = 0
code_position[0] += 1
return None
def bf_inc_op(bf: Brainfork, code_position:List[int], optimized_symbols, *u):
operand = ord(optimized_symbols[code_position[0]+1])
bf.cells[bf.cell_ptr] += operand
bf.cells[bf.cell_ptr] %= 256
code_position[0] += 2
return None
def bf_dec_op(bf: Brainfork, code_position:List[int], optimized_symbols, *u):
operand = (ord(optimized_symbols[code_position[0]+1])) % 256
bf.cells[bf.cell_ptr] -= operand
if bf.cells[bf.cell_ptr] < 0:
bf.cells[bf.cell_ptr] += 256
code_position[0] += 2
return None
def bf_decrement(bf:Brainfork, code_position:List[int], functional_symbols,
*u):
bf.cells[bf.cell_ptr] -= 1
if bf.cells[bf.cell_ptr] == -1:
bf.cells[bf.cell_ptr] = 255
code_position[0] += 1
return None
def bf_input(bf:Brainfork, code_position:List[int], functional_symbols,
*u):
"""
if inp contains more than 1 character, copy the first char value
"""
inp = input("Requesting input (1 char only): ")
if len(inp) > 1:
inp = inp[0]
bf.cells[bf.cell_ptr] = ord(inp)
code_position[0] += 1
return None
def bf_output(bf:Brainfork, code_position:List[int], functional_symbols,
trace, *u):
val = bf.cells[bf.cell_ptr]
c = chr(val)
bf.stdout += c
if trace:
sys.stdout.write(c)
code_position[0] += 1
return None
def bf_left_bracket(bf:Brainfork, code_position:List[int], functional_symbols,
*u):
if bf.cells[bf.cell_ptr] == 0:
# jump
left_brackets_saw = 0
code_position[0] += 1
# find right bracket
while code_position[0] < len(functional_symbols):
if functional_symbols[code_position[0]] == bf.l_r_tuple[0]:
left_brackets_saw += 1
elif functional_symbols[code_position[0]] == bf.l_r_tuple[1]:
if left_brackets_saw == 0:
break
left_brackets_saw -= 1
pass
code_position[0] += 1
if left_brackets_saw > 0:
# Not matching brackets
return "Non-matching brackets! Right not found"
else:
bf.stack.append(code_position[0])
code_position[0] += 1
def bf_right_bracket(bf:Brainfork, code_position:List[int], functional_symbols,
*u):
if bf.cells[bf.cell_ptr] != 0:
try:
jump_pos = bf.stack.pop()
bf.stack.append(jump_pos)
except IndexError:
return "Non-matching brackets! Left not found"
code_position[0] = jump_pos
pass
else:
try:
jump_pos = bf.stack.pop()
except IndexError:
return "Non-matching brackets! Left not found"
code_position[0] += 1
# BRAINFUCK_CLASSIC ============================================================
BRAINFUCK_CLASSIC_DICT = {
'>':bf_right_ptr_shift,
'<':bf_left_ptr_shift,
'+':bf_increment,
'-':bf_decrement,
'.':bf_output,
',':bf_input,
'[':bf_left_bracket,
']':bf_right_bracket
}
def brainfuck_string2syms(raw_string):
return list(raw_string) # Since brainfuck is operated on single characters
def brainfuck_equivalent(str_str_dict):
for key, val in str_str_dict.items():
str_str_dict[key] = BRAINFUCK_CLASSIC_DICT[val]
return str_str_dict
REVERSEFUCK_DICT = {
'>':'<',
'<':'>',
'+':'-',
'-':'+',
'.':',',
',':'.',
'[':']',
']':'['
}
brainfuck_equivalent(REVERSEFUCK_DICT)
def pika_string2syms(str_):
return str_.split()
PIKALANG_DICT = {
"pi":'+',
"ka":'-',
"pipi":'>',
"pichu":'<',
"pika":'[',
"chu":']',
"pikachu":'.',
"pikapi":','
}
brainfuck_equivalent(PIKALANG_DICT)
# ================ IMPLEMENT BRAINFUCKS HERE =======================
Brainfuck = Brainfork(BRAINFUCK_CLASSIC_DICT, brainfuck_string2syms, ('[',']'))
Reversefuck = Brainfork(REVERSEFUCK_DICT, brainfuck_string2syms,(']','['))
Pikalang = Brainfork(PIKALANG_DICT, pika_string2syms, ("pika", "chu"))
# ============== TESTING ZONE ===========================
from lite_unit_test import is_debug
if is_debug(__name__):
from lite_unit_test import *
use_multithreading()
brainfk_tests = {
# TEST 1===================================================
("""++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.
>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.""",):
"Hello World!\n",
# TEST 2===================================================
("""[ This program prints "Hello World!" and a newline to the screen, its
length is 106 active command characters. [It is not the shortest.]
This loop is an "initial comment loop", a simple way of adding a comment
to a BF program such that you don't have to worry about any command
characters. Any ".", ",", "+", "-", "<" and ">" characters are simply
ignored, the "[" and "]" characters just have to be balanced. This
loop and the commands it contains are ignored because the current cell
defaults to a value of 0; the 0 value causes this loop to be skipped.
]
++++++++ Set Cell #0 to 8
[
>++++ Add 4 to Cell #1; this will always set Cell #1 to 4
[ as the cell will be cleared by the loop
>++ Add 2 to Cell #2
>+++ Add 3 to Cell #3
>+++ Add 3 to Cell #4
>+ Add 1 to Cell #5
<<<<- Decrement the loop counter in Cell #1
] Loop till Cell #1 is zero; number of iterations is 4
>+ Add 1 to Cell #2
>+ Add 1 to Cell #3
>- Subtract 1 from Cell #4
>>+ Add 1 to Cell #6
[<] Move back to the first zero cell you find; this will
be Cell #1 which was cleared by the previous loop
<- Decrement the loop Counter in Cell #0
] Loop till Cell #0 is zero; number of iterations is 8
The result of this is:
Cell No : 0 1 2 3 4 5 6
Contents: 0 0 72 104 88 32 8
Pointer : ^
>>. Cell #2 has value 72 which is 'H'
>---. Subtract 3 from Cell #3 to get 101 which is 'e'
+++++++..+++. Likewise for 'llo' from Cell #3
>>. Cell #5 is 32 for the space
<-. Subtract 1 from Cell #4 for 87 to give a 'W'
<. Cell #3 was set to 'o' from the end of 'Hello'
+++.------.--------. Cell #3 for 'rl' and 'd'
>>+. Add 1 to Cell #5 gives us an exclamation point
>++. And finally a newline from Cell #6
""",):
"Hello World!\n"
}
UTEST_INSTANCE.add_tests(*TestEntry.multi_init(Brainfuck.execute,
str_eq, brainfk_tests))
reversefuck_test = {
("""----------]<-<---<-------<---------->>>>+
[<<<<,>+++,<-----------,+++++++++++,-,>>--,<---------------,<,-----------------,
+++++++++++++++++,-------------,-,++++++++++++++,>++++++++++++,
<----------------,++++++++++++++++++,--------,""",):
"dCode ReverseFuck",
("""----------]<-<---<-------<---------->>>>+[<<<--,<-,-------,,---,>>--
,<---------------,<,---,++++++,++++++++,>>-,>----------,""",):
"Hello World!"
}
UTEST_INSTANCE.add_tests(*TestEntry.multi_init(Reversefuck.execute,
str_eq, reversefuck_test))
pika_tests = {
("""pi pi pi pi pi pi pi pi pi pi pika
pipi pi pipi pi pi pi pipi pi pi pi pi pi pi pi
pipi pi pi pi pi pi pi pi pi pi pi pichu pichu pichu
pichu ka chu pipi pipi pipi pi pi pi pi pi pi pi pi
pi pi pikachu pipi pi pi pi pi pi pi pi pi pi pi pi
pikachu ka ka ka ka pikachu
ka ka ka ka ka ka pikachu pi pi pi pi pi pi pi pi
pikachu pi pi pikachu ka pikachu
""",): "Pokemon"
}
UTEST_INSTANCE.add_tests(*TestEntry.multi_init(Pikalang.execute,
str_eq, pika_tests))
UTEST_INSTANCE.execute()
|
3b7c13aaf291ec6ff92b20a62372ef98cf878bfe | janertl/BootCamp2017 | /ProbSets/Comp/PSet 1/calculator.py | 184 | 3.515625 | 4 | # calculator.py
"""Sum, Product, and square root functions"""
from math import sqrt
def root(a):
return sqrt(a)
def sum(a, b):
return a + b
def prod(a, b):
return a * b
|
37efb9e656dca33c78a53362aa9e4a2d904a43b4 | dedebenui/busy_escalade | /main.py | 6,589 | 3.640625 | 4 | import numpy as np
import datetime as dt
import matplotlib.pyplot as plt
import csv
import re
from config import config, strings
class time_selector:
"""
container class that stores functions of type
func(datetime_obj: datetime.datetime) -> any
"""
@staticmethod
def day(datetime_obj):
return datetime_obj.date()
@staticmethod
def week_day(datetime_obj):
return datetime_obj.weekday()
@staticmethod
def hour(datetime_obj):
return datetime_obj.hour
@staticmethod
def datetime(*dates):
"""return a function that assigns an index based on datetime delimiters
all delimiters must have the same type {date, time, datetime}
Parameters
----------
dates : datetime.date or datetime.time or datetime.datetime
datetime obj that delimit the groups.
Returns
----------
a function delimiter_selector(datetime_obj: datetime.datetime) -> any
Pseudo example:
----------
if dates = [yesterday, last week], the returned delimiter will assign one of 3 indices
0 : all dates before and including last week
1 : all dates strictly after last week but up to yesterday
2 : all dates strictly after yesterday
"""
dates = list(dates)
dates.sort()
if type(dates[0]) == dt.datetime:
desired_property = lambda d: d
elif type(dates[0]) == dt.date:
desired_property = lambda d: d.date()
elif type(dates[0]) == dt.time:
desired_property = lambda d: d.time()
else:
raise TypeError("delimiter is not of type datetime.datetime, datetime.date or datetime.time")
def delimiter_selector(datetime_obj):
for i, date in enumerate(dates):
if desired_property(datetime_obj) <= date:
return i
return i + 1
return delimiter_selector
@staticmethod
def combine(*selectors):
"""returns a function that's a combination of multiple selectors"""
def combined_selector(datetime_obj):
return tuple(selector(datetime_obj) for selector in selectors)
return combined_selector
def less_than_ten_is_five(s):
""" returns
Parameters
----------
s : str
Returns
----------
the number of percents, or 5 when <10
"""
if "<" in s:
return 5
else:
return int(re.search('[0-9]+', s).group(0))
def import_data(path, delimiter=' ', date_time_fmt='%Y-%m-%d %H:%M:%S', percent_fmt=less_than_ten_is_five):
"""imports the data. Assumes that date and time are sperate columns to be merged together with a space.
Parameters
----------
path : str
path to the data file
delimiter : str
character used to split the rows
date_time_fmt : str
exact format of date
percent_fmt : func(s: str) -> int
function that returns an int based on the string s
Returns
----------
time_stamps : list
percent : list
"""
time_stamps = []
percent = []
with open(path) as data_file:
reader = csv.reader(data_file, delimiter=delimiter)
for row in reader:
if len(row) > 2:
date_time_str = ' '.join(row[:2]).split('.')[0] # ignore milliseconds
percent_str = ' '.join(row[2:])
time_stamps.append(dt.datetime.strptime(date_time_str, date_time_fmt))
percent.append(percent_fmt(percent_str))
return time_stamps, percent
def grouped_mean(time_stamps, values, grouping_func=time_selector.day):
"""computes a mean percentage per specified group
Parameters
----------
time_stamps : list of datetime objects
values : list of numbers matched to time_stamps
grouping_func : func(datetime_obj: datetime.datetime) -> any
Returns
----------
keys : list of any
keys generated by the grouping_func
values : list of floats
mean of each group corresponding to keys
"""
out = {}
# First group the values
for t, v in zip(time_stamps, values):
key = grouping_func(t)
if key not in out:
out[key] = []
out[key].append(v)
keys = []
values = []
# then compute mean in each group
for key, val in out.items():
keys.append(key)
values.append(np.mean(val))
return keys, values
if __name__ == '__main__':
fritime, fripercents = import_data('Fribourg.txt')
givitime, givipercents = import_data('Givisiez.txt')
strings = strings['french']
_, perc = grouped_mean(fritime, fripercents, time_selector.datetime(dt.time(12, 0), dt.time(18,0)))
print(f'Occupation moyenne avant midi : {perc[0]:.0f}%')
print(f'Occupation moyenne entre midi et 18h : {perc[1]:.0f}%')
print(f'Occupation moyenne après 18h : {perc[2]:.0f}%')
# Plots
fig = plt.figure(figsize=(10, 5))
gs = plt.GridSpec(1, 2, wspace=0.05)
left = fig.add_subplot(gs[0])
left.set_title('Fribourg')
right = fig.add_subplot(gs[1])
right.set_title('Givisiez')
right.tick_params(labelleft=False)
for time, percents, ax in zip([fritime, givitime], [fripercents, givipercents], [left, right]):
weekday_hours, weekday_perc = grouped_mean(time, percents, time_selector.combine(time_selector.week_day, time_selector.hour))
global_hours, global_perc = grouped_mean(time, percents, time_selector.hour)
global_perc = np.array(global_perc)[np.argsort(global_hours)]
global_hours.sort()
weekdays = {} # reorganize in {weekday: [hour, mean_percent]} dictionary
for key, val in zip(weekday_hours, weekday_perc):
if key[0] not in weekdays:
weekdays[key[0]] = [[],[]]
weekdays[key[0]][0].append(key[1])
weekdays[key[0]][1].append(val)
for i, (key, val) in enumerate(weekdays.items()):
val = np.array(val)
val[1] = val[1][np.argsort(val[0])]
val[0].sort()
ax.plot(val[0], val[1], config['plot.linestyles'][i], c=config['plot.colors'][i], label=strings['weekdays'][key])
ax.plot(global_hours, global_perc, c='grey', label='Global')
ax.set_xlim(9, 23)
ax.set_xlabel(strings['timeofday'])
left.legend()
left.set_ylabel(strings['occupancy'] + ' (%)')
plt.show() |
6a88afd5c7522af2cdd7ed92cdb99c569376d904 | rishabh-bhargava/Special-Algos | /median_of_medians.py | 1,139 | 3.859375 | 4 | def median_of_medians(arr, index):
# compute the median of medians using the helper function given below
mom = get_median_of_medians(arr)
# partition aroun the median of medians calculated. Thhis sould be done in place, but we have done
# this using O(n) space. This is also O(n) time.
new_arr = []
for el in arr:
if el < mom:
new_arr.append(el)
k = len(new_arr)
new_arr.append(mom)
for el in arr:
if el > mom:
new_arr.append(el)
# Cases we could have
if k == index:
return mom
elif k > index:
return median_of_medians(new_arr[0:k], index)
else:
return median_of_medians(new_arr[k+1: len(new_arr)], index - k)
def get_median_of_medians(arr):
# Base case: lenght of array is 1
if len(arr) == 1:
return arr[0]
#Otherwise break array into chunks of n/5 and calculate for each o them separately
else:
medians = []
for i in xrange((len(arr)-1)/5 +1):
if i*5+5 > len(arr):
b = arr[i*5:len(arr)]
else:
b = arr[i*5:i*5+5]
b.sort()
medians.append(b[len(b)/2])
return get_median_of_medians(medians)
# Test case
a = [2,4,7,10,1,3,5,9,8,6]
print a
print median_of_medians(a, 0) |
9a47d716cfc275e4d67eab7bbc7465fbacc3088a | elrion018/CS_study | /beakjoon_PS/no11721.py | 144 | 3.859375 | 4 | word = input()
while True:
if len(word) > 10:
print(word[:10])
word = word[10:]
else:
print(word)
break
|
599c975998b156d175e179fba8efb661b4445065 | The5cheduler/IBM-ML0101EN-Machine-Learning-with-Python- | /MultipleLinearRegression.py | 4,441 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 25 20:51:30 2019
@author: Suat
"""
import matplotlib.pyplot as plt
import pandas as pd
import pylab as pl
import numpy as np
df = pd.read_csv(r"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/FuelConsumptionCo2.csv")
## take a look at the dataset
df.head()
##Lets select some features that we want to use for regression.
cdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_CITY',
'FUELCONSUMPTION_HWY','FUELCONSUMPTION_COMB','CO2EMISSIONS']]
cdf.head(9)
##Lets plot Emission values with respect to Engine size:
#plt.scatter(cdf.ENGINESIZE, cdf.CO2EMISSIONS, color='blue')
#plt.xlabel("Engine size")
#plt.ylabel("Emission")
#plt.show()
'''Creating train and test dataset
note: Please see SİmpleLinearRegression file for train and data set
explanations'''
msk = np.random.rand(len(df)) < 0.8 #80% of data selected as train set
train = cdf[msk]
test = cdf[~msk]
'''Train data distribution'''
plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')
plt.xlabel("Engine size")
plt.ylabel("Emission")
plt.show()
'''Multiple Regression Model'''
'''In reality, there are multiple variables that predict the Co2emission.
When more than one independent variable is present, the process is called
multiple linear regression. For example, predicting co2emission using
FUELCONSUMPTION_COMB, EngineSize and Cylinders of cars.
The good thing here is that Multiple linear regression is
the extension of simple linear regression model.'''
from sklearn import linear_model
regr = linear_model.LinearRegression()
x = np.asanyarray(train[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB']])
y = np.asanyarray(train[['CO2EMISSIONS']])
regr.fit (x, y)
# The coefficients
print ('Coefficients: ', regr.coef_)
print ('Intercept: ',regr.intercept_)
''' Coefficient and Intercept , are the parameters of the fit line.
Given that it is a multiple linear regression, with 3 parameters, and
knowing that the parameters are the intercept and coefficients of hyperplane,
sklearn can estimate them from our data. Scikit-learn uses plain
Ordinary Least Squares method to solve this problem.'''
'''Ordinary Least Squares (OLS)'''
'''OLS is a method for estimating the unknown parameters in a linear
regression model. OLS chooses the parameters of a linear function of a set of
explanatory variables by minimizing the sum of the squares of the differences
between the target dependent variable and those predicted by the linear
function. In other words, it tries to minimizes the sum of squared
errors (SSE) or mean squared error (MSE) between the target variable (y)
and our predicted output (y^) over all samples in the dataset.
OLS can find the best parameters using of the following methods:
- Solving the model parameters analytically using closed-form equations
- Using an optimization algorithm (Gradient Descent, Stochastic Gradient
Descent, Newton’s Method, etc.)'''
'''PREDICTION'''
y_hat = regr.predict(test[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB']])
x = np.asanyarray(test[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB']])
y = np.asanyarray(test[['CO2EMISSIONS']])
print("Residual sum of squares - 3VAR: %.2f"
% np.mean((y_hat - y) ** 2))
# Explained variance score: 1 is perfect prediction
print('Variance score for 3VAR: %.2f' % regr.score(x, y))
##multiple linear regression with another variables
##Instead of using combination, using city and highway fuelconsumption
##values. Will it change the results? Hint: NO!
regr2 = linear_model.LinearRegression()
z = np.asanyarray(train[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_CITY',
'FUELCONSUMPTION_HWY']])
q = y = np.asanyarray(train[['CO2EMISSIONS']])
regr2.fit (z, q)
q_hat = regr2.predict(test[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_CITY',
'FUELCONSUMPTION_HWY']])
z = np.asanyarray(test[['ENGINESIZE','CYLINDERS', 'FUELCONSUMPTION_CITY',
'FUELCONSUMPTION_HWY']])
q = np.asanyarray(test[['CO2EMISSIONS']])
print("Residual sum of squares - 4VAR: %.2f"
% np.mean((q_hat - q) ** 2))
# Explained variance score: 1 is perfect prediction
print('Variance score for 4VAR: %.2f' % regr2.score(z, q))
|
cce9a650c2030bf7a4fb894b1efabc09694ac116 | ErayB1042/GlobalAIHubPythonHomework | /hw_02.py | 1,239 | 4.5 | 4 | """The user will be defined. Get the data of this user by input method.
Obtain information from user as follow:
-First Name
-Last Name
-Age
-Date of birth
Pass the users information to the list and displays the screen using the for loop.
Print all user information on the screen.
If he is under 18, print 'You cant go out because its too dangerous' on the screen.
If he is over 18, print 'You can go out the street' on the screen."""
print ("Lütfen kayıt için bilgilerinizi giriniz...")
user=[]
user.append(input("Lütfen İsminizi girin:"))
user.append(input("Lütfen Soy isminizi girin:"))
user.append(int(input("Lütfen Yaşınızı giriniz:")))
user.append(int(input("Lütfen doğum tarihinizi-sadece yıl- giriniz:")))
for i in range(4):
if i == 0:
print("İsim: {}".format(user[0]))
elif i == 1:
print("Soy İsim: {}".format(user[1]))
elif i == 2:
print("Yaş: {}".format(user[2]))
else:
print("Doğum Tarihi: {}".format(user[3]))
if user[2] < 18 :
print("You cant go out because it's too dangerous/ Dışarısı çok tehlikeli yalnız dışarı çıkamazsın...")
else:
print("You can go out to the street/Yalnız dışarı çıkabilirsin...")
|
6b65c79cb899e9c6ba821ec3c00e0c2d3b4b09fc | fp-computer-programming/cycle-5-labs-P22Jhart | /lab_3-1.py | 222 | 3.625 | 4 | import time
import math
t0=time.perf_counter()
math.pow(2, 2)
t1 = time.perf_counter()
speed1 = t1 - t0
print(speed1)
# ** operator
t2 = time.perf_counter()
2**2
t3=time.perf_counter
speed2=t3-t2
print(speed2)
|
703128d8ee48204339bdb5b4470a38a4288e1b96 | HawChang/LeetCode | /5.最长回文子串.py | 5,176 | 3.65625 | 4 | #
# @lc app=leetcode.cn id=5 lang=python3
#
# [5] 最长回文子串
#
# @lc code=start
class Solution:
def longestPalindrome(self, s: str) -> str:
# return self.longestPalindrome1(s)
# return self.longestPalindrome2(s)
return self.longestPalindrome3(s)
def longestPalindrome3(self, s: str) -> str:
# dp[i]: 位置i的臂长。即以i为中心 能向左向右扩展多少个字符
dp = list()
max_arm = 0
max_str = ""
s = "#" + "#".join(s) + "#"
cur_right = -1
cur_center = -1
def expand(left, right):
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
# 到这里 上一次的匹配成功了 即[left + 1, right - 1]
# 长度为l = ((right - 1) - (left + 1) + 1)
# 该长度一定是奇数
# 该字符串的臂长为(l - 1) // 2
# 所以臂长为 (right - left - 2) // 2
return (right - left - 2) // 2
# 遍历s串各处
for cur_ind in range(len(s)):
# cur_ind在之前的回文串内 则可以少判断一些字符 从没开始判断的cur_right+1开始即可
cur_arm = 0
if cur_ind < cur_right:
# 当前位置关于当前最右的回文子串的中心的对称点
sym_ind = cur_center - (cur_ind - cur_center)
# 对称位置已确认其臂长 又该臂长可能不完全在当前最右的回文子串中
# 这里需要做判断
sym_arm = dp[sym_ind]
cover_length = cur_right - cur_ind
# 这里可以分情况讨论
# 当sym_arm cover_length不相等时 该处臂长就是较小的那个值
# 当相等时,则需要继续判断
if sym_arm < cover_length:
cur_arm = sym_arm
elif sym_arm > cover_length:
cur_arm = cover_length
else:
cur_arm = expand(cur_ind - sym_arm - 1, cur_ind + sym_arm + 1)
# 将三种情况合起来的话 代码简单了点 但是会多余一些匹配操作
# confirm_arm = min(sym_arm, cover_length)
# cur_arm = expand(cur_ind - confirm_arm - 1, cur_ind + confirm_arm + 1)
else:
cur_arm = expand(cur_ind - 1, cur_ind + 1)
dp.append(cur_arm)
# 更新最右回文子串的记录
if cur_arm + cur_ind > cur_right:
cur_right = cur_arm + cur_ind
cur_center = cur_ind
# 更新最长回文的记录
if cur_arm > max_arm:
max_arm = cur_arm
max_str = s[cur_ind - cur_arm + 1: cur_ind + cur_arm + 1: 2]
return max_str
def longestPalindrome2(self, s: str) -> str:
# 中心扩展法
def central_expand(left, right):
# 返回当前能扩展到的最长回文串
if s[left] == s[right]:
if (left == 0) or (right == (len(s) - 1)):
# 两侧到边界 停止扩展 最长为[left, right] 长度为right - left + 1
return s[left: right + 1]
return central_expand(left - 1, right + 1)
else:
# 上一次为最长 为[left + 1, right - 1] 长度为right - 1 - left - 1 + 1
return s[left + 1: right]
s_size = len(s)
max_len = 0
max_str = ""
def check_max(left, right):
nonlocal max_len, max_str
cur_str = central_expand(left, right)
cur_len = len(cur_str)
if cur_len > max_len:
max_len = cur_len
max_str = cur_str
for cur_ind in range(s_size):
check_max(cur_ind, cur_ind)
if cur_ind + 1 < s_size:
check_max(cur_ind, cur_ind + 1)
return max_str
def longestPalindrome1(self, s: str) -> str:
s_size = len(s)
# 状态转移方程 dp[i][j] = dp[i+1][j-1] and s[i] == s[j]
dp = [[False for _ in range(s_size)] for _ in range(s_size)]
# 特殊情况 dp[i][i] dp[i][i+1]
max_length = 0
max_str = ""
for end_pos in range(s_size):
for start_pos in range(end_pos + 1):
if end_pos == start_pos:
dp[start_pos][end_pos] = True
elif start_pos + 1 == end_pos:
dp[start_pos][end_pos] = True if s[start_pos] == s[end_pos] else False
else:
dp[start_pos][end_pos] = dp[start_pos + 1][end_pos - 1] and s[start_pos] == s[end_pos]
if dp[start_pos][end_pos]:
cur_length = end_pos - start_pos + 1
if max_length < cur_length:
max_length = cur_length
max_str = s[start_pos: end_pos + 1]
return max_str
# @lc code=end
|
c018cedd2956c8decc124f337230afaff3400b45 | Anasshukri/Lets-Learn-Python | /Hypotenuse.py | 222 | 4.28125 | 4 | print("Let's calculate a hypotenuse using Pythagoras Theorem!")
side_x = int(input("Insert side x: "))
side_y = int(input("Insert side y: "))
hypotenuse = (side_x**2 + side_y**2)**0.5
print("Hypotenuse : ", hypotenuse)
|
ea212bc2d1af2ca6495ee8a91b0a39ec184d4182 | DavidLeoni/algolab | /past-exams/2017-01-26/exercises/exercise1.py | 5,137 | 4.28125 | 4 | import unittest
class SwapArray:
""" A sequence of elements that can only be modified by swapping one element
with the successisarre one.
"""
def __init__(self, python_list):
""" Initializes the SwapArray with the elements found in python_list. """
self._arr = python_list[:] # we store a _copy_ of the array
def swap_next(self, i):
""" Swaps the elements at indeces i and i + 1
If index is negative or greater or equal of the last index, raises
an IndexError
"""
if i < 0 or i >= len(self._arr) - 1:
raise IndexError("Wrong index: " + str(i) )
tmp = self._arr[i]
self._arr[i] = self._arr[i + 1]
self._arr[i + 1] = tmp
def size(self):
""" Returns the size of the SwapArray """
return len(self._arr)
def get(self, i):
""" Returns the element at index i.
If index is outside the bounds of the array, raises an IndexError
"""
return self._arr[i]
def get_last(self):
""" Returns the last element of the array
If array is empty, raises an IndexError
"""
return self._arr[-1]
def __str__(self):
return "SwapArray: " + str(self._arr)
def is_sorted(sarr):
""" Returns True if the provided SwapArray sarr is sorted, False otherwise
NOTE: Here you are a user of SwapArray, so you *MUST NOT* access
directly the field _arr.
"""
raise Exception("TODO IMPLEMENT ME !")
def max_to_right(sarr):
""" Modifies the provided SwapArray sarr so that its biggest element is
moved to the last index. The order in which the other elements will be
after a call to this function is left unspecified (so it could be any).
NOTE: Here you are a user of SwapArray, so you *MUST NOT* access
directly the field _arr. To do changes, you can only use
the method swap(self, i).
NOTE: does *not* return anything!
"""
raise Exception("TODO IMPLEMENT ME !")
class SwapTest(unittest.TestCase):
def test_zero_element(self):
sarr = SwapArray([]);
with self.assertRaises(IndexError):
sarr.swap_next( 0)
with self.assertRaises(IndexError):
sarr.swap_next(1)
with self.assertRaises(IndexError):
sarr.swap_next(-1)
def test_one_element(self):
sarr = SwapArray(['a']);
with self.assertRaises(IndexError):
sarr.swap_next(0)
def test_two_elements(self):
sarr = SwapArray(['a','b']);
sarr.swap_next(0)
self.assertEqual(sarr._arr, ['b','a'])
def test_return_none(self):
sarr = SwapArray(['a','b', 'c', 'd']);
self.assertEquals(None, sarr.swap_next(1))
def test_long_list(self):
sarr = SwapArray(['a','b', 'c', 'd']);
sarr.swap_next(1)
self.assertEqual(sarr._arr, ['a', 'c','b', 'd'])
class IsSortedTest(unittest.TestCase):
def test_is_sorted_empty(self):
self.assertTrue(is_sorted(SwapArray([])))
def test_is_sorted_one(self):
self.assertTrue(is_sorted(SwapArray([6])))
def test_is_sorted_two(self):
self.assertTrue(is_sorted(SwapArray([7,7])))
self.assertTrue(is_sorted(SwapArray([6,7])))
self.assertFalse(is_sorted(SwapArray([7,6])))
def test_is_sorted_three(self):
self.assertTrue(is_sorted(SwapArray([6,7,8])))
self.assertFalse(is_sorted(SwapArray([8,8,7])))
class MaxToRightTest(unittest.TestCase):
def test_max_to_right_empty(self):
sarr = SwapArray([])
max_to_right(sarr)
self.assertEqual(sarr._arr, [])
def test_max_to_right_return_none(self):
sarr = SwapArray([])
self.assertEqual(None, max_to_right(sarr))
def test_right_max_to_right_1(self):
sarr = SwapArray([5])
max_to_right(sarr)
self.assertEqual(5, sarr.get(0))
def test_right_max_to_right_2_first(self):
sarr = SwapArray([7, 6])
max_to_right(sarr)
self.assertEqual(sarr.get(0), 6)
self.assertEqual(sarr.get(1), 7)
def test_right_max_to_right_2_last(self):
sarr = SwapArray([6,7])
max_to_right(sarr)
self.assertEqual(sarr.get_last(), 7)
def test_right_max_to_right_3_first(self):
sarr = SwapArray([8,6, 7])
max_to_right(sarr)
self.assertEqual(sarr.get(2), 8)
def test_right_max_to_right_3_middle(self):
sarr = SwapArray([7, 8, 6])
max_to_right(sarr)
self.assertEqual(sarr.get(2), 8)
def test_right_max_to_right_3_last(self):
sarr = SwapArray([7, 6, 8])
max_to_right(sarr)
self.assertEqual(sarr.get(2), 8)
#unittest.main() |
8e9bb2f6cce264a8c46331bc34bc4437aad0cf24 | ThomasLilley/ML_Assignment | /main.py | 493 | 3.6875 | 4 | import Task_1
import Task_2
def menu():
flag = True
while flag:
print('\nMain Menu')
print('---------')
print('1) Task 1')
print('2) Task 2')
print('3) Exit')
print('---------')
a = input('Please select an option: ')
if a == '1':
Task_1.task1()
elif a == '2':
Task_2.task2()
elif a == '3':
exit(0)
else:
print('Invalid option selected')
menu()
|
e0890ef7f5f2772176a27b2c98febc2725fca39b | C7110Emir/Python | /python/binary.py | 4,069 | 4.125 | 4 | class binary :
def __init__(self, data = None, left = None, right= None):
self.data = data
self.left = left
self.right = right
class binaryoperation:
def __init__(self):
self.root = None
def inserter(self,data):
node = binary(data)
if self.root == None:
self.root = node
else:
secroot = self.root
while True:
if data > secroot.data:
if secroot.right == None:
secroot.right = node
break
else:
secroot = secroot.right
elif data <= secroot.data:
if secroot.left == None:
secroot.left = node
break
else:
secroot = secroot.left
def maxremover(self):
maxdata = None
if self.root == None:
print("you can't because your tree is empty")
elif self.root.right == None and self.root.left == None:
maxdata = self.root.data
self.root = None
elif self.root.right == None and self.root.left != None:
secroot = self.root
maxdata = self.root.data
self.root = None
self.root = secroot.left
else:
secroot = self.root
while True:
if secroot.right.right == None:
maxdata = secroot.right.data
secroot.right = None
break
else:
secroot = secroot.right
return maxdata
def minremover(self):
minvalue = None
if self.root == None:
print("you can't because your tree is empty")
elif self.root.left == None and self.root.right == None:
minvalue = self.root.data
self.root = None
elif self.root.left == None and self.root.right != None:
secroot = self.root
minvalue = self.root.data
self.root = None
self.root = secroot.right
else:
secroot = self.root
while True:
if secroot.left.left == None:
minvalue = secroot.left.data
secroot.left = None
break
else:
secroot = secroot.left
return minvalue
def valuesearch(self,data):
if self.root == None:
return "tree is empty so your value doesn't exist"
else:
secroot = self.root
while True:
if secroot == None:
return f"{data} doesn't exist inside the list"
elif data > secroot.data:
secroot = secroot.right
elif data < secroot.data:
secroot = secroot.left
elif data == secroot.data:
valuereturn = f'{data} exists inside list'
return valuereturn
def preorder(self, root):
if root == None:
return
print(root.data)
self.preorder(root.left)
self.preorder(root.right)
def inorder(self,root):
if root == None:
return
self.preorder(root.left)
print(root.data)
self.preorder(root.right)
def postorder(self,root):
if root == None:
return
self.preorder(root.left)
self.preorder(root.right)
print(root.data)
if __name__ == "__main__":
binar = binaryoperation()
binar.inserter(8)
binar.inserter(3)
binar.inserter(10)
binar.inserter(1)
binar.inserter(6)
binar.inserter(4)
binar.inserter(7)
binar.inserter(14)
binar.inserter(13)
binar.preorder(binar.root)
#binar.inorder(binar.root)
binar.postorder(binar.root)
print(binar.valuesearch(13))
|
b1de09897eec542b79602aab63ee1e611e95b4de | rbarket/battlesnake2020 | /app/rf/moveScore.py | 1,069 | 3.625 | 4 | import operator
from utility import *
def scoreMove(moves, snakes, width, height):
snakeList = []
for snake in snakes:
snakeBody = snake['body'] # snakeBody = list of body parts for one snake
for piece in snakeBody: # iterae through each body piece of that snake
part = [piece['x'], piece['y']]
snakeList.append(part)
scoreDict = {}
for move, coord in moves.items():
if (move == 'down'):
scoreDict.update({'down': checkBubbleScore(coord, snakeList, width, height)})
if (move == 'up'):
scoreDict.update({'up': checkBubbleScore(coord, snakeList, width, height)})
if (move == 'right'):
scoreDict.update({'right': checkBubbleScore(coord, snakeList, width, height)})
if (move == 'left'):
scoreDict.update({'left': checkBubbleScore(coord, snakeList, width, height)})
max_val = max(scoreDict.values())
#WTF IS THE FUNCTION BELOW DOING LOL?
bestMove = [k for k, v in scoreDict.items() if v == max_val] # Note: will return a list with only 1 item
print('scoredict: {} and bestMove: {}'.format(scoreDict,bestMove))
return bestMove
|
7e8deecca5b8483f95d85d9201db89573f88d08c | Feier-4869/swipe | /python题目/工资jiesuanxit.py | 260 | 3.53125 | 4 | # from abc import ABCMeta, abstractclassmethod
# # print(dir(ABCMeta))
# class Employee(object, metaclass=ABCMeta)
#
# def __init__(self, name):
# self._name = name
#
# @property
# def name(self):
# return self._name
#
# @ |
3e721731fd5942e0ca530b8c32c3b025e552fa0c | shahhassansh/Python_Coding_Practice | /deletionDistance.py | 768 | 3.59375 | 4 | ## The below code takes two strings as input and return the number of deletion operations
## that would make these two strings same.
##
## Input:
##
## "heat", "hit"
##
## Output:
##
## 3
##
## Input:
##
## "Some", "thing"
##
## Output:
##
## 9
def deletionDistance(A,B):
m = len(A)
n = len(B)
memo = [[0 for i in range(n+1)] for j in range(m+1)]
for i in range(0,len(memo)):
for j in range(0,len(memo[0])):
if i == 0:
memo[i][j] = j
elif j == 0:
memo[i][j] = i
elif A[i-1] == B[j-1]:
memo[i][j] = memo[i-1][j-1]
else:
memo[i][j] = 1 + min(memo[i-1][j], memo[i][j-1])
return memo[i][j]
print(deletionDistance("some","thing")) |
468e7dbb3323e4a1f343c3102c07969db479285f | alimadeoliveiranatalia/Python | /funcao.py | 868 | 4 | 4 | def somar(a,b):
a = int(a)# converte os valores fornecidos em inteiros
b = int(b)
soma = a+b
return soma
def subtrair(a,b):
a = int(a)
b = int(b)
diferenca = a-b
return diferenca
# Programa Principal que faz a soma e a diferença de dois números
c = input('Informe um valor, por favor' )
d = input('Informe um segundo valor, por favor')
resultado = somar(c,d)
resultado1 = subtrair(c,d)
print(f'{c} + {d} = {resultado}')
print(f'{c} - {d} = {resultado1}')
#def linha():
# print('-'*60)
# Programa Principal
#linha()
#print(' Curso em Vídeo ')
#linha()
#print(' Aprenda Python ')
#linha()
#print(' Natália ')
#linha()
#def titulo(txt):
# print('-'*60)
# print(txt)
# print('-'*60)
#Programa Principal utilizando parâmetros
#titulo(' Curso em Vídeo ')
#titulo(' Aprenda Python ')
#titulo(' Natália ')
|
8790099ebe963a7d317ff4dccb0e05c2e802e341 | mateusnakajo/pcs3858-embedded-systems-controller | /models/event.py | 1,310 | 3.734375 | 4 | from enum import Enum
class EngineDirection(Enum):
FORWARD = 0
BACKWARD = 1
class InputEvent:
pass
class DirectionEvent(InputEvent):
@staticmethod
def is_coordinates_valid(x, y):
return (x ** 2) + (y ** 2) <= 1
def __init__(self, x, y):
#assert DirectionEvent.is_coordinates_valid(x, y)
self.x = x
self.y = y
def get_coordinates(self):
return self.x, self.y
class HaltEvent(InputEvent):
pass
class OutputEvent:
pass
class EngineInput(OutputEvent):
@staticmethod
def is_valid_engine_input(engine_input):
(magnitude, direction) = engine_input
return 0. <= magnitude <= 1. and direction in EngineDirection
def __init__(self, left_engine_input, right_engine_input):
#assert EngineInput.is_valid_engine_input(left_engine_input), "{} is not a valid input for left engine"\
# .format(left_engine_input)
#assert EngineInput.is_valid_engine_input(right_engine_input), "{} is not a valid input for right engine"\
# .format(right_engine_input)
self.left_engine_input = left_engine_input
self.right_engine_input = right_engine_input
|
2047a5a88922a3eb6b4aa9d51731279b4885d8a0 | personaluser01/Algorithm-problems | /20131209/AM/131209_tests/subway/check/subway2.py | 630 | 3.84375 | 4 | from collections import defaultdict
def canonical(s):
'''
Return canonical representation of tree given by string s,
assuming it starts from a particular root
'''
zeros = 0
ones = 0
current_start = 1
parts = []
for i in xrange(len(s)):
if s[i] == '0':
zeros += 1
else:
ones += 1
if zeros == ones:
parts.append('0' + canonical(s[current_start:i]) + '1')
current_start = i+2
return ''.join(sorted(parts))
n = int(raw_input())
unique = set()
for i in xrange(n):
unique.add(canonical(raw_input()))
print len(unique)
|
b24952ebc72eb742d933baff6635c39f1b564ec8 | ajaypraj/gittest | /banking_application.py | 1,119 | 3.953125 | 4 | import sys
class Bank:
bName="Cananra"
def __init__(self,name,balance=0):
self.name=name
self.balance=balance
def deposite(self,amount):
self.balance=self.balance+amount
print("Your balance is",self.balance)
def withdrawal(self,amount):
if amount>self.balance:
print("You have insufficient balance")
sys.exit()
self.balance=self.balance-amount
print("Your balance is",self.balance)
print("Welcome",Bank.bName)
name=input("Enter your name")
b=Bank(name)
while True:
ch=input("Enter your choice:For Deposit D \n for Withdrawal W \n and to exit E")
if ch=='D' or ch=='d':
amt=float(input("Enter the amount to be deopisted"))
b.deposite(amt)
elif ch=='w' or ch=='W':
amt=float(input("enter the amount to be withdrawn"))
b.withdrawal(amt)
elif ch=='E' or ch=='e':
sys.exit()
else:
print("ENter proper choice")
|
80639cbf1da436ee5ae32ff732ca3e5b8219ddba | scarlettlite/hackathon | /Tree/BST/InorderSuccessor.py | 1,566 | 3.703125 | 4 | class Solution(object):
def minimum(self, root):
ans = None
if root:
curr = root
while curr.left:
curr = curr.left
ans = curr
return ans
def getio(self, root, p, path):
ans = None
if root == p:
"""
if the root has a right child, then its inorder
succesor is the minimum node in its right
subtree
"""
if root.right:
ans = self.minimum(root.right)
elif path:
"""
if root doesnt have a right subtree then, its inorder
successor is the last ancestor greater than itself. if an
ancestor is greater than its children then we can reach its
smaller children by going to its left subtree. So every time
we take a left turn from an ancestor save it in a cache
"""
ans = path[-1]
else:
if p.val < root.val:
"""
we can just save the last node. No need to store all ancestors
"""
path.append(root)
ans = self.getio(root.left, p, path)
else:
ans = self.getio(root.right, p, path)
return ans
def inorderSuccessor(self, root, p):
"""
:type root: TreeNode
:type p: TreeNode
:rtype: TreeNode
"""
return self.getio(root, p, []) |
960af6e4f203f8505f9fc961578ef3020c9cbcf3 | T17CS050/zyanken | /Zyanken.py | 803 | 3.671875 | 4 | '''
Created on 2019/10/09
@author: t17cs050
'''
import random
num = random.randint(1, 3)
num2 = "0"
numB = 0
handA = "String"
handB = 'string'
print("じゃんけんシミュレート")
print("1~3の数字を入力!")
num2 = input()
numB = int(num2)
if num == 1:
handA = "グー"
elif num == 2:
handA = "チョキ"
elif num == 3:
handA = "パー"
if numB == 1:
handB = "グー"
elif numB == 2:
handB = "チョキ"
elif numB == 3:
handB = "パー"
print("Aの手:", handA, "VS Bの手:", handB)
if num == numB:
print("引き分け")
elif (num == 1 and numB == 2) or (num == 2 and numB == 3) or (num == 3 and numB == 1):
print("Aの勝ち")
elif (numB == 1 and num == 2) or (numB == 2 and num == 3) or (numB == 3 and num == 1):
print("Bの勝ち") |
99a22579731e92a7286d3241178fcc316d024c9b | cshintov/Learning-C | /c_projects/python_vm/testcases/reverse.py | 162 | 3.90625 | 4 | # computes the reverse of the number
num = 1234
reverse = 0
while num > 0:
rem = num % 10
reverse = reverse * 10 + rem
num = num / 10
print reverse
|
d99d348666ccd06d02027fbd2edc763e13dcff4c | UCSB-CS-Using-GitHub-In-Courses/github-acadwf-scripts | /disambiguateFunctions.py | 11,973 | 3.765625 | 4 | #!/usr/bin/python
import unittest
import csv
from string import maketrans
def containsDuplicates(aList):
"""Does list contain a duplicate
>>> containsDuplicates(['foo','bar','fum'])
False
>>> containsDuplicates(['foo','foo','fum'])
True
>>> containsDuplicates(['foo','fum','foo'])
True
>>> containsDuplicates(['bar','foo','bar'])
True
"""
copyList = list(aList)
copyList.sort()
for i in range(len(copyList)-1):
if copyList[i]==copyList[i+1]:
return True
return False
def firstNamesWithNCharsOfLastName(userList, indices, n):
"return list of new first names"
names = []
for i in range(len(indices)):
names.append(userList[indices[i]]['first'] + "_" +
userList[indices[i]]['last'][0:n])
return names
def disambiguateAllFirstNames(userList):
newUserList = list(userList)
firstDuplicateName = nameInFirstMatchingPairOfFirstNames(newUserList)
while ( firstDuplicateName != False):
print("Fixing duplicates for ",firstDuplicateName)
indices = findIndicesOfMatchingFirstNames(newUserList,firstDuplicateName)
newUserList = disambiguateFirstNamesOfTheseIndices(newUserList,indices)
firstDuplicateName = nameInFirstMatchingPairOfFirstNames(newUserList)
return newUserList
def disambiguateFirstNamesOfTheseIndices(userList,indices):
"return a new userList with certain first names disambiguated"
newList = list(userList)
needed = 1; # Need up through 0 only (i.e. 1 char)
firstNames = firstNamesWithNCharsOfLastName(userList,indices,needed)
#print("firstNames=",firstNames,"needed=",needed)
while( containsDuplicates(firstNames) ):
needed = needed + 1
firstNames = firstNamesWithNCharsOfLastName(userList,indices,needed)
#print("firstNames=",firstNames,"needed=",needed)
for i in range(len(indices)):
newList[indices[i]]['first'] = firstNames[i]
return newList
def nameInFirstMatchingPairOfFirstNames(userList):
"returns the first name that occurs more than once, or False if no dup first names"
for i in range(len(userList)):
for j in range(i+1,len(userList)):
if userList[i]['first'] == userList[j]['first']:
return userList[i]['first']
return False
def findIndicesOfMatchingFirstNames(userList,name):
"returns list of the indices of the elements in userList who first names match name"
indices = []
for i in range(len(userList)):
if userList[i]['first'] == name:
indices.append(i)
return indices
def makeUserDict(first,last,github,email,csil):
return {'first': first, 'last': last, 'github': github.lower(), 'email':email.lower(), 'csil':csil.lower() }
def convertUserList(csvFile):
userList = []
for line in csvFile:
userList.append(makeUserDict(line["First Name"],
line["Last Name"],
line["github userid"],
line["Umail address"],
line["CSIL userid"]))
for user in userList:
user["first"] = user["first"].strip().translate(maketrans(" ","_"));
return userList
def makeUserLookupDictByGithubId(userList):
"""
userList is a list of dictionaries with keys first,last,github,email,csil.
returned value is a dictionary where the keys are the github ids,
and the values are the original dictionaries with first,last,github,email,csil
"""
newDict = {}
for user in userList:
if user['github'] in newDict:
raise Exception("duplicate github user {0}".format(user['github']))
newDict[user['github']]=user
return newDict
def convertPairList(userList,csvFile):
"""
userList is a list of dictionaries with keys first,last,github,email,csil
csvFile is a list of dictionaries with keys Partner1_GithubID,Partner2_GithubID,labnumber
returned value should be a list of dictionaries with keys teamName,user1,user2, where user1 and user2 are the elements fromn userlist where the github ids match.
"""
pairList = []
userLookupDict = makeUserLookupDictByGithubId(userList)
for line in csvFile:
line['Partner1_GithubID']=line['Partner1_GithubID'].lower().strip()
line['Partner2_GithubID']=line['Partner2_GithubID'].lower().strip()
if not (line['Partner1_GithubID'] in userLookupDict):
raise Exception("Partner1_GithubID from pair file not found in user list: {0}".format(line['Partner1_GithubID']))
if not (line['Partner2_GithubID'] in userLookupDict):
raise Exception("Partner2_GithubID from pair file not found in user list: {0}".format(line['Partner2_GithubID']))
team = {}
user1 = userLookupDict[line['Partner1_GithubID']]
user2 = userLookupDict[line['Partner2_GithubID']]
if (user1["first"] > user2["first"]):
# Swap if out of order
temp = user1
user1 = user2
user2 = temp
team["user1"] = user1
team["user2"] = user2
team["teamName"]="Pair_" + user1['first'] + "_" + user2['first']
pairList.append(team)
return pairList
def getUserList(csvFilename):
with open(csvFilename,'r') as f:
csvFile = csv.DictReader(f,delimiter=',', quotechar='"')
userList = convertUserList(csvFile)
newUserList = disambiguateAllFirstNames(userList)
return newUserList
def getPairList(userList,csvFilename):
with open(csvFilename,'r') as f:
csvFile = csv.DictReader(f,delimiter=',', quotechar='"')
pairList = convertPairList(userList,csvFile)
return pairList
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.userList1 = [ makeUserDict('Chris','Jones','cj','cj@example.org','cj'),
makeUserDict('Chris','Smith','cs','cs@example.org','cs'),
makeUserDict('Mary Kay','Jones','mkj','mkj@example.org','mkj'),
makeUserDict('Mary','Kay','mkay','mkay@example.org','mkay') ]
self.userList1a = [ makeUserDict('Chris_J','Jones','cj','cj@example.org','cj'),
makeUserDict('Chris_S','Smith','cs','cs@example.org','cs'),
makeUserDict('Mary Kay','Jones','mkj','mkj@example.org','mkj'),
makeUserDict('Mary','Kay','mkay','mkay@example.org','mkay') ]
self.userList2 = [ makeUserDict('Chris_J','Jones','cj','cj@example.org','cj'),
makeUserDict('Chris_S','Smith','cs','cs@example.org','cs'),
makeUserDict('Mary Kay','Jones','mkj','mkj@example.org','mkj'),
makeUserDict('Mary','Kay','mkay','mkay@example.org','mkay') ]
self.userList3 = [ makeUserDict('Chris','Jones','cj','cj@example.org','cj'),
makeUserDict('Chris','Smith','cs','cs@example.org','cs'),
makeUserDict('Mary','Jones','mkj','mkj@example.org','mkj'),
makeUserDict('Mary','Kay','mkay','mkay@example.org','mkay'),
makeUserDict('Dave','Jones','dj','dk@example.org','dj'),
makeUserDict('Dave','Kay','dk','dj@example.org','dk') ]
self.userList3a = [ makeUserDict('Chris_J','Jones','cj','cj@example.org','cj'),
makeUserDict('Chris_S','Smith','cs','cs@example.org','cs'),
makeUserDict('Mary_J','Jones','mkj','mkj@example.org','mkj'),
makeUserDict('Mary_K','Kay','mkay','mkay@example.org','mkay'),
makeUserDict('Dave_J','Jones','dj','dk@example.org','dj'),
makeUserDict('Dave_K','Kay','dk','dj@example.org','dk') ]
self.userList4 = [ makeUserDict('Chris','Jones','cj','cj@example.org','cj'),
makeUserDict('Mary','Jones','mkj','mkj@example.org','mkj'),
makeUserDict('Dave','Kay','dk','dj@example.org','dk') ]
self.userList5 = [ makeUserDict('Mary','Jones','mkj','mkj@example.org','mkj'),
makeUserDict('Chris','Smyth','csmy','cj@example.org','cj'),
makeUserDict('Chris','Smith','csmi','cs@example.org','cs'),
makeUserDict('Mary','Kay','mkay','mkay@example.org','mkay'),
makeUserDict('Dave','Jones','dj','dk@example.org','dj'),
makeUserDict('Dave','Kay','dk','dj@example.org','dk') ]
self.userList5a = [ makeUserDict('Mary_J','Jones','mkj','mkj@example.org','mkj'),
makeUserDict('Chris_Smy','Smyth','csmy','cj@example.org','cj'),
makeUserDict('Chris_Smi','Smith','csmi','cs@example.org','cs'),
makeUserDict('Mary_K','Kay','mkay','mkay@example.org','mkay'),
makeUserDict('Dave_J','Jones','dj','dk@example.org','dj'),
makeUserDict('Dave_K','Kay','dk','dj@example.org','dk') ]
def test_firstNamesWithNCharsOfLastName1(self):
result = firstNamesWithNCharsOfLastName(self.userList1,[0,1,2,3],1)
self.assertEqual(result, ["Chris_J","Chris_S","Mary Kay_J","Mary_K"])
def test_firstNamesWithNCharsOfLastName2(self):
result = firstNamesWithNCharsOfLastName(self.userList1,[0,2],2)
self.assertEqual(result, ["Chris_Jo","Mary Kay_Jo"])
def test_disambiguateFirstNamesOfTheseIndices(self):
result = disambiguateFirstNamesOfTheseIndices(self.userList1,[0,1])
self.assertEqual(result,self.userList2)
def test_nameInFirstMatchingPairOfFirstNames1(self):
result = nameInFirstMatchingPairOfFirstNames(self.userList1);
self.assertEqual(result,"Chris");
def test_nameInFirstMatchingPairOfFirstNames3(self):
result = nameInFirstMatchingPairOfFirstNames(self.userList3);
self.assertEqual(result,"Chris");
def test_nameInFirstMatchingPairOfFirstNames4(self):
result = nameInFirstMatchingPairOfFirstNames(self.userList4);
self.assertFalse(result);
def test_nameInFirstMatchingPairOfFirstNames5(self):
result = nameInFirstMatchingPairOfFirstNames(self.userList5);
self.assertEqual(result,"Mary");
def test_findIndicesOfMatchingFirstNames1(self):
result = findIndicesOfMatchingFirstNames(self.userList1,'Chris');
self.assertEqual(result,[0,1]);
def test_findIndicesOfMatchingFirstNames3(self):
result = findIndicesOfMatchingFirstNames(self.userList3,'Mary');
self.assertEqual(result,[2,3]);
def test_findIndicesOfMatchingFirstNames4(self):
result = findIndicesOfMatchingFirstNames(self.userList4,'Dave');
self.assertEqual(result,[2]);
def test_findIndicesOfMatchingFirstNames5a(self):
result = findIndicesOfMatchingFirstNames(self.userList5,'Mary');
self.assertEqual(result,[0,3]);
def test_findIndicesOfMatchingFirstNames5b(self):
result = findIndicesOfMatchingFirstNames(self.userList5,'Chris');
self.assertEqual(result,[1,2]);
def test_disambiguateAllFirstNames1(self):
result = disambiguateAllFirstNames(self.userList1);
self.assertEqual(result,self.userList1a);
def test_disambiguateAllFirstNames3(self):
result = disambiguateAllFirstNames(self.userList3);
self.assertEqual(result,self.userList3a);
def test_disambiguateAllFirstNames4(self):
result = disambiguateAllFirstNames(self.userList4);
self.assertEqual(result,self.userList4);
def test_disambiguateAllFirstNames5(self):
result = disambiguateAllFirstNames(self.userList5);
self.assertEqual(result,self.userList5a);
if __name__ == '__main__':
unittest.main()
import doctest
doctest.testmod()
|
38b57d5931b42a767fc7665d25d86c7eb97bd158 | gcpdeepesh/harshis-python-code | /Who Are You.py | 177 | 4.03125 | 4 | name = input("What is your name ? ") .upper()
if name == ("HARSHI") :
print("Hi")
print("How are you ? ")
else :
print ("Sorry, who are you .. I don't know you . ")
|
be8111228f1415d9b78fbad87c3670b8a8be5508 | HasifAhmed/BhaloChele | /util/dbfuncs.py | 5,699 | 3.65625 | 4 | import sqlite3 #enable control of an sqlite database
def add_account(user, pswd): #enables adding accounts
DB_FILE="data/curbur.db"
db = sqlite3.connect(DB_FILE) #open if file exists, otherwise create
c = db.cursor() #facilitate db ops
c.execute("SELECT * FROM accounts")
id = 0
for thing in c:
if user == thing[1]:
db.commit() #save changes
db.close() #close database
return False
id = thing[0]
c.execute("INSERT INTO {0} VALUES( {1}, '{2}', '{3}');".format("accounts", int(id)+1, user, pswd))
db.commit() #save changes
db.close() #close database
return True
def search_stories(term): #returns a list of stories with the term specified
DB_FILE="data/curbur.db"
db = sqlite3.connect(DB_FILE)
c = db.cursor()
c.execute("SELECT * FROM list_stories")
stories = []
for thing in c:
if term.lower() in thing[0].lower():
stories.append(thing[0])
return stories
db.commit() #save changes
db.close() #close database
def find_id(user): #gets the account id from a username
DB_FILE="data/curbur.db"
db = sqlite3.connect(DB_FILE,check_same_thread=False) #open if file exists, otherwise create
c = db.cursor() #facilitate db ops
c.execute("SELECT * FROM accounts")
id = 0
for thing in c:
if user == thing[1]:
id = int(thing[0])
return id
return -1
db.commit() #save changes
db.close() #close databas
def add_to_viewed_stories(acc_id, title): #records which stories have the users particpated in
DB_FILE="data/curbur.db"
db = sqlite3.connect(DB_FILE)
c = db.cursor()
c.execute("INSERT INTO {0} VALUES( {1}, '{2}');".format('stories_viewable', acc_id, title))
db.commit() #save changes
db.close() #close database
def add_text(user, title, text): #adds text to an existing story
DB_FILE="data/curbur.db"
db = sqlite3.connect(DB_FILE,check_same_thread=False) #open if file exists, otherwise create
c = db.cursor() #facilitate db ops
acc_id = find_id(user)
add_to_viewed_stories(acc_id, title)
c.execute("SELECT entry_id FROM {0}".format(title))
entry_id = 0
for thing in c:
entry_id = thing[0]
c.execute("INSERT INTO {0} VALUES( {1}, '{2}');".format(title, entry_id+1, text))
db.commit() #save changes
db.close() #close database
def add_new_story(user,title,text): #adds a new story
DB_FILE="data/curbur.db"
db = sqlite3.connect(DB_FILE,check_same_thread=False) #open if file exists, otherwise create
c = db.cursor()
acc_id = find_id(user)
add_to_viewed_stories(acc_id, title)
c.execute("CREATE TABLE {0} ({1} INTEGER PRIMARY KEY, {2} TEXT UNIQUE);".format(title, "entry_id", "entry"))
c.execute("INSERT INTO {0} VALUES( {1}, '{2}');".format(title, 0, text))
c.execute("INSERT INTO {0} VALUES('{1}')".format("list_stories", title))
db.commit() #save changes
db.close() #close database
def get_accounts(user): #retrieves the password of the username if the account exists otherwise it returns an empty string
DB_FILE="data/curbur.db"
db = sqlite3.connect(DB_FILE,check_same_thread=False) #open if file exists, otherwise create
c = db.cursor()
c.execute("SELECT * FROM {0}".format("accounts"))
for thing in c:
if user == thing[1]:
x = thing[2]
db.commit() #save changes
db.close()
return x
db.commit() #save changes
db.close() #close database
return ""
def title_exist(title): #returns true if the title of a story is taken
DB_FILE="data/curbur.db"
db = sqlite3.connect(DB_FILE,check_same_thread=False) #open if file exists, otherwise create
c = db.cursor()
c.execute("SELECT * FROM {0}".format("list_stories"))
for thing in c:
if title == thing[0]:
return True
db.commit() #save changes
db.close()
return x
db.commit() #save changes
db.close() #close database
return False
def viewed_stories(user): #returns all the titles that a user has viewed
DB_FILE = "data/curbur.db"
db = sqlite3.connect(DB_FILE,check_same_thread = False)
c = db.cursor()
acc_id = find_id(user)
c.execute("SELECT * FROM {0} WHERE {1} = {2};".format("stories_viewable", "account_id", acc_id))
d = []
for item in c:
d.append(item[1])
return d
db.commit()
db.close()
def get_latest_update(title):# returns the last entry in a specified story
DB_FILE = "data/curbur.db"
db = sqlite3.connect(DB_FILE,check_same_thread = False)
c = db.cursor()
c.execute("SELECT {0} FROM {1}".format('entry',title))
latest = ""
for entry in c:
latest = entry[0]
return latest
db.commit()
db.close()
def get_added_accounts(title): #returns a list that added to a specified story
DB_FILE = "data/curbur.db"
db = sqlite3.connect(DB_FILE,check_same_thread = False)
c = db.cursor()
c.execute("SELECT {0} FROM {1} WHERE {2} = '{3}'".format('account_id', "stories_viewable", "titles", title))
ids = []
for thing in c:
ids.append(thing[0])
print(ids)
return ids
db.commit()
db.close()
def whole_story(title): # returns the whole story in a string
DB_FILE = "data/curbur.db"
db = sqlite3.connect(DB_FILE,check_same_thread = False)
c = db.cursor()
c.execute("SELECT {0} FROM {1}".format("entry", title))
text = ""
for thing in c:
text += thing[0] + "\n"
print(text)
return text
db.commit()
db.close()
def all_stories(user): # returns a list of all stories
DB_FILE = "data/curbur.db"
db = sqlite3.connect(DB_FILE,check_same_thread = False)
c = db.cursor()
c.execute("SELECT * FROM list_stories")
stories = []
for thing in c:
stories.append(thing[0])
return stories
db.commit() #save changes
db.close() #close database
|
29478381bc6101d41d1abfb1367013bf70fc127c | lenzfilipski/Survie-de-poissons | /Poisson.py | 12,006 | 3.671875 | 4 | import random
from time import sleep
from tabulate import tabulate # Affichage du tableau
# ██████ ██ █████ ███████ ███████ ███████ ███████
# ██ ██ ██ ██ ██ ██ ██ ██
# ██ ██ ███████ ███████ ███████ █████ ███████
# ██ ██ ██ ██ ██ ██ ██ ██
# ██████ ███████ ██ ██ ███████ ███████ ███████ ███████
class Poisson: # La classe qui definit les Poisson
def __init__(self, x, y, nombre):
self.x = x
self.y = y
self.nombre = nombre
# Definit comment comparer les Poissons entre eux
def __lt__(self, other): # less than
return self.nombre < other.nombre
def __gt__(self, other): # greater than
return self.nombre > other.nombre
class Cellule: # Restes de Marco
def __init__(self):
print("Je suis pelle")
# ███ ███ ██████ ███ ██ ██████ ███████
# ████ ████ ██ ██ ████ ██ ██ ██ ██
# ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ █████
# ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
# ██ ██ ██████ ██ ████ ██████ ███████
class Monde: # la superclasse qui definit le Monde
def __init__(self, nbPoissons, taille):
self.taille = taille # Taille d'1 cote, car le Monde est carre
self.nbPoissons = nbPoissons # nb Poisson = aire du Monde
self.ListePoisson = [] # Contient les Poisson
self.nombreMorts = 0 # Compteur de morts
self.mortsTotaux = [] # Liste les Poisson morts
self.rencontre = 0
self.deplacements = 0
# Creation des poissons
# Cree une liste de 2 a self.nbPoissons+2 soit de nbPoissons
NombreListe = [i for i in range(2, self.nbPoissons+2)]
for i in range(self.nbPoissons): # Pour le nb de Poissons
x = random.randint(0, self.taille)
y = random.randint(0, self.taille)
# Choisit un nombre au hasard dans NombreListe
nombre = random.choice(NombreListe)
# Cree un poisson avec ses coordonnees et un numero unique
self.ListePoisson.append(Poisson(x, y, nombre))
# Supprime le nombre attribue au poisson
NombreListe.remove(nombre)
def deplacer(self):
for i in self.ListePoisson: # Pour chaque Poisson
# Change x et son y du Poisson
x = random.randint(-1, 1)
y = random.randint(-1, 1)
i.x = (x + i.x) % self.taille
i.y = (y + i.y) % self.taille
if x != 0 and y != 0:
self.deplacements += 1
def affichage(self, koRound): # Affichage pour le debogage
tableauMonde = [] # Tableau pour utiliser la fonction tabulate
# Pour chaque ligne
for y in range(self.taille):
poissonsLigne = [] # Contient les Poissons de la ligne y
# Pour chaque Case
for x in range(self.taille):
placeContainer = '' # String qui stocke les poissons d'1 case
listePoissCase = [] # Liste qui stocke les poisson d'1 case
# Cette methode permet de verifier qu'il y a 1+ Poisson sur la
# case et de retourner '_' si il n'y en a pas ainsi que de
# retourner les Poisson sans les '[]' des listes
for p in self.ListePoisson: # Pour chaque Poisson
if p.x == x and p.y == y: # Si coord Poisson == coord Case
# Ajoute les Poisson de la case
listePoissCase.append(p.nombre)
if listePoissCase == []: # Si pas de poisson dans la case
placeContainer += '\033[35m_\033[0m' # Met un '_' violet
else:
# Trie Poisson dans l'ordre croissant pour + de lisibilite
listePoissCase = sorted(listePoissCase)
for poisson in listePoissCase: # Pour chaque Poisson
# Si le Poisson est le dernier
if poisson == listePoissCase[-1]:
placeContainer += str(poisson)
else: # Sinon ajoute ', ' derriere le Poisson
placeContainer += str(poisson) + ', '
# Ajoute les Poisson a la liste de la ligne
poissonsLigne.append(placeContainer)
# Ajoute la ligne dans le tableau
tableauMonde.append(poissonsLigne)
# Affiche le tableau
print(tabulate(tableauMonde, tablefmt='grid'))
print('Morts du tour : ', koRound, '\n') # Affiche les Poisson morts
def bataille(self): # Gere les conflicts entre les Poisson d'1 meme case
# print('ko :') # DEBUG
koRound = [] # Liste les Poisson ko a la fin du round/bataille
for y in range(self.taille):
for x in range(self.taille):
listePoissCase = [] # Liste qui stocke les poisson d'1 case
for p in self.ListePoisson:
if p.x == x and p.y == y: # Si coord Poisson == coord Case
# Ajoute les Poisson de la case
listePoissCase.append(p.nombre)
# Combat seulement si il y au moins 2 Poisson dans la case
if len(listePoissCase) > 1:
# Trie les Poisson dans l'ordre croissant pour simplifier
listePoissCase = sorted(listePoissCase)
koCase = [] # liste les ko pour la case actuelle
# Ici on fait combatre chaque poisson entre eux une seule
# fois. Par ex pour 3 Poisson : 1 vs 2 || 1 vs 3 && 2 vs 3
# On prend tous les Poisson SAUF le dernier -> '[:-1]'
for aPos, a in enumerate(listePoissCase[:-1]):
for b in listePoissCase[aPos+1:]:
# Si a % b == 0 alors b est divisible par a
# On ajoute b aux ko
if b in koCase:
pass
else:
if b % a == 0:
koCase.append(b)
koRound.append(b)
self.mortsTotaux.append(b)
self.rencontre += 1
# Tuer les poissons
for i in koRound:
toRemove = next(x for x in self.ListePoisson if x.nombre == i)
self.ListePoisson.remove(toRemove)
self.nombreMorts += len(koRound)
return len(koRound)
# Renvoie liste des Poisson en vie + total de rencontres et de deplacements
def renvoi(self, arg=0):
listeNum = []
for i in self.ListePoisson:
listeNum.append(i.nombre)
if arg == 0:
return listeNum
else:
return listeNum, self.rencontre, self.deplacements
# ███████ ██████ ███ ██ ██████ ████████ ██ ██████ ███ ██ ███████
# ██ ██ ██ ████ ██ ██ ██ ██ ██ ██ ████ ██ ██
# █████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ███████
# ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
# ██ ██████ ██ ████ ██████ ██ ██ ██████ ██ ████ ███████
def cls(): print('\n' * 10)
def primeNumber(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up the squareroot of n
# for all odd numbers
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
def onlyPrimeNumber(liste):
onlyPrime = 0
for number in liste:
if not primeNumber(number):
onlyPrime += 1
if onlyPrime > 0:
return False
else:
return True
# ███████ ██ ██ ███████ ██████ ██████ ██████ ██ ███████ ███████ ██████ ███ ██
# ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██
# █████ ███ █████ ██ ██████ ██ ██ ██ ███████ ███████ ██ ██ ██ ██ ██
# ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
# ███████ ██ ██ ███████ ██████ ██ ██████ ██ ███████ ███████ ██████ ██ ████
def execPoisson(repStat=1, tailleMonde=5, nbPoissons=10, null=0):
listMondes = []
listRep, listPoissonsRestants = [], []
listRencontre, listDeplacements = [], []
for nbMonde in range(repStat):
listMondes.append(Monde(nbPoissons, tailleMonde))
for each in listMondes:
queNombrePrimaire = False
rep = 0
while not queNombrePrimaire:
rep += 1
each.deplacer()
each.bataille()
queNombrePrimaire = onlyPrimeNumber(each.renvoi())
poissonsRestants, rencontre, deplacements = each.renvoi(arg=1)
listRep.append(rep)
listPoissonsRestants.append(poissonsRestants)
listRencontre.append(rencontre)
listDeplacements.append(deplacements)
return listRep, listPoissonsRestants, listRencontre, listDeplacements
def execPoissonAff(repStat=1, tailleMonde=5, nbPoissons=10, sleepTime=1):
listMondes = []
listRep, listPoissonsRestants = [], []
listRencontre, listDeplacements = [], []
for nbMonde in range(repStat):
listMondes.append(Monde(nbPoissons, tailleMonde))
for each in listMondes:
nombreCompose = True
rep = 0
each.affichage(0)
print("DEPART\n_________________\n")
while nombreCompose:
sleep(sleepTime)
cls()
rep += 1
print('/\\/\\/\\/\\/\\/\\/\\ TOUR N° :', rep, ' /\\/\\/\\/\\/\\/\\/\\')
each.deplacer()
ko = each.bataille()
each.affichage(ko)
nombreCompose = not onlyPrimeNumber(each.renvoi())
poissonsRestants, rencontre, deplacements = each.renvoi(arg=1)
listRep.append(rep)
listPoissonsRestants.append(poissonsRestants)
listRencontre.append(rencontre)
listDeplacements.append(deplacements)
return listRep, listPoissonsRestants, listRencontre, listDeplacements
# **** SCRIPT ****
# testLP = execPoissonAff(10, 100, 0.01)
# print(testLP, '\n', testMT)
|
ead65b2d0599e32fbe11ddc4ef8fc94d9b5cbad5 | Shivajsk/Turtle | /spiral.py | 1,529 | 3.78125 | 4 | from turtle import *
import random
import pygame
w=Turtle()
s=Screen()
shape("circle")
l=[ "red","blue","orange","yellow","green"]
s.bgcolor("black")
w.speed(-1)
w.pensize(1)
def t(x):
w.rt(60)
w.fd(x)
w.rt(120)
w.fd(x)
w.rt(120)
w.fd(x)
def sq(x):
for i in range(2):
w.fd(x)
w.rt(90)
w.fd(x)
w.rt(90)
def rect(x,y):
for i in range(2):
w.fd(x)
w.rt(90)
w.fd(y)
w.rt(90)
o=.5
k=10
for i in range(0):
# w.color(random.choice(l))
# w.begin_fill()
# w.circle(o)
# w.end_fill()
w.lt(10)
#w.color("green")
t(k)
# w.color(random.choice(l))
w.color("yellow")
t(k)
k-=4
w.rt(250)
#w.color("brown")
#w.pensize(10)
w.pensize(.1)
w.color("yellow")
#w.fd(550)
#w.circle(10)
#done()
#for i in range(36):
# w.color(random.choice(l))
# w.circle(100)
# w.lt(10)
# w.fd(35)
#w.rt(90)
#w.fd(200)
w.penup()
w.setpos(-400,0)
w.pendown()
while 1:
w.color(random.choice(l))
w.speed(0)
for i in range(18):
w.fd(100)
w.lt(160)
w.rt(10)
w.fd(70)
# w.lt(10)
w.fd(200)
for i in range(60):
w.color(random.choice(l))
w.circle(30)
w.lt(6)
w.fd(200)
for i in range(60):
w.color(random.choice(l))
w.circle(19)
w.lt(6)
w.fd(200)
for i in range(60):
w.color(random.choice(l))
w.circle(10)
w.lt(6)
def t(x):
w.rt(60)
w.fd(x)
w.rt(120)
w.fd(x)
w.rt(120)
w.fd(x)
#t(60)
done() |
a2d1e931447ef62293e35b6619c52ad2bf6f6030 | DT211C-2019/programming | /Year 2/Saul Burgess/Labs/2020-10-15/Lab9(2).py | 388 | 4.625 | 5 | def number_printer_odd_or_even (max):
"""When passed a number, this function will iterate from 0-Input while also displaying if the number is odd or even"""
for i in range(0, max+1):
if i % 2 > 0:
print(i, "Is odd")
else:
print(i, "Is even")
#Driver
user_input = int(input("Please enter a number: "))
number_printer_odd_or_even(user_input) |
74c1a916516a8c0d534f71f550b930bdf41a11f0 | quick0831/QuickPython | /Basic/operator.py | 228 | 3.71875 | 4 | # Just a reminder
a=3+6
b=3-6
c=3*6
d=3/6
e=9//6 # Answer will be an Interger
#print(d)
#print(e)
f=5**2 # Power 5^2
#print(f)
g=7%3 # 7 mod 3 = 1
#print(g)
#...............
# Add up
x=5
print(x)
x=x+5
print(x)
x+=5
print(x) |
a02d891f0bcdfa088e839d62be0eeff9718bea05 | evmiguel/udacity_ds_algo | /Problems_vs_Algorithms/problem3.py | 1,725 | 4.1875 | 4 | def mergesort_descending(items):
if len(items) <= 1:
return items
mid = len(items) // 2
left = items[:mid]
right = items[mid:]
left = mergesort_descending(left)
right = mergesort_descending(right)
return merge(left, right)
def merge(left, right):
merged = []
left_index = 0
right_index = 0
while left_index < len(left) and right_index < len(right):
if left[left_index] > right[right_index]:
merged.append(left[left_index])
left_index += 1
else:
merged.append(right[right_index])
right_index += 1
merged += left[left_index:]
merged += right[right_index:]
return merged
def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
descending_list = mergesort_descending(input_list)
update = 0
multiplier = 1
max_sum = [0,0]
for i, item in enumerate(descending_list):
if i > 0 and i % 2 == 0:
multiplier = 10
max_sum[update] = max_sum[update]*multiplier + item
update = not update
return max_sum
def test_function(test_case):
output = rearrange_digits(test_case[0])
solution = test_case[1]
if sum(output) == sum(solution):
print("Pass")
else:
print("Fail")
test_function([[1, 2, 3, 4, 5], [531, 42]])
test_function([[4, 6, 2, 5, 9, 8], [964, 852]])
# Test 2 elements
test_function([[1, 100], [100, 1]])
# Test 1 element
test_function([[1], [1, 0]])
# Test 0 elements
test_function([[], [0, 0]])
|
2d14fa45ef91b8387c1dc21b4f673081f2c4e280 | sweenejp/learning-and-practice | /treehouse/python-beginner/yatzy/dice.py | 1,483 | 3.703125 | 4 | import random
class Die:
def __init__(self, sides=2, outcome=0):
if not sides >= 2:
raise ValueError("Must have at least 2 sides")
if not isinstance(sides, int):
raise ValueError("Sides must be a whole number")
# this was super confusing to me at first...
# the outcome argument is set to 0 as a default. If you pass in something other than 0,
# then outcome will be "false" (because 0 gets false in a boolean expression). If it is
# false, then self.butt gets random.randint(1, sides)
self.outcome = outcome or random.randint(1, sides)
def __int__(self):
return self.outcome
def __eq__(self, other):
return int(self) == other
def __ne__(self, other):
return int(self) != other
def __gt__(self, other):
return int(self) > other
def __lt__(self, other):
return int(self) < other
def __ge__(self, other):
return int(self) >= other
def __le__(self, other):
return int(self) <= other
def __add__(self, other):
return int(self) + other
def __radd__(self, other):
return int(self) + other
def __repr__(self):
return str(self.outcome)
class D6(Die):
def __init__(self, outcome=0):
super().__init__(sides=6, outcome=outcome)
class D20(Die):
def __init__(self, outcome=0):
super().__init__(sides=20, outcome=outcome)
a = D20()
print(a.outcome)
|
54f5257d87605dc1ae5ec4420f4870278a597896 | cabarca01/PythonDojo | /exercises/exe_1_2.py | 205 | 3.625 | 4 | hours = raw_input("Enter hours worked: ")
rate = raw_input("Enter rate per hour: ")
grossPay = float(hours) * float(rate)
print "Hours: ", hours
print "Rate: ", rate
print "Gross Pay: ", grossPay |
7d7d8d1086a8223da5f9021954edaf7c4c8ce6f7 | lovms/code_snippets | /algorithms/quicksort.py | 2,685 | 3.90625 | 4 | import random
import sys
import numpy as np
'''
Core Idea:
1. Split an number array into to parts: left one are smaller than PIVOT,
and right one are bigger than PIVOT.
2. We always swap the number pointed by index `h` with the pivot, due to
the traversing order from left to right.
'''
def quicksort(array, low, high):
if low >= high:
return
# pivot = random.randint(low, high)
# #print('low: %s ; high: %s; pivot: %s' % (low, high, pivot))
# if pivot > low:
# tmp = array[low]
# array[low] = array[pivot]
# array[pivot] = tmp
pivot = low
l = low + 1
h = high
while l <= h:
while l < high and array[l] < array[pivot]: # use array[l] <= array[pivot] leads to unstable sort
l += 1
while h > pivot and array[h] >= array[pivot]: # use array[h] >= array[pivot] here leads to stable sort
h -= 1
if l < h:
tmp = a[l]
a[l] = a[h]
a[h] = tmp
l += 1
h -= 1
tmp = a[h]
a[h] = a[pivot]
a[pivot] = tmp
pivot = h
quicksort(array, low, pivot)
quicksort(array, pivot + 1, high)
'''
思想就是找到一个pivot,然后通过前后遍历整个数组,将其分成两个部分:
小索引部分都是不大于pivot的;
大索引部分都是不小于pivot的。
基本的想法是通过索引low从左边找大于pivot的,通过high从右边找小于pivot的然后作交换;
pivot选择low的起始位置;
但是实际的quicksort算法使用了技巧,就是先将pivot保存起来,然后先后依次将high找到的小于pivot的数放到low,然后将low找到的大于pivot的数放到high,
最后当low==high时,再将pivot放到low索引最后的位置,从而省去了多次交换!!!
'''
def std_quicksort(array, low, high):
if low >= high:
return
pivot = low
l = low
h = high
pivot_data = array[l]
while l < h:
while l < h and array[h] >= pivot_data:
h -= 1
#if h != l:
array[l] = array[h]
while l < h and array[l] <= pivot_data: # 本行的l < h条件不能换成 l <= high; 因为此时array[h] 其实是pivot_data,只是没有填上去。(考虑序列:48, 34, 49)
l += 1
if l != h:
array[h] = array[l]
array[l] = pivot_data #最后h == l
pivot = l
std_quicksort(array, low, pivot)
std_quicksort(array, pivot+1, high)
if __name__ == '__main__':
a = list(np.random.randint(100, size=50))
print(a)
#quicksort(a, 0, len(a) - 1)
std_quicksort(a, 0, len(a) - 1)
print("Sorted")
print(a)
|
bfab37738a359d62146a70320cd2796b697a182f | seluccaajay/Full-Stack-Self-Learned-Codes | /Zenclass/4/D4_program using ASCII.py | 243 | 3.828125 | 4 | ## Write a program to convert the list x as mentioned below
## x = ['a','e','m','r'] to ['b','f','n','s']
x = ['a','e','m','r']
z = []
length = len(x)
for i in range(0,length):
y = chr(ord(x[i])+1)
z.append(y)
i += 1
print(z)
|
301ac5e0d6d65524b6833a70c4f6aee7fed6f556 | tombasche/debut | /examples/main.py | 4,528 | 3.578125 | 4 | from debut import Slide, TitleSlide, SlideShow, Text, DotPointText
def main():
title_slide = TitleSlide(
title="Agile Principle #9",
author="Thomas Basche 🤓 "
)
slide_1 = Slide(
heading="Introduction",
text=Text(["Continuous attention to technical excellence and good design enhances agility."]),
border="\\"
)
slide_2 = Slide(
heading="What is technical excellence?",
text=DotPointText([
"A level of quality, maintainability and extensibility of software expressed through a lack of defects and an abundance in business value.",
"This means software which works and software that is valuable.",
"It means software that's easy to change at the drop of a hat!"
]),
border="\\"
)
slide_3 = Slide(
heading="What is good design?",
text=DotPointText([
"A good design: ",
"* Satisfies certain goals within a set of constraints, ",
"* takes into account aesthetic and functional considerations, ",
"* and interacts efficiently within its environment."
]),
border="\\"
)
slide_4 = Slide(
heading="How do these things enhance agility?",
text=DotPointText([
"Software that's well-designed is software that allows us to maintain a constant pace indefinitely.",
"Good design reduces the amount of mental overhead spent reasoning about code.",
"Highly-cohesive and loosely-coupled components mean faster delivery.",
"... which also means better and more thorough testing.",
"Less time spent fixing bugs and mistakes.",
"More time spent adding features and value."
]),
border="\\"
)
slide_5 = Slide(
heading="How do we maintain 'continuous attention' to these things?",
text=DotPointText([
"Pair-programming helps us stay honest. Question the why and the how of an implementation. Play devil's advocate! 😈 ",
"Let's talk about the code during a desk check!",
"* What might you have done differently?",
"* What ideas did you discard along the way and why?",
"* What were the challenges?",
"* Can the person reading the code understand what it does without you explaining it?",
"* Is there something in this solution that might hinder us in future?"
]),
border="\\"
)
slide_6 = Slide(
heading="How do we maintain 'continuous attention' to these things?",
text=DotPointText([
"Put yourself in the shoes of a customer or product owner",
"* Would they be happy with a 'hacky solution'? ",
"* They're paying a lot of money for it!"
]),
border="\\"
)
slide_7 = Slide(
heading="So how do we get there?",
text=DotPointText([
"Come to the software engineering chapter!",
"There's resources left, right and centre about technical excellence and good design: ",
"* 📖 Clean Code, by Robert C. Martin (Uncle Bob)",
"* 📖 The Pragmatic Programmer by Andy Hunt and Dave Thomas",
"* 📖 Test-Driven Development by Example by Kent Beck",
"* 📺 Dozens of conference talks on YouTube!",
"* 💬 TALK to your fellow software engineers about your code. You'll either be surprised by how much they have to say, or what they're willing to learn."
]),
border="\\"
)
slide_8 = Slide(
heading="Questions? ⁉️",
text=Text([
"This presentation was created by me and is on github: ",
"* github.com/tombasche/debut",
"The framework is something I created because ... why not. It uses 'curses' under the hood, a nearly 30-year old API that ships with UNIX/POSIX systems which efficiently writes text to the terminal.",
"You could pull the code down and create your own 'slideshow' with it if you were so inclined...\n",
"slide_show = SlideShow([title_slide, slide_1, slide_2, slide_3, slide_4, slide_5, slide_6, slide_7, slide_8],)",
"slide_show.present()"
]),
border="\\"
)
slide_show = SlideShow(
slides=[title_slide, slide_1, slide_2, slide_3, slide_4, slide_5, slide_6, slide_7, slide_8],
show_page_numbers=True
)
slide_show.present()
if __name__ == "__main__":
main()
|
6b19ce3f6b3df325caf1de7a10111dd92e81237d | shubham2704/patterns-python | /pattern-12.py | 126 | 3.75 | 4 | for x in range(1,6):
for y in range(1,x+1):
print(y,end='')
print()
"""
# Pattern
1
12
123
1234
12345
""" |
a73be5b80c733ed58ff4fb5de5f75d9254c6a51d | picaindahouse/Code-Wars-Projects | /Just Practice- 40 to 99/Side Project 81 (5 Kyu) (Numbers that are a power of their sum of digits)/Side Project 81.py | 735 | 3.5625 | 4 | # Most Efficient:
def power_sumDigTerm(n):
return sorted([x**y for x in range(109) for y in range(14) if sum([int(r) for r in str(x**y)]) == x and x**y > 80])
# What I had come up with first:
from itertools import combinations_with_replacement
def power (n):
if n in [sum([int(x) for x in str(n)]) ** y for y in [3,4,5,6,7,8,9,10,13]]:
return n
else: return None
def power_sumDigTerm(n):
print(n)
if n == 1: return 81
elif n > 35: t = 11
elif n > 15: t = 10
else: t = 5
numbers= [0,1,2,3,4,5,6,7,8,9]
tom = [sum(x) ** y for x in combinations_with_replacement(numbers,t) for y in [3,4,5,6,7,8,9,10,13]]
return sorted([x for x in {x for x in tom} if x> 511 and power(x) == x])[n-2] |
d08f230971504a042cf96a1b61fb82e603f732cf | jlyons6100/Wallbreakers | /Week_1/flipping_an_image.py | 821 | 4.125 | 4 | # Flipping An Imagine:
# Flip a matrix horizontally, then invert it
class Solution:
# flip(A): Reverses each row in A matrix
def flip(self, A: List[List[int]]) -> None:
for row in range(len(A)):
for col in range(int(len(A[0])/2)):
rev_col = len(A[0]) - 1 - col
A[row][col], A[row][rev_col] = A[row][rev_col], A[row][col]
# invert(A): Swaps 0's and 1's in a matrix
def invert(self, A: List[List[int]]) -> None:
for row in range(len(A)):
for col in range(int(len(A[0]))):
A[row][col] = 1 if A[row][col] == 0 else 0
# flipAndInvertImage: Flips, then inverts matrix A.
def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]:
self.flip(A)
self.invert(A)
return A
|
12e3750c8010d635970938fa8dbd1857ece26f45 | raam1210/PythonBasics | /PythonBasics/Palindrome.py | 131 | 4.125 | 4 | s = input("Enter a string: ")
revstr = s[::-1]
if revstr == s:
print("It is a palindrome")
else:
print("Not a palindrome") |
a81a05847130c2f2080221ed87b0c1f7c6799d2e | sudevansujit/2_Python | /A2080_Reverse_a_List.py | 414 | 4.375 | 4 | # Python Program to Reverse List Elements
newlist = [1,2,3,4,5,6,7]
j = len(newlist)-1
i = 0
while(i < j):
element = newlist[i]
newlist[i] = newlist[j]
newlist[j] = element
i = i + 1
j = j - 1
print("\nThe Reversed List is = ", newlist)
# O/P
# The Reversed List is = [7, 6, 5, 4, 3, 2, 1]
|
48d55682aa9c621448be888d16245821c0599cde | nxv1317/YouTude-Video-Downloader | /youtube.py | 917 | 3.703125 | 4 | from pytube import YouTube
#enter the link from the browser and retrieve all the streams with the resolutions
yt = YouTube(str(input("Enter the video link: ")))
videos = yt.streams.all()
#loop through the videos and assign a number to each video
print(" ")
s = 1
for v in videos:
print(str(s)+". "+str(v))
s += 1
#ask the user to enter the number of the specific video to be downloaded
print(" ")
n = int(input("Enter the number of the video: "))
vid = videos[n-1]
#ask the user to enter the area where the file should be downloaded
print(" ")
destination = str(input("Enter the destination: "))
#ask the user to name the file
print(" ")
fileName = str(input("Please enter the name of the file: "))
#begin the download
print(" ")
vid.download(destination, filename=fileName) #download the file to the destination the user entered
print("Download successful.") #print a success message to the user
|
f02d56c4a997426394b852471eef9853332a6061 | nichro02/python_hangman | /app.py | 1,768 | 4.15625 | 4 | import random
#selected_word = ''
word_bank = ['pizza', 'python', 'sleep', 'class']
#get random word
def get_random_word():
return random.choice(word_bank).upper()
#DECLARE WORD CLASS -----------------------------
class Word():
def __init__(self, chosen_word=None):
self.chosen_word = get_random_word()
pass # this method will split the word up into a list of dictionaries with 2 attributes:
pass # the letter/character, and a boolean representing whether or not it has been guessed
def split_string(self):
word_to_list = list(self.chosen_word)
print(word_to_list)
def print_word(self):
print('Hit print word', self.chosen_word)
def check_letter(self):
print('Hit check letter')
answer = Word()
#test that random word gets selected and split into list
answer.print_word()
answer.split_string()
#FUNCTIONS -------------------------------------
def decrement_round():
print('starting round', game['guesses_left'])
game['guesses_left'] -= 1
print('rounds left,', game['guesses_left'])
def game_flow_logic():
pass #inset game flow here
if game['guesses_left'] > 0:
guess = input('Please guess a letter ').upper()
#evaluate if guessed letter is in word
print(guess)
win_scenario()
else:
print('Too bad! You ran out of guesses before you could spell the word')
def win_scenario():
if game['current_word'] == answer.chosen_word:
print('You have won the game')
#GAME OBJECT -------------------------------------
game = {
'current_word': ' _ ' * len(answer.chosen_word),
'guessed_letters': [],
'guesses_left': 8
#'decrement_round': decrement_round
}
#decrement_round()
game_flow_logic() |
f67ade2364082b1786faede7cab2dd8181025d88 | kaprushka/my_homeworks | /04. Python_2/python_2.py | 211 | 3.671875 | 4 | N = input('Введите число: ')
N = int(N, base=10)
i = 0
while i < N:
a = input('Введите слово: ')
if a == 'программирование':
break
print(a)
i += 1
|
45833f4c95e8ff9e7752638f04a161e7cecbc7d7 | davidpneal/adventofcode | /2018/day02/d02-2.py | 1,255 | 3.765625 | 4 | #12/2/2018
#This puzzle looks for two strings that only differ by a single character then
# returns all of the common characters shared by those strings
import itertools
input = open("d02-1input.txt")
#input = open("d02-2test.txt")
data = input.read()
boxid = []
for line in data.splitlines():
boxid.append(line)
#itertools can replace the standard nested for loops, this syntax generates all possible 2-item combinations
for str1, str2 in itertools.combinations(boxid, 2):
numdiff = 0
#The zip generator returns a list of tuple pairs, enumerate adds a counter to these tuples when looping them
#The for sets the counter to index and the characters from the tuple pair to (c1,c2)
for index, (c1, c2) in enumerate(zip(str1, str2)):
#Compare the two strings character by character, if there is a difference set that to diffpos
if c1 != c2:
diffpos = index
numdiff += 1
#If this is the second difference, move on
if numdiff == 2:
break
#If there was exactly one difference, a match was found
if numdiff == 1:
#Omit the character at diffpos using slicing
match = str1[:diffpos] + str1[(diffpos + 1):]
print("Common letters:",match)
break
''' MISC
Correct answer: bvnfawcnyoeyudzrpgslimtkj
'''
|
2cabfa68a1a14fdf492822584a2eed96824e8cce | abhishekkuber/leetcode | /leetcode_389.py | 942 | 3.859375 | 4 | '''
You are given two strings s and t.
String t is generated by random shuffling string s and then add one more letter at a random position.
Return the letter that was added to t.
Example 1:
Input: s = "abcd", t = "abcde"
Output: "e"
Explanation: 'e' is the letter that was added.
Example 2:
Input: s = "", t = "y"
Output: "y"
Example 3:
Input: s = "a", t = "aa"
Output: "a"
Example 4:
Input: s = "ae", t = "aea"
Output: "a"
'''
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
alpha_1 = [0] * 26
alpha_2 = [0] * 26
for i in s:
idx = ord(i) - 97
alpha_1[idx] += 1
for i in t:
idx = ord(i) - 97
alpha_2[idx] += 1
for i in range(26):
if alpha_1[i] != alpha_2[i]:
return chr(i + 97) |
b0d7817f5e640abc1ae10fcc04ed755ab1f00a18 | gitmkb/pyt | /FilterMapReduce.py | 299 | 3.71875 | 4 | from functools import reduce
num = [5, 4, 3, 8, 9, 2, 1, 6, 11, 10]
print('Python list: ', num)
evens = list(filter(lambda x: x%2==0, num))
print('Filter: ', evens)
doubles = list(map(lambda x: x*2, evens))
print('Doubles: ', doubles)
sum = reduce(lambda x, y: x+y, doubles)
print('Sum: ', sum)
|
aafab5926bd54e4279f1afe12144d7cae466af14 | Francisco-FP/Practicas | /python/juego2.py | 435 | 3.984375 | 4 | """Adivina el numero."""
from random import randint
numero_aleatorio = randint(1,10)
print("Adivina el numero entre el 1 y 10.\n")
mi_numero = int(input("Numero: "))
while mi_numero != numero_aleatorio:
print("El numero es incorrecto.")
if mi_numero < numero_aleatorio:
print(" El numero es mas grande.")
else:
print("El numero es mas pequeño.")
mi_numero = int(input("Numero"))
print("Ganaste") |
1e8f179beff204233bbb2318a64a1b132c2a17f5 | Risauce/Pre2015Code | /CSCI 127/Labs/vowelslab3.py | 1,752 | 4.15625 | 4 | # --------------------------------------
# CSCI 127, Lab 3
# September 19, 2017
# Riley Roberts
# --------------------------------------
import string
def count_vowels(sentence):
count = 0
count += sentence.count("i")
count += sentence.count("e")
count += sentence.count("o")
count += sentence.count("u")
#count += sentence.count("y") #Y ISNT A VOWEL??!
count += sentence.count("a")
return count
def count_vowels_iterative(sentence):
count = 0
vowels = "aeoui"
for i in sentence:
if i in vowels:
count += 1
return count
def count_vowels_recursive(sentence):
count = 0
vowels = "aeoui"
if len(sentence) == 1:
if sentence[0] in vowels:
return 1
return 0
else:
if sentence[0] in vowels:
count = 1 + count_vowels_recursive(sentence[1:])
return count
else:
count = count_vowels_recursive(sentence[1:])
return count
# --------------------------------------
def main():
answer = "yes"
while (answer == "yes") or (answer == "y"):
sentence = input("Please enter a sentence to evaluate: ")
sentence = sentence.lower() # convert to lowercase
print()
print("Number of vowels using count =", count_vowels(sentence))
print("Number of vowels using iteration =", count_vowels_iterative(sentence))
print("Number of vowels using recursion =", count_vowels_recursive(sentence))
print()
answer = input("Would you like to continue: ").lower()
print()
# --------------------------------------
main()
|
e669dd8e8beb78edaa37e5145cce2d88de1a75cb | kjb4494/PythonStudy | /_20180424_q/q_04.py | 504 | 3.734375 | 4 | def q_04():
# 두 정수를 입력으로 받아
# 앞수가 뒷수 보다 크면 >
# 앞수가 뒷수 보다 작으면 <
# 같으면 =
# 를 출력하는 프로그램을 작성하세요.
while True:
try:
num1, num2 = map(int, input("두 정수 입력: ").split(' '))
print(">" if num1 > num2 else "<" if num1 < num2 else "=")
return
except Exception as e:
print("입력 값이 잘못되었습니다.", e) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.