blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
32cc2a74873ed67c2b0acec7a1cb147ab49d5f4e
|
yawei798/AlgorithmsAndDataStructures
|
/用Python解决数据结构和算法/4:递归/four_9.py
| 1,733 | 3.5625 | 4 |
"""
动态规划:找零钱问题
"""
# # 通过循环,但是没有跟踪
# def dpMakeChange(coinValueList, change, minCoins):
# for cents in range(change+1):
# coinCount = cents # 这是按每个都是1美分时的最大情况
# for j in [c for c in coinValueList if c <= cents]:
# if minCoins[cents-j] + 1 < coinCount:
# coinCount = minCoins[cents-j] + 1
# minCoins[cents] = coinCount
# return minCoins[change]
#
#
#
# a = [5, 1, 10, 25]
# b = 10
# c = [0] * 11
# d = dpMakeChange(a, b, c)
# print(c)
# print(d)
# 通过循环,有跟踪
def dpMakeChange(coinValueList, change, minCoins, coinsUsed):
for cents in range(change+1):
coinCount = cents # 这是按每个都是1美分时的最大情况
newCoin = 1
for j in [c for c in coinValueList if c <= cents]:
if minCoins[cents-j] + 1 < coinCount:
coinCount = minCoins[cents-j] + 1
newCoin = j
minCoins[cents] = coinCount
coinsUsed[cents] = newCoin
return minCoins[change]
# a = [1, 5, 10, 25]
# b = 11
# c = [0] * 12
# d = [0] * 12
# m, n = dpMakeChange(a, b, c, d)
# print(m)
# print(n)
def printCoins(coinsUsed, change):
coin = change
while coin > 0:
thisCoin = coinsUsed[coin]
print(thisCoin)
coin = coin - thisCoin
def main():
amnt = 45
clist = [1, 5, 10, 21, 25]
coinCount = [0] * (amnt+1)
coinsUsed = [0] * (amnt + 1)
print('Making change for', amnt, 'requires')
print(dpMakeChange(clist, amnt, coinCount, coinsUsed))
print('They are:')
printCoins(coinsUsed, amnt)
print('coinCount: ', coinCount)
print('coinsUsed: ', coinsUsed)
main()
|
c4ce8cb096120452a9e25f7d1fb86f9a4ffb2570
|
PrajjwalDatir/CP
|
/gfg/jug1.py
| 2,795 | 4.1875 | 4 |
# Question 1
"""
so we have linked list with data only equal to 0 , 1 or 2 and we have to sort them in O(n) as I think before prajjwal knows the answer of this question
"""
#so first we need linked list to start withs
class Node:
"""docstring for Node"""
def __init__(self, data):
self.data = data
self.next = None
class linkedList:
"""docstring for linkedList"""
def __init__(self):
self.head = None
def push(self, data):
temp = self.head
newnode = Node(data)
if self.head is None:
self.head = newnode
return
else:
while temp.next is not None:
temp = temp.next
temp.next = newnode
def printList(self):
temp = self.head
if self.head is None:
print("List is empty")
return 0
while temp.next:
print(temp.data, end="->")
temp = temp.next
print(temp.data)
return 1
def sortList(self):
if self.head is None:
print("Nothing to sort here.")
return
elif self.head.next is None:
return
# here zero one and two are to point at the latest 0 1 2 countered so that we can just swap with them
last_zero = None
last_one = None
last_two = None
temp = None
current = self.head
if self.head.data == 1:
last_one = current
elif self.head.data == 0:
last_zero = current
else:
last_two = current
# print(f"current is {current.data}")
# self.printList()
current = current.next
while current.next:
# print(f"current is {current.next.data}")
if current.next.data == 0:
print(f"current is {current.next.data}")
temp = current.next
if last_zero is None:
current.next = temp.next
temp.next = self.head
self.head = temp
last_zero = temp
self.printList()
else:
current.next = temp.next
temp.next = last_zero.next
last_zero.next = temp
last_zero = temp
self.printList()
elif current.next.data == 1:
# print(f"current is {current.next.data}")
# self.printList()
temp = current.next
if last_one is None:
print(f"current is {current.next.data}")
self.printList()
current.next = temp.next
if last_zero is None:
temp.next = self.head
self.head = temp
else:
temp.next = last_zero.next
last_zero.next = temp
last_one = temp
self.printList()
else:
current.next = temp.next
temp.next = last_one.next
last_one.next = temp
last_one = temp
else:
print(f"current is {current.next.data}")
self.printList()
current = current.next
ll = linkedList()
# test case : 12012010 answer should be 00011122
# bug is when we encounter 1 before encountering
ll.push(2)
ll.push(1)
ll.push(0)
# ll.push(1)
# ll.push(0)
# ll.push(2)
# ll.push(0)
# ll.push(1)
# ll.push(0)
ll.printList()
ll.sortList()
ll.printList()
|
1a1ab1382d7b17c9eda914a0d482ed0ac6c28578
|
bercik29/pythoncourse
|
/rkapitulacia.py
| 589 | 3.5625 | 4 |
#!/usr/bin/env python
import csv
import sys
import statistics
file_name = sys.argv[1]
data = []
with open(file_name, 'r') as f:
reader = csv.reader(f)
for row in reader:
for e in row:
data.append(int(e.strip()))
print(data)
print(len(data))
print(min(data))
print(max(data))
print(statistics.mean(data))
print(statistics.median(data))
positive = [num for num in data if num > 0]
negative = [num for num in data if num < 0]
zeroes = [num for num in data if num == 0]
print(positive)
print(negative)
print(zeroes)
|
248cd5a664b182aef291084a8f40aa5e68b7e503
|
tianhaomin/algorithm4
|
/Stack1.py
| 999 | 3.984375 | 4 |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#链表实现,可动态处理lalala
class node(object):
def __init__(self):
self.item = None
self.next = None
class Stack(object):
first = node()
def __init__(self):#初始化
self.first = None
self.n = 0#计数
def isEmpty(self):
return self.first == None
def size(self):
return self.n
def push(self,v):#添加
oldFirst = node()
oldFirst = self.first
self.first = node()
self.first.item = v
self.first.next = oldFirst
self.n += 1
def pop(self):#退出第一个数(remove)
temp = self.first.item
self.first = self.first.next
self.n -= 1
return temp
def peek(self):#只是返回最早添加的数但不删除
return self.first.item
#测试代码
if __name__ == "__main__":
s = Stack()
s.push(3)
s.push(4)
s.push(1)
print s.pop()
|
00b7e0584a958e551657b126bb2d1a331383f2b8
|
fancunwei95/MD_MC_molecular_simulation
|
/stat.py
| 718 | 3.59375 | 4 |
#!/usr/bin/env python
import sys
from math import sqrt
fo_name = sys.argv[-1]
fo = open(fo_name,"r")
average = 0.0
count = 0.0
data = []
for line in fo:
this_num = float(line.split()[-1])
data.append(this_num)
accept = data[-1]
start = int(round(0.125*len(data)))
print start
average = 0.0
std_2 = 0.0
count = 0.0
for i in range(start, len(data)-1):
average = average + data[i]
count += 1.0
average = average/(count)
for i in range(start, len(data)-1):
std_2 += (data[i]-average)*(data[i]-average)
std =sqrt(std_2/(count-1.0))
print str(fo_name) + ":"
print "accept ratio:",this_num
print "average :",average
print "std :",std
print "stand error :",std/sqrt(count)
fo.close()
|
f34b640719dad2fc38b2dcb820b24dcccc26f4dc
|
jmtellez/beautyParlorApi
|
/TestProgram.py
| 1,238 | 3.75 | 4 |
__author__ = 'Juan Tellez'
from API import *
while 1:
showMenu()
choice = int(raw_input())
if choice is -1:
print" Bye..."
break
elif choice is 1:
print "Your options are: Barber, Hair Stylist, Receptionist"
val= raw_input()
getStaffByPosition(val)
elif choice is 2:
print "Your options are:\n 1: Christine Rielly\n 2: Jonatan Reyes"
val = raw_input()
getStaffByOwner(val)
elif choice is 3:
print "Please enter an Appointment time (10-19) and a staff id (20-23) ex: 13:00:00, 20"
val= raw_input()
getClientInfo(val.split(',')[0],val.split(',')[1])
elif choice is 4:
print"Please enter a Hair Product Brand ex: Pantene"
val= raw_input()
getProductCount(val)
elif choice is 5:
print" Pleae enter an Appointment time (10-19) and an amount of appointments ex: 15:00:00, 3"
val= raw_input()
getStaffByAppointments(val.split(',')[0],int(val.split(',')[1]))
elif choice is 6:
print" Please enter two Appointment times, one where staff is free and other where staff is busy ex: 13:00:00, 17:00:00"
val= raw_input()
getStaffForEval(val.split(',')[0],val.split(',')[1])
|
1dd0b6d5d74e9dc35335c72d06c7061b64749611
|
bossjoker1/algorithm
|
/pythonAlgorithm/Practice/151翻转字符串里的单词.py
| 566 | 3.75 | 4 |
# 我的sb解法
# 因为python string 不可变所以必须得有个额外的结果数组
class Solution:
def reverseWords(self, s: str) -> str:
temp = s.split(' ')
temp.reverse()
temp = [x.strip() for x in temp if x.strip() != '']
print(temp)
return ' '.join(x for x in temp)
class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(s.split()[::-1])
# c++空间复杂度才能达到O(1)
# 思路是先去除左右空格和中间的多余空格
# 然后反转整个字符串再反转单词
|
a7d201fcaa89ec97ca9fc07b104672b665b10c24
|
myano/primes
|
/list_of_primes.py
| 558 | 4.34375 | 4 |
#!/usr/local/bin/python
import Is_Prime
def findprimes(h):
'''
This function will generate a 'list' of prime numbers up to the given number inputted by the user.
'''
li=[]
for n in range(2, h):
j=0
if Is_Prime.Is_Prime(n) == True:
j+=1
li.append(n)
return li
if __name__ == '__main__':
print getattr(findprimes,'__doc__')
usernum=raw_input("Please enter up to what number you want to see a list of prime numbers: ")
usernum=int(usernum)
print findprimes(usernum)
|
bd190ff7638072ae4befb62e0c73c880d61bb371
|
FabianoBill/Estudos-em-Python
|
/Curso-em-video/115-exerciciospython/d073_times.py
| 576 | 4.21875 | 4 |
# Exercício Python 73: Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro de Futebol, na ordem de colocação. Depois mostre: a) Os 5 primeiros times.b) Os últimos 4 colocados.c) Times em ordem alfabética.d) Em que posição está o time da Chapecoense.
times = ("a", "e", "i", "o", "u", "b", "c", "d", "f", "g")
print("Os 5 primeiros colocados são: ", times[:5])
print("Os 4 últimos colocados são: ", times[-4:])
print("Times em ordem alfabética: ", sorted(times))
print(f"O time c está na {times.index('c') + 1}ª posição.")
|
6227bc8f36dce8eda0b78bf590f9b7cbf6516135
|
ckeown/learning_rule
|
/NeuralNetwork.py
| 9,176 | 3.625 | 4 |
import imp
import random
import math
from arabic_dataset import *
# imp.reload(arabic_dataset)
# Node for a neural netowrk
# It's set up so you can traverse the network up or down (may be overkill)
class Node:
def __init__(self):
self.activation = 0.0 # current activation of the node
self.inputs = [] # list of input nodes--empty for input layer
self.weights = [] # list of float for weights--empty for output layer
self.outputs = [] # list of output nodes--empty for output layer
self.weight_change = 0.0 # variable created for backprop
# for printing a node
def __str__(self):
output = ""
output += "There are " + str(len(self.inputs)) + " input nodes.\n"
output += "There are " + str(len(self.outputs)) + " output nodes.\n"
output += "Weights are " + str(self.weights) + "\n"
output += "Change in weights are " + str(self.weight_change) + "\n"
output += "Activation is " + str(self.activation) + "\n"
return output
# Computes the linear combination. It can either apply logistic
# or the nondifferentialbe if > 0, 1 else 0
def update_activation(self):
total = 0.0
for i, input_node in enumerate(self.inputs):
total += input_node.activation * self.weights[i]
# apply nonlinearity
# The simple version
# self.activation = 0 if total < 0 else 1
# logistic function as describe on wikipedia for neural networks. Set beta = 10
self.activation = 1.0 / (1.0 + math.pow(math.e,-2*10*total))
# Class for the network
class Network:
def __init__(self, input_layer_size, hidden_layer_size, output_layer_size):
# Initialize our three variables:
self.input_layer = [ Node() for i in range(input_layer_size)]
self.hidden_layer = [ Node() for i in range(hidden_layer_size)]
self.output_layer = [ Node() for i in range(output_layer_size)]
# to print out a network ( a more complete version of this is commented out below)
def __str__(self):
output = ""
output += "===============OUTPUT LAYER===============\n"
for node in self.output_layer:
output += str(node)
return output
"""
def __str__(self):
output = ""
output += "There are " + str(len(self.input_layer)) + " nodes in the input layer.\n"
output += "There are " + str(len(self.hidden_layer)) + " nodes in the hidden layer.\n"
output += "There are " + str(len(self.output_layer)) + " nodes in the output layer.\n"
output += "===============INPUT LAYER===============\n"
for node in self.input_layer:
output += str(node)
output += "===============HIDDEN LAYER===============\n"
for node in self.hidden_layer:
output += str(node)
output += "===============OUTPUT LAYER===============\n"
for node in self.output_layer:
output += str(node)
return output
"""
# Adds all the connections to the network after it has been initialized.
def connect_all(self):
# Connect input layer to hidden layer
for input_node in self.input_layer:
for hidden_node in self.hidden_layer:
input_node.outputs.append(hidden_node)
for hidden_node in self.hidden_layer:
for input_node in self.input_layer:
hidden_node.inputs.append(input_node)
hidden_node.weights.append(random.uniform(-1,1))
# Connect hidden layer to output layer
for hidden_node in self.hidden_layer:
for output_node in self.output_layer:
hidden_node.outputs.append(output_node)
for output_node in self.output_layer:
for hidden_node in self.hidden_layer:
output_node.inputs.append(hidden_node)
output_node.weights.append(random.uniform(-1,1))
# Evaluates the whole network given some input values
def evaluate(self, input):
# set the input values
for i, input_node in enumerate(self.input_layer):
input_node.activation = float(input[i])
# update activation in the hidden layer
for i, hidden_node in enumerate(self.hidden_layer):
hidden_node.update_activation()
# update activation in the output layer
for i, output_node in enumerate(self.output_layer):
output_node.update_activation()
# Just returns the current output state of the network
def get_output(self):
output = []
for output_node in self.output_layer:
output.append(output_node.activation)
return output
# This is the learning rule function for weights between input and hidden layer.
# It takes in the coefficients from the GA and updates the weights.
def update_hidden_layer_weights(self, coeffs):
for input_node in self.input_layer:
input_node.weight_change = 0.0
for j,hidden_node in enumerate(self.hidden_layer):
for i in range(len(hidden_node.weights)):
original_weight = hidden_node.weights[i]
weight_change = \
coeffs[1] * hidden_node.weights[i] + \
coeffs[2] * hidden_node.activation + \
coeffs[4] * hidden_node.inputs[i].activation + \
coeffs[5] * hidden_node.weights[i] * hidden_node.weights[i] + \
coeffs[6] * hidden_node.weights[i] * hidden_node.activation + \
coeffs[8] * hidden_node.weights[i] * hidden_node.inputs[i].activation + \
coeffs[9] * hidden_node.activation * hidden_node.activation + \
coeffs[11] * hidden_node.activation * hidden_node.inputs[i].activation + \
coeffs[14] * hidden_node.inputs[i].activation * hidden_node.inputs[i].activation + \
coeffs[15] * hidden_node.weight_change + \
coeffs[16] * hidden_node.weight_change * hidden_node.weight_change + \
coeffs[17] * hidden_node.weight_change * hidden_node.inputs[i].activation + \
coeffs[18] * hidden_node.weights[i] * hidden_node.weight_change + \
coeffs[19] * hidden_node.activation * hidden_node.weight_change
# scale the output
weight_change *= coeffs[0]
print "Delta weight: " + str(weight_change)
hidden_node.weights[i] += weight_change
# make sure it's within bounds
if hidden_node.weights[i] > 1: hidden_node.weights[i] = 1
if hidden_node.weights[i] < -1: hidden_node.weights[i] = -1
# This is storing the weight changes for backprop.
# Haven't confirmed it's working exactly yet.
hidden_node.inputs[i].weight_change += abs(hidden_node.weights[i] - original_weight)
# This is the learning rule function for weights between hidden and output layer.
# It takes in the coefficients from the GA and updates the weights.
# It's slightly different from the one above since it has access to different variables.
def update_output_layer_weights(self, target, coeffs):
for hidden_node in self.hidden_layer:
hidden_node.weight_change = 0.0
for j,output_node in enumerate(self.output_layer):
for i in range(len(output_node.weights)):
original_weight = output_node.weights[i]
weight_change = \
coeffs[1] * output_node.weights[i] + \
coeffs[2] * output_node.activation + \
coeffs[3] * target[j] + \
coeffs[4] * output_node.inputs[i].activation + \
coeffs[5] * output_node.weights[i] * output_node.weights[i] + \
coeffs[6] * output_node.weights[i] * output_node.activation + \
coeffs[7] * output_node.weights[i] * target[j] + \
coeffs[8] * output_node.weights[i] * output_node.inputs[i].activation + \
coeffs[9] * output_node.activation * output_node.activation + \
coeffs[10] * output_node.activation * target[j] + \
coeffs[11] * output_node.activation * output_node.inputs[i].activation + \
coeffs[12] * target[j] * target[j] + \
coeffs[13] * target[j] * output_node.inputs[i].activation + \
coeffs[14] * output_node.inputs[i].activation * output_node.inputs[i].activation
# scale the output
weight_change *= coeffs[0]
# print "Delta weight: " + str(weight_change)
output_node.weights[i] += weight_change
# make sure it's within bounds
if output_node.weights[i] > 1: output_node.weights[i] = 1
if output_node.weights[i] < -1: output_node.weights[i] = -1
output_node.inputs[i].weight_change += abs(output_node.weights[i] - original_weight)
|
c7b8055766f7d476069f35da0a4b31ac050e7a44
|
jazywica/Algorithms
|
/_03_AlgorithmsOnGraphs/Python/_08_FastestRoute.py
| 6,182 | 4.3125 | 4 |
""" Simple example with Naive and dijkstra algorithm on a directed graph G(V, E), based on the '_08_FastestRoute.JPG' """
from collections import deque
# EDGE RELAXATION:
# Observation: any sub-path of an optimal path is also optimal, which takes us to the following property: If S-> ..-> u-> t is the shortest path from S to then d(S, t) = d(S, u) + w(u, t)
# dist[v] will be an upper bound on the actual distance from S to v, unlike in BFS, this value will most likely be updated many times during the procedure
# the EDGE RELAXATION for an edge (u, v) checks whether going from S to v through u improves the current value of dist, it pertains to the last edge before t at a given stage
class Vertex:
""" class to set up NODE (VERTEX) properties. fields must all be public as we use them in another class """
def __init__(self):
self.known = False # flags if a VERTEX is confirmed to be safe (dijkstra)
self.dist = 2147483647 # initializes the node distances
self.path = -1
class FastestRoute:
def __init__(self, adjList, costList):
self.adj = adjList # ADJACENCY LIST, which is a representation of our test graph containing EDGES (pointers) to other VERTICES:
self.cost = costList # list for storing the initial uncorrected costs
self.nodes = [Vertex() for _ in range(len(adjList))] # after we instantiate the 'nodes' we have to populate it with the 'Vertex' objects with default values
def naive_fastest_route(self, s, t): # based on iterative correction of distances from origin until there is nothing to update anymore
self.nodes[s].dist = 0 # the only non-max value to start with is going to be the start node, so when we start scanning edges we will start updating distances from the start implicitly
is_changed = True
while(is_changed): # the 'do' loop stops as soon as there is an iteration with no further updates
is_changed = False
for u in range(len(self.adj)):
for i in range(len(self.adj[u])): # in this case we use indices inside the lists in order to maintain the relation between 'adj' and 'cost'
v = self.adj[u][i] # v stores the index of the node on the other end, as usual
if self.nodes[u].dist == 2147483647: # if the starting node u hasn't been discovered yet, we just move on
continue
elif self.nodes[v].dist > self.nodes[u].dist + self.cost[u][i]: # for visited neighbours we RELAX THE EDGES if possible
self.nodes[v].dist = self.nodes[u].dist + self.cost[u][i]
self.nodes[v].path = u
is_changed = True # this variable will become True each time we change something
self.display_values()
return self.reconstruct_path(s, t)
def dijkstra(self, s, t): # based on a fact that the smallest distance to all available nodes is enough to move onto next node, the other nodes can only be bigger
self.nodes[s].dist = 0 # the only non-max value to start with is going to be the start node, so when we start scanning edges we will start updating distances from the start implicitly
while True:
u = self.extract_min()
if u == -1 or all(map(lambda x: x.known, self.nodes)): # first condition checks for non-connected nodes and the second if all nodes have been verified
break
for i in range(len(self.adj[u])): # in this case we use indices inside the lists in order to maintain the relation between 'adj' and 'cost'
v = self.adj[u][i] # v stores the index of the node on the other end, as usual
if self.nodes[v].dist > self.nodes[u].dist + self.cost[u][i]: # for direct neighbours we RELAX THE EDGES if possible
self.nodes[v].dist = self.nodes[u].dist + self.cost[u][i]
self.nodes[v].path = u
self.nodes[u].known = True # this is how we can CHANGE THE PRIORITY
self.display_values()
return self.reconstruct_path(s, t)
def extract_min(self): # helper function that returns the element u index which has the smallest distance
smallest = 2147483647
index = -1
for i in range(0, len(self.nodes), 1):
if self.nodes[i].dist < smallest and self.nodes[i].known == False:
smallest = self.nodes[i].dist
index = i
return index # we always compare the distances, but we return the index
def reconstruct_path(self, s, t): # we have to pass instance members as parameters because they are not allowed inside STATIC METHODS
result = deque()
while t != s:
result.appendleft(t)
t = self.nodes[t].path
result.appendleft(s) # the loop above stops when reaching the start node, so if we want, we can include it here
return result
def display_values(self): # testing function that prints all node properties
for i in range(0, len(self.nodes), 1):
print("node index: {0}, distance to the source: {1}, received from: {2}".format( i, self.nodes[i].dist, self.nodes[i].path))
def run_tests():
adj_small = [[1, 2], [2], [], [0]] # first case from the exercises
cost_small = [[1, 5], [2], [], [2]]
graph_small = FastestRoute(adj_small, cost_small)
route_small = graph_small.naive_fastest_route(0, 2)
print(route_small)
print()
graph_small_2 = FastestRoute(adj_small, cost_small)
route_small_2 = graph_small_2.dijkstra(0, 2)
print(route_small_2)
print()
adj_big = [[1, 2], [2, 3], [4, 5], [1], [], [1], [2], []]
cost_big = [[9, 5], [2, 2], [9, 8], [5], [], [1], [4], []]
graph_big = FastestRoute(adj_big, cost_big)
route_big = graph_big.naive_fastest_route(0, 5)
print(route_big)
print()
graph_big_2 = FastestRoute(adj_big, cost_big)
route_big_2 = graph_big_2.dijkstra(0, 5)
print(route_big_2)
print()
run_tests()
|
6ee265b6d22c2879354a7baae74c085a03f898c2
|
antonio00/blue-vscode
|
/MODULO 01/AULA 09/aula 09_EX01.py
| 560 | 4 | 4 |
L = [5, 7, 2, 9, 4, 1, 3]
print(f'A lista original é: {L}') #printa a lista original
print(f'A lista possui {len(L)} posições') # mostra o tamanho da lista
print(f'O maior número é: {max(L)}') #MAX mostra o maior
print(f'O menor número é: {min(L)}') #min mostra o menor
print(f'A soma de todos os valores da lista é {sum(L)}') #cria uma variavel soma com a função 'sum'=soma
L.sort() # ordem crescente
print(f'A ordem crescente é:{L}')# printa a lista em ordem crescente
L.sort(reverse=True) # Ordem decrescente
print(f'A ordem decrescente é:{L}')
|
568e4eb7865bf005e2eae3ce87b0f46e661d531a
|
akozyreva/python-learning
|
/5-python-statements/5-for-loops.py
| 1,160 | 4.375 | 4 |
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# simple example
for num in mylist:
print(num)
for num in mylist:
# Check for even
if num % 2 == 0:
print(num)
else:
# syntax for inserting the val of variable in print function
print(f'Odd number: {num}')
list_sum = 0
for num in mylist:
list_sum = list_sum + num
print(list_sum)
# we can iterrate through strings
myString = 'Hello World'
for letter in myString:
print(letter)
tup = (1, 2, 3)
for i in tup:
print(i)
mylist = [(1, 2, 3), (3, 4, 5), (5,6,7)]
# you can reproduce the type of sequence and have access directly in them, so you don't
# need to execute for in for
for (a, b, c) in mylist:
print(a,b,c)
# or you can print only second element of every tuple in list
for (a,b,c) in mylist:
print(b)
# example with dicts
d = {'k1': 1, 'k2': 2, 'k3': 3}
# by default it iterates only through keys!
for item in d:
print(item)
#in order to receive values of dict, use this construction
for item in d.items():
print(item)
# or
for key, val in d:
print(val)
# or - antoher method for retrieveing values
for val in d.values():
print(val)
|
98201176305f67bdb98a3345039d6351e0aeee6c
|
pasko-evg/miptLabs
|
/lab008_Recursion/task_05_MinkowskiCurve.py
| 1,262 | 4 | 4 |
# Нарисуйте кривую Минковского. Кривая Минковского нулевого порядка - горизонтальный отрезок.
# Затем на каждом шаге каждый из отрезков заменяется на ломанную, состоящую из 8 звеньев.
import sys
from turtle import Screen, Turtle
def draw(length, n, turtle):
# при нулевом - рисуем прямую
if n == 0:
turtle.forward(length)
return
length = length / 4
draw(length, n - 1, turtle)
turtle.left(90)
draw(length, n - 1, turtle)
turtle.right(90)
draw(length, n - 1, turtle)
turtle.right(90)
draw(length, n - 1, turtle)
draw(length, n - 1, turtle)
turtle.left(90)
draw(length, n - 1, turtle)
turtle.left(90)
draw(length, n - 1, turtle)
turtle.right(90)
draw(length, n - 1, turtle)
if __name__ == "__main__":
sys.setrecursionlimit(20)
screen = Screen()
turtle = Turtle()
turtle.shape('turtle')
turtle.penup()
turtle.goto(-400, 0)
turtle.pendown()
turtle.speed('fastest')
length = 800
draw(length, 4, turtle)
turtle.right(120)
input()
turtle.end_fill()
|
45c545c918402af234a299f2c6a30daebb2494a5
|
andrewharukihill/ProjectEuler
|
/43.py
| 1,197 | 3.859375 | 4 |
#The number, 1406357289, is a 0 to 9 pandigital number because it
#is made up of each of the digits 0 to 9 in some order, but it also
#has a rather interesting sub-string divisibility property.
#Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following:
#d2d3d4=406 is divisible by 2
#d3d4d5=063 is divisible by 3
#d4d5d6=635 is divisible by 5
#d5d6d7=357 is divisible by 7
#d6d7d8=572 is divisible by 11
#d7d8d9=728 is divisible by 13
#d8d9d10=289 is divisible by 17
#Find the sum of all 0 to 9 pandigital numbers with this property.
import time
def pandigital(num):
num = str(num)
num_list = []
for i in range(len(num)):
num_list.append(num[i])
digits = ['1','2','3','4','5','6','7','8','9','0']
pandigital = True
idx = 0
while (pandigital == True and idx < len(digits)):
if (digits[idx] not in num_list):
pandigital = False
else:
digits[idx] == 10
idx += 1
return pandigital
def property(num):
num = str(num).split()
def main():
start_time = time.time()
for i in range(1000000000, 2000000000):
if (pandigital(i)):
print(i)
elapsed_time = time.time() - start_time
print("\nTime elapsed: " + str(elapsed_time))
main()
|
6ba93b98a276a527b5b61e2eebf9ed49df7c57d3
|
hanao18182/100nk
|
/100nk02.py
| 602 | 4.125 | 4 |
#最初にUTF-8に設定しておく
#-*- coding: utf-8 -*-
#パトカーとタクシーを変数に代入する
pat = "パトカー"
tax = "タクシー"
#あらかじめ"パタトカシーー"を入れる変数を用意しておく
#文字列を入力するため""を設定しておく
moji = ""
#for文を用いて文字を先頭から交互に用意した変数に格納する
#zipを利用することで先頭から一番短い文字の長さまで順に連結してくれる
for x, y in zip(pat, tax):
moji += x + y
#最終的にmojiに格納されているのを呼び出す
print(moji)
|
6f6ba280c84bf54115fa26bbb1cd695e6a5c168b
|
amritat123/login-signup
|
/login_sign_up.py
| 4,537 | 3.78125 | 4 |
import json
def sign_up():
username=input("please enter your user name:-")
password1=input("please create your password:- ")
password2=input("confrom your password: ")
dict={}
if password1!=password2:
print("both passward are not same😏")
else:
if "a" in password1 or "b" in password1 or "c" in password1 or "d" in password1 or "e" in password1 or "f" in password1 or "g" in password1 or "h" in password1 or "i"in password1 or "j" in password1 or "k" in password1 or "l" in password1 or "m" in password1 or "n" in password1 or "o" in password1 or "p"in password1 or "q" in password1 or "s" in password1 or "t" in password1 or "u" in password1 or "v" in password1 or "w"in password1 or "x" in password1 or "y" in password1 or "z"in password1:
if "@" in password1 or "#" in password1 or "$" in password1:
if "1" in password1 or "2" in password1 or "3" in password1 or "4" in password1 or "5" in password1 or "6" in password1 or "7" in password1 or "8"in password1 or "9"in password1:
with open("main.json","r") as file:
all_data = json.load(file)
i=0
while i<len(all_data["user"]):
file=(all_data["user"][i])
if file["username"]==username:
print("**************😏you alredy exist😏 *****************")
break
i+=1
else:
dict["username"]=username
dict["passward"]=password1
all_data["user"].append(dict)
with open("main.json","w") as my_file:
json.dump(all_data,my_file,indent=4)
print()
print("congress",username,"😇your account sign-up sucessfully😇")
print()
details=input("enter the discreption:---😇")
Birthday_date=input("enter the birthday date😍:---")
Hobbis=input("enter the hobbis😍:---")
Gender=input("enter the gender😍:---")
dict_bio={}
dict_bio["Descreption"]=details
dict_bio["dob"]=Birthday_date
dict_bio["Hobbis"]=Hobbis
dict_bio["Gender"]=Gender
dict["profile"]=dict_bio
with open("main.json","w") as my_file:
json.dump(all_data,my_file,indent=4)
else:
print("oops! number are not in password")
else:
print("sorry! special character are not in strong password")
else:
print("sorry ! alphabet are not in strong password ")
def login():
my_username=input("please! enter the user name for login :")
password_1=input("please enter the password for login :")
my_data=open("main.json", "r")
data=json.load(my_data)
# print(data)
my_data.close()
i=0
while i<len(data["user"]):
file=(data["user"][i])
if file["username"]==my_username:
print(my_username, "😇!your account is login successfully:-😇")
print("-------------------------------------------------")
print()
print("*****************😈your profile😈***********************")
print()
print("Username:-",my_username)
print("Gender:-", file['profile']['Gender'])
print("Bio:-", file['profile']["Descreption"])
print("Hobbis:-", file['profile']['Hobbis'])
print("Hobbis:-",file['profile']['Hobbis'])
print("Dob:-", file['profile']['dob'])
break
i=i+1
else:
print("sorry! invalid username😈")
def main():
print("WELCOME! login/signup:-:-")
print("------------------------------------------------")
print("enter the sign up and login 1/2=")
print("-------------------------------------------------")
user_want=input("do you want to sign-up😍 login your account😍:-")
print("-----------------------------------------------------")
if user_want=="1":
sign_up()
elif user_want=="2":
login()
else:
print("sign_up or login😍")
main()
|
9ff16468c89488a9793b15a7c4e2979740b14af7
|
wngus9056/Datascience
|
/Python&DataBase/5.24/Pandas03_13_GawiBawiBo_김주현.py
| 3,918 | 3.71875 | 4 |
# 묵 찌 빠
# 2 1 3
import random
cwin = 0
uwin = 0
whowin = []
num_total = 0
def defnum1():
global uwin
global cwin
global num_total
if computer == 1:
num_total += 1
print('\tCom : 가위 / User : 가위\t You Draw! 비겼습니다!',end='\n\n')
print('\t=> 현재 스코어 %d : %d ( 컴퓨터 : 당신 ) 입니다.'%(cwin, uwin))
print()
elif computer == 2:
num_total += 1
print('\tCom : 바위 / User : 가위\t You Lose! 당신이 졌습니다!',end='\n\n')
cwin += 1
print('\t=> 현재 스코어 %d : %d ( 컴퓨터 : 당신 ) 입니다.'%(cwin, uwin))
print()
elif computer == 3:
num_total += 1
print('\tCom : 보 / User : 가위\t You Win! 당신이 이겼습니다!',end='\n\n')
uwin += 1
print('\t=> 현재 스코어 %d : %d ( 컴퓨터 : 당신 ) 입니다.'%(cwin, uwin))
print()
def defnum2():
global uwin
global cwin
global num_total
if computer == 1:
num_total += 1
print('\tCom : 가위\t/\tUser : 바위\t\t You Win! 당신이 이겼습니다!',end='\n\n')
uwin += 1
print('\t=> 현재 스코어 %d : %d ( 컴퓨터 : 당신 ) 입니다.'%(cwin, uwin))
print()
elif computer == 2:
num_total += 1
print('\tCom : 바위\t/\tUser : 바위\t\t Draw! 비겼습니다!',end='\n\n')
print('\t=> 현재 스코어 %d : %d ( 컴퓨터 : 당신 ) 입니다.'%(cwin, uwin))
print()
elif computer == 3:
num_total += 1
print('\tCom : 보\t/\tUser : 바위\t\t You Lose! 당신이 졌습니다!',end='\n\n')
cwin += 1
print('\t=> 현재 스코어 %d : %d ( 컴퓨터 : 당신 ) 입니다.'%(cwin, uwin))
print()
def defnum3():
global uwin
global cwin
global num_total
if computer == 1:
num_total += 1
print('\tCom : 가위\t/\tUser : 보\t\t You Lose! 당신이 졌습니다!',end='\n\n')
cwin += 1
print('\t=> 현재 스코어 %d : %d ( 컴퓨터 : 당신 ) 입니다.'%(cwin, uwin))
print()
elif computer == 2:
num_total += 1
print('\tCom : 바위\t/\tUser : 보\t\t You Win! 당신이 이겼습니다!',end='\n\n')
uwin += 1
print('\t=> 현재 스코어 %d : %d ( 컴퓨터 : 당신 ) 입니다.'%(cwin, uwin))
print()
elif computer == 3:
num_total += 1
print('\tCom : 보\t/\tUser : 보\t\t Draw! 비겼습니다!',end='\n\n')
print('\t=> 현재 스코어 %d : %d ( 컴퓨터 : 당신 ) 입니다.'%(cwin, uwin))
print()
def defnum4():
if cwin > uwin:
whowin = '패배'
print('\t총 %d회의 게임 중 컴퓨터가 %d회, 당신이 %d회 이겼습니다.'%(num_total, cwin, uwin))
print('\t따라서 최종 스코어 %d : %d ( 컴퓨터 : 당신 )로 당신의 %s입니다.'%(cwin, uwin, whowin))
print()
elif cwin == uwin:
print('\t총 %d회의 게임 중 컴퓨터가 %d회, 당신이 %d회 이겼습니다.'%(num_total, cwin, uwin))
print('\t따라서 최종 스코어 %d : %d ( 컴퓨터 : 당신 )로 무승부입니다.'%(cwin, uwin))
print()
else:
whowin = '승리'
print('\t총 %d회의 게임 중 컴퓨터가 %d회, 당신이 %d회 이겼습니다.'%(num_total, cwin, uwin))
print('\t따라서 최종 스코어 %d : %d ( 컴퓨터 : 당신 )로 당신의 %s입니다.'%(cwin, uwin, whowin))
print()
while True:
computer = random.randint(1,3)
print('-'*70,end='\n\n')
print(' 1. 가위 \t2. 바위 3. 보 \t 4. 횟수입력\t 9. 종료',end='\n\n')
user_input = input('\t번호를 선택하세요 : ')
print()
if user_input == '':
print('숫자를 입력해주세요.')
continue
else:
user_input = int(user_input)
if user_input == 9:
print('종료합니다.')
break
elif user_input not in range(1,5):
print('숫자를 확인해주세요.')
elif user_input == 1:
defnum1()
elif user_input == 2:
defnum2()
elif user_input == 3:
defnum3()
elif user_input == 4:
defnum4()
|
244213bc990346c40d156df4545493aa66f5ed17
|
playsam32/oddments
|
/SungKyunKwan University/Freshman/Engineering Computer Programming (GEDT018-43)/2020313793.정우성.HW2.py
| 9,901 | 3.9375 | 4 |
#!/usr/bin/env python3
#
# Copyright (c) 2020 by 정우성, All rights reserved.
#
# File : 2020313793.정우성.HW2.py
# Written on : April. 05, 2020
#
# Student ID : 2020313793
# Author : 정우성 ([email protected])
# Affiliation: School of Electrical Engineering
# Sungkyunkwan University
# py version : tested by CPython 3.8.2, 64-bit
# Class : Engineering Computer Programming (GEDT018-43)
# Subject : Lab-02, 'Strings' program
#
# Modification History:
# * version 1.0, by 정우성, Apr. 05, 2020
# - 1st released on this day.
# end of Modification History
#
"""Test three functions when it is executed as a script.
The three functions are:
convert2minutes(timeofday)
replaced_first_by_second(string)
swap(s1,s2)
These functions were made without using 'if', 'while', and 'for'.
However, testmain(), the function to test these three functions, uses 'if',
'while', and 'for'.
If it is called as module, nothing will happen.
"""
def convert2minutes(timeofday):
"""Convert the time string of the 24-hour format to minutes since midnight.
This function expresses the 24-hour format in minutes.
Initially, divide by hour and minutes in str type based on ':'.
And if hour and minute have a single digit, put a zero in front of it.
In this way, we unify the hour and the minute into two digits.
For example, '3' -> '03', '11' -> '11'
And then we divide the hour and minute into the tens place and ones place.
Then, convert each places into int type.
And make new_hour and new_minute in int type.
After convert hour unit to minute unit, assign the value as the sum of
converted new_hour and and new_minute.
:param timeofday: time of day 'H[H]:M[M]',
where [] means that it is optional.
:type timeofday: str
:return: minutes since midnight
:rtype: int
:precondition:
timeofday should be a string of format 'H[H]:M[M]', i.e.,
1 or 2 digit followed by ':' and followed by 1 or 2 digit.
The 1st digit(s) are hours, and the 2nd digit(s) are
minutes. There is no white spaces inside the string.
:constraint:
Do not use 'if', 'for' and/or 'while' in this function.
:example:
timeofday: '02:23' returns 143 (== 2*60+23)
timeofday: '2:3' returns 123 (== 2*60+3)
timeofday: '2:03' returns 123 (== 2*60+3)
timeofday: '10:3' returns 603 (== 10*60+3)
timeofday: '11:13' returns 673 (== 11*60+13)
"""
# Find where ':' is to separate the frontward(hour) and backward(minute).
partition = timeofday.index(':')
# Separates the hour part and minute part.
hour = timeofday[:partition]
minute = timeofday[partition+1:]
# Unifies the hours and minutes into length 2 adding 0.
# If the initial len(str) = 2, nothing happens.
# eg. '3' -> '03', '11' -> '11'
hour = hour.zfill(2)
minute = minute.zfill(2)
# Divides tens place and ones place both hour and minute.
# And converts them into int.
hour_tens = int(hour[0])
hour_ones = int(hour[1])
minute_tens = int(minute[0])
minute_ones = int(minute[1])
# Converts hour and minute to one integer by using tens and ones place.
new_hour = hour_tens*10 + hour_ones
new_minute = minute_tens*10 + minute_ones
# Adds the hour to minutes after converting hour to the minute unit.
value = new_hour*60 + new_minute
return value
def second_replaced_by_first(string):
"""Return a string from a given string where the 2nd occurrence of
its first character have been changed to '$', except the first character
itself.
Start by distinguishing the first spelling and the other parts of the word.
Assign the the other parts of the word as body_part.
Then find the index rule between string and second_occurrence.
(you can find more deatail in line 133)
Changes the second_occurrence in string into '$' and assign changed string
as value. And finally, return that value.
:param string: any string can input, even symbol and number.
:type string: str
:return: string which changed 2nd occurrence into $.
:rtype: str
:precondition: len(string) >= 2 and the the 2nd occurrence always exist
:constraint: Do not use 'if', 'for' and/or 'while' in this function.
:example:
Sample String : 'restart'
Expected Result : 'resta$t'
"""
# To find the 2nd occurrence in a word, specify the first_character.
first_character = string[0]
# Assign body_part which excludes string[0] from 'string'.
# ex: string == 'apple'
# body_part == 'pple'
body_part = string[1:]
# As body_part is equal to string without string[0],
# body_part[n] = string[n+1].
# Therefore, the index number of second_occurrence in string is same with
# the (index number of second_occurrence in body_part + 1)
second_occurrence = body_part.index(first_character) + 1
# Changes the second_occurrence to '$' and assigns them as value in str.
value = string[:second_occurrence] + '$' + string[second_occurrence+1:]
return value
def swap(s1, s2):
"""Return a single string from two given strings, separated by a space and
swap the 1st two characters of each string.
Slice the front two digits in s1 and s2 and assign new_s1 and new_s2 which
switch the front seats each other. After that, connect new_s1 and new_s2
with ' ' and then assign it as value.
Finally, return this value.
In all of these processes, the variables are all str type.
:param s1: any string can input, even symbol and number.
:type s1: str
:param s2: any string can input, even symbol and number.
:type s2: str
:return: single string which swap the 1st two characters and connect them
with white space.
:rtype: str
:precondition:
len(s1) >= 2
len(s2) >= 2
:constraint: Do not use 'if', 'for' and/or 'while' in this function.
:example:
Sample String : 'abc', 'xyz'
Expected Result : 'xyc abz'
"""
# Separate 1st two characters of each string.
particle_of_s1 = s1[:2]
particle_of_s2 = s2[:2]
# Make new_s1 and new_s2 with exchange each two characters.
# ex) s1 == abc, s2 == def
# new_s1 == dec, new_s2 == abf
new_s1 = particle_of_s2 + s1[2:]
new_s2 = particle_of_s1 + s2[2:]
# Connect new_s1 and new_s2 with ' '.
value = new_s1 + ' ' + new_s2
return value
# Test function
def testmain():
"""This is the function for test above three functions.
convert2minute(timeofday) is substituted from '00:00' to '23:59'.
second_replaced_by_first(string) is tested 4 cases.
swap(s1, s2) is also tested 4 cases.
Just type testmain() for test.
:param: none
:return: none
:precondition: function convert2minutes(timeofday)
function replaced_first_by_second(string)
function swap(s1,s2)
should be defined first.
"""
#
# Test convert2minutes()
#
print('--- Testing function convert2minutes()')
# count will increase by one if one test passed.
count = 0
# Possible timeline is from '00:00' to '23:59'
for hours in range(0, 24):
for minutes in range(0, 60):
# Make the expected answer(return value) first.
answer = 60*hours + minutes
# Make timeofday(str type) which satisfies precondition.
# timeofday looks like 'HH:MM'
# ex) '03:12', '11:02'
hours_test = str(hours).zfill(2)
minutes_test = str(minutes).zfill(2)
timeofday = f'{hours_test}:{minutes_test}'
# Test whether function works well.
if convert2minutes(timeofday) == answer:
# Test pass
count += 1
else:
# Test fail
print(f'ERROR!: It doesn\'t satisfy {timeofday}')
# If all test passed.
if count == 1440:
print('All test passed')
#
# Test second_replaced_by_first()
#
print('-- Testing function second_replaced_by_first()')
# Reset the count. It will also increase by one if one test passed.
count = 0
# Make 4 test elements in list which satisfy precondition.
# Also, make expected answer list to check wheter fuction works well.
test_list = ['restart', 'u-plus', '001112', 'gg']
answer_list = ['resta$t', 'u-pl$s', '0$1112', 'g$']
# Test 4 elements.
for indx, val in enumerate(answer_list):
if second_replaced_by_first(test_list[indx]) == val:
# Test pass
count += 1
else:
# Test fail
print(f'Error!, it doesn\'t satisfy {test_list[indx]}.')
# If all test passed.
if count == len(answer_list):
print('All test passed')
#
# Test swap()
#
print('-- Testing function swap()')
# Reset the count. It will also increase by one if one test passed.
count = 0
# Make test parameter(s1, s2) and answer for 4 tests.
test_s1_list = ['abc', 'ab', 'a0b', '0a']
test_s2_list = ['def', 'de', '1c', '1b']
answer_list = ['dec abf', 'de ab', '1cb a0', '1b 0a']
# Start test
for indx, val in enumerate(answer_list):
if swap(test_s1_list[indx], test_s2_list[indx]) == val:
# Test pass
count += 1
else:
# Test fail
print(f'ERROR! swap({test_s1_list[indx]}, {test_s2_list[indx]} ')
# If all test passed.
if count == len(answer_list):
print('All test passed')
# Test if executed as script.
if __name__ == '__main__':
# Call test function.
testmain()
# -- end of 2020313793.정우성.HW2.py
|
a4493e924b78edfeeab1d1577d472f14491dc58b
|
dorgek/aoc2020
|
/src/day21/challenge.py
| 2,859 | 3.578125 | 4 |
import numpy as np
import re
def callculate_allergens( food_allergens ) :
allergy_list = {}
products_list = []
solved_products = []
for food_allergen in food_allergens :
allergens = re.findall( "(?<=contains)[\\sa-zA-Z,]+", food_allergen )[0].replace( " ", "")
products = re.findall( "[a-zA-Z\\s]+(?=\()", food_allergen )[0].split()
products_list.extend( products )
# check if any of these products already have a value assigned to it and then
# if so remove from list of available products
products = [i for i in products if i not in solved_products]
for allergy in allergens.split( "," ) :
if allergy not in allergy_list :
allergy_list[allergy] = products
else :
# compare current products against whats available and remove
# those that don't appear
current_allergens = allergy_list[allergy]
if len( current_allergens ) != 1 :
temp = list( set( current_allergens ) & set( products ) )
allergy_list[allergy] = temp
# check if one value is available then this is the value of the allergy
# update the dictionary to list possible values
if len( temp ) == 1 :
value = temp[0]
remove_allergen( allergy_list, allergy, value, solved_products )
solved_products.append( value )
# find all items that is not an allergen
allergy_values = []
for k in sorted( allergy_list ) :
allergy_values.append( allergy_list[k][0] )
no_allergens = np.setdiff1d( products_list, allergy_values )
count = 0
for no_allergen in no_allergens :
count += products_list.count( no_allergen )
print( "Part One: ", count )
print( "Part Two: ", ",".join( allergy_values ) )
def remove_allergen( allergy_list, allergy, product, solved_products ) :
remove_allergens = {}
for k in allergy_list :
if k != allergy and product in allergy_list[k] :
temp = allergy_list[k]
temp.remove( product )
# determine if new value also needs to be removed
if len( allergy_list[k] ) == 1 :
remove_allergens[k] = allergy_list[k][0]
solved_products.append( allergy_list[k][0] )
# remove used allergens
for k in remove_allergens :
remove_allergen( allergy_list, k, allergy_list[k][0], solved_products )
def main() :
a_file = open( "src/day21/puzzleInput.txt" )
data_input = a_file.read().splitlines()
a_file.close()
callculate_allergens( data_input )
if __name__ == '__main__' :
main()
|
5bdaa6d600bdcde565d783b605dda8f27723aacb
|
dnoronha15/git_practice
|
/fillDisk/fillDisk.py
| 2,141 | 4.09375 | 4 |
# Written to fill current drive by truncating file size. Will create new file if existing Garbage file is present
import shutil
import os
# function to confirm user exit
def press_to_exit():
input("Press Enter to exit...")
print("Goodbye")
exit()
# Returns total,used, and free for drive in GiB
def get_usage(param):
total, used, free = shutil.disk_usage("/")
if param == "total":
return total
elif param == "used":
return used
elif param == "free":
return free
else:
print("Invalid")
# returns size of file required to leave desiredGiB on disk
def calculate_size_for_desiredGiB(desired):
GiBs = ((1024 ** 3) * desired)
size = get_usage("free") - GiBs
return int(size)
# ------------------------------------------------------------------------------------
print("Total: %.2f GiB" % (get_usage("total") / (2 ** 30)))
print("Used: %.2f GiB" % (get_usage("used") / (2 ** 30)))
print("Free: %.2f GiB" % (get_usage("free") / (2 ** 30)))
# Error handling in the case that entered value exceeds available disk space, is a negative input, or NaN
try:
desiredGiB = float(input("Enter desired remaining space on HDD (GiB): "))
except ValueError:
print("*Error: Input must be a number*")
press_to_exit()
if desiredGiB <= 0:
print("*Error: Must be a positive value*")
press_to_exit()
if desiredGiB > get_usage("free") / (2 ** 30):
print("*Error: Desired remaining space on HDD exceeds free disk space*")
press_to_exit()
sizeInBytes = calculate_size_for_desiredGiB(desiredGiB)
print("Size needed to leave %d GiB on drive: %2f GiB" % (desiredGiB, sizeInBytes/2**30))
# fills HDD with garbage.dat if remaining space > desired remaining space
if get_usage("free") / (2 ** 30) > desiredGiB:
i = 0
while os.path.exists("Garbage(%s).dat" % i):
i += 1
print("Creating file of size %d bytes..." % sizeInBytes)
with open("Garbage(%s).dat" % i, "wb") as out:
out.truncate(sizeInBytes)
print("File creation complete! Remaining Space on drive: %.2f GiB" % (get_usage("free") / (2 ** 30)))
press_to_exit()
|
0395af4323894a5e0829c0f34dd675b2a959b032
|
butterflylady/exercism
|
/leap/1.py
| 3,261 | 4.25 | 4 |
from typing import Dict, Optional, Tuple
import string
# Complete the max_result_expression function below.
# You may add any imports you require from the standard library.
# Feel free to define your own helper functions, classes etc as you see fit.
def max_result_expression(expression: str, variables: Dict[str, Tuple[int, int]]) -> Optional[int]:
"""
Evaluates the prefix expression and calculates the maximum result for the given variable ranges.
Arguments:
expression: the prefix expression to evaluate.
variables: Keys of this dictionary may appear as variables in the expression.
Values are tuples of `(min, max)` that specify the range of values of the variable.
The upper bound `max` is NOT included in the range, so (2, 5) expands to [2, 3, 4].
Returns:
int: the maximum result of the expression for any combination of the supplied variables.
None: in the case there is no valid result for any combination of the supplied variables.
"""
output = "None"
operands = []
expression_list = expression.split()
if variables == {}:
while len(expression_list) > 0:
temp = expression_list.pop()
try:
if temp not in ["+", "-", "*", "/"] and int(temp) > 0:
operands.append(int(temp))
elif temp in ["+", "-", "*", "/"]:
if temp == "+":
output = operands.pop() + operands.pop()
operands.append(output)
if temp == "-":
output = operands.pop() - operands.pop()
operands.append(output)
if temp == "*":
output = operands.pop() * operands.pop()
operands.append(output)
if temp == "/":
output = operands.pop() / operands.pop()
operands.append(output)
raise ValueError("Incorrect expression!")
except ValueError as ve:
pass
else:
variable = []
while len(expression_list) > 0:
temp = expression_list.pop()
try:
if temp not in ["+", "-", "*", "/"] and temp.lower() not in string.ascii_lowercase and int(temp) > 0:
operands.append(int(temp))
elif temp in ["+", "-", "*", "/"]:
if temp == "+":
output = operands.pop() + operands.pop()
operands.append(output)
if temp == "-":
output = operands.pop() - operands.pop()
operands.append(output)
if temp == "*":
output = operands.pop() * operands.pop()
operands.append(output)
if temp == "/":
output = operands.pop() / operands.pop()
operands.append(output)
raise ValueError("Incorrect expression!")
except ValueError:
pass
return output
if __name__ == '__main__':
exp = str(input())
variables = eval(input())
res = max_result_expression(exp, variables)
print(res)
|
921e9699c12104305b67d56edb0d35ab9ca7f1ce
|
AFazzone/Python-Homework
|
/[email protected]_hw_11_7.7.py
| 1,434 | 3.546875 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 19 21:31:06 2019
@author: alf11
"""
class LinearEquation:
def __init__(self, a, b, c, d, e, f):
self.__a = a
self.__b = b
self.__c = c
self.__d = d
self.__e = e
self.__f = f
def getA(self):
return self.__a
def getB(self):
return self.__b
def getC(self):
return self.__c
def getD(self):
return self.__d
def getE(self):
return self.__e
def getF(self):
return self.__f
def isSolveable(self):
if ((self.__a * self.__d) - (self.__b * self.__c)) != 0:
return True
def getX(self):
return (((self.__e * self.__d) - (self.__b * self.__f))/
((self.__a * self.__d) - (self.__b * self.__c)))
def getY(self):
return (((self.__a * self.__f) - (self.__e * self.__c))/
((self.__a * self.__d) - (self.__b * self.__c)))
def main():
a, b, c, d, e, f = eval(input("Enter a, b, c, d, e, f: "))
equation = LinearEquation(a, b, c, d, e, f)
denominator = equation.isSolveable()
if denominator != True:
print("The equation has no solution")
else :
print("X is ", equation.getX(), "Y is ", equation.getY())
main()
|
f7a7116b8f540cf47b9979392c14ee5058698bb3
|
ParanoidAndroid19/Common-Patterns_Grokking-the-Coding-Interview
|
/3. Fast & Slow Pointers/2_Find Start of Cycle (medium).py
| 1,174 | 3.703125 | 4 |
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def checkCycle(link):
slow = link
fast = link
while fast != None and fast.next != None:
fast = fast.next.next
slow = slow.next
if(fast == slow):
return cycleLength(slow)
return False
def cycleLength(slow):
current = slow
cycleLen = 0
while True:
current = current.next
cycleLen = cycleLen + 1
if(current == slow):
break
return cycleLen
def findStartCycle(head, cycleLen):
p1 = head
p2 = head
while cycleLen > 0:
p2 = p2.next
cycleLen = cycleLen - 1
while p1 != p2:
p1 = p1.next
p2 = p2.next
return p1.data
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
head.next.next.next.next = Node(5)
head.next.next.next.next.next = Node(6)
head.next.next.next.next.next.next = head.next.next
cycleLen = checkCycle(head)
print(cycleLen)
print(findStartCycle(head, cycleLen))
|
6c2fb8422a8737fd920af0eb4ff441b140e194aa
|
99YuraniPalacios/scientific-computing-hw-
|
/Waring.py
| 984 | 3.8125 | 4 |
# Jun/09/2016
# Yurani Melisa Palacios Palacios
# La conjetura de Warin: cada numero entero impar exceding 3 es cither un numero primo o la suma de tres numeros primos
# Escribir una funcion que dado un numero entero positivo mayor que 3 decide si la conjetura de Waring es cierto.
# Debe devolver el numero si es primo, los tres primeros numeros enteros que sumen el numero 0 o si la conjetura es falsa
# The number has to be larger than 0
# f = 0 No primo
# f = 1 Primo
def isprime(u):
h = 0
if u == 1:
f = 0
else:
for k in range(2, u):
if u % k == 0:
h = 1
break
if h == 1:
f = 0
else:
f = 1
return f
# Program designed to test Waring's conjecture
n = input ('Numero = ')
def waring(n):
if isprime(n) == 1:
return n
else:
for p in range(2, n):
if isprime(p) == 1:
k = n - p
for q in range(2, k):
if isprime(q) == 1:
r = k - q
if isprime(r) == 1:
return p, q, r
return 0
g = waring(n)
print g
|
64357e28f4a78e95932b41791afebf6bcfeea36d
|
mumarkhan999/python_practice_files
|
/Lists/15_a_use_buil_in_instead_of_complex_comprehensions.py
| 633 | 4.71875 | 5 |
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
print(matrix)
# * is to for unpacking arguments list
# it is to tell that
# don't take matrix as a single positional arugment
# rather take it as
# [1, 2, 3, 4] ---- first argument
# [5, 6, 7, 8] ---- second argument
# [9, 10, 11, 12] ---- third argument
# zip() will return the iterators of all these
# three lists
# list() will make list of tuples using these iterators
# for example
# { ( first elem from iterator 1 , first elem from iterator 2 , first elem from iterator 3) , ....
# and so on
transpose = list(zip(*matrix))
print(transpose)
|
2ae461c9881d56a2eef93b5b7270b7ecea2d9cb1
|
Xyleff2049/hexagone
|
/Objects.py
| 2,553 | 3.640625 | 4 |
# { Objects } #
class Tile:
length = 0 # Number of objects
tiles = [] # List of all objects
tilesCoords = [] # List of coords of objects
external = [] # List of external Tile
def __init__(self, listSprite, posTile, external=False, selected=False, team="Neutral", occup=False):
if external == False:
(self.x, self.y) = posTile # Position (in px) of the Tile
self.pos = posTile
if team == "Neutral": self.sprite = listSprite[0]
elif team == "Zeta": self.sprite = listSprite[1]
elif team == "Meya": self.sprite = listSprite[2]
self.listSprite = listSprite
self.width = self.sprite.get_width()
self.height = self.sprite.get_height()
self.selected = selected # Status of the Tile, selected or not
self.team = team # To which team belongs the Tile
self.occup = occup # Status of the Tile, occuped or not
Tile.length += 1
Tile.tiles.append(self)
Tile.tilesCoords.append((self.x,self.y))
else:
self.sprite = listSprite[3] # External sprite
(self.x, self.y) = posTile # Position (in px) of the Tile
self.pos = posTile
Tile.external.append(self)
def changeTeam(self, team):
self.team = team
if team == "Neutral": self.sprite = self.listSprite[0]
elif team == "Zeta": self.sprite = self.listSprite[1]
elif team == "Meya": self.sprite = self.listSprite[2]
self.occup = True
class Unit:
length = 0
units = [] # List of all objects
def __init__(self, listSprite, aTile, team="", life=20):
if team == "Zeta": self.sprite = listSprite[0]
elif team == "Meya": self.sprite = listSprite[1]
(xTile, yTile) = aTile.pos
self.x = xTile + (aTile.width // 2 - self.sprite.get_width() // 2)
self.y = yTile + (aTile.height // 2 - self.sprite.get_height() // 2)
self.pos = (self.x, self.y)
self.team = team
self.life = life
Unit.length += 1
Unit.units.append(self)
class Selector:
pos = (0,0)
sprite = None
def __init__(self, sprite, posSelect):
Selector.pos = posSelect
Selector.sprite = sprite
class Inv:
spriteInv = None
spriteSelect = None
posInv = (0,0)
posSelect = (0,0)
step = 0
stuff = []
def __init__(self, Surface, spriteInv, spriteSelect, step=50, listStuff=[]):
Inv.spriteInv = spriteInv
Inv.spriteSelect = spriteSelect
Inv.posInv = Inv.posSelect = (Surface.get_width() // 2 - spriteInv.get_width() // 2, Surface.get_height() - 50)
Inv.step = step
Inv.stuff = listStuff
def moveSelector(self, case):
(xInv, yInv) = Inv.posInv
Inv.posSelect = (xInv + (self.step * case), yInv)
|
5605bb7c5c7609f800efdc4425956d470361b04d
|
rashmitallam/PythonPrograms
|
/strg1.py
| 276 | 4.15625 | 4 |
#WAP to accept 2 strings from user and swap their 1st two characters
str1=input('Enter 1st string:')
str2=input('Enter 2nd string:')
#Slicing 1st 2 characters of both strings and swapping their positions
str3= str2[:2]+str1[2:]+' '+str1[:2]+str2[2:]
print(str3)
|
68ec1d13982f68a3d0a917cccc16961bcd89e843
|
arislam0/Python
|
/Anusur Islam Py file/p64.py
| 146 | 4.09375 | 4 |
import re
#pattern = r"ice(-)?cream"
pattern = r"a{1,3}$"
if re.match(pattern,"aaaa"):
print("Matched")
else:
print("Not Matched")
|
c5ac022094f80eeda111f4dc3143d8511713f1fd
|
DaHuO/Supergraph
|
/codes/CodeJamCrawler/16_0_3_neat/16_0_3_vk_eipi_C-coinjam.py
| 1,268 | 3.53125 | 4 |
#!/usr/bin/python
import random
import sys
import math
# Sieve
MAX = 100000
primes = []
#divisor = [1 for i in xrange(MAX)]
is_prime = [True for i in xrange(MAX)]
is_prime[0] = False
is_prime[1] = False
for p in xrange(2, MAX):
if is_prime[p]:
primes.append(p)
for multiple in xrange(p*p, MAX, p):
# divisor[multiple] = p
is_prime[multiple] = False
def try_coin(coin):
divs = []
for base in xrange(2, 10+1):
bbase = int(coin, base)
plim = int(math.sqrt(bbase))
for p in primes:
if p > plim:
return None
if bbase%p == 0:
divs.append(p)
break
else:
return None
return divs
T= int(sys.stdin.readline())
assert(T == 1)
N, J= map(int, sys.stdin.readline().split())
triedcoins = set()
jamcoins = []
jamdivs = {}
TIMES = 100000
print "Case #1:"
for trial in xrange(TIMES):
b2 = random.randrange(2**(N-2), 2**(N-1))*2+1
coin = "{0:b}".format(b2)
if coin in triedcoins:
continue
divs = try_coin(coin)
triedcoins.add(coin)
if divs is None:
#print "fail", coin
continue
assert len(divs) == 9
print coin, " ".join(map(str, divs))
jamcoins.append(coin)
jamdivs[coin] = tuple(divs)
if (len(jamcoins) >= J):
break
else:
print "only found ", len(jamcoins)
|
79d50c5d7a5916bdb265a6d7305023b57de943cf
|
encukou/gillcup
|
/gillcup/expressions.py
| 43,048 | 4.34375 | 4 |
"""Dynamic numeric value primitives
This module makes it possible to define arithmetic expressions that are
evaluated at run-time.
For example, given an Expression ``x``, the Expression ``x * 2`` will
always evaulate to twice the value of ``x``.
The power of Expressions becomes apparent when we mention that
:class:`~gillcup.clocks.Clock` time can be used an input.
Gillcup includes expression that smoothly changes value as time progresses.
Combined with other expressions, "animations" on numbers can be created.
Gillcup's expressions can simplify themselves,
so that e.g. a sum of constants (``1 + 2``) becomes a single constant (``3``).
When an animation ends, the fact that Gillcup time cannot go backwards usually
makes it possible to remove the dynamic aspect of the expression involved.
Gillcup expressions are actually 1-D vectors.
Each Expression has a fixed :term:`size` that determines how many
numbers it contains.
Operations such as addition are element-wise
(``<1, 2> + <3, 4>`` results in ``<4, 6>``).
To get the value of an Expression, use either the :meth:`~Expression.get`
method, or iterate the Expression::
>>> exp = Constant(1, 2, 3)
>>> exp
<1.0, 2.0, 3.0>
>>> tuple(exp)
(1.0, 2.0, 3.0)
>>> x, y, z = exp
>>> print(x, y, z)
1.0 2.0 3.0
Expressions with a single component can be converted directly to a number::
>>> exp = Constant(1.5)
>>> exp
<1.5>
>>> float(exp)
1.5
>>> int(exp)
1
>>> bool(exp)
True
Like arithmetic operations, comparisons are element-wise,
``(<1, 2> == <1, 3>)`` results in ``<False, True>``.
Comparisons with more than one element cannot be converted directly to
a single boolean; you need to use Python's :func:`all` or :func:`any`
functions to check them:
>>> if all(Constant(1, 2, 3) == Constant(1, 2, 3)):
... print('yes, they are equal')
yes, they are equal
>>> if any(Constant(1, 1, 1) > Constant(100, 200, 0)):
... print('yes, some are larger')
yes, some are larger
Expression values are floating-point numbers,
so they cannot be used for precise computation [#goldberg]_.
Gillcup expressions are geared for smooth interpolation,
not for high mathematics on custom types.
.. (the real reason for just using floats is possibility of
C-level optimizations)
Most Expressions are immutable, but their *values* can change ofer time.
For example, there is no way to change ``x + 1`` to ``x - 3``, but the value
of ``x`` is potentially recomputed on every access.
Compound Expressions, and operators such as ``+``, ``-``, or ``/`` that
create them, take other expressions as arguments.
Instead of expressions, they accept tuples of the appropriate size,
or plain numbers.
If a plain number is given where a multi-element expression is required,
the number will be repeated::
>>> Value(1, 2, 3) + (10, 10, 10)
<11.0, 12.0, 13.0>
>>> Value(1, 2, 3) + 10
<11.0, 12.0, 13.0>
>>> Sum([Value(1, 2, 3), 10])
<11.0, 12.0, 13.0>
.. rubric:: Footnotes
.. [#goldberg] The obligatory link to David Goldberg's paper
*What Every Computer Scientist Should Know About Floating-Point Arithmetic*
is
`here <http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html>`_.
Expression invariants
---------------------
These invariants are assumed:
* The size (as determined by :func:`len`) of every Expression is constant
throughout the Expression's lifetime.
* For any Expression ``exp``, the simplified Expression (``exp.replacement``)
has the same value as ``exp``
* While any Expression is being evaluated, the value of any (other) Expression
stays constant.
Reference
---------
.. autoclass:: gillcup.expressions.Expression
Basic Expressions
.................
.. autoclass:: gillcup.expressions.Constant
.. autoclass:: gillcup.expressions.Value
.. autoclass:: gillcup.expressions.Progress
Compound Expressions
....................
.. autoclass:: gillcup.expressions.Reduce
.. autoclass:: gillcup.expressions.Map
.. autoclass:: gillcup.expressions.Interpolation
.. autoclass:: gillcup.expressions.Box
Arithmetic Expressions
~~~~~~~~~~~~~~~~~~~~~~
For the following, using the appropriate operator is preferred
to constructing them directly:
.. autoclass:: gillcup.expressions.Sum
.. autoclass:: gillcup.expressions.Product
.. autoclass:: gillcup.expressions.Difference
.. autoclass:: gillcup.expressions.Quotient
.. autoclass:: gillcup.expressions.Power
.. autoclass:: gillcup.expressions.Modulus
.. autoclass:: gillcup.expressions.FloorQuotient
.. autoclass:: gillcup.expressions.Neg
.. autoclass:: gillcup.expressions.Slice
.. autoclass:: gillcup.expressions.Concat
Internal Expressions
....................
.. autoclass:: gillcup.expressions.Time
Debugging helpers
.................
.. autofunction:: gillcup.expressions.dump
Helpers
.......
.. autofunction:: gillcup.expressions.simplify
.. autofunction:: gillcup.expressions.coerce
Safe Arithmetic
~~~~~~~~~~~~~~~~~~~~~~
.. autofunction:: gillcup.expressions.safediv
.. autofunction:: gillcup.expressions.safepow
.. autofunction:: gillcup.expressions.safemod
.. autofunction:: gillcup.expressions.safefloordiv
"""
import operator
import functools
import itertools
import math
import asyncio
from gillcup.signals import signal
from gillcup.util.slice import get_slice_indices
def simplify(exp):
"""Return a simplified version the given expression
Let's use :class:`Sum` as an example expression.
The Sum keeps a list of the expressions it adds together:
>>> val = Sum([Value(1), Value(2), Value(3)])
>>> print(dump(val))
+ <6.0>:
Value <1.0>
Value <2.0>
Value <3.0>
Usually, expressions are simplified automatically.
For example, if the Sum expression is given constants,
it adds them together directly:
>>> val = Sum([1, 2, 3])
>>> print(dump(val))
+ <6.0>:
Constant <6.0>
Calling :func:`simplify` is not needed to get this kind of simplification.
However, some expressions can be simplified even further:
this Sum can just be entirely replaced with the constant.
However, we cannot really change the types of objects,
so in this case we have the Sum signal that it can be replaced
with a simpler expression::
>>> simplified = simplify(val)
>>> print(dump(simplified))
Constant <6.0>
If the expression cannot be simplified, :func:`simplify` simply returns
the original unchanged:
>>> print(dump(simplify(Value(1))))
Value <1.0>
Some expressions can be simplified at some time after initialization,
for example after calling :meth:`Value.fix` or when a :class:`Progress`
reaches its end time.
When this happens, the expression's
:meth:`~Expression.replacement_available` signal is triggered,
and :func:`simplify` will start returning the new replacement.
"""
return exp.replacement
def coerce(value, *, size=None, strict=True):
"""Turn an Expression, constant, or number into an Expression
:param value: The value to be coerced
:param size: The size of the resulting expression
:param strict: If true, output size is enforced.
..
>>> coerce([1, 2, 3])
<1.0, 2.0, 3.0>
>>> coerce(Value(1, 2, 3))
<1.0, 2.0, 3.0>
If an Expression is given, it is simplified (see :meth:`simplify`).
If :token:`strict` is true, and :token:`size` is given, the size of
input expressions and iterable values is checked::
>>> coerce((1, 2), size=3)
Traceback (most recent call last):
...
ValueError: Mismatched vector size: 2 != 3
>>> coerce((1, 2), size=3, strict=False)
<1.0, 2.0>
Numeric inputs are repeated :token:`size` times
(regardless of :token:`strict`)::
>>> coerce(2)
<2.0>
>>> coerce(2, size=3)
<2.0, 2.0, 2.0>
"""
try:
value.get # See if this quacks like an Expression
except AttributeError:
tup = _nonexpression_as_tuple(value, size, strict)
return Constant(*tup)
else:
if strict and size is not None:
_check_len(value, size)
return simplify(value)
class Expression:
"""A dynamic numeric value.
This is a base class, subclass it but do not use it directly.
Subclassing reference:
Overridable members:
.. automethod:: get
.. autoattribute:: children
.. autoattribute:: pretty_name
Replacing:
See :func:`simplify` for details on simplification.
To request replacement, store the simplified expression in the
:attr:`replacement` attribute.
This will automatically trigger the :meth:`replacement_available`
signal.
Note that the original expression must continue to match the
replacement even after this request is made.
A compound expression should listen on the replacement_available
signal of its components, so it can update itself when they are
simplified.
.. autoattribute:: replacement
.. automethod:: replacement_available
Operations:
.. autospecialmethod:: __len__
.. autospecialmethod:: __iter__
.. autospecialmethod:: __float__
.. autospecialmethod:: __int__
.. autospecialmethod:: __getitem__
.. automethod:: replace
.. function:: self == other
self != other
self < other
self <= other
self > other
self >= other
*a.k.a.* :token:`__eq__(other)` etc.
Return an Expression that compares the this expression
element-wise to :token:`other`.
The resing is an expression whose elements can be 0 or 1.
.. function:: self + other
self - other
self * other
self / other
self ** other
self % other
self // other
*a.k.a.* :token:`__add__(other)` etc.
Return a nes Expression that evaluates an element-wise
operation on two values.
These operations create a :class:`Sum`, :class:`Difference`,
:class:`Product`, or :class:`Quotient`, respectively.
The reverse operations (``other + self``/``__radd__``, etc)
are also supported.
.. autospecialmethod:: __pos__
.. autospecialmethod:: __neg__
"""
@signal
def replacement_available():
"""Notifies that a simplified replacement is available"""
def __len__(self):
"""Size of this expression
This must be constant throughout the life of the expression.
The base class wastefully calls :meth:`get`; override if possible.
"""
return len(self.get())
def __iter__(self):
"""Iterator over this expression's current value"""
return iter(self.get())
def __float__(self):
"""For one-element Expressions, return the numeric value.
Raises :class:`ValueError` for other Expressions.
"""
value = self.get()
try:
[number] = value
except ValueError:
raise ValueError('need one component, not {}'.format(len(self)))
return float(number)
def __int__(self):
"""Returns ``int(float(exp))``."""
return int(float(self))
def __bool__(self):
size = len(self)
if size == 1:
return bool(float(self))
elif size == 0:
return False
else:
raise ValueError('using a vector as a boolean is ambiguous; '
'use `all` or `any` to clarify')
def __repr__(self):
try:
value = tuple(self)
except Exception as e:
return '<%s while getting value>' % type(e).__name__
return '<{}>'.format(', '.join(str(n) for n in value))
def get(self):
"""Return the current value of this expression, as a tuple.
This method should be kept free of side effects; in particular,
it may not change (even indirectly) the value of any other
Expression.
"""
raise NotImplementedError()
@property
def replacement(self):
"""A simplified version of this expression
If a simplified version does not exist, the value is self.
"""
try:
replacement = self.__replacement
except AttributeError:
return self
else:
while True:
try:
replacement = replacement.__replacement
except AttributeError:
self.__replacement = replacement
return replacement
@replacement.setter
def replacement(self, new_exp):
if new_exp is not self.replacement:
self.__replacement = new_exp
self.replacement_available()
@property
def children(self):
"""The children of this Expression
This attribute gives an iterable over the components, or inputs,
of this Expression.
It is used in pretty-printing and dumping the structure of expressions.
See :func:`dump` for more discussion.
"""
return ()
@property
def pretty_name(self):
"""Name for pretty-printing
"""
return type(self).__name__
def __getitem__(self, index):
"""Take a slice this expression using standard Python slicing rules
>>> exp = Constant(1, 2, 3)
>>> exp[0]
<1.0>
>>> exp[:-1]
<1.0, 2.0>
"""
return simplify(Slice(self, index))
def __eq__(self, other):
return simplify(_Compare('=', operator.eq, (self, other)))
def __ne__(self, other):
return simplify(_Compare('≠', operator.ne, (self, other)))
def __lt__(self, other):
return simplify(_Compare('<', operator.lt, (self, other)))
def __gt__(self, other):
return simplify(_Compare('>', operator.gt, (self, other)))
def __le__(self, other):
return simplify(_Compare('≤', operator.le, (self, other)))
def __ge__(self, other):
return simplify(_Compare('≥', operator.ge, (self, other)))
def __add__(self, other):
return simplify(Sum((self, other)))
__radd__ = __add__
def __mul__(self, other):
return simplify(Product((self, other)))
__rmul__ = __mul__
def __sub__(self, other):
return simplify(Difference((self, other)))
def __rsub__(self, other):
return simplify(Difference((other, self)))
def __truediv__(self, other):
return simplify(Quotient((self, other)))
def __rtruediv__(self, other):
return simplify(Quotient((other, self)))
def __floordiv__(self, other):
return simplify(FloorQuotient((self, other)))
def __rfloordiv__(self, other):
return simplify(FloorQuotient((other, self)))
def __mod__(self, other):
return simplify(Modulus((self, other)))
def __rmod__(self, other):
return simplify(Modulus((other, self)))
def __pow__(self, other):
return simplify(Power((self, other)))
def __rpow__(self, other):
return simplify(Power((other, self)))
def __pos__(self):
"""Return this Expression unchanged"""
return self
def __neg__(self):
"""Return an element-wise negation of this Expression"""
return simplify(Neg(self))
def replace(self, index, replacement):
"""Replace the given element (or slice) with a value
(This is the equivalent of :token:`__setitem__`, but it returns a new
Expression instead of modifying the old.)
:param index: Index, or slice, to be replaced
:param replacement: The new value
:type replacement: Expression, tuple, or a simple number
Any element of an expression can be replaced::
>>> Constant(1, 2, 3).replace(0, -2)
<-2.0, 2.0, 3.0>
This can be used to change the size of the expression::
>>> Constant(1, 2, 3).replace(0, (-2, -3))
<-2.0, -3.0, 2.0, 3.0>
Slices can be replaced as well::
>>> Constant(1, 2, 3).replace(slice(0, -1), (-2, -3))
<-2.0, -3.0, 3.0>
>>> Constant(1, 2, 3).replace(slice(1, 1), (-8, -9))
<1.0, -8.0, -9.0, 2.0, 3.0>
>>> Constant(1, 2, 3).replace(slice(1, None), ())
<1.0>
>>> Constant(1, 2, 3).replace(slice(None, None), ())
<>
When replacing a slice by a plain number, the number is repeated
so that the size does not change::
>>> Constant(1, 2, 3).replace(slice(0, -1), -1)
<-1.0, -1.0, 3.0>
>>> Constant(1, 2, 3).replace(slice(0, -1), (-1,))
<-1.0, 3.0>
Of course this does not happen when using a tuple or expression::
>>> Constant(1, 2, 3).replace(slice(0, -1), Constant(-1))
<-1.0, 3.0>
"""
start, stop = get_slice_indices(len(self), index)
replacement = coerce(replacement, size=stop - start, strict=False)
return simplify(Concat(self[:start], replacement, self[stop:]))
def dump(exp):
"""Return a pretty-printed tree of an Expression and its children
Formats the value, :attr:`~Expression.pretty_name`, and, recursively,
:attr:`~Expression.children`, of the given Expression
arranged in a tree-like structure.
>>> exp = Value(0) + Value(1) / Value(2)
>>> print(dump(exp))
+ <0.5>:
Value <0.0>
/ <0.5>:
Value <1.0>
Value <2.0>
The dumper deals with repeated expressions using YAML-style markers:
>>> exp = Value(3, 3, 3) + 3
>>> exp = exp / exp
>>> print(dump(exp))
/ <1.0, 1.0, 1.0>:
+ <6.0, 6.0, 6.0>: (&1)
Value <3.0, 3.0, 3.0>
Constant <3.0, 3.0, 3.0>
+ <6.0, 6.0, 6.0> (*1)
>>> exp = Value(3, 3, 3)
>>> print(dump(exp + exp + exp))
+ <9.0, 9.0, 9.0>:
Value <3.0, 3.0, 3.0> (&1)
Value <3.0, 3.0, 3.0> (*1)
Value <3.0, 3.0, 3.0> (*1)
Expressions are encouraged to "lie" about their structure in
:attr:`~Expression.children`, if it leads to better readibility.
For example, an expression with several heterogeneous children
can wrap each child in a :class:`Box`::
>>> exp = Interpolation(Value(0), Value(10), Value(0.5))
>>> print(dump(exp))
Interpolation <5.0>:
start <0.0>:
Value <0.0>
end <10.0>:
Value <10.0>
t <0.5>:
Value <0.5>
Here the ``start``, ``end``, and ``t`` are dynamically generated
:class:`Box` expressions whose only purpose is to provide the name to make
the dump more readable.
"""
# Value of next marker to be assigned
counter = 1
# Memo of all exps seen so far, keyed by id(exp)
# a value of None → seen only once (don't print a marker)
# a number → print the number as a marker
memo = {}
def gen(exp, indent):
"""Generate the lines of the dump
Yields records suitable for fmt() below, tuples of:
- indent: the indentation level, as int
- exp: the expression itself
- sigil: '&' if this is the first time we see this exp, '*' otherwise
(this is used in the YAML-style markers: '&' means definition,
'*' is reference)
- children_follow: True if exp's children are listed after this line.
If exp has no children, this is False
(used to display ':' if an indented block follows)
"""
nonlocal counter
try:
# Have we seen exp before?
entry = memo[id(exp)]
except KeyError:
# No! Record it, and yield it, along with any children
memo[id(exp)] = None
children = list(exp.children)
yield indent, exp, '&', bool(children)
for child in children:
yield from gen(child, indent + 1)
else:
# Yes! Yield it, but don't bother listing children again
yield indent, exp, '*', False
# If this is the second (but not third, etc.) time we've seen it,
# assign a marker value
if entry is None:
memo[id(exp)] = counter
counter += 1
# Running exp() to exhaustion will fill up `memo`
entries = list(gen(exp, 0))
def fmt(indent, exp, sigil, children_follow):
"""Format a single line of the dump
See gen() for the input
"""
marker = memo.get(id(exp))
if marker is None:
postfix = ''
else:
postfix = ' (%s%s)' % (sigil, marker)
return '{indent}{exp.pretty_name} {exp}{colon}{postfix}'.format(
indent=' ' * indent,
exp=exp,
colon=':' if children_follow else '',
postfix=postfix,
)
return '\n'.join(fmt(*entry) for entry in entries)
def _replace_child(exp, listener):
"""Move listener from an expression to its replacement, return replacement
"""
replacement = exp.replacement
if replacement is exp:
return exp
else:
exp.replacement_available.disconnect(listener)
if not isinstance(replacement, Constant):
replacement.replacement_available.connect(listener)
return replacement
def _nonexpression_as_tuple(value, size=None, strict=True):
try:
iterator = iter(value)
except TypeError:
if size is None:
return (float(value), )
else:
return (float(value), ) * size
else:
result = tuple(float(v) for v in iterator)
if strict and size is not None:
_check_len(result, size)
return result
def _as_tuple(value, size=None):
try:
get = value.get
except AttributeError:
return _nonexpression_as_tuple(value, size)
else:
if size is not None:
_check_len(value, size)
return get()
class Constant(Expression):
"""A constant expression.
The value of this expression cannot be changed.
"""
def __init__(self, *value):
self._value = tuple(float(v) for v in value)
def get(self):
return self._value
def __getitem__(self, index):
start, end = get_slice_indices(len(self), index)
return Constant(*self._value[slice(start, end)])
class Value(Expression):
"""A mutable value.
Methods:
.. automethod:: set
.. automethod:: fix
"""
def __init__(self, *value):
self._value = tuple(float(v) for v in value)
self._size = len(self._value)
self._fixed = False
def __len__(self):
return self._size
def get(self):
return self._value
def set(self, *value):
"""Set the value
>>> exp = Value(1, 2, 3)
>>> exp
<1.0, 2.0, 3.0>
>>> exp.set(3, 2, 1)
>>> exp
<3.0, 2.0, 1.0>
The :attr:`size` of the new value must be equal to the old one.
The value cannot be changed after :meth:`fix` is called.
"""
if self.replacement is self:
value = tuple(float(v) for v in value)
if len(value) != self._size:
raise ValueError('Mismatched vector size: {} != {}'.format(
len(value), self._size))
self._value = value
else:
raise ValueError('value has been fixed')
def fix(self, *value):
"""Freezes the current value.
After a call to :token:`fix()`, the value becomes immutable,
and the expression can be simplified to a :class:`Constant`.
If arguments are given, they are passed to :meth:`set` before freezing.
"""
if value:
self.set(*value)
self.replacement = Constant(*self)
@property
def pretty_name(self):
if self._fixed:
return '{} (fixed)'.format(type(self).__name__)
else:
return type(self).__name__
def _coerce_all(exps):
exps = tuple(exps)
for exp in exps:
try:
size = len(exp)
except TypeError:
pass
else:
break
else:
size = 1
return tuple(coerce(e, size=size) for e in exps)
def _reduce_tuples(operands, op):
reducer = functools.partial(functools.reduce, op)
return tuple(map(reducer, zip(*operands)))
def _check_len_match(a, b):
if len(a) != len(b):
raise ValueError('Mismatched vector size: {} != {}'.format(
len(a), len(b)))
def _check_len(exp, expected):
if len(exp) != expected:
raise ValueError('Mismatched vector size: {} != {}'.format(
len(exp), expected))
class Reduce(Expression):
"""Applies a :func:`reduce <functools.reduce>` operation
element-wise on a number of Expressions.
Assumes the `op` function is pure, and takes number of arguments equal
to the number of operands.
All operands must be the same size.
Class attributes:
.. attribute:: commutative
True to enable optimizations that assume `op` implements a
commutative operator
.. attribute:: identity_element
If not None, gives the number that can be ignored for this
operation (or if :token:`commutative` is true, the number that
can be ignored if it's not the first operand).
For example, 0 for ``+`` or ``-``, 1 for ``*`` or ``/``.
"""
commutative = False
identity_element = None
def __init__(self, op, operands):
self._op = op
self._operands = tuple(_coerce_all(operands))
for i, oper in enumerate(self._operands):
oper.replacement_available.connect(self._replace_operands)
self._replace_operands()
def get(self):
return _reduce_tuples(self._operands, self._op)
def __len__(self):
return len(self._operands[0])
@property
def pretty_name(self):
return '{}({})'.format(type(self).__name__, self._op)
@property
def children(self):
return self._operands
def _replace_operands(self, commutative=False):
new = []
size = len(self._operands[0])
def _generate_operands(operands):
for i, oper in enumerate(operands):
oper = _replace_child(oper.replacement, self._replace_operands)
if ((self.commutative or i == 0) and
type(oper) == type(self) and
oper._op == self._op):
yield from _generate_operands(oper._operands)
else:
yield oper
for oper in _generate_operands(self._operands):
if (new and isinstance(oper, Constant) and
(self.commutative or len(new) == 1) and
isinstance(new[-1], Constant)):
new[-1] = Constant(*tuple(map(self._op,
tuple(new[-1]),
tuple(oper))))
else:
new.append(oper)
if (new and isinstance(oper, Constant) and
(self.commutative or len(new) > 1) and
all(x == self.identity_element for x in new[-1])):
new.pop()
if not new:
new.append(Constant(*[self.identity_element] * size))
self._operands = new
if len(self._operands) == 1:
[self.replacement] = self._operands
class Sum(Reduce):
"""Element-wise sum
"""
pretty_name = '+'
commutative = True
identity_element = 0
def __init__(self, operands):
super().__init__(operator.add, operands)
def _dump_name(self):
return '+'
class Product(Reduce):
"""Element-wise product
"""
pretty_name = '*'
commutative = True
identity_element = 1
def __init__(self, operands):
super().__init__(operator.mul, operands)
class _Compare(Reduce):
"""Element-wise comparison
"""
@property
def pretty_name(self):
return '`{}`'.format(self._symbol)
def __init__(self, symbol, op, operands):
super().__init__(op, operands)
self._symbol = symbol
class Difference(Reduce):
"""Element-wise difference
"""
pretty_name = '-'
identity_element = 0
def __init__(self, operands):
super().__init__(operator.sub, operands)
def safediv(a, b):
"""Divide a by b, but return NaN or infinity on division by zero
The behavior is equivalent to Numpy with the 'ignore' setting.
"""
try:
return a / b
except ZeroDivisionError:
sign = a * b
if a and not math.isnan(a):
return math.copysign(float('inf'), sign)
else:
return float('nan')
class Quotient(Reduce):
"""Element-wise quotient
Division by zero will result in NaN or infinity, rather than raising
an exception -- see :func:`safediv`.
"""
pretty_name = '/'
identity_element = 1
def __init__(self, operands):
super().__init__(safediv, operands)
def safefloordiv(a, b):
"""Divide a by b and floor the result; NaN or infinity on division by zero
The behavior is equivalent to Numpy with the 'ignore' setting,
except it uses Python's behavior for (-x // inf) and (x // -inf),
as described in http://bugs.python.org/issue22198
"""
try:
return a // b
except ZeroDivisionError:
sign = a * b
if a and not math.isnan(a):
return math.copysign(float('inf'), sign)
else:
return float('nan')
class FloorQuotient(Reduce):
"""Element-wise floored quotient
Division by zero will result in NaN or infinity, rather than raising
an exception -- see :func:`safefloordiv`.
"""
pretty_name = '//'
def __init__(self, operands):
super().__init__(safefloordiv, operands)
def safemod(a, b):
"""Modulus of a and b, but return NaN or infinity on division by zero
The behavior is equivalent to Numpy with the 'ignore' setting.
"""
try:
return a % b
except ZeroDivisionError:
return float('nan')
class Modulus(Reduce):
"""Element-wise modulus
Division by zero will result in NaN or infinity, rather than raising
an exception -- see :func:`safemod`.
"""
pretty_name = '%'
def __init__(self, operands):
super().__init__(safemod, operands)
def safepow(a, b):
"""Raise a to b-th power, but return NaN on float domain error"""
try:
return math.pow(a, b)
except ValueError:
return float('nan')
class Power(Reduce):
"""Element-wise power
Math domain errors will result in NaN, rather than raising an exception.
"""
pretty_name = '**'
identity_element = 1
def __init__(self, operands):
super().__init__(safepow, operands)
class Map(Expression):
"""Applies a function element-wise on a zipped Expressions.
Assumes the `op` function is pure, and takes as many numeric arguments
as there are operands.
All operands must be the same size.
"""
def __init__(self, op, *operands):
self._operands = tuple(_coerce_all(operands))
self._op = op
for i, oper in enumerate(self._operands):
oper.replacement_available.connect(self._replace_operands)
self._replace_operands()
@property
def pretty_name(self):
return 'Map {}'.format(self._op.__name__)
def __len__(self):
return len(self._operands[0])
def get(self):
return tuple(map(self._op, *(op.get() for op in self._operands)))
@property
def children(self):
yield from self._operands
def _replace_operands(self, commutative=False):
self._operands = tuple(_replace_child(op, self._replace_operands)
for op in self._operands)
if all(isinstance(op, Constant) for op in self._operands):
self.replacement = Constant(*self)
class Neg(Map):
"""Element-wise negation"""
pretty_name = 'Neg'
def __init__(self, operand):
super().__init__(operator.neg, operand)
class Slice(Expression):
"""Slice of an Expression
Typical result of an ``exp[start:stop]`` operation
"""
def __init__(self, source, index):
self._source = simplify(source)
self._start, self._stop = get_slice_indices(len(source), index)
self._len = self._stop - self._start
if self._len <= 0:
self.replacement = Constant()
self._len = 0
elif self._start <= 0 and self._stop >= len(source):
self.replacement = source
else:
source.replacement_available.connect(self._replace_source)
self._replace_source()
def __len__(self):
return self._len
@property
def pretty_name(self):
return '[{}:{}]'.format(self._start, self._stop)
@property
def children(self):
yield self._source
def get(self):
return self._source.get()[self._start:self._stop]
def _replace_source(self):
self._source = src = _replace_child(self._source, self._replace_source)
if isinstance(src, Constant):
self.replacement = Constant(*self)
elif isinstance(src, Slice):
self._source = src._source
self._start = self._start + src._start
self._stop = self._stop + src._start
elif isinstance(src, Concat):
start = self._start
new_children = []
children_iter = iter(list(src._children))
for child in children_iter:
if start > len(child):
start -= len(child)
else:
if start:
first_child = child[start:]
else:
first_child = child
break
else:
raise AssertionError('out of children (at start)')
length_remaining = self._len
for child in itertools.chain([first_child], children_iter):
if not length_remaining:
break
assert length_remaining > 0
if length_remaining > len(child):
new_children.append(child)
length_remaining -= len(child)
else:
new_children.append(child[:length_remaining])
break
else:
raise AssertionError('out of children (at end)')
self.replacement = Concat(*new_children)
class Concat(Expression):
"""Concatenation of several Expressions.
>>> Concat(Constant(1, 2), Constant(3))
<1.0, 2.0, 3.0>
Usually created as a result of :meth:`~Expression.replace`.
"""
def __init__(self, *children):
children_gen = (coerce(c) for c in children)
self._children = tuple(c for c in children_gen if len(c))
self._len = sum(len(c) for c in self._children)
self._simplify_children()
for child in self._children:
child.replacement_available.connect(self._simplify_children)
@property
def children(self):
return self._children
def __len__(self):
return self._len
def get(self):
return sum((c.get() for c in self._children), ())
def _simplify_children(self):
def gen_children(children):
for child in children:
if isinstance(child, Concat):
yield from gen_children(child._children)
else:
yield child
new_children = []
for child in gen_children(self._children):
child = simplify(child)
if (isinstance(child, Constant) and
new_children and
isinstance(new_children[-1], Constant)):
new_const = Constant(*new_children[-1].get() + child.get())
new_children[-1] = new_const
elif (isinstance(child, Slice) and
new_children and
isinstance(new_children[-1], Slice) and
child._source is new_children[-1]._source and
child._start == new_children[-1]._stop):
new_index = slice(new_children[-1]._start, child._stop)
new_children[-1] = simplify(Slice(child._source, new_index))
else:
new_children.append(child)
self._children = tuple(new_children)
if len(self._children) == 1:
[self.replacement] = self._children
def __getitem__(self, index):
start, end = get_slice_indices(len(self), index)
new_children = []
for child in self._children:
child_len = len(child)
if end <= 0:
break
elif start >= child_len:
pass
else:
if start <= 0 and end >= child_len:
new_children.append(child)
else:
new_children.append(child[start:end])
start -= child_len
if start < 0:
start = 0
end -= child_len
return Concat(*new_children)
class Box(Expression):
"""Mutable container expression
Proxies to another Expression.
:param name: The name used in :meth:`pretty_name` and :func:`dump`
:param value: An expression this evaluates to.
May be changed after creation by setting the
:attr:`value` attribute.
Also useful to show structure of complicated expressions when debugging,
see :func:`dump` for an example.
"""
def __init__(self, name, value):
self._name = name
self.value = value
def get(self):
return self.value.get()
@property
def pretty_name(self):
return self._name
@property
def children(self):
yield self.value
class Interpolation(Expression):
"""Evaluates to a weighted average of two expressions.
:param a: Start expression, returned when t=0
:param b: End expression, returned when t=1
:param t: The weight
The :token:`t` parameter must be a scalar (single-element) expression.
Note that :token:`t` is not limited to [0..1]; extrapolation is possible.
"""
def __init__(self, start, end, t):
self._start, self._end = _coerce_all([start, end])
self._t = coerce(t, size=1)
if len(self._t) != 1:
raise ValueError('Interpolation coefficient must be '
'a single number')
self._start.replacement_available.connect(self._replace_start)
self._end.replacement_available.connect(self._replace_end)
self._t.replacement_available.connect(self._replace_t)
self._replace_t()
self._replace_const_to_const()
def get(self):
t = float(self._t)
nt = 1 - t
return tuple(a * nt + b * t for a, b in zip(self._start, self._end))
def _replace_start(self):
self._start = _replace_child(self._start, self._replace_start)
self._replace_const_to_const()
def _replace_end(self):
self._end = _replace_child(self._end, self._replace_end)
self._replace_const_to_const()
def _replace_t(self):
self._t = t = _replace_child(self._t, self._replace_t)
if isinstance(t, Constant):
if t == 0:
self.replacement = simplify(self._start)
elif t == 1:
self.replacement = simplify(self._end)
def _replace_const_to_const(self):
if (isinstance(self._start, Constant) and
isinstance(self._end, Constant) and
all(self._start == self._end)):
self.replacement = self._start
@property
def children(self):
yield Box('start', self._start)
yield Box('end', self._end)
yield Box('t', self._t)
class Time(Expression):
"""Gives the time on a clock
This is a monotonically increasing scalar Expression, i.e.,
its value is a single number that can never decrease.
"""
def __init__(self, clock):
self._clock = clock
def get(self):
return (self._clock._time_value, )
class Progress(Expression):
"""Gives linear progress according to a Clock
The value of this expression is
0 at the start (:token:`clock`'s current time + :token:`delay`),
and 1 at the end (:token:`duration` time units after start).
Between those two times, it changes smoothly as the clock advances.
If :token:`clamp` is true, the value stays 0 before the start
and 1 after end.
Otherwise, it is extrapolated: it will be negative before the start,
and greater than 1 after the end.
:token:`duration` may not be negative.
If :token:`duration` is zero, the value changes from 0 to 1 abruptly
at :token:`delay` time units in the future.
In this case, :token:`clamp` must be true.
"""
def __init__(self, clock, duration, *, delay=0, clamp=True):
self._clock = clock
self._start = float(clock.time) + float(delay)
self._duration = float(duration)
self._done = asyncio.Future()
self.done = clock.wait_for(self._done)
if self._duration < 0:
raise ValueError('negative duration')
if not clamp and not duration:
raise ValueError('extrapolation to infinity')
self._clamp = clamp
if clamp:
end_time = delay + duration
if end_time >= 0:
clock.schedule(end_time, self._fix)
else:
self._fix()
def __len__(self):
return 1
def get(self):
progress_time = float(self._clock.time) - self._start
if self._duration:
rv = progress_time / self._duration
if self._clamp:
if rv <= 0:
return (0, )
elif rv >= 1:
return (1, )
return (rv, )
elif progress_time < 0:
return (0, )
else:
return (1, )
def _fix(self):
self.replacement = Constant(1)
self.done.set_result(True)
|
aa73b42a0e92709a37e92e6fd691a267a62245a9
|
AjithPanneerselvam/Algo-Problems
|
/firecode/powerOf4.py
| 776 | 3.984375 | 4 |
"""
Google
Power of 4
Write a method to determine whether a given integer (zero or positive number) is a power of 4 without using the multiply or divide operator. If it is, return True, else return False.
Examples:
is_power_of_four(5) ==> False
is_power_of_four(16) ==> True
Hint: An integer is considered to be a power of 4 if
1) it is one or
2) there is only one bit set in its binary representation and the number of bits to the right of the set bit is even.
"""
def is_power_of_four(number):
if (number & (number - 1) == 0):
temp = 1
count = 0
while ((number | temp) != number):
count += 1
temp <<= 1
if (not(count % 2)):
return True
return False
else:
return False
|
5fc5ed482ac72484804cb1611adc2254cfa49140
|
ubuntu-prasad/myPython
|
/pythonStudy/assignments/as4_empSalary.py
| 269 | 3.65625 | 4 |
# WAP to get the basic salary from employee and calculate it gross salary (Basic salary + 10% DA and 12%TA)
basicSalary = input("Enter Basic Salary: ")
grossSalary = basicSalary + 0.1 * basicSalary + 0.12 * basicSalary
print "Gross Salary of Employee: ", grossSalary
|
067860a7b88eb6654c342a35fbbce04e5413edf8
|
yukaixue/spyder
|
/汉诺塔游戏.py
| 397 | 3.828125 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 13 15:07:57 2020
@author: Administrator
"""
count = 0
def hanoi(n,src,dst,mid):
global count
if n == 1:
print('{}:{}->{}'.format(1,src,dst))
count +=1
else:
hanoi(n-1,src,mid,dst)
print('{}:{}->{}'.format(n,src,dst))
count +=1
hanoi(n-1,mid,dst,src)
hanoi(2,'左','右','中')
print(count)
|
334043e5b75ce0d220b594983c05714db2b07f81
|
chavhanpunamchand/pythonYogeshSir
|
/Weekend/weekend_30-08-2020/weekend/variables.py
| 8,907 | 3.640625 | 4 |
name = "Python"
version = 3.8
val1 = "This is {} lang and version is {}".format(name,version) # position
val2 = "This is {1} lang and version is {0}".format(version,name) #index
val3 = "This is {nm} lang and version is {vr}".format(nm=name,vr=version) #name
val4 = f"This is {name} lang and version is {version}" #formatting-->
print("This is %s lang and version is %d" % (name,version) ) # not in use --** # decimal place
print(val1)
print(val2)
print(val3)
print(val4)
import sys
sys.exit(0)
'''
Types of methods --> static instance class
Types of Variables --> global local nonlocal class instance
Types of Paramerter/args --> positional named default *args **kwargs
string formatting --> positional/named/
class --> object- -. str-- repr --> init --> eq--- hash-->
'''
def m1(x,y=20,*args,**kwargs): #functions/methods/innerfunctions/inner functions --> applicable
pass
m1() # error --> x - mandatory
m1(20) # x=20 y=20 empty empty
m1(10,"A") #x=10 y="A" empty empty
m1(10,20,30,40) #x=10 y=20 (30,40) empty
m1(50,y=20,a=58,x=20) # 50 20 empty (a:,x:)
#def m1(**kwargs,*args): # named --first nad the position ---No --> rule break..*
# pass
#m1(a=20,30,40,5) #named params --> last to first-- right to left-->
m1() #yes empty empty
m1(a=20) #empty {a:20}
m1(20,30,40,{"a":20,"Y":20},(1,2),[2,34,{1:23,4:55}],a=2993) #(20,30,40,{"a":20,"Y":20},(1,2),[2,34,{1:23,4:55}]) empty
def m1(x=None,*args,**kwargs):
print(x,args)
m1(x=30) # priority -- name la --> x=30 empty empty
m1(30,30,x=50,y=30) # x-30 (30) {x:50,y:30}
m1() # x-none args:empty--kwargs =empty
m1(10) #x =10 --> empty empty
m1(10,"A","x",20,{1:20}) #x-10,(a,x,20,{1:20}) ---> empty
m1(10,a=20,b=20) #x-10 empty dict--a:20,b:20
m1(10,10,20,3,(10,20),x=20,y=(10,20,30)) #x -->10 (10,20,3,(10,20)) x:20 y:(10,20,30)
m1(10) # x--> 10 args--empty
m1(10,20,30) # x-->10 --->20,30
m1() #in case of default params -> works--> 10 --> None,Empty
import sys
sys.exit(0)
def m1(**kargs): #many ---> dict -->name:key ---->value:value
print('inside m1',kargs,len(kargs))
#print(kargs.get('x').get('c'))
print(kargs.get('c')) # as dict directly..
#d = {'a': 10, 'b': 20, 'c': 30, 'd': 40}
m1(a=10,b=20,c=30,d=40) #multiple params --named
import sys
sys.exit(0)
#*args -->
def m1(*args): # multiple --params
sum = 0
for item in args: # iterate to tuple --> elements
if type(item) in (int,float,complex):
sum = sum+item
print(sum)
m1(10,20,30,"A","B","3",True)
import sys
sys.exit(0)
def m1(x):
print(x,len(x)) # no of elements ? -->
def m2(*x): # if u are not sure about no of params --> *arg --> internally type wud be tuple.. zero to n
print(x,len(x)) # len --> 1--> 5
m1(10,20,30,40,50) # error --> 1
m2(10,20,30,40,50) #zero to n
# *args --> arbitary
# **kwargs --> keyword args
#key present key absent
#dict.get(key) value none get(key)--> try: dict[key] --> return None
#dict[key] value keyerror
def calculation(*args): # args --> tuple -->
print("Ans is -->",args,len(args))
print("Type of args -->",type(args))
# read tuple --> type dict
print("Val -->",args[2].get("TT")) # dict[key]-->value--->agrsv--in key absent--error -->value
#dict.get(key)-->value --> key absent --> None -->value
print('---------------------------\n')
#calculation()
#calculation(10)
#calculation(10,20,30)
#calculation(10,20,30,40,"A","B","X",30,4,5,67,("X","Y"),["P","Q","R"],{"XX":100,"YY":200},{10,20})
calculation(("X","Y"),["P","Q","R"],{"XX":100,"YY":200},{10,20},10,"A",True,None)
import sys
sys.exit(0)
#positional param -- no of params + seq/position
#named params --> no of params --> names
#default ---> shud start from right to left--> mandatory = all params - default params-->
# positional or named
def fun(n1,n2,n3,n4=40,n5=50):
print(n1,n2,n3,n4,n5)
fun(10,20,30) #n1 n2 n3
fun(10,20,30,40,52)# n1 n2 n3 n4
fun(n1=10,n2=20,n3=30,n5=56) # named with default*
#param --> args
#no of args #sequence/position params-arg-names remarks
#positional --> yes yes -
#names --> yes no same
#default --> all params-default @Position--yes - make sure default value
# @named --No same assignments shud start from last
def fun1(id,name,age=30,sal=2278.34): #params #fun1("XXXX",20,3993.34)
print('inside function')
print("ID :{} Name :{} Age :{} Sal : {}".format(id,name,age,sal))
#fun1(101,"Mr. XXXX",30,34505.6) #args--> position --> positional args--> no of param ??
#fun1(name="Mr YYY",sal=3773.4,id=123,age=32) # named params/args --> param and args names exactly same
#default with
#fun1(101,"Mr. XXXX",30,2000.3) # position
#fun1(name="Mr YYY",id=123,age=32) # named
import sys
sys.exit(0)
#ref --> read -->first inside same ref --> class-->
#nonlocal --> cannot same variable inside innerfu
#nonlocal keyword --> will always be inside --> inner function-->
#wherever u write nonlocal -- in that function same variable name cannot be there
#provides write access to nearest local variable ---*
#global and nonlocal --> keyword provide write access
#global -> global variable --> funcitons/innnerfunction/method/inner methods
#nonlocal --> nearest local variables ---> inside functions--> inside method--> not possible for global
var = "X" # global --*****
def outer():
global var #no local --> as its already accessing to global
var = "A" # do we have local variable here ??? --> no
#nonlocal --> global
def inner1():
#nonlocal var # modify access to nearest local --> outer -check local var -->
global var
var = "B" # this will be modified..
def inner2():
global var #
var2 = "X" #*
def inner3(): #3 2 1 outer global
nonlocal var2 #no problem ?
var2="Y"
# print(var1) #read--> check inside local scope ??--no--stepback--> n n y
print(var2) #read --> no no y
# print(var3) #read no y
print(var) #read n n n n y
var = "A"
def outer():
var = "B" #local to outer
print('inside outer1 -->',var) #B # read -->local
def inner():
nonlocal var #inner--> cannot have--var variable --> can modify/update--> outer local var value
print('Inside Inner3 --',var) # C --> local scope ?--> outer--> yes
var = "C"
print('Inside Outer2 -->',var) #B
inner()
print('After Inner Calling4-->',var)#B
outer()
print('Execution Completed5..',var)#A
'''
types -->
global --> defined at module/file level --> global -- just provide write access to the function--> global variable cha
local --> inside method/function/inner[method/fun]
nonlocal --> provides write access to nearest local variable --> this keyword will always inside inner function/method
class --> defined at class level or using class name
instance --> defined with object refer
type of methods how we can access --> ideally purpose
static --> () --> @staticmethod --> classname or ref classname common business
class (cls) -->@classmethod --> classname or ref classname factory method
instance (self) --> ---- --> ref ref business--specific for objects
types of params -->
positional
named
default
args --> arbitary --*
kargs --> keyword args --**
'''
|
1cda37636512c3fe865e055c83cddbeba573bd09
|
reshmaladi/Python
|
/1.Class/Language_Python-master/Language_Python-master/LC8_HW6_CheckArmstrongNumber.py
| 275 | 3.875 | 4 |
def sum(n,s):
if n==0:
return 0
else:
s=(n%10)**3+sum(int(n/10),s)
return s
def main():
n=eval(input("Enter Digit\t"))
s=sum(n,0)
if(n==s):
print(n,"Is an armstrong number")
else:
print(n,"is not an armstrong number")
if __name__=='__main__':
main()
|
0caf83d41a07b95a510d62a236ce1d401ebcddf6
|
Byliguel/python1-exo7
|
/code/vie/vie_code_3_2.py
| 1,004 | 3.609375 | 4 |
def evolution(tab):
""" Calcule l'évolution en un jour
Entrée : un tableau à deux dimension
Sortie : un tableau à deux dimension """
nouv_tab = [[0 for j in range(p)] for i in range(n)]
for j in range(p):
for i in range(n):
# Cellule vivante ou pas ?
if tab[i][j] != 0:
cellule_vivante = True
else:
cellule_vivante = False
# Nombres de voisins
nb_voisins = nombre_voisins(i,j,tab)
# Règle du jeu de la vie
if cellule_vivante == True and (nb_voisins == 2 or nb_voisins == 3):
nouv_tab[i][j] = 1
if cellule_vivante == False and nb_voisins == 3:
nouv_tab[i][j] = 1
return nouv_tab
# Test
print("--- Position de départ ---")
voir_tableau(tableau)
print("--- Nombre de voisins ---")
voir_voisins(tableau)
print("--- Après évolution ---")
tableau = evolution(tableau)
voir_tableau(tableau)
|
746481dc27ac58fee99a0dcc15c0ad65c3256d00
|
yeshengwei/PythonLearning
|
/04函数学习/08-函数嵌套调用应用-计算.py
| 203 | 3.984375 | 4 |
def sum_num(x, y, z):
return x + y + z
# result=sum_num(3,5,6)
def average_num(x, y, z):
result = sum_num(x, y, z)
return result / 3
average = average_num(4, 9, 5)
print(int(average))
|
f24e247ea3dead367e47c4081fec0840319ed2d9
|
phulei/chirico
|
/python/curses1.py
| 1,100 | 4.1875 | 4 |
#!/usr/bin/env python
# Ref: http://www.amk.ca/python/howto/curses/
import curses,time
stdscr = curses.initscr()
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
curses.noecho()
stdscr.keypad(1)
x=20;y=7
h=5;w=40
win=curses.newwin(h,w,y,x)
stdscr.addstr(0,0,"Current mode: Typing mode", curses.A_REVERSE)
pad = curses.newpad(100, 100)
# These loops fill the pad with letters; this is
# explained in the next section
for y in range(0, 100):
for x in range(0, 100):
try: pad.addch(y,x, ord('a') + (x*x+y*y) % 26 )
except curses.error: pass
# Displays a section of the pad in the middle of the screen
stdscr.addstr(0, 0, "Current mode: Typing mode",
curses.A_REVERSE)
stdscr.refresh()
pad.refresh( 0,0, 5,5, 20,75)
time.sleep(3)
stdscr.addstr(0,0, "RED ALERT!", curses.color_pair(1) )
time.sleep(3)
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
stdscr.addstr(0, 0, " **** ",
curses.A_REVERSE)
pad.refresh( 0,0, 5,5, 20,75)
stdscr.refresh()
time.sleep(3)
curses.endwin()
|
9234239d2500bcbd51ba113521ac8d308df4bc03
|
hoangperry/Tree-Visualization
|
/BST_AVL.py
| 17,823 | 3.9375 | 4 |
import datetime
class Node:
def __init__(self, key, size:int):
self.key = key
self.size = size
self.left = None
self.right = None
class Node1:
def __init__(self, key, size:int, height:int):
self.key = key
self.size = size
self.height = height
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def printNode(self, x:Node):
print(x.key)
print(x.left.key)
print(x.right.key)
def size(self) -> int:
return self.sizeNode(self.root)
def sizeNode(self, x:Node) -> int:
if x == None:
return 0
return x.size
def height(self) -> int:
return self.heightNode(self.root)
def heightNode(self, x:Node) -> int:
if x == None:
return -1
else:
leftHeight = self.heightNode(x.left)
rightHeight = self.heightNode(x.right)
if leftHeight > rightHeight:
return leftHeight + 1
return rightHeight + 1
def put(self, key):
self.root = self.putNode(self.root, key)
def putNode(self, x:Node, key) -> Node:
if x == None:
return Node(key, 1)
if key < x.key:
x.left = self.putNode(x.left, key)
elif key > x.key:
x.right = self.putNode(x.right, key)
else:
x.key = key;
x.size = 1 + self.sizeNode(x.left) + self.sizeNode(x.right);
return x
def lrn(self):
return self.lrnNode(self.root)
def lrnNode(self, x:Node):
retStr = ""
if x != None:
retStr += self.lrnNode(x.left)
retStr += self.lrnNode(x.right)
print(str(x.key) + " ")
retStr += (str(x.key) + "\n")
return retStr
def lnr(self):
return self.lnrNode(self.root)
def lnrNode(self, x:Node):
retStr = ""
if x != None:
retStr += self.lnrNode(x.left)
retStr += (str(x.key) + "\n")
print(str(x.key) + " ")
retStr += self.lnrNode(x.right)
return retStr
def nlr(self):
return self.nlrNode(self.root)
def nlrNode(self, x:Node):
retStr = ""
if x != None:
retStr += (str(x.key) + "\n")
print(str(x.key) + " ")
retStr += self.nlrNode(x.left)
retStr += self.nlrNode(x.right)
return retStr
def nlrNoPrint(self):
return self.nlrNodeNoPrint(self.root)
def nlrNodeNoPrint(self, x:Node):
ret = []
if x != None:
ret.append(x)
ret += self.nlrNodeNoPrint(x.left)
ret += self.nlrNodeNoPrint(x.right)
return ret
def nrl(self):
return self.nrlNode(self.root)
def nrlNode(self, x:Node):
retStr = ""
if x != None:
retStr += (str(x.key) + "\n")
print(str(x.key) + " ")
retStr += self.nrlNode(x.right)
retStr += self.nrlNode(x.left)
return retStr
def rnl(self):
return self.rnlNode(self.root)
def rnlNode(self, x:Node):
retStr = ""
if x != None:
retStr += self.rnlNode(x.right)
retStr += (str(x.key) + "\n")
print(str(x.key) + " ")
retStr += self.rnlNode(x.left)
return retStr
def rln(self):
return self.rlnNode(self.root)
def rlnNode(self, x:Node):
retStr = ""
if x != None:
retStr += self.rlnNode(x.right)
retStr += self.rlnNode(x.left)
retStr += (str(x.key) + "\n")
print(str(x.key) + " ")
return retStr
def get(self, key) -> Node:
return self.getNode(self.root, key)
def getNode(self, x:Node, key) -> Node:
if x == None:
return x
if key < x.key:
return self.getNode(x.left, key)
elif key > x.key:
return self.getNode(x.right, key)
else:
return x
def searchWithName(self, key:str):
self.searchWithNameNode(self.root, key)
def searchWithNameNode(self, x:Node, key:str):
if x != None:
if x.key.name == key:
print(x.key)
self.searchWithNameNode(x.right, key)
self.searchWithNameNode(x.left, key)
def searchWithID(self, key:int):
self.searchWithIDNode(self.root, key)
def searchWithIDNode(self, x:Node, key:int):
if x != None:
if x.key.id == key:
print(x.key)
self.searchWithIDNode(x.right, key)
self.searchWithIDNode(x.left, key)
def searchWithBirthday(self, key:str):
self.searchWithBirthdayNode(self.root, key)
def searchWithBirthdayNode(self, x:Node, key:str):
if x != None:
if x.key.birthday == key:
print(x.key)
self.searchWithBirthdayNode(x.right, key)
self.searchWithBirthdayNode(x.left, key)
def searchWithCredit(self, key:int):
self.searchWithCreditNode(self.root, key)
def searchWithCreditNode(self, x:Node, key:int):
if x != None:
if x.key.credit == key:
print(x.key)
self.searchWithCreditNode(x.right, key)
self.searchWithCreditNode(x.left, key)
def searchWithScore(self, key:float):
self.searchWithScoreNode(self.root, key)
def searchWithScoreNode(self, x:Node, key:float):
if x != None:
if x.key.score == key:
print(x.key)
self.searchWithScoreNode(x.right, key)
self.searchWithScoreNode(x.left, key)
def min(self) -> Node:
return self.minNode(self.root)
def minNode(self, x:Node) -> Node:
if x.left == None:
return x
return self.minNode(x.left)
def max(self) -> Node:
return self.maxNode(self.root)
def maxNode(self, x:Node) -> Node:
if x.right == None:
return x
return self.maxNode(x.right)
def findMinMax(self):
print("Min = " + str(self.minNode(self.root).key))
print("Max = " + str(self.maxNode(self.root).key))
def createTree(self, inp:list):
for i in inp:
self.put(i)
def creatLeftSkewTree(self, inp:list):
inp = sorted(inp)
for i in inp :
self.put(i)
def creatRightSkewTree(self, inp:list):
inp = sorted(inp, reverse=True)
for i in inp :
self.put(i)
def printAsc(self):
self.lnrNode(self.root)
def printDsc(self):
self.rnlNode(self.root)
def contains(self, key) -> bool:
return self.getNode(self.root, key) != None
def containsID(self, id) -> bool:
return self.getNodeWithID(self.root, id) != None
def getNodeWithID(self, x:Node, id) -> Node:
if x != None:
if id < x.key.id:
return self.getNodeWithID(x.left, id)
elif id > x.key.id:
return self.getNodeWithID(x.right, id)
return x
return None
def deleteMin(self):
self.root = self.deleteMinNode(self.root)
def deleteMinNode(self, x:Node)-> Node:
if x.left == None:
return x.right
x.left = self.deleteMinNode(x.left)
x.size = self.sizeNode(x.left) + self.sizeNode(x.right) + 1
return x
def delete(self, key):
self.root = self.deleteNode(self.root, key)
def deleteNode(self, x:Node, key) -> Node:
if x == None:
return x
if key < x.key:
x.left = self.deleteNode(x.left, key)
elif key > x.key:
x.right = self.deleteNode(x.right, key)
else:
if x.right == None:
return x.left
if x.left == None:
return x.right
t = x
x = self.minNode(t.right)
x.right = self.deleteMinNode(t.right)
x.left = t.left
x.size = self.sizeNode(x.left) + self.sizeNode(x.right) + 1
return x
def deleteMax(self):
self.root = self.deleteMaxNode(self.root)
def deleteMaxNode(self, x:Node) -> Node:
if x.right == None:
return x.left
x.right = self.deleteMaxNode(x.right)
x.size = self.sizeNode(x.left) + self.sizeNode(x.right) + 1
return x
def deleteList(self, inp:list):
for i in inp:
self.root = self.deleteNode(self.root, i)
def getPredecessor(self, key) -> Node:
if self.get(key) == None:
return None
if self.get(key).left != None:
return self.maxNode(self.get(key).left)
return None
def getSuccessor(self, key) -> Node:
if self.get(key) == None:
return None
if self.get(key).right != None:
return self.minNode(self.get(key).right)
return None
def updateName(self, id:int, name:str):
self.updateNameNode(self.root, id, name)
def updateNameNode(self, x:Node, id:int, name:str):
if x != None:
if id < x.key.id:
self.updateNameNode(x.left, id, name)
elif id > x.key.id:
self.updateNameNode(x.right, id, name)
else:
x.key.name = name
def updateBirthday(self, id:int, birthday:str):
try:
datetime.datetime.strptime(birthday, '%d/%m/%Y')
except ValueError:
raise ValueError("Incorrect data format, should be DD/MM/YYYY")
self.updateBirthdayNode(self.root, id, birthday)
def updateBirthdayNode(self, x:Node, id:int, birthday:str):
if x != None:
if id < x.key.id:
self.updateNameNode(x.left, id, birthday)
elif id > x.key.id:
self.updateNameNode(x.right, id, birthday)
else:
x.key.birthday = birthday
def updateCredit(self, id:int, credit:int):
self.updateCreditNode(self.root, id, credit)
def updateCreditNode(self, x:Node, id:int, credit:int):
if x != None:
if id < x.key.id:
self.updateCreditNode(x.left, id, credit)
elif id > x.key.id:
self.updateCreditNode(x.right, id, credit)
else:
x.key.credit = credit
def updateScore(self, id:int, score:float):
if score > 10:
raise ValueError("Credit must less than 10")
self.updateScoreNode(self.root, id, score)
def updateScoreNode(self, x:Node, id:int, score:float):
if x != None:
if id < x.key.id:
self.updateScoreNode(x.left, id, score)
elif id > x.key.id:
self.updateScoreNode(x.right, id, score)
else:
x.key.score = score
###########################
# AVL
###########################
class AVL:
def __init__(self):
self.root = None
def printNode(self, x:Node1):
print(x.key)
print(x.left.key)
print(x.right.key)
def size(self) -> int:
return self.sizeNode(self.root)
def sizeNode(self, x:Node1) -> int:
if x == None:
return 0
return x.size
def height(self) -> int:
return self.heightNode(self.root)
def heightNode(self, x:Node1) -> int:
if x == None:
return -1
return x.height
def put(self, key):
self.root = self.putNode(self.root, key)
def putNode(self, x:Node1, key) -> Node1:
if x == None:
return Node1(key, 1, 0)
if key < x.key:
x.left = self.putNode(x.left, key)
elif key > x.key:
x.right = self.putNode(x.right, key)
else:
x.key = key
x.size = 1 + self.sizeNode(x.left) + self.sizeNode(x.right)
x.height = 1 + max(self.heightNode(x.left), self.heightNode(x.right))
return x
def putBalance(self, key):
self.root = self.putBalanceNode(self.root, key)
def putBalanceNode(self, x:Node1, key) -> Node1:
if x == None:
return Node1(key, 1, 0)
if key < x.key:
x.left = self.putBalanceNode(x.left, key)
elif key > x.key:
x.right = self.putBalanceNode(x.right, key)
else:
x.key = key
x.size = 1 + self.sizeNode(x.left) + self.sizeNode(x.right)
x.height = 1 + max(self.heightNode(x.left), self.heightNode(x.right))
return self.balanceNode(x)
def balanceFactor(self, x:Node1) -> int:
return self.heightNode(x.left) - self.heightNode(x.right)
def checkBalance(self) -> bool:
if abs(self.balanceFactor(self.root)) > 1:
return False
return True
def rotateRight(self, x:Node1) -> Node1:
y = x.left
x.left = y.right
y.right = x
y.size = x.size
x.size = 1 + self.sizeNode(x.left) + self.sizeNode(x.right)
x.height = 1 + max(self.heightNode(x.left), self.heightNode(x.right))
y.height = 1 + max(self.heightNode(y.left), self.heightNode(y.right))
return y
def rotateLeft(self, x:Node1) -> Node1:
y = x.right
x.right = y.left
y.left = x
y.size = x.size
x.size = 1 + self.sizeNode(x.left) + self.sizeNode(x.right)
x.height = 1 + max(self.heightNode(x.left), self.heightNode(x.right))
y.height = 1 + max(self.heightNode(y.left), self.heightNode(y.right))
return y
def balance(self):
while abs(self.balanceFactor(self.root)) > 1:
self.root = self.balanceNode(self.root)
def balanceNode(self, x:Node1) -> Node1:
if self.balanceFactor(x) < -1:
if self.balanceFactor(x.right) > 0:
x.right = self.rotateRight(x.right)
x = self.rotateLeft(x)
elif self.balanceFactor(x) > 1:
if self.balanceFactor(x.left) < 0:
x.left = self.rotateLeft(x.left)
x = self.rotateRight(x)
return x
def lrn(self):
return self.lrnNode(self.root)
def lrnNode(self, x: Node):
retStr = ""
if x != None:
retStr += self.lrnNode(x.left)
retStr += self.lrnNode(x.right)
print(str(x.key) + " ")
retStr += (str(x.key) + "\n")
return retStr
def lnr(self):
return self.lnrNode(self.root)
def lnrNode(self, x: Node):
retStr = ""
if x != None:
retStr += self.lnrNode(x.left)
retStr += (str(x.key) + "\n")
print(str(x.key) + " ")
retStr += self.lnrNode(x.right)
return retStr
def nlr(self):
return self.nlrNode(self.root)
def nlrNode(self, x: Node):
retStr = ""
if x != None:
retStr += (str(x.key) + "\n")
print(str(x.key) + " ")
retStr += self.nlrNode(x.left)
retStr += self.nlrNode(x.right)
return retStr
def nlrNoPrint(self):
return self.nlrNodeNoPrint(self.root)
def nlrNodeNoPrint(self, x:Node):
ret = []
if x != None:
ret.append(x)
ret += self.nlrNodeNoPrint(x.left)
ret += self.nlrNodeNoPrint(x.right)
return ret
def nrl(self):
return self.nrlNode(self.root)
def nrlNode(self, x: Node):
retStr = ""
if x != None:
retStr += (str(x.key) + "\n")
print(str(x.key) + " ")
retStr += self.nrlNode(x.right)
retStr += self.nrlNode(x.left)
return retStr
def rnl(self):
return self.rnlNode(self.root)
def rnlNode(self, x: Node):
retStr = ""
if x != None:
retStr += self.rnlNode(x.right)
retStr += (str(x.key) + "\n")
print(str(x.key) + " ")
retStr += self.rnlNode(x.left)
return retStr
def rln(self):
return self.rlnNode(self.root)
def rlnNode(self, x: Node):
retStr = ""
if x != None:
retStr += self.rlnNode(x.right)
retStr += self.rlnNode(x.left)
retStr += (str(x.key) + "\n")
print(str(x.key) + " ")
return retStr
def getNodeWithID(self, x:Node, id) -> Node:
if x != None:
if id < x.key.id:
return self.getNodeWithID(x.left, id)
elif id > x.key.id:
return self.getNodeWithID(x.right, id)
return x
return None
def get(self, key) -> Node1:
return self.getNode(self.root, key)
def getNode(self, x:Node1, key) -> Node1:
if x == None:
return None
if key < x.key:
return self.getNode(x.left, key)
elif key > x.key:
return self.getNode(x.right, key)
else:
return x
def contains(self, key) -> bool:
return self.getNode(self.root, key) != None
def containsID(self, id) -> bool:
return self.getNodeWithID(self.root, id) != None
def min(self) -> Node1:
return self.minNode(self.root)
def minNode(self, x:Node1) -> Node1:
if x.left == None:
return x
return self.minNode(x.left)
def max(self) -> Node1:
return self.maxNode(self.root)
def maxNode(self, x:Node1) -> Node1:
if x.right == None:
return x
return self.maxNode(x.right)
def findMinMax(self):
print("Min = " + str(self.minNode(self.root).key))
print("Max = " + str(self.maxNode(self.root).key))
def deleteMin(self):
self.root = self.deleteMinNode(self.root)
def deleteMinNode(self, x:Node1) -> Node1:
if x.left == None:
return x.right
x.left = self.deleteMinNode(x.left)
x.size = 1 + self.sizeNode(x.left) + self.sizeNode(x.right)
x.height = 1 + max(self.heightNode(x.left), self.heightNode(x.right))
return self.balanceNode(x)
def deleteMax(self):
self.root = self.deleteMaxNode(self.root)
def deleteMaxNode(self, x:Node1) -> Node1:
if x.right == None:
return x.left
x.right = self.deleteMaxNode(x.right)
x.size = 1 + self.sizeNode(x.left) + self.sizeNode(x.right)
x.height = 1 + max(self.heightNode(x.left), self.heightNode(x.right))
return self.balanceNode(x)
def delete(self, key):
if not self.contains(key):
return
self.root = self.deleteNode(self.root, key)
def deleteNode(self, x:Node1, key) -> Node1:
if key < x.key:
x.left = self.deleteNode(x.left, key)
elif key > x.key:
x.right = self.deleteNode(x.right, key)
else:
if x.left == None:
return x.right
elif x.right == None:
return x.left
else:
y = x
x = self.minNode(y.right)
x.right = self.deleteMinNode(y.right)
x.left = y.left
x.size = 1 + self.sizeNode(x.left) + self.sizeNode(x.right)
x.height = 1 + max(self.heightNode(x.left), self.heightNode(x.right))
return self.balanceNode(x)
def createTree(self, inp:list):
for i in inp:
self.putBalance(i)
def getPredecessor(self, key) -> Node:
if self.get(key) == None:
return None
if self.get(key).left != None:
return self.maxNode(self.get(key).left)
return None
def getSuccessor(self, key) -> Node:
if self.get(key) == None:
return None
if self.get(key).right != None:
return self.minNode(self.get(key).right)
return None
def updateName(self, id:int, name:str):
self.updateNameNode(self.root, id, name)
def updateNameNode(self, x:Node1, id:int, name:str):
if x != None:
if id < x.key.id:
self.updateNameNode(x.left, id, name)
elif id > x.key.id:
self.updateNameNode(x.right, id, name)
else:
x.key.name = name
def updateBirthday(self, id:int, birthday:str):
try:
datetime.datetime.strptime(birthday, '%d/%m/%Y')
except ValueError:
raise ValueError("Incorrect data format, should be DD/MM/YYYY")
self.updateBirthdayNode(self.root, id, birthday)
def updateBirthdayNode(self, x:Node1, id:int, birthday:str):
if x != None:
if id < x.key.id:
self.updateNameNode(x.left, id, birthday)
elif id > x.key.id:
self.updateNameNode(x.right, id, birthday)
else:
x.key.birthday = birthday
def updateCredit(self, id:int, credit:int):
self.updateCreditNode(self.root, id, credit)
def updateCreditNode(self, x:Node1, id:int, credit:int):
if x != None:
if id < x.key.id:
self.updateCreditNode(x.left, id, credit)
elif id > x.key.id:
self.updateCreditNode(x.right, id, credit)
else:
x.key.credit = credit
def updateScore(self, id:int, score:float):
if score > 10:
raise ValueError("Credit must less than 10")
self.updateScoreNode(self.root, id, score)
def updateScoreNode(self, x:Node1, id:int, score:float):
if x != None:
if id < x.key.id:
self.updateScoreNode(x.left, id, score)
elif id > x.key.id:
self.updateScoreNode(x.right, id, score)
else:
x.key.score = score
|
b1296a208db9ad413e4d7a2be1bc6d43738d05d3
|
MrLotU/AdventOfCode2020
|
/solutions/sixteen.py
| 2,384 | 3.53125 | 4 |
import re
import functools
TEST_INPUT = '''departure class: 0-1 or 4-19
row: 0-5 or 8-19
departure seat: 0-13 or 16-19
your ticket:
11,12,13
nearby tickets:
3,9,18
15,1,5
5,14,9'''
PATTERN = r'(?P<rules>(?:[a-z ]+: \d+-\d+ or \d+-\d+\n?)+)\n{2}your ticket:\n(?P<ticket>(?:\d+,?)+)\n+nearby tickets:\n(?P<other_tickets>(?:\d+,?\n?)+)'
with open('inputs/sixteen.txt', 'r') as f:
input_text = f.read()
# input_text = TEST_INPUT
parts = re.match(PATTERN, input_text).groupdict()
print('---- DAY SIXTEEN PART ONE ----') # 26941
def _range(a,b):
return range(a, b+1)
def numarr_from_rule(r):
ranges = r.split(': ')[-1]
ranges = ranges.split(' or ')
arr = []
for _r in ranges:
r = _range(*map(lambda e: int(e), _r.split('-')))
arr.extend([i for i in r])
return arr
tickets = parts['other_tickets'].split('\n')
rules = parts['rules'].split('\n')
valid_numbers = []
invalid_numbers = []
valid_tickets = []
for r in rules:
valid_numbers.extend(numarr_from_rule(r))
for ticket in tickets:
invalid_ticket_nums = [int(i) for i in ticket.split(',') if int(i) not in valid_numbers]
if invalid_ticket_nums == []:
valid_tickets.append(ticket)
else:
invalid_numbers.extend(invalid_ticket_nums)
print(functools.reduce(lambda a,b: a + b, invalid_numbers, 0))
print('---- DAY SIXTEEN PART TWO ----')
my_ticket = [int(x) for x in parts['ticket'].split(',')]
rules_dict = {}
for ticket in valid_tickets:
for idx, value in enumerate([int(i) for i in ticket.split(',')]):
v = rules_dict.get(idx, None)
if not v:
v = rules
rules_dict[idx] = [r for r in v if value in numarr_from_rule(r)]
rules_list = sorted(rules_dict.items(), key=lambda e: len(e[-1]))
idx = 0
while True:
index, rules = rules_list[idx]
if len(rules) == 1:
r = rules[0]
for i in range(idx + 1, len(rules_list)):
a,b = rules_list[i]
_i = b.index(r)
# print(idx, i, _i, (a, b[:_i] + b[_i+1:]))
rules_list[i] = (a, b[:_i] + b[_i+1:])
if idx == len(rules_list) - 1:
break
else:
idx += 1
values = []
for (idx, rules) in rules_list:
rule = rules[0]
if rule.startswith('departure'):
values.append(my_ticket[idx])
print(values)
print(functools.reduce(lambda a,b: a * b, values, 1))
|
be6ef2887148d826c5bd45ccbdae7204cbb4bf5f
|
ookun1415/guess-number
|
/number.py
| 618 | 3.859375 | 4 |
import random #import載入 random 模組-隨機
start = input('請輸入隨機數字範圍開始值')
end = input('請輸入隨機數字範圍結束值')
start = int(start)
end = int(end)
r = random.randint(start,end) #randint 隨機整數(random+int)
r = int(r)
count = 0 #count 計數
while True:
count += 1 #count = count + 1的快寫法
num = input('請猜數字')
num = int(num)
if num == r:
print('猜中了!!')
print('這是你猜的第', count, '次')
break
elif num > r:
print('答案比', num, '小')
elif num < r:
print("答案比", num, '大')
print('這是你猜的第', count, '次')
|
f71dacc1e69c7775907d6718b48d27a8efe2b751
|
Chaitanya-Raj/Semester6
|
/DataMining/ControlStructures/1/sum.py
| 240 | 3.859375 | 4 |
def sumofdigits(n):
sum = 0
while n != 0:
sum += n % 10
n = n // 10
print(sum)
def startingPoint():
val = int(input("Enter Number : "))
sumofdigits(val)
if __name__ == "__main__":
startingPoint()
|
c461936e2c9f99c4f80a3ae2e1f93a86c1e2e365
|
LogicalFish/DiscordBot
|
/python/modules/dice/godroll.py
| 2,261 | 3.6875 | 4 |
import random
from config import configuration
from .standard_diceroller import StandardDiceRoller
class GodRoller(StandardDiceRoller):
def dice_result_to_string(self, dice_results):
result_response = ""
if len(dice_results) < configuration['dice']['dice_softcap']:
for result in dice_results:
if result_response:
result_response += "+"
if result[2]:
composite = "{}+{}".format(result[1], result[2])
else:
composite = result[1]
result_response += " {}*({})* ".format(result[0], composite)
result_response += " = "
dice_sum = sum(result[0] for result in dice_results)
result_response = "\tResult: {}**{}**.\n".format(result_response, dice_sum)
return result_response
def roll_the_dice(self, dice_pairs):
"""
A method that generates a random number based on a list of dice-pairs.
:param dice_pairs: A list of tuples, each tuple having a length of two and representing dice notation.
:return: A list containing a random number for each dice in the dice_pairs list.
"""
results = []
modifier = self.get_modifier(dice_pairs)
for pair in dice_pairs:
x, y = pair
signbit = -1 if x < 0 else 1
if 1 < y <= configuration['dice']['dice_max_sides'] and len(results) <= configuration['dice']['dice_hardcap']:
amount = min(abs(x), configuration['dice']['dice_hardcap'] - len(results))
for i in range(amount):
straight_roll = random.randint(1, y)*signbit
final_number = self.translate_number(straight_roll + modifier)
results.append((final_number, straight_roll, modifier))
return results
@staticmethod
def get_modifier(dice_pairs):
modifier = 0
for x, y in dice_pairs:
if y == 1:
modifier += x
return modifier
@staticmethod
def translate_number(number):
if number < 2:
return 0
if number < 6:
return 1
if number < 10:
return 2
return 4
|
55db89b8638149590ed2c0e4f6654131be5a3d78
|
maxmoro/matrices_decision_making
|
/DecisionMakingWithMatrices.py
| 7,286 | 3.828125 | 4 |
# Decision making with Matrices
# This is a pretty simple assingment. You will do something you do everyday, but today it will be with matrix manipulations.
# The problem is: you and your work firends are trying to decide where to go for lunch. You have to pick a resturant thats best for everyone. Then you should decided if you should split into two groups so eveyone is happier.
# Displicte the simplictiy of the process you will need to make decisions regarding how to process the data.
# This process was thoughly investigated in the operation research community. This approah can prove helpful on any number of decsion making problems
# that are currently not leveraging machine learning.
import numpy as np
#from sklearn.feature_extraction import DictVectorizer
from scipy.stats import rankdata
#%%
# You asked your 10 work friends to answer a survey. They gave you back the following dictionary object.
people = {'Jane': {'willingness to travel': 5
,'desire for new experience': 3
,'cost': 8
,'indian food': 8
,'mexican food': 9
,'hipster points': 1
,'vegitarian': 5
}
,'Max': {'willingness to travel': 9
,'desire for new experience': 6
,'cost': 9
,'indian food': 3
,'mexican food': 4
,'hipster points': 1
,'vegitarian': 1
}
,'Anna Maria': {'willingness to travel': 9
,'desire for new experience': 8
,'cost': 4
,'indian food': 5
,'mexican food': 6
,'hipster points': 2
,'vegitarian': 1
}
,'Letizia': {'willingness to travel': 9
,'desire for new experience': 8
,'cost': 2
,'indian food': 8
,'mexican food': 3
,'hipster points': 5
,'vegitarian': 9
}
,'Daniele': {'willingness to travel': 6
,'desire for new experience': 5
,'cost': 7
,'indian food': 5
,'mexican food': 8
,'hipster points': 1
,'vegitarian': 5
}
,'Brooke': {'willingness to travel': 3
,'desire for new experience': 3
,'cost': 4
,'indian food': 9
,'mexican food': 3
,'hipster points': 7
,'vegitarian': 8
}
,'David': {'willingness to travel': 5
,'desire for new experience': 3
,'cost': 6
,'indian food': 4
,'mexican food': 8
,'hipster points': 1
,'vegitarian': 5
}
,'Joe': {'willingness to travel': 9
,'desire for new experience': 7
,'cost': 1
,'indian food': 8
,'mexican food': 5
,'hipster points': 1
,'vegitarian': 5
}
,'Diana': {'willingness to travel': 3
,'desire for new experience': 2
,'cost': 7
,'indian food': 2
,'mexican food': 5
,'hipster points': 4
,'vegitarian': 8
}
,'Jeremy': {'willingness to travel': 5
,'desire for new experience': 2
,'cost': 2
,'indian food': 6
,'mexican food': 8
,'hipster points': 1
,'vegitarian': 2
}
}
#%%
# Transform the user data into a matrix(M_people). Keep track of column and row ids.
M_people = np.zeros((len(people),7))
for i, p in enumerate(people):
M_people[i,] = np.array(list(people[p].values()))
people_names = list(people)
people_cols =list(people[people_names[1]])
#%%
# Next you collected data from an internet website. You got the following information.
restaurants = {'flacos':{'distance' : 3
,'novelty' : 2
,'cost': 1
,'average rating': 5
,'cuisine': 8
,'vegitarians': 3
}
,'Pizza Hut':{'distance' : 9
,'novelty' : 1
,'cost': 9
,'average rating': 2
,'cuisine': 2
,'vegitarians': 4
}
,'Flat Bread':{'distance' : 8
,'novelty' : 4
,'cost': 4
,'average rating': 7
,'cuisine': 8
,'vegitarians': 6
}
,'10 Barrels':{'distance' : 6
,'novelty' : 6
,'cost': 5
,'average rating': 8
,'cuisine': 7
,'vegitarians': 4
}
,'The Fork':{'distance' : 3
,'novelty' : 9
,'cost': 2
,'average rating': 7
,'cuisine': 8
,'vegitarians': 8
}
}
#%%
# Transform the restaurant data into a matrix(M_resturants) use the same column index.
M_restaurants = np.zeros((len(restaurants),6))
for i, r in enumerate(restaurants):
M_restaurants[i,] = np.array(list(restaurants[r].values()))
rest_names = list(restaurants)
rest_cols =list(restaurants[rest_names[1]])
#%%
# The most imporant idea in this project is the idea of a linear combination.
# Informally describe what a linear combination is and how it will relate to our resturant matrix.
#%%
# Choose a person and compute(using a linear combination) the top restaurant for them.
# What does each entry in the resulting vector represent.
np.dot(M_people[1,],M_restaurants)
#%%
# Next compute a new matrix (M_usr_x_rest i.e. an user by restaurant) from all people. What does the a_ij matrix represent?
# Sum all columns in M_usr_x_rest to get optimal restaurant for all users. What do the entry’s represent?
# Now convert each row in the M_usr_x_rest into a ranking for each user and call it M_usr_x_rest_rank.
# Do the same as above to generate the optimal resturant choice.
# Why is there a difference between the two? What problem arrives? What does represent in the real world?
# How should you preprocess your data to remove this problem.
# Find user profiles that are problematic, explain why?
# Think of two metrics to compute the disatistifaction with the group.
# Should you split in two groups today?
# Ok. Now you just found out the boss is paying for the meal. How should you adjust. Now what is best restaurant?
# Tommorow you visit another team. You have the same restaurants and they told you their optimal ordering for restaurants.
# Can you find their weight matrix?
|
e3d5fd7f8d28171309155f9d5a6f0bb2a37d2f59
|
happycupofjava/Data-Mining
|
/data_mining_p1.py
| 13,670 | 3.75 | 4 |
import numpy as np
import sys
import matplotlib.pyplot as plt
from sklearn import svm
'''
File Name TEMP_FILE_NAME is used to store
the pickdataclass output and splitData2TestTrain as Input.
'''
TEMP_FILE_NAME = 'test.out'
'''
Converts the string passed to corresponding integers using ASCII values.
ASCII(<LETTER>) - 64
64=ASCIIVALUE('A')-1
'''
def letter_to_digit_convert(mystr):
m_list = []
mystr = mystr.upper()
for i in mystr:
if i.isalpha():
m_list.append(ord(i) - 64)
return m_list
'''
Splits the data in the file passed as an argument, based on the class ids given by the
letter_to_digit_convert function. It stores the output into TEMP_FILE_NAME.
'''
def pickDataClass(filename, class_ids):
data = np.genfromtxt(filename, delimiter=',')
#print(data)
list_ClassifierCol = []
for i in class_ids:
a= np.where(data[0] == i) # returns index locations of the perticular class
#print(a)
list_ClassifierCol.extend(np.array(a).tolist()) # appending columns into a string
#print(listOfClassifierColumn)
list_ClassifierCol = [item for sublist in list_ClassifierCol for item in sublist] # forming a array
np.savetxt(TEMP_FILE_NAME, data[:, list_ClassifierCol], fmt="%i", delimiter=',')
#fh = open(TEMP_FILE_NAME,"r")
#print (fh.read())
'''
splitData2TestTrain takes arguments filename, number_per_class, test_instances
split the data into testVector, testLabel, trainVector, trainLabel
Get list of train instances, test instances, strip them and add into respective matrix.
'''
def splitData2TestTrain(filename, number_per_class, test_instances):
start, end = test_instances.split(":")
listTest = list(range(int(start), int(end) + 1))
listTrain = list((set(list(range(0, number_per_class))) - set(listTest)))
Training = []
Test = []
data = np.genfromtxt(filename, delimiter=',')
#print("x val",data[1].size)
for i in range(0, data[0].size, number_per_class):
templistTest = [x + i for x in listTest]
templistTrain = [x + i for x in listTrain]
templistTest.sort()
templistTrain.sort()
if len(Test) == 0:
Test = data[:, templistTest]
else:
Test = np.concatenate((Test, data[:, templistTest]), axis=1)
if len(Training) == 0:
Training = data[:, templistTrain]
else:
Training = np.concatenate((Training, data[:, templistTrain]), axis=1)
return Test[1:, ], Test[0], Training[1:, ], Training[0]
'''
Stores the np type array into fileName after stacking label over train.
'''
def store(trainX, trainY, fileName):
np.savetxt(fileName, np.vstack((trainY, trainX)), fmt="%i", delimiter=',')
'''
printAccuracy returns the accuracy comparision from Ytest and calculated label
'''
SVM = svm.SVC()
def printAccuracy(sampleLabel, calculatedLabel):
err_test_padding = sampleLabel - calculatedLabel
TestingAccuracy_padding = (1 - np.nonzero(err_test_padding)[0].size / float(len(err_test_padding))) * 100
return (TestingAccuracy_padding)
'''
Linear regression:
Xtest_padding : formed by adding ones to bottom of Xtest
Xtrain_padding: formed by adding ones to bottom of Xtrain
Ytrain_Indent : Form array with class label index as 1 other are zero.
e.g LabelVector = [1,5]
| 1 1 1 0 0 0 |
| 0 0 0 1 1 1 |
return Accuracy.
'''
def linear(Xtrain, Xtest, Ytrain, Ytest):
RowToFill = 0
A_train = np.ones((1, len(Xtrain[0])))
#print(A_train)
A_test = np.ones((1, len(Xtest[0])))
Xtrain_padding = np.row_stack((Xtrain, A_train))
Xtest_padding = np.row_stack((Xtest, A_test))
ele, indx, count = np.unique(Ytrain, return_counts=True, return_index=True)
#print(ele, indx, count) #[1. 2. 3. 4. 5.] [ 0 30 60 90 120] [30 30 30 30 30]
ele = Ytrain[np.sort(indx)]
#print(np.sort(indx))
Ytrain_Indent = np.zeros((int(max(ele)), count[0] * len(ele)))
#print(Ytrain_Indent)
#print(Ytrain_Indent.shape) # (5, 150)
for i, j in zip(count, ele):
Ytrain_Indent[int(j) - 1, RowToFill * i:RowToFill * i + i] = np.ones(i)
RowToFill += 1
#print(Ytrain_Indent)
#print(Xtrain_padding.T)
B_padding = np.dot(np.linalg.pinv(Xtrain_padding.T), Ytrain_Indent.T)
Ytest_padding = np.dot(B_padding.T, Xtest_padding)
#print(Ytest_padding)
Ytest_padding_argmax = np.argmax(Ytest_padding, axis=0) + 1
#print(Ytest_padding_argmax)
err_test_padding = Ytest - Ytest_padding_argmax
#print(err_test_padding)
TestingAccuracy_padding = (1 - np.nonzero(err_test_padding)[0].size / float(len(err_test_padding))) * 100
return TestingAccuracy_padding
'''
kNearestNeighbor(X_train, y_train, X_test, k)
return y_test
Find eucledean distance between points, shorlist least k
returns the dominent label of k.
'''
def kNearestNeighbor(Xtrain, Ytrain, Xtest, k):
preds = []
for i in range(len(Xtest[0])):
t_Test = Xtest[:, i]
dist = []
target_class = []
for iNN in range(len(Xtrain[0])):
temp_square=np.square(t_Test - Xtrain[:, iNN])
temp=np.sum(temp_square)
d = np.sqrt(temp)
dist.append([d, iNN])
dist = sorted(dist)
for iNN in range(k):
index = dist[iNN][1]
target_class.append(Ytrain[index])
#print("@@@",target_class)
preds.append(max(set(target_class), key=target_class.count))
#print(preds)
preds = list(int(i) for i in preds)
return preds
'''
Using the Scikit library sklearn to to implement the svm method on the data.
'''
def svmClassifier(train, trainLabel, test, testLabel):
train = train.transpose()
test = test.transpose()
SVM.fit(train, trainLabel)
SVM.predict(test)
#print(test)
return test
'''
centroid method compares the eucledean distance between the
nearest centroid.
'''
def centroid(trainV, trainL, testV):
temp_arr = []
#print(len(trainV[0]))
#print("$$",trainL)
res = []
for j in range(0, len(trainV[0]), 8):
colMean = []
colMean.append(trainL[j])
#print(colMean)
for i in range(len(trainV)):
x=np.mean(trainV[i, j:j + 7])
colMean.append(x)
#print("trainV[i, j:j + 7]:",trainV[i, j:j + 7])
#print(colMean)
if not len(temp_arr):
temp_arr = np.vstack(colMean)
#print(temp_arr)
else:
tempx =np.vstack(colMean)
temp_arr = np.hstack((temp_arr, tempx))
#print("$$",temp_arr)
#print("testV[0]:",len(testV[0]))
for jN in range(len(testV[0])):
distances = []
for m in range(len(temp_arr[0])):
temp=np.square(testV[:, jN] - temp_arr[1:, m])
temp=np.sum(temp)
eucleadian_dist = np.sqrt(temp)
distances.append([eucleadian_dist, int(temp_arr[0, m])])
distances = sorted(distances, key=lambda distances: distances[0])
res.append(distances[0][1])
#print("Cnetroid result",res)
return res
'''
General task function for the Task C and Task D.
'''
def TaskC(uString):
l_convert = letter_to_digit_convert(uString)
pickDataClass('HandWrittenLetters.txt', l_convert)
c_AccList = []
knnAccList = []
linearAccList = []
print('Calculating ' + '.' * 3 )
for i in range(5, 39, 5):
#print(str(i))
testV, testL, trainV, trainL = splitData2TestTrain(TEMP_FILE_NAME, 39, str(i) + ':38')
c_result = centroid(trainV, trainL, testV)
c_AccList.append(printAccuracy(testL, c_result))
X = ['', '(5, 34)', '(10,29)', '(15,24)', '(20,19)', '(25,24)', '(30,9)', '(35,4)']
fig = plt.figure()
x1 = fig.add_subplot(111)
x1.set_xticklabels(X, minor=False)
x1.set_xlabel('(Train, Test)')
x1.set_ylabel('Accuracy (%)')
x1.plot(c_AccList, 'ro', color='black')
x1.plot(c_AccList, color='grey')
x1.set_title('Centroid Classification.')
for i, j in zip(range(7), c_AccList):
x1.annotate("%.2f" % j, xy=(i + 0.2, j))
plt.show()
def main():
choice= input("Please enter which task to be performed(Task A, Task B, Task C or Task D):")
#raw_input("Please enter which task to be performed(Task A, Task B, Task C):")
if choice== 'A' or choice == 'a' or choice =='Task A':
# Task A
'''TASK A :
Use the data-handler to select "A,B,C,D,E" classes from the hand-written-letter data.
From this smaller dataset, Generate a training and test data: for each class.
using the first 30 images for training and the remaining 9 images for test.
Do classification on the generated data using the four classifers.'''
print("Performing Task A\n\n\n")
pickDataClass('HandWrittenLetters.txt', letter_to_digit_convert('ABCDE')) # classes for the test
testVector, testLabel, trainVector, trainLabel = splitData2TestTrain(TEMP_FILE_NAME, 39, '30:38') #data split ratio
svmMatrix = svmClassifier(trainVector, trainLabel, testVector, testLabel)
c_res = centroid(trainVector, trainLabel, testVector)
linear_res = linear(trainVector, testVector, trainLabel, testLabel)
knn_res = kNearestNeighbor(trainVector, trainLabel, testVector, 5)
svm_res = SVM.score(svmMatrix, testLabel)
svm_res *= 100
c=printAccuracy(testLabel, c_res)
print('\n\nAccuracy of SVM is %0.2f \n' % svm_res)
print('Accuracy of Centroid is %0.2f\n' % c)
print('Accuracy of Linear is %0.2f\n' % linear_res)
v=printAccuracy(testLabel, knn_res)
print('Accuracy of 5-NN is %0.2f\n' % v)
elif choice== 'B' or choice == 'b' or choice =='Task B':
# Task B
'''TASK B
On ATNT data, run 5-fold cross-validation (CV) using each of the
four classifiers: KNN, centroid, Linear Regression and SVM.
If you don't know how to partition the data for CV, you can use the data-handler to do that.
Report the classification accuracy on each classifier.
Remember, each of the 5-fold CV gives one accuracy. You need to present all 5 accuracy numbers
for each classifier. Also, the average of these 5 accuracy numbers.'''
print("Performing Task B\n\n\n")
svmAccList = []
centroidAccList = []
knnAccList = []
linearAccList = []
print('Calculating' + '.' * 3)
for i in range(0, 10, 2):
testVector, testLabel, trainVector, trainLabel = splitData2TestTrain('ATNTFaceImages400.txt', 10,
str(i) + ':' + str(i + 1))
#change the split ratio: change for in range(0,10, taining numebr) and i+test-1
"""
print("",testVector)
print(testLabel)
print(trainVector)
print(trainLabel)
print("data",str(i), str(i+1))"""
svm_Matrix = svmClassifier(trainVector, trainLabel, testVector, testLabel)
centroid_res = centroid(trainVector, trainLabel, testVector)
linearAccList.append(linear(trainVector, testVector, trainLabel, testLabel))
knn_res = kNearestNeighbor(trainVector, trainLabel, testVector, 5)
svm_res = SVM.score(svm_Matrix, testLabel)
svm_res *= 100
svmAccList.append(svm_res)
centroidAccList.append(printAccuracy(testLabel, centroid_res))
knnAccList.append(printAccuracy(testLabel, knn_res))
knn_r=sum(knnAccList) / len(knnAccList)
print('\nAverage accuracy of 5-NN after 5-Fold is %0.2f' % knn_r)
print(knnAccList)
centroid_r=sum(centroidAccList) / len(centroidAccList)
print('\nAverage accuracy of Centroid after 5-Fold is %0.2f' % centroid_r)
print(centroidAccList)
svm_r=sum(svmAccList) / len(svmAccList)
print('\nAverage accuracy of SVM after 5-Fold is %0.2f' % svm_r)
print(svmAccList)
linear_r=sum(linearAccList) / len(linearAccList)
print('\nAverage accuracy of Linear after 5-Fold is %0.2f' % linear_r)
print(linearAccList)
elif choice== 'C' or choice == 'c' or choice =='Task C':
# Task C
''' TASK C :
On handwritten letter data, fix on 10 classes. Use the data handler to generate training and test data files.
Do this for seven different splits: (train=5 test=34), (train=10 test=29), (train=15 test=24) ,
(train=20 test=19), (train=25 test=24) , (train=30 test=9) , (train=35 test=4).
On these seven different cases, run the centroid classifier to compute average test image classification
accuracy. Plot these 7 average accuracy on one curve in a figure. What trend can you observe?
When do this task, the training data and test data do not need be written into files.'''
print("Performing Task C\n\n\n")
TaskC('ABCDEFXYZG')
elif choice== 'D' or choice == 'd' or choice =='Task D':
''' TASK D:
Repeat task (D) for another different 10 classes. You get another 7 average accuracy.
Plot them on one curve in the same figure as in task (D). Do you see some trend?'''
print("Performing Task D\n\n\n")
TaskC('MNOPQRSTUV')
else:
print( "pick one of the tasks in A, B c or D only!!!\n\n\n")
main()
main()
|
9f93ca4542f88dff119a1531732b4fe5af9ca344
|
chetanpv/python_learn
|
/4_functions.py
| 3,849 | 3.859375 | 4 |
# ----------------------------------------------------------------------------------------
# Function call without return value
# ----------------------------------------------------------------------------------------
def a(name):
print "hello", name # hello Chetan # when you use , operator a default space is given
a("Chetan")
# ----------------------------------------------------------------------------------------
# Function call with return value
# ----------------------------------------------------------------------------------------
def b(number):
return number + 1
print b(4) # 5
print "="*20
# ----------------------------------------------------------------------------------------
# Scope of a variable
# i cannot be changed inside a function
# Parameter passed value can be changed. But within the scope and sent back
# ----------------------------------------------------------------------------------------
i = 4
def c(number):
print "Inside c: i:", i
# i += 1 # i cannot be changed. i here is referred as out of scope variable
print "Inside c: number:", number
number += 1
print "Inside c: number:", number
return number
output = c(i)
print "Output of the function", output
print "Outside c: i:", i
# Inside c: i: 4
# Inside c: number: 4
# Inside c: number: 5
# Output of the function 5
# Outside c: i: 4
print "="*20
# ----------------------------------------------------------------------------------------
# Function call with arguments
# keyword args must always be at the end
# Empty string OR 0 are also values. They will oeverride default parameter
# ----------------------------------------------------------------------------------------
def d(name, age, work="hp"):
print name
print age
print work
d("Chetan","27","") # Chetan 27 None
d("Chetan","27") # Chetan 27 hp
d("Chetan","27","hpe") # Chetan 27 hpe
print "="*20
# ----------------------------------------------------------------------------------------
# Arbitrary arguments
# ----------------------------------------------------------------------------------------
def e(*name):
print name
d("Chetan", "Vivek", "Naveen") # Chetan Vivek Naveen
def f(**generally_called_kwargs):
print generally_called_kwargs
keywords = {'keyword1': 'foo', 'keyword2': 'bar'}
f(keyword1='foo', keyword2='bar') # {'keyword2': 'bar', 'keyword1': 'foo'}
f(**keywords) # {'keyword2': 'bar', 'keyword1': 'foo'}
print "="*20
def g(*name, **generally_called_kwargs):
print name, generally_called_kwargs
print type(name) # <type 'tuple'>
keywords = {'keyword1': 'foo', 'keyword2': 'bar'}
g("Chetan",keyword1='foo', keyword2='bar') # ('Chetan',) {'keyword2': 'bar', 'keyword1': 'foo'}
g("Chetan",**keywords) # ('Chetan',) {'keyword2': 'bar', 'keyword1': 'foo'}
# ----------------------------------------------------------------------------------------
# Recursion
# ----------------------------------------------------------------------------------------
def fact(n):
if n == 1:
return 1
else:
return (n * fact(n-1))
output = fact(4)
print output # 24
# ----------------------------------------------------------------------------------------
# Anonymous Function/Lamda function
# ----------------------------------------------------------------------------------------
double = lambda x: x * 2
print double(5) # 10
# ----------------------------------------------------------------------------------------
# Filter()
# The function is called with all the items in the list and a new list is returned
# which contains items for which the function evaluats to True.
# ----------------------------------------------------------------------------------------
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list) # [4, 6, 8, 12]
|
a54899924fa7c8bf7f61253d9184d4d31c0eef3f
|
maher-mouelhi/backup
|
/project_one/myexercice.py
| 647 | 3.828125 | 4 |
#input data family 1 and 2
familiesList = []
PersonneDictionary = {"name":'',"age":0}
PersoneList = []
for i in range(2):
fam = input("data family plz give name ")
pere = input(" plz give name pere ")
pereAge = input(" plz give age pere ")
PersonneDictionary["name"]= pere
PersonneDictionary["age"]= pereAge
PersoneList.append(PersonneDictionary)
mere = input(" plz give name mere ")
mereAge = input(" plz give age mere ")
PersonneDictionary["name"] = mere
PersonneDictionary["age"] = mereAge
PersoneList.append(PersonneDictionary)
familiesList.append(PersoneList)
print(familiesList)
|
1f75dcecf445d0edd97e84e2ef944ff08a52661d
|
raaffaaeel/github-course
|
/usp_python.py
| 1,252 | 4.25 | 4 |
print('Eu serei expert em python')
10
type(10)
<class 'int'>
type("tudo bem")
<class 'str'>
5 / 2
<2.5>
type(5 / 2)
<float>
10 // 3
<3>
10 % 3
<1>
# colocqndo 2 variaveis #
peso = 78
altura = 1.83
print (peso)
print (altura)
# buscando o indice de massa corporal, peso / altura elevado ao quadrado #
IMC = peso / (altura ** 2)
IMC
IMCinteiro = int(IMC)
IMCinteiro
# escrevendo variavel e contando caracter #
texto = "Bom dia, tudo bem"
len(texto)
17
# alterando uma variavel para string #
temp = str(texto)
'Bom dia, tudo bem'
# alterando uma variavel para string #
temp = str(IMC)
temp
'23.291229956104985'
len(temp)
18
------------------------
temperaturaFahrenheit = 98
temperaturaCelsius = (float(temperaturaFahrenheit) - 32) * 5 / 9
print ("A temperatura em celsius é", temperaturaCelsius)
A temperatura em celsius é >25.555555555555557<
------------------------
temperaturaFahrenheit = input("Digite uma temperatura em Fahrenheit: ")
temp = float(temperaturaFahrenheit)
temperaturaCelsius = (temperaturaFahrenheit - 32) * 5 / 9
-----------------------
nomeDamae = input("Qual o nome da sua mãe? ")
nomeDoPai = input("Qual o nome do seu Pai? ")
print("Bom dia Sra.", nomeDamae, "!!! E Bom dia Sr." nomeDoPai, ",")
|
7333865760e217ab5cafb17c63884852d80cfee0
|
Competitive-Programmers-Community/LeetCode
|
/492. Construct the Rectangle/main.py
| 272 | 3.546875 | 4 |
class Solution:
def constructRectangle(self, area):
"""
:type area: int
:rtype: List[int]
"""
W = int(math.sqrt(area))
for w in range(W, 0, -1):
if area%w == 0:
return [area//w , w]
|
bb978ee5cb0408e8ef673e531bb5232c8b18a999
|
yoon50/ds-algorithms
|
/tree/print_reverse_level_order.py
| 999 | 4.0625 | 4 |
from node import Node
def print_reverse_level_order(root):
"""
Put in the right child followed by the left child of the
recently popped parent. Place parent in the stack.
Once we have processed all the nodes, then
we will pop each element from the stack and print the data.
"""
if root is None:
return
queue = [root]
stack = []
while len(queue):
cnode = queue.pop(0)
stack.append(cnode)
if cnode.right:
queue.append(cnode.right)
if cnode.left:
queue.append(cnode.left)
while len(stack):
node = stack.pop(-1)
print node.data,
print
"""
1
/ \
3 5
/ \
2 9
"""
tree_root = Node(data=1)
lvl1_node0 = tree_root.left = Node(data=3)
lvl1_node1 = tree_root.right = Node(data=5)
lvl2_node0 = lvl1_node0.left = Node(data=2)
lvl2_node1 = lvl1_node0.right = Node(data=9)
# print
# 2 9 3 5 1
print_reverse_level_order(tree_root)
|
38fd3c77094e41fe7352738069ed697e2a2555c2
|
ajitnak/py_pgms_heap
|
/kth_smallest.py
| 1,199 | 3.640625 | 4 |
def smallest(list, k):
return kth_smallest(list, 0, len(list) - 1, k-1)
def kth_smallest(arr, low, high, k):
# If k is smaller than number of
# elements in array
if (k >= 0 and k <= high - low ):
pos = partition(arr, low, high)
#print pos, low,k
if pos - low == k:
return arr[pos]
if pos - low > k : # If position is more,
return kth_smallest(arr, low, pos - 1, k)
# Else recur for right subarray
return kth_smallest(arr, pos + 1, high, k - pos + low - 1)
# If k is more than number of
# elements in array
return None
def partition(arr, low, high):
x = arr[high]
i = low
for j in range(low, high):
if (arr[j] <= x):
arr[i], arr[j] = arr[j], arr[i]
i += 1
arr[i], arr[high] = arr[high], arr[i]
return i
print smallest([12, 3, 5, 7, 4, 19, 26], 1)
print smallest([12, 3, 5, 7, 4, 19, 26], 2)
print smallest([12, 3, 5, 7, 4, 19, 26], 3)
print smallest([12, 3, 5, 7, 4, 19, 26], 4)
print smallest([12, 3, 5, 7, 4, 19, 26], 5)
print smallest([12, 3, 5, 7, 4, 19, 26], 6)
print smallest([12, 3, 5, 7, 4, 19, 26], 7)
|
f46691b8d9b02993bc536efcec3b5ababf9cf2d0
|
sf-playground/hack-usability
|
/research/languages/python.py
| 475 | 3.640625 | 4 |
def f(x): return (x % 3 == 0) or (x %% 5 == 0)
filter(f, range(2, 25))
# [3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]
# --------------------------------
def cube(x): return x ** 3
map(cube, range(1, 11))
# [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
# --------------------------------
seq = range(8)
def add(x, y): return x + y
map(add, seq, seq)
# [0, 2, 4, 6, 8, 10, 12, 14]
# --------------------------------
def add(x, y): return x + y
reduce(add, range(1, 11))
# 55
|
aed9fbc08f9669ff5f5dd4d3b58ffe7303183646
|
isidorogu/Intro-to-Programming
|
/PS_2/calculator.py
| 322 | 3.75 | 4 |
value = input("Home Value: ")
down = input("Down Payment: ")
p = input("Term (in years): ")
i = input("Annual Int Rate: ")
value = float(value)
down = float(down)
p = float(p)
i = float(i)
l = value - down
p = p*12
i = i/100
import mortgage
a = mortgage.mortgage_pymnt(l, p, i)
print('Your payment is', round(a, 2))
|
45abb1998d003274803b40881f00a7839704c60a
|
aliakseik1993/skillbox_python_basic
|
/module1_13/module2_hw/task_5.py
| 1,066 | 4.21875 | 4 |
print('Задача 5. Вход в систему')
# Что нужно сделать
# Исправьте программу и допишите необходимые команды для получения нужного результата.
# Будьте внимательны при исправлении и помните о правилах названия переменных.
# Программа:
first_name = input('Введите имя пользователя: ')
greeting = 'Привет'
print(greeting, first_name)
invalid = "К сожалению, у Вас нет доступа к системе."
info_invalid = "Пожалуйста, обратитесь к системному администратору."
print(invalid)
print(info_invalid)
# Ожидаемый результат:
# Введите имя пользователя: Роман
# Привет, Роман
# К сожалению, у Вас нет доступа к системе.
# Пожалуйста, обратитесь к системному администратору.
|
d92f38987702a22918faefd9d909765d62984faa
|
zhzeshu/Algorithm-Problem-Solutions
|
/Data Structure Implementations/UpTree.py
| 1,447 | 3.5 | 4 |
#!/usr/bin/env python3
class UpTree:
def __init__(self):
self.parent = dict(); self.size = dict()
def __len__(self):
return len(self.parent)
def __getitem__(self, key): # "find" function
if key not in self.parent:
raise KeyError(str(key))
q = [key]
while self.parent[q[-1]] is not None:
q.append(self.parent[q[-1]])
sentinel = q.pop(); n_to_sub = 0
for n in q:
self.parent[n] = sentinel # path compression
self.size[n] -= n_to_sub; n_to_sub += self.size[n]
return sentinel
def __iter__(self):
return iter(self.parent.keys())
def __next__(self):
return next(iter(self.parent.keys()))
def add(self, key):
if key in self.parent:
raise ValueError("Duplicate key: %s" % str(key))
self.parent[key] = None; self.size[key] = 1
def sentinels(self):
return {n for n in self.parent if self.parent[n] is None}
def union(self, u, v):
if u not in self.parent:
raise KeyError(str(u))
if v not in self.parent:
raise KeyError(str(v))
sentinel_u = self[u]; sentinel_v = self[v]
if sentinel_u == sentinel_v:
return
elif self.size[sentinel_u] > self.size[sentinel_v]: # union by size
self.parent[sentinel_v] = sentinel_u
else:
self.parent[sentinel_u] = sentinel_v
|
90b2fb5cd10c6510892d918cef64ea27d6d30b89
|
aticomismana/turma51487
|
/logica/exercicios/4.listas/icaro_listas.py
| 2,219 | 4.21875 | 4 |
"""
1. Crie uma lista notas e, por meio de while, calcule a média: 7,8,8,7.5,8.5,9,10
2. Calcule a média com notas obtidas a partir do teclado que serão armazenadas em uma lista.
3. Crie um programa que ler cinco números, armazena-os em uma lista e depois solicita que o usuário escolha um número a mostrar.
"""
def lista():
notas = [7,8,8,7.5,8.5,9,10.0]
soma = 0
x = 0
while x < len(notas):
#soma = sum(notas)
soma+=notas[x]
x+=1
print("A media é ",soma/x)
#----------------------------------------------------------------------
def calcMedia():
x = 1
qM = int(input("Digite quantas medias você quer fazer: "))
lista = list(range(qM))
cont=0
while x <= qM:
lista[cont] = float(input("digite a %d° nota:"%(x)))
cont +=1
x+=1
media = sum(lista)/qM
print(media)
DverNot = str(input("Digite S se você quer escolher a nota:"))
if DverNot == "s" or DverNot == "S":
eM = int(input("Escolha qual numero você quer:"))
eM-=1
if (eM < qM):
print(lista[eM])
else:
print("Numero maior que a quantidade da lista")
#----------------------------------------------------------------------
def vMed():
x = 1
cont = 0
lista = list(range(5))
while cont < 5:
lista[cont] = float(input("digite a %d° nota:"%(cont)))
cont+=1
VerNot = int(input("Digite qual numero você quer ver:"))
enc= False
cont = 0
while cont<len(lista):
if lista[cont] == VerNot:
print("numero encontrado na posição: %d"%cont)
enc = True
cont+=1
if(enc==False):
print('numero não encontrado')
#---------------------------------------------------------------------
print("Digite 1 se você quer lista notas e, por meio de while\n2° se você quer Calcule a média com notas obtida\n3 se você quer ler cinco números, armazena-os")
escolha = int(input("Digite: "))
if (escolha == 1):
print("Rodando exercicio 1:")
lista()
elif (escolha == 2):
print("Rodando exercicio 2:")
calcMedia()
elif (escolha == 3):
print("Rodando exercicio 3:")
vMed()
|
339422678c5c7ce5cc1557b81d7fade312f20816
|
DoctorSad/_Course
|
/Lesson_08/_2_dict_1_zip.py
| 1,751 | 4.15625 | 4 |
"""
Создание словаря с помощью zip.
zip(iter1, iter2)
запаковывает элементы последовательностей iter1 и iter2
и возвращает объект zip из которого можно сделать словарь
dict(zip(iter1, iter2))
* при не равном количестве элементов последовательностей,
лишние ключи либо значения - игнорируются, т.е. создаются только пары
"""
from pprint import pprint
def main():
keys = ["name", "email", "age"]
values = ["Max", "[email protected]", 21]
user_data = dict(zip(keys, values))
print(user_data) # {'name': 'Max', 'email': '[email protected]', 'age': 21}
print(dict(zip("abc", "123"))) # {'a': '1', 'b': '2', 'c': '3'}
print(dict(zip("abc", range(1, 100)))) # {'a': 1, 'b': 2, 'c': 3}
print(dict(zip(["name", "age"], ["Max"]))) # {'name': 'Max'}
def dict_from_list():
users = [
["Max", "[email protected]", 21],
["Ann", "[email protected]", 22],
["John", "[email protected]", 23],
["Jane", "[email protected]", 24],
]
data = []
for user_data in users:
data.append(
{"name": user_data[0], "email": user_data[1], "age": user_data[2]}
)
print(data)
def dict_from_list_zip():
users = [
["Max", "[email protected]", 21],
["Ann", "[email protected]", 22],
["John", "[email protected]", 23],
["Jane", "[email protected]", 24],
]
ns = ["name", "email", "age"]
data = []
for user_data in users:
data.append(dict(zip(ns, user_data)))
pprint(data)
if __name__ == "__main__":
main()
dict_from_list()
dict_from_list_zip()
|
dd395eb40a4645720921a9279091c12a698aa3fb
|
Aasthaengg/IBMdataset
|
/Python_codes/p02939/s471464271.py
| 128 | 3.65625 | 4 |
S=input()
pre="#"
cur=""
cnt=0
for s in S:
cur+=s
if pre!=cur:
cnt+=1
pre=cur
cur=""
print(cnt)
|
f216c35de9fccf98a84cb33869eb1bb576c51c8a
|
Didred/MSI
|
/lab4/lab4.py
| 2,419 | 3.546875 | 4 |
import random
import math
import primes
def exp(base, power, m):
result = 1
for _ in range(power):
result = (result * base) % m
return result
def get_p():
a = primes.a
rand = random.randint(100, len(a))
return a[rand]
def get_fact(p):
fact = []
n = p - 1
for i in range(2, int(math.sqrt(n))):
if n % i == 0:
fact.append(i)
while n % i == 0:
n /= i
if n > 1:
fact.append(n)
return fact
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
def get_antiderivative_root(p, fact):
g = random.randint(2, p - 1)
for i in range(len(fact)):
if exp(g, int((p - 1) / fact[i]), p) == 1:
return get_antiderivative_root(p, fact)
return g
def get_k(p):
while True:
k = random.randint(1, p - 1)
if gcd(k, p - 1) == 1:
return k
def generate_keys():
p = get_p()
g = get_antiderivative_root(p, get_fact(p))
x = random.randint(2, p - 1)
y = exp(g, x, p)
print()
print(" Открытые ключи:")
print(f" p = {p}")
print(f" g = {g}")
print(f" y = {y}")
print()
print(" Закрытый ключ")
print(f" x = {x}")
print()
return {"p": p, "g": g, "y": y}, x
def encrypt(message, p, g, y):
encrypted = []
for m in message:
k = get_k(p)
a = exp(g, k, p)
b = exp(y, k, p)
b = (b * m) % p
encrypted.append(a)
encrypted.append(b)
return encrypted
def decrypt(message, p, x):
decrypted = []
for i in range(0, len(message) - 1, 2):
a = message[i]
b = message[i + 1]
m = (b * a ** (p - 1 - x)) % p
decrypted.append(chr(m))
return decrypted
if __name__ == "__main__":
public_keys, private_key = generate_keys()
with open("input.txt", "r") as f:
message = f.readline()
message_chars = []
for m in message:
message_chars.append(ord(m))
encrypted = encrypt(message_chars, public_keys["p"], public_keys["g"], public_keys["y"])
with open('output_encrypted.txt', "w") as f:
f.write(str(encrypted))
decrypted = decrypt(encrypted, public_keys["p"], private_key)
with open("output_decrypted.txt", "w") as f:
f.write("".join(decrypted))
|
80f08beaef85afd213a59fb1b512a97fb4d38b7c
|
srcmarcelo/Python-Studies
|
/PythonTest/ex020.py
| 185 | 3.78125 | 4 |
people = {'name': 'Marcelo', 'gender': 'M', 'age': 17}
print(people)
print(people['name'])
people['weight'] = 54
for k, v in people.items():
print(f'{k}: {v}')
del people['weight']
|
485d649ba950fb42db98fc5f3c321d5b6fe1849a
|
ShawnWuzh/algorithms
|
/空格替换.py
| 1,562 | 3.9375 | 4 |
'''
请编写一个方法,将字符串中的空格全部替换为“%20”。假定该字符串有足够的空间存放新增的字符,并且知道字符串的真实长度(小于等于1000),同时保证字符串由大小写的英文字母组成。
给定一个string iniString 为原始的串,以及串的长度 int len, 返回替换后的string。
测试样例:
"Mr John Smith”,13
返回:"Mr%20John%20Smith"
”Hello World”,12
返回:”Hello%20%20World”
'''
# written by HighW
'''
首先统计出空格的数目,然后算出最终字符串的长度,然后从字符串的最后面开始遍历,遇到非空格,就移动到新字符串的对应位置,如果遇到空格,在相应位置上填上规定字符。
'''
class Replacement:
def replaceSpace(self, iniString, length):
num_space = 0
for i in range(length):
if iniString[i] == ' ':
num_space += 1
new_length = length - num_space + num_space * 3
new_string = [None for i in range(new_length)]
for j in range(length-1,-1,-1):
if iniString[j] != ' ':
new_string[new_length-1] = iniString[j]
new_length -= 1
else:
new_string[new_length-1] = '0'
new_string[new_length-2] = '2'
new_string[new_length-3] = '%'
new_length -= 3
return ''.join(new_string)
if __name__ == '__main__':
replacement = Replacement()
iniString = "aabcb"
print(replacement.replaceSpace(iniString,5))
|
2717ae50c1c24c997dfe6df031265cf4e63e8a0b
|
treviza153/DailyCoding
|
/ListExercises/Test.py
| 394 | 3.515625 | 4 |
#!/usr/local/bin python3
import Main
import unittest
class TestList(unittest.TestCase):
def testNumDivisible10(self):
self.assertEqual(Main.numDivisible(10), [2,5], "Should be [2,5]")
def testNumDivisible30(self):
self.assertEqual(Main.numDivisible(30), [2, 3, 5, 6, 10, 15], "Should be [2, 3, 5, 6, 10, 15]")
if __name__ == '__main__':
unittest.main()
|
e3a71eba44f4898bcc6f13d22a976719860310a9
|
Asky-M/dscnf-06
|
/scripts/01.basic/04.set.py
| 551 | 3.890625 | 4 |
s = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4}
print(s)
# length/size
print(len(s), s)
# add item to set
s.add(4)
s.add(5)
print(s)
# conversion from/to set
## list
l = list(s)
print(l)
l = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
s = set(l)
print(s)
## tuple
t = tuple(s)
print(t)
t = (1, 2, 2, 3, 3, 3, 4, 4, 4, 4)
s = set(t)
print(s)
# set operation
s = {1, 2, 3, 4, 5}
t = {2, 3, 5, 7, 11}
## difference
print(s.difference(t))
print(t.difference(s))
# intersection
print(s.intersection(t))
print(t.intersection(s))
# union
print(s.union(t))
print(t.union(s))
|
3b80bf8a4d1e9ead14896aeedb0dc2f7c67d8209
|
mario-alop/primeros_programas_python
|
/src/sumatorio.py
| 239 | 3.578125 | 4 |
sumatorio = 0
i = 1
while i <= 1000:
sumatorio += 1
print(sumatorio)
i += 1
print('Hecho')
sumatorio1 = 0
contador = 0
while contador < 1000:
contador += 1
sumatorio1 += contador
print(sumatorio1)
print(sumatorio1)
|
b682521c0358dd22beddaaed8fe60a975ed77284
|
n73274246/280201001
|
/lab10/example3.py
| 237 | 3.8125 | 4 |
def sum_of_nested(x):
if not isinstance(x,list):
return x
else:
sum_result = 0
for item in x:
sum_result += sum_of_nested(item)
return sum_result
a_list = [3,12,76,[4,56,43],[2,8],81,75]
print(sum_of_nested(a_list))
|
9e6f3b431f657b5ccc47ef940603f1235bac5686
|
analylx/learn
|
/temp2/re_way.py
| 350 | 3.609375 | 4 |
# coding=utf-8
import re
r1= re.compile(r'way')
with open('newfile.txt','r') as f:
for a in f.readlines():
s = re.search(r1,a)
#如果加了re.M|re.I就不能用预编译的pattern
#如果没有匹配到那么b的值就是none,此时的b是没有group属性的。先判断b再取值
if s:
print(a)
|
edf91b0c35168bca9ba9f32065fd14d7c835fc75
|
RajeshReddyG/PythonScripts
|
/SongDownloader.py
| 1,531 | 3.53125 | 4 |
'''
Download any song
Author : Sushaanth P
Sample Input -
5
Kygo It Ain't Me
Gryffin & Illenium ft. Daya - Feel Good
Taylor Swift- We Are Never Ever Getting Back Together
Alesso Years
Adele- Rolling in the Deep
'''
import urllib
import urllib.request as urllib2
from bs4 import BeautifulSoup
# import winsound
def save(link, SaveAs):
urllib2.urlretrieve(link, SaveAs)
def getLink(url, search, attr):
query = urllib.parse.quote(search)
response = urllib2.urlopen(url + query)
soup = BeautifulSoup(response.read(),"lxml")
for vid in soup.findAll(attrs={'class':attr})[0:1]:
return vid['href']
def download(SongName):
SongToSearch = SongName+' lyrics'
#get the video link from youtube
getURL = "https://www.youtube.com/results?search_query="
attr = 'yt-uix-tile-link'
div = getLink(getURL, SongToSearch, attr)
songLink = 'https://www.youtube.com' + div
#get the download link using the video link
getURL = "https://www.youtubeinmp3.com/download/?video="
attr = 'button'
div = getLink(getURL, songLink, attr)
downloadLink = 'https://www.youtubeinmp3.com'+div
print("Hi")
save(downloadLink, SongName+'.mp3')
n = int(input())
for i in range(n):
song = input()
print('>>> Downloading Song : \t'+song)
try:
download(song)
print('>>> '+(str(i+1))+' down '+str(n-i-1)+' to go\t\t'+song+' is Done\n')
except:
print('Exception : I guess you need to check the internet connection')
print('ALL SONGS ARE DOWNLOADED')
# winsound.Beep(2000,4000)
|
d9e709ab5825a0660f75cd1d8fffa9282f158e04
|
Aasthaengg/IBMdataset
|
/Python_codes/p02384/s044416712.py
| 1,963 | 3.546875 | 4 |
# 10_*
class Dice:
def __init__(self, label: list):
self.top, self.front, self.right, self.left, self.back, self.bottom = label
def roll(self, direction: str):
if direction == "N":
self.top, self.front, self.right, self.left, self.back, self.bottom = (
self.front,
self.bottom,
self.right,
self.left,
self.top,
self.back,
)
elif direction == "W":
self.top, self.front, self.right, self.left, self.back, self.bottom = (
self.right,
self.front,
self.bottom,
self.top,
self.back,
self.left,
)
elif direction == "S":
self.top, self.front, self.right, self.left, self.back, self.bottom = (
self.back,
self.top,
self.right,
self.left,
self.bottom,
self.front,
)
elif direction == "E":
self.top, self.front, self.right, self.left, self.back, self.bottom = (
self.left,
self.front,
self.top,
self.bottom,
self.back,
self.right,
)
def output_top(self):
print(self.top)
def get_top_front(self):
return f"{self.top} {self.front}"
def print_right(self):
print(self.right)
# 10_A
# (*label,) = map(int, input().split())
# dice = Dice(label)
# for i in input():
# dice.roll(i)
# dice.output_top()
# 10_B
(*label,) = map(int, input().split())
dice = Dice(label)
q = int(input())
for _ in range(q):
t, f = map(int, input().split())
for i in "EEEN" * 2 + "EEES" * 2 + "EEEN" * 2:
if f"{t} {f}" == dice.get_top_front():
dice.print_right()
break
dice.roll(i)
|
b6e8e7c18f414837f95453b703638926bac936c9
|
Tuzosdaniel12/learningPython
|
/functions_basics/cart.py
| 303 | 3.71875 | 4 |
#packing
def cal_total(*args):
total = sum(args)
print(args)
cal_total(25,25,20,100)
#unpacking
def unpacking():
return 1,2,3
var1, var2, var3 = unpacking()
print(var1)
print(var2)
print(var3)
first, last = input('Enter your full name: \n').split(" ")
print(first + " " + last)
|
6a5ffc2f7e603f0ae9309d3ad91cabc676fc42fc
|
gcoop-libre/ejemplos_cursosfp
|
/alumnos/facu_albarracin/adivinarnumeroCgcoop.py
| 943 | 3.875 | 4 |
#! -*- coding: utf8 -*-
# Problemas con if, while, booleanos.
import random
# Problema 3. Adivinar número al azar
print ("Bienvenido! Adivine un número en tres intentos!")
numerodef= random.randint (1, 8)
intentos= 3
intento= 0
# Sentencia break que rompe con la iteracion de un bucle!
while intentos > 0 and intentos <= 3:
intento= intento + 1
print ("\nIntento", intento, "de", intentos)
tunumero= int (input ("\nPor favor ingresá un número a continuación: "))
print ("\nIngresaste el número: ", tunumero)
if tunumero < numerodef:
print ("\nTu número es menor que el que tenés que adivinar ;)")
elif tunumero > numerodef:
print ("\nTu número es mayor al que tenés que adivinar ;)")
if tunumero == numerodef:
print ("\nAcierto y Ganaste :D")
break
if intento > 2:
print ("\nPerdiste. El número a adivinar era el %d " % numerodef)
break
|
cb34459def65311b65ea6cd00610b8086d7580dd
|
jtanwk/reddit-dailyprogrammer
|
/easy-challenges/45_e.py
| 1,639 | 3.953125 | 4 |
# Challenge 45, easy
# https://www.reddit.com/r/dailyprogrammer/comments/sv6lw/4272012_challenge_45_easy/
# Sample grid
# ----------------
# | |XXXX| |
# | |XXXX| |
# |XXXX| |XXXX|
# |XXXX| |XXXX|
# | |XXXX| |
# | |xxxx| |
# ----------------
# given dimensions, draws a row of x squares n times
# open_rows draws top line, draw_rows draws two sides and bottom
def draw_grid(nrows, ncols):
draw_line(int(ncols))
for i in range(int(nrows)):
draw_row(int(ncols), i) # i keeps track of even/odd rows
draw_line(int(ncols))
def draw_line(ncols):
grid_length = (int(ncols) * 5) + 1
print("-" * grid_length)
def draw_row(ncols, row_number):
if int(row_number) % 2 == 1: # row is odd-numbered
draw_odd_row(ncols)
draw_odd_row(ncols)
else: # row is even-numbered
draw_even_row(ncols)
draw_even_row(ncols)
def draw_odd_row(ncols):
for i in range(int(ncols)):
if i == 0:
print("|", " " * 4, "|", sep = "", end = "")
elif i % 2 == 1:
print("X" * 4, "|", sep = "", end = "")
else:
print(" " * 4, "|", sep = "", end = "")
print("\n", end = "")
def draw_even_row(ncols):
for i in range(int(ncols)):
if i == 0:
print("|", "X" * 4, "|", sep = "", end = "")
elif i % 2 == 0:
print("X" * 4, "|", sep = "", end = "")
else:
print(" " * 4, "|", sep = "", end = "")
print("\n", end = "")
nrows = input("How many rows? ")
ncols = input("How many columns? ")
draw_grid(nrows, ncols)
|
1df6711edf5488e80960f7afa97cf347653ebd19
|
MiKueen/Data-Structures-and-Algorithms
|
/Leetcode/0051-0100/0092-reverse-linked-list.py
| 1,076 | 3.984375 | 4 |
'''
Author : MiKueen
Level : Medium
Problem Statement : Reverse Linked List II
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if m == n:
return head
curr, prev = head, None
while m > 1:
prev = curr
curr = curr.next
m, n = m-1, n-1
tail, ptr = curr, prev
while n:
temp = curr.next
curr.next = prev
prev = curr
curr = temp
n -= 1
if ptr:
ptr.next = prev
else:
head = prev
tail.next = curr
return head
|
e8c1cb0ed750040a5e13250c1e9f6cecb9584a35
|
nicolageorge/idiomaticpython
|
/presentation/3 0 multiple exit points.py
| 1,415 | 3.921875 | 4 |
# Distinguishing multiple exit points in loops
# Donald Knuth came up with some structured equivalent
# need flag variable to say if something is found or not found
# the code could be returned/exited earlier when value is found, however this type of code is
# usually a portion of a bigger functionality thus can't be exited early
def find(seq, target):
found = False
for i, value in enumerate(seq):
if value == target:
found = True
break
if not found:
return -1
return i
# a better way, the else clause
# basically, the for loop says:
# if loop not finished, keep doing the body
# if loop not finished, keep doing the body
# if body finished and no break was encountered - else
# so se can have an else clause, it's associated with if
# else should be called nobreak
# if it sould have that name, everybody would use it properly
def find(seq, target):
for i, value in enumerate(seq):
if value == target:
break
else:
return -1
return i
# in the future,
# emphasis on why it should be called no break
# two ways to exit the loop:
# finish it normally
# break out
# search your house for the keys, two outcomes
# find the keys
# searched all the rooms and didn't find
# if finished the loop and didn't encounter a break, do else
# should be called no break and everybody would know what it does
# just like if lambda would be called makefunction
# nobody would ask what lambda does anymore
|
3ff5eedf311417f583ed5276b24cdd477ede95ad
|
naghashzade/my-python-journey
|
/day2-AgeLeftcalculator.py
| 423 | 4 | 4 |
age = input("Insert your age: ")
age_to_month = int(age) * 12
age_to_week = int(age) * 52
age_to_day = int(age) * 365
remain_year = 90 - int(age)
remain_month = 90*12 - int(age_to_month)
remain_week = 90*52 - int(age_to_week)
remain_day = 90*365 - int(age_to_day)
print(f"you will live {remain_year} years or {remain_month} months or {remain_week} weeks or {remain_day}")
print("if you are lucky enough to live 90 years")
|
780d5bdabee7f7fd3c91a7ff2929d5d3982a6d4e
|
krailis/hackerrank-solutions
|
/Algorithms/Warmup/time_conversion.py
| 383 | 3.65625 | 4 |
import sys
def timeConversion(s):
# Complete this function
s = s.split(':')
pm_am = s[-1][-2:]
s[-1] = s[-1][:2]
if (pm_am == 'AM'):
if (s[0] == '12'):
s[0] = '00'
elif (pm_am == 'PM'):
if (s[0] != '12'):
s[0] = str(int(s[0]) + 12)
return ':'.join(s)
s = input().strip()
result = timeConversion(s)
print(result)
|
ec6b4bc7b7245e37f6897694e70f623650d5d8fd
|
hafizadit/Muhammad-Hafiz-Aditya_I0320064_AbyanNaufal_Tugas6
|
/I0320064_Exercise6_8.py
| 126 | 3.78125 | 4 |
for i in range(2,17,3): # dari 2 sampai kurang dari 17 dengan inkremen 3
print("Kuadrat dari {} adalah {}".format(i,i**2))
|
cd4b5c8e599c1a72b87f416e973521ccd479f9ed
|
omarelhariry/Gotta-Catch-em-All
|
/PythonApplication2/PriorityW.py
| 598 | 3.671875 | 4 |
import queue;
class PriorityW(queue.PriorityQueue):
def __init__(self):
queue.PriorityQueue.__init__(self)
self.counter = 0
self.lower = 0
self.upper = 0
def put(self, item, priority):
queue.PriorityQueue.put(self, (priority, self.counter, item))
self.counter += 1
if priority > self.upper :
self.upper = priority;
if priority < self.lower :
self.lower = priority;
def get(self, *args, **kwargs):
_, _, item = queue.PriorityQueue.get(self, *args, **kwargs)
return item
|
0546fbd254448e88c3fd199fb7770e0b47959dc5
|
sikibuton/test_repo
|
/turtle_test.py
| 6,152 | 3.59375 | 4 |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: koki
#
# Created: 27/08/2013
# Copyright: (c) koki 2013
# Licence: <your licence>
#-------------------------------------------------------------------------------
from turtle import TK,RawTurtle,TurtleScreen,Vec2D
import Tkinter
import time
import math
import random
class Player(RawTurtle):
def hiding(self):
print("calle hidding!")
self.ht()
self.up()
self.clear()
self.k_to_high = 0
self.k_to_middle = 0
self.k_to_low = 0
self.k_to_producer = 0
self.v -= self.v
self.setposition(2000,2000)
def get_K(self,player):
if player.strengthpower == 3:
return self.k_to_high
elif player.strengthpower == 2:
return self.k_to_middle
elif player.strengthpower == 1:
return self.k_to_low
else:
return self.k_to_producer
def __init__(self,turtleScreen,player_type,posVector,k_to_high,k_to_middle,k_to_low,k_to_producer,m,R):
RawTurtle.__init__(self,turtleScreen) #タートル生成
self.up() #軌跡は書かない
self.setpos(posVector) #初期位置
self.resizemode("user")
self.shape("circle") #プレイヤーの形
self.shapesize(0.5)
if player_type == "high_level_predator":
self.color("red") #高域捕食者
self.strengthpower = 3
self.shape("triangle")
elif player_type == "middle_level_predator":
self.color("yellow") #中域捕食者
self.strengthpower = 2
self.shape("square")
elif player_type == "low_level_predator":
self.color("blue") #低域捕食者
self.strengthpower = 1
self.shape("turtle")
else :
self.color("dark green") #生産者
self.strengthpower = 0
self.shape("circle")
#このクラスで新しく追加した変数
self.acc = Vec2D(0,0) #初期加速度ゼロ
self.v= Vec2D(0,0) #初期速度ゼロ
self.m = m #質量
self.k_to_high = k_to_high #高域捕食者に対するK
self.k_to_middle = k_to_middle #中域捕食者に対するK
self.k_to_low = k_to_low #低域捕食者に対するK
self.k_to_producer = k_to_producer #生産者に対するK
self.R = R #視野半径
self.energy = 10
def close(root):
root.destroy()
root.quit()
def main():
player_N = 15
root = TK.Tk()
canvas = TK.Canvas(root, width=1200, height=700, bg="#ddffff")
canvas.pack()
turtleScreen = TurtleScreen(canvas)
turtleScreen.bgcolor("gray")
turtleScreen.tracer(0,0)
pl = []
for i in range(player_N): #プレイヤーの生成
random.seed()
window_h = turtleScreen.window_height()/2
window_w = turtleScreen.window_width()/2
x = random.uniform(-window_w,window_w)
y = random.uniform(-window_h,window_h)
m = random.uniform(1,5)
R = 600
pl_type = random.choice(["high_level_predator","middle_level_predator","low_level_predator","producer"])
k_high = random.uniform(0,150)
k_middle = random.uniform(0,150)
k_low = random.uniform(0,150)
k_producer = random.uniform(0,150)
if pl_type == "high_level_predator":
#k_high = 0
pass
elif pl_type == "middle_level_predator":
k_middle = 0
k_high *= -1
elif pl_type == "low_level_predator":
#k_low = 0
k_high *= -1
k_middle *= -1
elif pl_type == "producer":
#k_producer = 0
k_high *= -1
k_middle *= -1
k_low *= -1
pl.append(Player(turtleScreen,pl_type,(x,y),k_high,k_middle,k_low,k_producer,m,R))
turtleScreen.update()
#time.sleep(1)
while(1):
for me in turtleScreen.turtles():
me.acc -= me.acc
for you in turtleScreen.turtles():
r = you.pos()-me.pos()
r_d = abs(r)
if me != you and r_d<me.R and you.isvisible():
me.acc += (me.get_K(you)/(me.m*pow(r_d,3)))*r
if me.strengthpower == you.strengthpower:
me.acc = 0.3*me.acc+0.7*((r_d/me.R)*me.acc + ((me.R-r_d)/me.R)*you.acc)
if r_d<10 :
if me.strengthpower > you.strengthpower:
you.hiding()
me.energy += you.energy
me.v -= 1.1*me.v
elif me.strengthpower == you.strengthpower:
me.v = -0.1*r
me.v += me.acc
if abs(me.v)>10:
me.v = me.v*(10/abs(me.v))
me.setpos(me.pos()+me.v)
if me.xcor()<-600 or me.xcor()>600 or me.ycor()<-350 or me.ycor()>350:
me.v = (-0.5/abs(me.pos()))*me.pos()
me.acc -= me.acc
#print(me.energy)
turtleScreen.update()
time.sleep(0.01)
if __name__ == '__main__':
main()
|
99b1ccb16d97e508a03024f40758854082f085aa
|
yashwanth033/competitive_Programming
|
/competitive programming/Week1/Day4/FindInOrderedSet.py
| 452 | 3.9375 | 4 |
def binarySearch(arr, l, h, x):
while l <= h:
mid = l + (h - l) // 2;
if arr[mid] == x:
return True
elif arr[mid] < x:
l = mid + 1
else:
h = mid - 1
return False
def contains(ordered_list, number):
result = binarySearch(ordered_list, 0, (len(ordered_list) - 1), number)
return result
if __name__ == '__main__':
print(contains([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 8))
|
b5c62a8ea0c97b65c7d627db55130e131de55fb1
|
ASHWINIBAMBALE/snake_game
|
/snake.py
| 1,326 | 3.859375 | 4 |
from turtle import Turtle, position
POSITIONS=[(0,0),(-20,0),(-40,0)]
MOVE_FORWARD=20
UP=90
DOWN=270
RIGHT=0
LEFT=180
class Snake:
def __init__(self) :
self.snake_body=[]
self.create_snake()
self.head=self.snake_body[0]
def create_snake(self):
for position in POSITIONS:
self.add_parts(position)
def add_parts(self,position):
tim=Turtle("square")
tim.color("white")
tim.penup()
tim.goto(position)
self.snake_body.append(tim)
def extend(self):
self.add_parts(self.snake_body[-1].position())
def move(self):
for seg_num in range(len(self.snake_body)-1,0,-1 ):
new_x=self.snake_body[seg_num-1].xcor()
new_y=self.snake_body[seg_num-1].ycor()
self.snake_body[seg_num].goto(new_x,new_y)
self.head.forward(MOVE_FORWARD)
def up(self):
if self.head.heading()!=DOWN:
self.head.setheading(UP)
def down(self):
if self.head.heading()!=UP:
self.head.setheading(DOWN)
def left(self):
if self.head.heading()!=RIGHT:
self.head.setheading(LEFT)
def right(self):
if self.head.heading()!=LEFT:
self.head.setheading(RIGHT)
|
6e21ea6274ab202bf9b139407b4b119346c1603f
|
Mi-clouds/py_practice
|
/write_create_files.py
| 758 | 4.625 | 5 |
# write to an existing file
# to write an existing file, you must add a paramenter to the open() functions:
# "a" - append - will append to the end of the file
# "w" - write - will overwrite any existing comments
# open the file and append the content to the file:
f = open("../files/demo_text2.txt", "a")
f.write("Now the file has even more and more and more content!")
f.close()
#open and read the file after the appending:
f = open("../files/demo_text2.txt", "r")
print(f.read())
# open the file "demofile3.txt" and overwrite the content
f = open("../files/demo_file3.txt", "w")
f.write("Whoops! I have deleted the content!")
f.close()
# open and read the file after appending:
f = open("../files/demo_file3.txt", "r")
print(f.read())
f.close()
|
1cac639aea4f5146b3d9b85f01c1a90e55ab4a5f
|
vinceajcs/all-things-python
|
/algorithms/graph/dfs/topological_sort.py
| 557 | 3.75 | 4 |
"""Given a DAG, return a topological ordering of its nodes."""
def topological_sort(graph):
visited = collections.defaultdict(bool)
stack = []
for node in graph.keys():
if not visited[node]:
dfs(graph, node, visited, stack)
return stack # stack should contain the topological order of the nodes in the DAG
def dfs(graph, node, visited, stack):
visited[node] = True
for neighbor in graph[node]:
if not visited[neighbor]:
dfs(graph, neighbor, visited, stack)
stack.insert(0, node)
|
3102d414a6ffbd3f4ee6b3a03be5334757570e29
|
feizei2008/nowcoder-huawei
|
/044.py
| 1,185 | 3.890625 | 4 |
# 检查这个数能不能填
def check(sudoku, i, j):
cur = sudoku[i][j]
for k in range(9):
if k != i and sudoku[k][j] == cur:
return False
if k != j and sudoku[i][k] == cur:
return False
if (k//3 != i%3 or k%3 != j%3) and sudoku[i//3*3+k//3][j//3*3+k%3] == cur:
return False
return True
# 回溯法,对第一个空位尝试填空
# 都不对说明前面有错,改回0
def solve(sudoku):
flag = 0
for i in range(9):
for j in range(9):
if sudoku[i][j] == 0:
flag = 1
break
if flag == 1:
break
if flag == 0:
return True
for k in range(1, 10):
sudoku[i][j] = k
if not check(sudoku, i, j):
continue
flag = solve(sudoku)
if flag == True:
return True
sudoku[i][j] = 0
return False
while True:
try:
sudoku = []
for i in range(9):
line = list(map(int, input().split()))
sudoku.append(line)
solve(sudoku)
for line in sudoku:
print(' '.join(map(str, line)))
except:
break
|
ace47dda6ea0352fde438d913e357c97f196fad6
|
asimoglufatih/gaih-students-repo-example
|
/Homeworks/HW3.py
| 654 | 4.09375 | 4 |
student = dict()
listOfGrade = []
def getGrade():
for index in range(5):
student[index] = {}
midterm = int(input("Enter midterm grade: "))
project = int(input("Enter project grade: "))
final = int(input("Enter final grade: "))
listOfGrade.insert(index, calculatePassingGrade(midterm,project,final))
student[index]["midterm"] = midterm
student[index]["project"] = project
student[index]["final"] = final
listOfGrade.sort(reverse = True)
def calculatePassingGrade(midterm, project, final):
return midterm * (0.3) + project * (0.3) + final * (0.4)
getGrade()
print(listOfGrade)
|
d2cb61cb6f92243fa67a658a4af87addbd28c814
|
amiraHag/python-basic-course2
|
/database/database4.py
| 1,331 | 4.1875 | 4 |
# --------------------------------------------------------
# -- Databases => SQLite => Retrieve Data From Database --
# --------------------------------------------------------
# - fetchone => returns a single record or None if no more rows are available.
# - fetchall => fetches all the rows of a query result. It returns all the rows
# as a list of tuples. An empty list is returned if there is no record to fetch.
# - fetchmany(size) =>
# ------------------------------------------------------
# Import SQLite Module
import sqlite3
# Create Database And Connect
db = sqlite3.connect("app.db")
# Setting Up The Cursor
cr = db.cursor()
# Create The Tables and Fields
# cr.execute("create table if not exists users (user_id integer, name text)")
# cr.execute(
# "create table if not exists skills (name text, progress integer, user_id integer)")
#Inserting Data
cr.execute("insert into users(user_id, name) values(1, 'Amira')")
cr.execute("insert into users(user_id, name) values(2, 'Ahmed')")
cr.execute("insert into users(user_id, name) values(3, 'Sara')")
# Fetch Data
cr.execute("select * from users")
print(cr.fetchone())
print(cr.fetchone())
print(cr.fetchone())
print(cr.fetchone())
# print(cr.fetchall())
# print(cr.fetchmany(2))
# Save (Commit) Changes
db.commit()
# Close Database
db.close()
|
901f42f0930c5a74c5671b6fdedf2e74591e0fd1
|
VisualAcademy/PythonNote
|
/PythonNote/32_Algorithms/12_GroupAlgorithm/GroupAlgorithm.py
| 1,765 | 3.625 | 4 |
#[?] 컬렉션 형태의 데이터를 특정 키 값으로 그룹화
# 그룹 알고리즘(Group Algorithm): 특정 키 값에 해당하는 그룹화된 합계 리스트 만들기
# 테스트용 레코드 클래스
class Record():
def __init__(self, name, quantity):
self.name = name # 상품명
self.quantity = quantity # 수량
def main():
#[1] Input
records = [ Record("RADIO", 3), Record("TV", 1), Record("RADIO", 2), Record("DVD", 4) ] # 입력 데이터
groups = [] # 출력 데이터
N = len(records) # 의사코드
#[2] Process: GROUP 알고리즘(SORT -> SUM -> GROUP)
#[A] 그룹 정렬: SORT - Selection Sort
for i in range(N - 1):
for j in range(i + 1, N):
if (records[i].name > records[j].name):
temp = records[i]
records[i] = records[j]
records[j] = temp # SWAP
#[B] 그룹 소계: GROUP
subtotal = 0 # 소계
for i in range(N):
subtotal = subtotal + records[i].quantity # 같은 상품명의 수량을 누적(SUM)
#[!] 다음 레코드가 없거나, 현재 레코드와 다음 레코드가 다르면 저장
if ((i + 1) == N or records[i].name != records[i + 1].name):
# (한 그룹의 키(Key) 지정, 소계)
groups.append(Record(records[i].name, subtotal)) # 하나의 그룹 저장
subtotal = 0 # 하나의 그룹이 완료되면 소계 초기화
#[3] Output
print("[1] 정렬된 원본 데이터:")
for r in records:
print(f"{r.name.rjust(6)} - {r.quantity}")
print("[2] 이름으로 그룹화된 데이터:")
for g in groups:
print(f"{g.name.rjust(6)} - {g.quantity}")
if __name__ == "__main__":
main()
|
896f385641c959390dc44fefcb6907709468bdea
|
david12d/projects
|
/Numbers/Fibonacci.py
| 596 | 4.40625 | 4 |
""" **Fibonacci Sequence** -
Enter a number and have the program generate the Fibonacci sequence to that number or to the Nth number.
"""
import sys
print("This program is a Fibonacci Sequence Generator.\n")
while True:
try:
x = int(input("Enter a number: \n"))
if x < 0:
continue
except ValueError:
print("Sorry, enter a whole number please")
continue
else:
break
n = 1
m = 1
result = 1
print("1, ")
for a in range(0, x):
print(result,end = ", ")
n = m
m = result
result = n + m
|
080d28c6f1467abf777e76ac49a786b0e0055333
|
chrismvelez97/GuideToPython
|
/techniques/functions/built_in_functions/sum.py
| 478 | 4.15625 | 4 |
# How to use the sum() function
'''
The sum() function adds all the numbers up from a list of numbers.
Note that for min, max, and sum, you can only do them on lists full of numbers.
also it is not a method attached to the number datatype which is why it is in
the techniques folder instead of the num_methods folder.
'''
numbers = list(range(11))
print (numbers)
# results: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print (sum(numbers))
# results: 55
|
9aee4347b18e20e71991dd52682697d23724127f
|
barvaliyavishal/DataStructure
|
/Leetcode Problems/48. Rotate Image .py
| 520 | 3.5625 | 4 |
def rotate(matrix):
n = len(matrix[0])
for i in range(n // 2 + n % 2):
for j in range(n // 2):
tmp = [0] * 4
row, col = i, j
for k in range(4):
tmp[k] = matrix[row][col]
row, col = col, n - 1 - row
for k in range(4):
matrix[row][col] = tmp[(k - 1) % 4]
row, col = col, n - 1 - row
arr = [[1,2,3],[4,5,6],[7,8,9]]
rotate(arr)
for i in arr:
for j in i:
print(j,end=" ")
print()
|
04ff07eadbbb9ea1d581dd795c11457f3d5fc5e2
|
falecomlara/CursoEmVideo
|
/ex079.py
| 1,194 | 4.21875 | 4 |
# Digite varios valores numéricos e cadastre uma lista
# caso o numero já existe, ele não irá cadastrar
# mostrar todos os numeros em ordem crescente
# Solução do curso:
numeros = []
while True:
n = int(input('Digite um valor: '))
if n not in numeros:
numeros.append(n)
print(f'Valor adicionado com sucesso')
else:
print('Valor duplicado. Não vou adicionar...')
r = str(input('Quer continuar [S/N] '))
if r in 'Nn':
break
numeros.sort()
print(f'Valores adicionados em ordem crescente foram: {numeros}')
print('=-='*30)
""" Minha resolução:
valores = []
continuar = 'S'
num = int(input('Digite um valor: '))
print('Valor adicionado com sucesso..')
while continuar == 'S':
valores.append(num)
continuar = str(input('Quer continuar? [S/N] ')).upper().rstrip()
if continuar == 'S':
num = int(input('Digite um valor: '))
for c in range(len(valores)):
if valores[c-1] == num:
print('Valor duplicado. Não vou adicionar...')
valores.remove(num)
print('Valor adicionado com sucesso..')
valores.sort()
print(f'Você digitou os valores {valores}')
"""
|
959e4d74244a354022e8939345f03185dab566c2
|
SanJin1213/Python
|
/multiprocessing/code/pool_multiprocessing.py
| 740 | 3.53125 | 4 |
import multiprocessing as mp
def job(x):
return x * x
def multicore():
# 不加参数,就是默认使用所有的核
# 要设置用几个核 用processes=
pool = mp.Pool()
res = pool.map(job, range(10))
res1 = pool.apply_async(job, (2,))
multi_res = [pool.apply_async(job, (i,)) for i in range(10)]
# res2 = pool.apply_async(job, range(10))
print(res)
print(res1)
# 输出结果 <multiprocessing.pool.ApplyResult object at 0x000002702D525F28>
print(res1.get())
# 只能获取一个值
# print(res2.get())
# 输出也要进行迭代
print([res.get() for res in multi_res])
if __name__ == "__main__":
multicore()
# 输出结果 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
|
602de06bff0a78969c81b114e42acbc81ab22328
|
Lisanity2019/Learning
|
/day6/封装.py
| 1,409 | 3.859375 | 4 |
# -*- coding: utf-8 -*-
# ----> 封装:属性和方法都藏起来,不被外部访问 变量名或方法名左边添加双下划线
# 所有的私有属性或方法,不能被类外部访问
# class Person:
# def __init__(self,name,passwold):
# self.name=name
# self.__passwold=passwold #----> 私有属性
#
# def __get_pwd(self): #----> 私有方法
# print(self.__dict__)
# return self.__passwold #----> 在类的内部使用私有属性,会自动带上 _类名 进行转换 _Person__passwold
#
# alex=Person('alex','ssss')
# print(alex._Person__passwold) #----> 可以特殊调用,一般不这么做
# print(alex._Person__get_pwd())
# property 方法伪装成属性
# ----> 内置装饰器函数 只在面向对象中使用
# class Person:
# def __init__(self,name):
# self.__name=name
# @property
# def name(self):
# return self.__name+'同学'
# @name.setter #----> setter getter deleter--del关联
# def name(self,newname):
# self.__name=newname
# xiaowang=Person('小王')
# print(xiaowang.name)
class Goods: # ----> 实现打折活动
discount = 0.5
def __init__(self, name, price):
self.__name = name
self.__price = price
@property
def price(self):
return self.__price * Goods.discount
apple = Goods('苹果', 5)
print(apple.price)
|
ecbe968a88bf2811a54102d014cb6b4da11973f6
|
nucfive/Python
|
/ex5_dictionary.py
| 369 | 3.875 | 4 |
#dictionary 字典类型 {}
my_phone = {"iphone" : 1000, "Sumsang" : 900}
#取出键中的值 用[]
iphone_price = my_phone["iphone"]
print(iphone_price)
#更改键值
my_phone["iphone"] = 4000
print(my_phone["iphone"])
print("Iphone price :" + str(my_phone["iphone"]))
my_dic = {1 : "wrf1", 2 : "wrf2", 3 : "wrf3"}
str1 = my_dic[1]
my_phone.clear()
print(my_phone)
|
ef7f416952bce64499197ba24c63ab3690f186f1
|
SethDeVries/My-Project-Euler
|
/Python/Problem102.py
| 863 | 3.640625 | 4 |
#credit to jasonbhill for most of this code, placing this
#here because my code did not work for reasons unbeknownst to me
def num_divisors(n):
# if n is divisible by 2
if (n % 2 == 0):
n = n/2
divisors = 1
count = 0
while (n % 2 == 0):
count += 1
n = n/2
divisors = divisors * (count + 1)
#calculating any odd divisors
p = 3
while (n != 1):
count = 0
while n % p == 0:
count += 1
n = n/p
divisors = divisors * (count + 1)
p += 2
return divisors
def find_triangular_index(factor_limit):
n = 1
lnum, rnum = num_divisors(n), num_divisors(n+1)
while lnum * rnum < 500:
n += 1
lnum, rnum = rnum, num_divisors(n+1)
return n
index = find_triangular_index(500)
triangle = (index * (index + 1)) / 2
print (triangle)
|
dcc2cdb3f7159f80d6a48f0923696b8439a2537e
|
dhruvarora93/Algorithm-Questions
|
/Array Problems/prod_of_numbers_except_index.py
| 432 | 4.09375 | 4 |
def product(ar):
product_of_numbers_before_index = []
product_of_numbers_before_index.append(1)
product=1
for i in range(1,len(ar)):
product *= ar[i-1]
product_of_numbers_before_index.append(product)
product=1
for i in range(len(ar)-1,-1,-1):
product_of_numbers_before_index[i] *= product
product *= ar[i]
print(product_of_numbers_before_index)
product([2, 7, 3, 4])
|
b848aec45bf58fa0c8a05c7a3cdfbc254f50f309
|
MaX-Lo/ProjectEuler
|
/010_summation_of_primes.py
| 842 | 3.890625 | 4 |
"""
Task:
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
"""
import time
def main():
start_time = time.time()
limit = 2000000
# list containing for every number whether it has been marked already
numbers = {}
for x in range(3, limit, 2):
numbers[x] = False
primes = [2, 3]
p = 3
while p < limit:
for i in range(p, limit, p):
numbers[i] = True
for i in range(p, limit, 2):
if not numbers[i]:
p = i
numbers[i] = True
primes.append(i)
break
else:
p += 1
#print(primes)
print("sum of found primes:", sum(primes))
print("time:", time.time() - start_time)
if __name__ == '__main__':
main()
|
8c35a32d6773be93f021a5f10a7e2cd536a8c3b8
|
NguyenHung2602/baikt
|
/bai4.py
| 418 | 3.90625 | 4 |
def Fibonacci():
n = int(input())
if n<2:
print("Nhập lại n lớn hơn 2")
n = int(input())
lst = []
for i in range(n):
if i == 0:
lst.append(i)
elif i == 1:
lst.append(i)
else:
lst.append(lst[i-1]+lst[i-2])
return lst
def main():
print(Fibonacci())
if __name__=="__main__":
main()
|
d9b07428e020b201e237a48cab5da0a2e0d7d5dc
|
TheDurableDane/coding_pirates
|
/diceRoll.py
| 832 | 3.875 | 4 |
"""
Dice roll -- Showing the law of large numbers: https://en.wikipedia.org/wiki/Law_of_large_numbers
author: Thomas Lolk Schmidt
email: [email protected]
date: 29jan2017
"""
import numpy as np
import matplotlib.pylab as plt
# Get some random numbers
np.random.seed(1)
N = 10000
randomNumbers = np.random.rand(N)
diceRoll = np.ceil(randomNumbers*6)
# Plot histogram to show uniformity
plt.hist(diceRoll, bins=np.arange(1,8)-0.5)
plt.xlabel("Number of eyes on dice")
plt.ylabel("Number of rolls")
# Find the average of the rolls after each new roll
meanDiceRoll = np.zeros(N)
meanDiceRoll[0] = diceRoll[0]
for i in range(1,N):
meanDiceRoll[i] = np.mean(diceRoll[:i+1])
# Plot average vs numbers of rolls
plt.figure()
plt.plot(meanDiceRoll)
plt.axhline(y=3.5)
plt.xlabel("Number of dice rolls")
plt.ylabel("Average of dice rolls")
plt.show()
|
49a232a4893712d640d0ee136d8520c71de22c5c
|
fwr666/ai1810
|
/aid/day03/juzhon.py
| 239 | 3.515625 | 4 |
s1 = 'hello!'
s2 = """i'm studing python!"""
s3 = 'i like python! '
s4 = '+--------------------------+'
n=len(s4)-2
s = print(s4)
s = print('|'+s1.center(n)+'|')
s = print('|'+s2.center(n)+'|')
s = print('|'+s3.center(n)+'|')
s = print(s4)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.