blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
1451fa9c04e5ce8636d023001c663fb6a988b0bf
wajishagul/wajiba
/Task4.py
884
4.375
4
print("*****Task 4- Variables and Datatype*****") print("Excercise") print("1. Create three variables (a,b,c) to same value of any integer & do the following") a=b=c=100 print("i.Divide a by 10") print(a,"/",10,"=",a/10) print("ii.Multiply b by 50") print(b,"*",50,"=",b*50) print("iii.Add c by 60") print(c,"+",50,"=",b+50) print("2.Create a String variable of 5 characters and replace the 3rd character with G") str="ABCDE" print("Length of the string is:",len(str)) s1="C" s2="G" print("new string after replacement:",str.replace(s1,s2)) print("3.Create two values (a,b) of int,float data type & convert the vise versa") a,b=200,55.5 print("a=",a,"b=",b) a=float(a) b=int(b) print("value of a and b after type conversion:") print("a=",a,"b=",b) print("data type of a after conversion:",type(a)) print("data type of b after conversion:",type(b)) print("-----Task 4 Completed-----")
ac8beccafc68748818a0de9915cfc0cec1c81cb7
Reynbra/Portfolio
/python/TurtleFrogger/scoreboard.py
1,993
3.921875
4
from turtle import Turtle FONT = ("Courier", 20, "normal") SCORE_COLOR = "white" ROAD_LINE_COLOR = "white" SCORE_ALIGNMENT = "left" LIVES_ALIGNMENT = "right" GAME_OVER_ALIGNMENT = "center" LEVEL_TEXT = "Level" LIVES_TEXT = "Lives" GAME_OVER = "GAME OVER" class Scoreboard(Turtle): def __init__(self): super().__init__() self.penup() self.color(SCORE_COLOR) self.level = 0 self.lives = 3 self.update_level() # self.car_chance = CAR_SPAWN_RATE_CHANCE def draw_road_lines(self): self.hideturtle() self.penup() self.pencolor(ROAD_LINE_COLOR) self.goto(280, -230) self.setheading(180) for _ in range(600): self.pendown() self.forward(20) self.penup() self.forward(20) self.goto(280, 230) self.setheading(180) for _ in range(600): self.pendown() self.forward(20) self.penup() self.forward(20) # TODO Make the goto function iterate by a total of 40 pixels # TODO Make the loop use the new increased value for position # TODO Possibly optimize the drawing function by repeating 10 or so times def update_level(self): self.draw_road_lines() self.goto(-290, 260) self.write(f"{LEVEL_TEXT}: {self.level}", align=SCORE_ALIGNMENT, font=FONT) self.goto(290, 260) self.write(f"{LIVES_TEXT}: {self.lives}", align=LIVES_ALIGNMENT, font=FONT) def increase_level(self): self.level += 1 # self.car_chance -= 1 self.clear() self.update_level() def decrease_lives(self): self.lives -= 1 self.clear() self.update_level() def game_over(self): if self.lives == 0: self.goto(0, 0) self.write(arg=f"GAME OVER", align=GAME_OVER_ALIGNMENT, font=FONT) return False else: return True
fc7353b01d945e9bbbaebd7aa6a6dd8f59ed8d2a
LucindaDavies/codeclan_caraoke
/tests/room_test.py
1,236
3.671875
4
import unittest from classes.room import Room from classes.guest import Guest from classes.song import Song class TestRoom(unittest.TestCase): def setUp(self): self.song1 = Song("Help", "The Beatles") self.song2 = Song("Saturday Night", "Sam Cooke") self.songs = [self.song1, self.song2] self.guest1 = Guest("Hannah") self.guest2 = Guest("Louise") self.guest3 = Guest("Harry") self.guests = [self.guest1, self.guest2, self.guest3] self.room = Room("Motown", 3) def test_room_has_name(self): self.assertEqual("Motown", self.room.get_name()) def test_can_add_song(self): song = self.song2 self.room.add_song_to_room(song) self.assertEqual(1, self.room.number_of_songs()) def test_can_check_in_guest(self): self.room.check_in_guest(self.guest1) self.assertEqual(1, self.room.number_of_guests()) def test_room_has_capacity(self): self.assertEqual(3, self.room.get_capacity()) def test_can_check_guest_out(self): self.room.check_in_guest(self.guest3) self.room.check_out_guest(self.guest3) self.assertEqual(0, self.room.number_of_guests())
302f242cb6fc42a6350e476cc19a5460bd56361f
50Leha/automation_tests
/rospartner/utils.py
390
4.0625
4
""" Module with utility functions """ from random import choice import string def generate_email_name(): """ utility to generate random name and email :return: tuple(email, name) """ name = [choice(string.ascii_letters) for _ in range(5)] email_tail = '@foo.bar' # join to string name = ''.join(name) email = name + email_tail return email, name
c6f8241e148b4e503af3f3709885ee964e931838
x-jeff/Tensorflow_Code_Demo
/Demo3/3.1.MNIST_classification_simple_version.py
1,542
3.53125
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data #载入数据集 #该语句会自动创建名为MNIST_data的文件夹,并下载MNIST数据集 #如果已存在,则直接读取数据集 mnist=input_data.read_data_sets("MNIST_data",one_hot=True) #mini-batch size batch_size=100 #训练集的数目 #print(mnist.train.num_examples)#55000 #一个epoch内包含的mini-batch个数 n_batch=mnist.train.num_examples // batch_size #定义网络的输入和输出 x=tf.placeholder(tf.float32,[None,784])#28*28*1=784 y=tf.placeholder(tf.float32,[None,10])#0,1,2,3,4,5,6,7,8,9 #创建一个简单的神经网络(无隐藏层) W=tf.Variable(tf.zeros([784,10])) b=tf.Variable(tf.zeros([10])) prediction=tf.nn.softmax(tf.matmul(x,W)+b) #均方误差 loss=tf.reduce_mean(tf.square(y-prediction)) #梯度下降法 train_step=tf.train.GradientDescentOptimizer(0.2).minimize(loss) #初始化变量 init=tf.global_variables_initializer() #统计预测结果 correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#返回一个布尔型的列表 accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) with tf.Session() as sess: sess.run(init) for epoch in range(21): for batch in range(n_batch): batch_xs,batch_ys=mnist.train.next_batch(batch_size) sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys}) acc=sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}) print("Iter "+str(epoch)+", Testing Accuracy "+str(acc))
340e077ad8099cd7baca8c3b057c004ea81f827e
vspatil/Python3-HandsOn
/Chapter_4_IF_stmts/exercise_5.1.py
863
3.796875
4
car ='golf' car == 'olf' ##print(car) """ car = 'Golf' print("Is car == 'Golf'? , I predict True.") print(car == 'Golf') print("\nIs car == 'Audi'? , I predict False.") print(car == 'Audi') deserts = 'Kheer' print("Is desrt == 'Kheer'? , I predict True.") print(deserts == 'Kheer') print("Is desert == 'Ice Cream'? , I predict False.") print (deserts == 'Ice Cream') name = 'vani' print(name == 'vani') print(name== 'Trisha') print(name == 'Vani') print(name.title()== 'Vani') print(name.upper() == 'vani') print(name.lower() == 'vani') print(name != 'vani') age = 18 print( age > 21) print(age < 21) print( age == 21) print (age > 10 and age < 15 ) print(age > 10 and age < 20 ) print (age> 10 or age <15) print(age != 18) print(age) """ name = ['Santosh','Vani','Trisha','Aditi'] print('Vani' in name) print('Usha' in name) print('Vani' not in name)
209d0d207a72810d04216d15b8bafdbea0c50c36
vspatil/Python3-HandsOn
/Chapter_8_Classes_Methods/Exercise_9.13.py
675
3.890625
4
#9.13 """ from collections import OrderedDict favourite_languages = OrderedDict() favourite_languages['Brad'] = 'SQL' favourite_languages['Adam'] = 'ERP' favourite_languages['Mike'] = 'Python' favourite_languages['Chris'] = 'JAVA' for name , language in favourite_languages.items(): print( name.title() + " 's favourite language is : " + language.title()) """ #9.14 #from random import randint #x = randint(1,6) #print(x) from random import randint class dice(): def __init__(self,sides): self.sides = sides def roll_dice(self): x= randint(1,self.sides) print( "Random number now we got is : " + str(x)) d= dice(20) d.roll_dice()
e4849cacfa472b48f1fdb666339c05655b491ffa
vspatil/Python3-HandsOn
/Chapter_6_UserInputs_whileLoops/Exercise_7.5.py
1,580
4.15625
4
"""prompt = "Enter a series of toppings : " message = "" while message != 'quit': message = input(prompt) if message == 'quit': break else: print("We will add " + message + " to the pizza!")""" """ age='' while age != 'quit': age = input("Enter your age : ") if age == 'quit': break elif age < 3: print("The ticket is free!") elif age > 3 and age < 12: print("The ticket costs $10!") else: print("The ticket costs $15!") """ #using condition in the while stmt """age='' while age != 'quit': age = input("Enter your age : ") if age == 'quit': break elif age <= 3: print("The ticket is free!") elif age > 3 and age <= 12: print("The ticket costs $10!") elif age > 12 : print("The ticket costs $15!")""" #Using active variable to control the loop """active = True while active: age = input("Enter your age : ") if age == 'quit': active = False elif age <= 3: print("The ticket is free!") elif age > 3 and age <= 12: print("The ticket costs $10!") else: print("The ticket costs $15!")""" #using break stmt to exit the loop """ age='' while age != 'quit': age = input("Enter your age : ") if age == 'quit': break elif age <= 3: print("The ticket is free!") elif age > 3 and age <= 12: print("The ticket costs $10!") else: print("The ticket costs $15!")""" # loop that never ends or infinte loop x = 1 while x <= 5: print(x) # x=x+1
9badd15b93c998b8ae1eae271cbb7062d96aa860
duxinn/data_structures_algorithms
/算法和数据结构的应用/顺序表相关/search.py
1,168
3.953125
4
# 搜索是在一个项目集合中找到一个特定项目的算法过程。搜索通常的答案是真的或假的,因为该项目是否存在。 # 当然可以按照具体需求,返回值可以设为要查找的元素的下标,不存在返回-1 # 搜索的几种常见方法:顺序查找、二分法查找、二叉树查找、哈希查找 # 本文只是基于顺序表实现的查找算法,二叉树,哈希以后在介绍 def find(L, item): '''顺序查找,对排序的顺序表没有要求 最优:O(1) 最差:O(n) ''' for i in L: if i == item: return True return False def binary_search(L, item): '''二分查找,也叫折半查找, 对排序的顺序表要求是:有序列表,不可以是链表(链表不能定位访问) 最优:O(1) 最差:O(logn) ''' n = len(L) if n == 0: return False mid = n // 2 if L[mid] == item: return True elif L[mid] < item: return binary_search(L[mid + 1:], item) else: return binary_search(L[:mid - 1], item) if __name__ == '__main__': l = [x for x in range(10)] print(l) # 顺序查找测试 print(find(l, 88)) # 二分查找测试 print(binary_search(l, 9))
fd54b8243950b9f4fa2a96387dae8962fc2aa9d1
duxinn/data_structures_algorithms
/数据结构/栈和队列/queue.py
597
4
4
class Queue(object): '''队列的实现,通过list存储数据''' def __init__(self): self.__queue = [] def enqueue(self, item): '''入队操作''' self.__queue.append(item) def dequeue(self): '''出队操作''' return self.__queue.pop(0) def is_empty(self): '''判断是否为空''' return not self.__queue def size(self): '''返回队列的长度''' return len(self.__queue) if __name__ == '__main__': queue = Queue() queue.enqueue(5) queue.enqueue(4) queue.enqueue(3) queue.enqueue(2) print(queue.size()) print(queue.is_empty()) print(queue.dequeue())
26248c4900a2793b3fa9d03434f62af8cffacbc9
mihail-serafim/Pytest_Doxygen_Flake8
/src/CircleT.py
1,887
3.65625
4
## @file CircleT.py # @author Mihail Serafimovski # @brief Defines a circle ADT # @date Jan. 10, 2021 from Shape import Shape ## @brief Defines a circle ADT. Assumption: Assume all inputs # provided to methods are of the correct type # @details Extends the Shape interface class CircleT(Shape): ## @brief Constructor for CircleT # @param x A real number which is the x-component of the center of mass # @param y A real number which is the y-component of the center of mass # @param r A real number which is the radius of the circle # @param m A real number which is the mass of the circle # @throws ValueError if the radius or mass are not both greater than zero def __init__(self, x, y, r, m): if not(r > 0 and m > 0): raise ValueError self.x = x self.y = y self.r = r self.m = m ## @brief Getter for x-component of center of mass # @returns A real number which is the x-component # of the circle's center of mass def cm_x(self): return self.x ## @brief Getter for y-component of center of mass # @returns A real number which is the y-component # of the circle's center of mass def cm_y(self): return self.y ## @brief Getter for mass of circle # @returns A real number which is the mass of the circle def mass(self): return self.m ## @brief Getter for moment of inertia of the circle # @returns A real number which is the moment of inertia of the circle def m_inert(self): return self.m * (self.r**2) / 2 ## @brief Method to help with object comparison when testing # @param other Another shape to test for equality # @returns A boolean, true iff both objects have the same state variables def __eq__(self, other): return self.__dict__ == other.__dict__
a3824f6e28c7cc6f87bca06600ee9f162c03f1f7
AliMorty/B.SC.-Project
/Code/Queen.py
3,023
3.703125
4
from random import randint from ProblemFile import ProblemClass gameSize = 8 class QueenProblem(ProblemClass): def get_initial_state(self): arr = [] for i in range( 0 , gameSize): arr.append(i) # for i in range (0 , gameSize): # print(arr[i]) return QueenState(arr) def get_initial_state_random(self): arr = [] for i in range( 0 , gameSize): arr.append(-1) for i in range (0 , gameSize): rand = randint(0,7-i) count=0 for j in range (0, gameSize): if arr[j]==-1: if count == rand: arr[j] = i break if count != rand: count += 1 return QueenState(arr) def get_actions(self, state): # print ("This is a test!") return state.get_actions() def get_result(self, state, action): arr = list(state.arr) i= action.first j= action.second tmp=arr[i] arr[i]=arr[j] arr[j]=tmp return QueenState(arr) def is_goal(self, state): return state.is_goal() def get_score(self, state): return state.get_score() def get_cost(self, state, action): return 1 def is_equal(self, state1, state2): return state1.is_equal(state2) def show_state(self, state): state.show_state() class QueenState(): def __init__(self, initialArr): self.arr = initialArr return def get_actions (self): actions = [] for i in range (0, gameSize): for j in range (i+1, gameSize): actions.append(QueenAction(i, j)) # print("actions", len(actions)) return actions def is_goal(self): for i in range (0 , gameSize): for j in range (i+1, gameSize): if (abs(self.arr[j]-self.arr[i])==j-i): return False return True def get_score(self): score=0 for i in range (0 , gameSize): for j in range (i+1, gameSize): if (abs(self.arr[j]-self.arr[i])==j-i): score+=1 score=-score return score def is_equal (self, s): arr = s.arr for i in range (0 , gameSize): if self.arr[i] !=arr[i]: return False return True def show_state(self): # for i in range (0 , gameSize): # for j in range (0, gameSize): # if (self.arr[i]==j): # print ("#", end='') # else: # print ("-", end='') # print() print("[", end='') for i in range (0, gameSize -1 ): print (self.arr[i], ",", end='') print(self.arr[gameSize-1],"]") class QueenAction(): def __init__(self, first, second): self.first= first self.second=second return
45dfca16469965060a325a60de88582be64df8ce
gousiosg/attic
/coding-puzzles/graph.py
2,340
3.828125
4
#!/usr/bin/env python3 import queue as q from typing import List class Node(): def __init__(self, value): self.visited = False self.neighbours: List[Node] = [] self.value = value def __repr__(self): return str(self.value) class Graph(): def __init__(self, nodes): self.nodes: List[Node] = nodes def reset(self): for n in self.nodes: n.visited = False def bfs(self, n_start: Node) -> List[Node]: result = [] work_queue = q.Queue() work_queue.put(n_start) result.append(n_start) n_start.visited = True while not work_queue.empty(): cur = work_queue.get() for n in cur.neighbours: if not n.visited: work_queue.put(n) n.visited = True result.append(n) return result def dfs(self, n_start: Node) -> List[Node]: result = [] result.append(n_start) n_start.visited = True for n in n_start.neighbours: if not n.visited: for r in self.dfs(n): result.append(r) return result def topo_visit(self, node, stack = [], visited : set = set()) -> List[Node]: if node not in visited: visited.add(node) for neighbour in node.neighbours: self.topo_visit(neighbour, stack, visited) stack.append(node) def topo(self): stack = [] visited = set() for node in self.nodes: self.topo_visit(node, stack, visited) return stack a, b, c, d, e, f = Node("A"), Node("B"), Node("C"), Node("D"), Node("E"), Node("F") h = Node("H") a.neighbours = [b, c, e] b.neighbours = [d, a] c.neighbours = [a, d, h] d.neighbours = [b, c, f] e.neighbours = [a] f.neighbours = [d] h.neighbours = [c, f] #g = Graph([a, b, c, d, e, f, h]) #assert(g.bfs(a) == ['A', 'B', 'C', 'E', 'D', 'H', 'F']) #assert(g.bfs(h) == ['H', 'C', 'F', 'A', 'D', 'B', 'E']) #print(f"BFS from A:{g.bfs(a)}") #print(f"BFS from A:{g.dfs(a)}") a.neighbours = [b, c, e] b.neighbours = [d] c.neighbours = [h, d] d.neighbours = [f] e.neighbours = [] f.neighbours = [] h.neighbours = [f] g = Graph([a, b, c, d, e, f, h]) print(f"Topological sort:{g.topo()}")
e1c3c0e94463b139ac244a685556d19698fd0e5c
grigil/Useless_functions
/sortByHeight/sortByHeight.py
204
3.625
4
def sortByHeight(a): b=0 k=0 while k < len(a): i=0 while i < len(a): if a[i]!=-1: if a[k]!=-1: if a[k]<a[i]: b=a[i] a[i]=a[k] a[k]=b i=i+1 k=k+1 return a a
8386925eadcb21fba3a504222cac6fadbc610e37
ashwani-rathee/DIC_AI_PROGRAM
/8-andgate.py
3,269
3.5
4
# create a proper neural network to classify 00,01,10,11 # importing numpy library import numpy as np from numpy import linspace import numpy as np import matplotlib.pyplot as plt from mpl_toolkits import mplot3d from scipy import signal # sigmoid function def sigmoid(x): return 1/(1+np.exp(-x)) x1 = 0 x2 = 1 w1 = np.random.random() w2 = np.random.random() w3 = np.random.random() w4 = np.random.random() w5 = np.random.random() w6 = np.random.random() w7 = np.random.random() w8 = np.random.random() w9 = np.random.random() b1 = np.random.random() b2 = np.random.random() b3 = np.random.random() b4 = np.random.random() z1 = 0 z2 = 0 z3 = 0 a1 = 0 a2 = 0 a3 = 0 z4 = 0 a4 = 0 losses = [] def plotgraph(name ,x = range(1,10000), y = losses): # Data for plotting fig, ax = plt.subplots() ax.plot(x, y) ax.set(xlabel='Steps(i)', ylabel='Loss(loss)', title='Loss Vs Steps') ax.grid() fig.savefig("{}.png".format(name)) plt.show() return def forwardpropagation(x1,x2,w1,w2,w3,w4,w5,w6,w7,w8,w9,b1,b2,b3,b4): global z1, z2, z3, z4, a1, a2, a3, a4 z1 = w1*x1 + w4*x2 + b1 z2 = w2*x1 + w5*x2 + b2 z3 = w3*x1 + w6*x2 + b3 a1 = sigmoid(z1) a2 = sigmoid(z2) a3 = sigmoid(z3) z4 = w7*a1 + w8*a2 + w9*a3 + b4 a4 = sigmoid(z4) def backwardpropagation(expected_output): global w1, w2, w3, w4, w5, w6, w7, w8, w9, b1, b2, b3, b4 global z1, z2, z3, z4, a1, a2, a3, a4 # calculating derivative of loss function dl_da4 = -(expected_output - a4) # calculating derivative of sigmoid function dl_dz4 = dl_da4 * a4 * (1-a4) dl_db4 = dl_dz4 dl_dw7 = dl_dz4 * a1 dl_dw8 = dl_dz4 * a2 dl_dw9 = dl_dz4 * a3 dl_da1 = dl_dz4*w7 dl_da2 = dl_dz4*w8 dl_da3 = dl_dz4*w9 dl_dz1 = dl_da1*a1*(1-a1) dl_dz2 = dl_da2*a2*(1-a2) dl_dz3 = dl_da3*a3*(1-a3) dl_db1 = dl_dz1 dl_db2 = dl_dz2 dl_db3 = dl_dz3 dl_dw1 = dl_dz1*x1 dl_dw2 = dl_dz2*x1 dl_dw3 = dl_dz3*x1 dl_dw4 = dl_dz1*x2 dl_dw5 = dl_dz2*x2 dl_dw6 = dl_dz3*x2 lr = 1 w1 = w1 - lr*dl_dw1 w2 = w2 - lr*dl_dw2 w3 = w3 - lr*dl_dw3 w4 = w4 - lr*dl_dw4 w5 = w5 - lr*dl_dw5 w6 = w6 - lr*dl_dw6 w7 = w7 - lr*dl_dw7 w8 = w8 - lr*dl_dw8 w9 = w9 - lr*dl_dw9 b1 = b1 - lr*dl_db1 b2 = b2 - lr*dl_db2 b3 = b3 - lr*dl_db3 b4 = b4 - lr*dl_db4 loss = 0.5*(expected_output - a4)**2 return loss for i in range(1,10000): dataset = [[0,0,0],[0,1,0],[1,0,0],[1,1,1]] print("Step:",i) i = np.random.randint(0,4) x1 = dataset[i][0] x2 = dataset[i][1] expected_output = dataset[i][2] # print("x1: ",x1,"x2: ",x2,", expected_output: ",expected_output) forwardpropagation(x1,x2,w1,w2,w3,w4,w5,w6,w7,w8,w9,b1,b2,b3,b4) loss = backwardpropagation(expected_output) losses.append(loss) print("Loss :{0:.3f}".format(loss)) if loss == 0: break # plotgraph("And") # graph of loss versus steps while(True): x1 = int(input("Enter x1 : ")) x2 = int(input("Enter x2 : ")) forwardpropagation(x1,x2,w1,w2,w3,w4,w5,w6,w7,w8,w9,b1,b2,b3,b4) print(x1,x2,w1,w2,w3,w4,w5,w6,w7,w8,w9,b1,b2,b3,b4) print("Output : {0:.3f}".format(a4))
04859558d6e5f72cfb55f04050eb86543567c754
JonathanGrimmSD/projecteuler
/031-040.py
8,156
3.5625
4
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import division __author__ = "Jonathan Grimm" __date__ = "07.02.18" import math # 031: Coin sums: def count(S, m, n): if n == 0: return 1 if n < 0: return 0 if m <= 0 and n >= 1: return 0 return count(S, m - 1, n) + count(S, m, n - S[m - 1]) def project031(): d = [200, 100, 50, 20, 10, 5, 2, 1] m = len(d) return count(d, m, 200) # 032: Pandigital products: def project032(): erg=[] for i in range(1,100): for j in range(100,10000): temp=str(i)+str(j)+str(i*j) if "0" not in temp: if len(temp)==9 and len(set(temp))==9: if i*j not in erg: erg.append(i*j) return sum(erg) # 033: Digit cancelling fractions: def project033(): frac=[1,1] for numerator in range(10,100): for denominator in range(numerator+1,100): if numerator%10!=0 or denominator%10!=0: dupes=getduplicates(numerator,denominator) if dupes is not None: num=str(numerator).replace(dupes,"") den=str(denominator).replace(dupes,"") if numerator/denominator==int(num)/int(den): frac=[frac[0]*numerator,frac[1]*denominator] return frac[1]//ggt(frac[0],frac[1]) def ggt(x,y): if y>x: temp=x x=y y=temp while True: if x%y==0: return y else: rest=x%y x=y y=rest def getduplicates(x,y): xy=str(x)+str(y) myset=set(xy) duplicates=[] for each in myset: count = xy.count(each) if count==2: duplicates.append(each) if len(duplicates)==1 and xy.count("0")==0 and str(x).count(duplicates[0])==1: return duplicates[0] else: return # 034: Digit factorials def nfak(n): fak = 1 i = 1 while i < n + 1: fak *= i i += 1 return fak def check034(x): res = 0 for i in xrange(len(str(x))): res += nfak(int(str(x)[i])) return res == x def project034(): n = 1 while n * nfak(9) > 10 ** n: n += 1 res = 0 for i in xrange(3, 10 ** n): if check034(i): res += i return res # 035: Circular primes: class project035: def __init__(self): self.digits = "024568" # if one of these is last digit it cant be a prime number self.primes = [] for i in xrange(1000000): if self.is_prime(i) and self.intersect(i): self.primes.append(i) def intersect(self, x): if len(str(x)) == 1: return True else: return not (len(set(str(x)).intersection(set(self.digits))) > 0) def is_prime(self, n): if n == 2: return True if n % 2 == 0 or n <= 1: return False sqr = int(math.sqrt(n)) + 1 for divisor in range(3, sqr, 2): if n % divisor == 0: return False return True def rotation(self, n): n = str(n) r = [int(n)] for i in range(len(n) - 1): n = n[1:] + n[0] r.append(int(n)) return list(set(r)) def calc(self): res = 0 n = 0 while True: if n + 1 >= len(self.primes): break prm = self.rotation(self.primes[n]) if set(prm).issubset(self.primes): res += len(prm) self.primes = [x for x in self.primes if x not in prm] else: n += 1 return res # 036: Double-base palindromes def check_palindrome(x): if len(str(x)) == 1: return True for i in range(len(str(x)) / 2): if str(x)[i] != str(x)[-1 * (i + 1)]: return False return True def project036(): res = 0 for i in range(0, 1000000): if check_palindrome(i): if check_palindrome(int("{0:b}".format(i))): print i, " --- ", int("{0:b}".format(i)) res += i return res # 037: Truncatable primes: from math import sqrt; from itertools import count, islice def isPrime(n): return not (n > 1 and all(n % i for i in islice(count(2), int(sqrt(n) - 1)))) def primes2(n): #credit to 'Robert William Hanks' https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n/3035188#3035188 """ Input n>=6, Returns a list of primes, 2 <= p < n """ n, correction = n - n % 6 + 6, 2 - (n % 6 > 1) sieve = [True] * (n / 3) for i in xrange(1, int(n ** 0.5) / 3 + 1): if sieve[i]: k = 3 * i + 1 | 1 sieve[k * k / 3::2 * k] = [False] * ((n / 6 - k * k / 6 - 1) / k + 1) sieve[k * (k - 2 * (i & 1) + 4) / 3::2 * k] = [False] * ( (n / 6 - k * (k - 2 * (i & 1) + 4) / 6 - 1) / k + 1) return [2, 3] + [3 * i + 1 | 1 for i in xrange(1, n / 3 - correction) if sieve[i]] def project037(p=100): while True: primes = primes2(p) x = primes x = x[4:] for n in range(len(x) - 1, -1, -1): a = [(x[n] // (10 ** i)) % 10 for i in range(int(math.ceil(math.log(x[n], 10))) - 1, -1, -1)] b = set([0, 4, 6, 8]) if len(set(a).intersection(b)) > 0: del x[n] elif a[0] == 1 or a[-1] == 1: del x[n] trunc = [] for i in x: n = i cond = True for j in xrange(len(str(n)) - 1): if isPrime(int(str(n)[:j + 1])): cond = False break if isPrime(int(str(n)[j + 1:])): cond = False break if cond: trunc.append(i) if len(trunc) >= 11: break else: p *= 10 return sum(trunc) # 038: Pandigital multiples: def project038(): erg=[None,None,0] i=0 cond=True while cond: i+=1 n=1 prod="" while True: prod+=str(i*n) if n==1 and len(prod)>5: cond=False break if prod.count("0")>0: break if len(prod)!=len(set(prod)): break if len(prod)>9: break if len(prod)==9: if int(prod)>int(erg[2]): erg=[i,range(1,n+1),prod] break #print i,range(1,n+1),prod n+=1 return erg[2] # 039: Integer right triangles: def project039_old(): maxlen=[0,None] for p in xrange(2,1000,2): tris=len(getTriangles(p)) if tris>maxlen[0]: maxlen=[tris,p] return maxlen[1] def getTriangles(p): erg=[] for a in xrange(1,p): b=a if p<math.sqrt(a**2+b**2)+a+b: break for b in xrange(a,p): if p>a+b>p-(a+b): if p==math.sqrt(a**2+b**2)+a+b: erg.append([a,b,p-(a+b)]) if p<math.sqrt(a**2+b**2)+a+b: break return erg def project039(): C={} for a in range(1,500): for b in range(a,500): c=int(math.sqrt(a*a+b*b)) if a*a+b*b==c*c: try: C[a+b+c]+=1 except KeyError: C[a+b+c]=1 p=-1 maxvar=-1 for i,j in C.iteritems(): if j>maxvar: p=i maxvar=j return p # 040: Champernowne's constant def project040(): irr = "" i = 1 while len(irr) < 1000000: irr += str(i) i += 1 fac = 1 for i in range(0, 7): fac *= int(irr[(10 ** i) - 1]) return fac import time t = time.time() # print project031() # print project032() # print project033() # print project034() # print project035().calc() # print project036() # print project037() # print project038() # print project039() # print project040() print time.time()-t
4291e627f6dee78285a3d018a8ea6c9fc7a8ffd9
Jackroll/aprendendopython
/exercicios_udemy/Programacao_Procedural/perguntas_respostas_57.py
1,548
3.765625
4
#sistema de perguntas e respostas usando dicionário #criado dicionário Perguntas que contem chave pergunta, e o valor da che é outro dicionário #com perguntas e respostas perguntas = { #{pk} : {pv} 'pergunta 1' : { #{pv[pergunta]} 'pergunta': 'Quanto é 2 + 2 ?', #{rk} : {rv} 'respostas' : {'a': 1, 'b' : 4, 'c': 55}, #{pv[resposta_certa]} 'resposta_certa' : 'b' }, 'pergunta 2' : { 'pergunta': 'Quanto é 2 * 10 ?', 'respostas' : {'a': 20, 'b' : 350, 'c': 55}, 'resposta_certa' : 'a' }, 'pergunta 3' : { 'pergunta': 'Quanto é 15 / 3 ?', 'respostas' : {'a': 230, 'b' : 3, 'c': 5}, 'resposta_certa' : 'c' }, } resposta_certa = 0 #variável para armazenar as respostas certas for pk, pv in perguntas.items(): #iteração para percorrer o dicionário pai print(f'{pk} : {pv["pergunta"]}') print('Respostas :') for rk, rv in pv['respostas'].items(): #iteraão para percorrer o dicionário filho print(f'[{rk}] : {rv}') resposta_usuario = input('Sua resposta : ') if resposta_usuario == pv['resposta_certa']: print('Acertou !! \n') resposta_certa += 1 else: print('Errou !! \n') qtd_perguntas = len(perguntas) erros = qtd_perguntas - resposta_certa percentual = int(resposta_certa / qtd_perguntas * 100) print(f'Acertos: {resposta_certa}\nErros: {erros}\n{percentual} % de acerto')
fc70c57920b9e56aae696754aa6ff347e7971aba
Jackroll/aprendendopython
/exercicios_udemy/desafio_contadores_41.py
375
4.3125
4
"""fazer uma iteração para gerar a seguinte saída: 0 10 1 9 2 8 3 7 4 6 5 5 6 4 7 3 8 2 """ # método 01 - usando while i = 0 j = 10 while i <= 8: print(i, j) i = i+1 j = j-1 print('------------------') # método 02 - usando for com enumerate e range for r, i in enumerate(range(10,1, -1)): #enumerate conta quantas vezes houve a iteração print(r, i)
88cce404c8ad3f07c9e4f09b09d80a8ffc660acb
Jackroll/aprendendopython
/exercicios_udemy/Orientacao_Objetos/desafio_poo/banco.py
879
3.921875
4
# Classe Banco, possui cadastro com agencias, clientes e contas class Banco: def __init__(self): self.agencia = [111, 222, 333] self.clientes = [] self.contas = [] #método para cadastrar clientes no banco def cadastrar_cliente(self, cliente): self.clientes.append(cliente) #método para cadastrar conta no banco def cadastrar_conta(self, conta): self.contas.append(conta) #método para autenticação, somente será possível fazer transações se o cliente, a cota e a agencia existirem no banco #ou seja se já tiverem sido cadastrados def validacao(self, cliente): if cliente not in self.clientes: return False if cliente.conta not in self.contas: return False if cliente.conta.agencia not in self.agencia: return False return True
972a883e10eda7523b400da701755868927938e8
Jackroll/aprendendopython
/agregacao/classes.py
982
4.3125
4
""" Agregação é quando uma classe pode existir sozinha, no entanto ela depende de outra classe para funcionar corretamente por exemplo: A Classe 'Carrinho de compras' pode existir sózinha, mas depende da classe 'Produtos' para pode funcionar corretamente pois seus métodos dependem da classe produto. E classe Produtos por sua vez existe sozinha e não depende em nada da classe Carrinho de compras """ class CarrinhoDeCompras: def __init__(self): self.produtos = [] def inserir_produto(self, produto): self.produtos.append(produto) def lista_produtos(self): i = 0 for produto in self.produtos: i = i+1 print(f'Item : {i} - {produto.nome} R$ {produto.valor}') def soma_total(self): total = 0 for produto in self.produtos: total += produto.valor return total class Produto: def __init__(self, nome, valor): self.nome = nome self.valor = valor
0c1622a3e7497ab2ef4a8274bf3cae27492824df
Jackroll/aprendendopython
/exercicios/PythonBrasilWiki/exe003_decisao.py
490
4.1875
4
#Faça um Programa que verifique se uma letra digitada é "F" ou "M". Conforme a letra escrever: F - Feminino, M - Masculino, Sexo Inválido. letra = str(input('Digite F ou M :')) letra_upper = letra.upper() #transforma a string para Uppercase para não haver erro em caso de digitação da letra em minusculo if letra_upper == 'F': print(f'{letra_upper} - é feminino') elif letra_upper == 'M' : print(f'{letra_upper} - é masculino') else : print ('Sexo invalido')
55dace0617bee83c0abef6e191326eb87f464c6a
Jackroll/aprendendopython
/exercicios_udemy/Programacao_Procedural/arquivos/arquivo_aula_83.py
1,867
4.125
4
file = open('abc.txt', 'w+') #cria o arquivo 'abc.txt' em modo de escrita w+ apaga tudo que ta no arquivo antes de iniciar a escrita file.write('linha 1\n') #escreve varias linhas no arquivo file.write('linha 2\n') file.write('linha 3\n') file.write('linha 4\n') print('-=' * 50) file.seek(0,0) #coloca o cursor no inicio do arquivo para fazer a leitura print('Lendo o arquivo :') print(file.read()) #faz a leitura do arquivo print('-=' * 50) file.seek(0, 0) #coloca o cursor no inicio do arquivo para fazer a leitura print(file.readlines()) #gera uma lista com as linhas do arquivo print('-=' * 50) file.seek(0, 0) for linha in file.readlines(): #lendo atraves de um for print(linha, end='') #end = '' retira a quebra de linha file.close() #fecha o arquivo print('-=' * 50) with open ('abc2.txt', 'w+') as file: #utilizando o with não precisar mandar fechar o arquivo com file.close() file.write('Arquivo 2 - linha 1\n') #escreve varias linhas no arquivo file.write('Arquivo 2 - linha 2\n') file.write('Arquivo 2 - linha 3\n') file.write('Arquivo 2 - linha 4\n') file.seek(0) print(file.read()) print('-=' * 50) with open ('abc3.txt', 'a+') as file: #Adicionando linhas ao arquivo, o a+ manda o cursor para o final do arquivo file.write('Adcicionando linhas 1\n') file.write('Adcicionando linhas 2\n') file.write('Adcicionando linhas 3\n') file.write('Adcicionando linhas 4\n') file.write('Adcicionando linhas 5\n') file.seek(0) print(file.read()) print('-=' * 50) with open ('abc3.txt', 'r+') as file: #lendo oque esta dentro do arquivo e mostrando na tela atraves do r+ print(file.read())
5a335fbe510d1f1f212e5f14d7658c5419433237
Jackroll/aprendendopython
/exercicios_udemy/Orientacao_Objetos/composicao/main.py
681
3.90625
4
"""Composição: Uma classe é dona de objetos de outra classe Se a classe principal for apagada todas as classes que foram usadas pela classe principal serão apgadas com ela """ #Por conta da composição, não houve a necessidad de importação da classe endereço, já que ela compoe a classe Cliente from classes import Cliente print('-='*15) c1 = Cliente('Jacson', 33) c1.insere_endereco('Imarui', 'SC') c1.lista_enderecos() print('-='*15) c2 = Cliente('Pedro', 12) c2.insere_endereco('Londrina', 'PR') c2.lista_enderecos() print('-='*15) c3 = Cliente('Bia', 43) c3.insere_endereco('Salvador', 'BA') c3.insere_endereco('Belem', 'PA') c3.lista_enderecos() print('-='*15)
d5e351dc79c6ce6ef0e4eff3683a8640af0adfdf
Jackroll/aprendendopython
/exercicios_udemy/Orientacao_Objetos/composicao/classes.py
931
3.765625
4
#classe cliente que recebe uma instancia da classe endereço para atualizar sua lista de endereços class Cliente: def __init__(self, nome, idade): self.nome = nome self.idade = idade self.enderecos = [] def insere_endereco(self, cidade, estado): self.enderecos.append(Endereco(cidade, estado)) #neste ponto é feita a composição, quando uma instancia da classe Endereço é chamada def lista_enderecos(self): for endereco in self.enderecos: print(endereco.cidade, endereco.estado) #neste ponto tambem é feita a composição através do acesso aos atributos padrão #atraves do instaciamento da classe Endereco() #classe endereço,recebe dois atributos padrão class Endereco: def __init__(self, cidade, estado): self.cidade = cidade self.estado = estado
14aaf8a634e733d0cc8b08e69615b924fc9274ef
Jackroll/aprendendopython
/exercicios_udemy/poo/aula90_classes/pessoas.py
1,555
4.03125
4
from datetime import datetime class Pessoa: ano_atual = int(datetime.strftime(datetime.now(), '%Y')) #atributo de classe def __init__(self, nome, idade, comendo = False, falando=False): #atributo do objeto, o de método self.nome = nome self.idade = idade self.comendo = comendo self.falando = falando def falar(self, assunto): if self.comendo: print(f'{self.nome} esta comendo não pode falar') return if self.falando: print(f'{self.nome} já esta falando') return print(f'{self.nome} esta falando sobre {assunto}') self.falando = True def comer(self, alimento): if self.falando: print(f'{self.nome} esta falando não pode comer') return if self.comendo: print(f'{self.nome} já esta comendo') return print(f'{self.nome} esta comendo {alimento}') self.comendo = True def parar_falar(self): if not self.falando: print(f'{self.nome} já não esta falando') return print(f'{self.nome} parou de falar') self.falando = False def parar_comer(self): if not self.comendo: print(f'{self.nome} já não esta comendo') return print(f'{self.nome} parou de comer') self.comendo = False def ano_nascimento(self): ano = self.ano_atual - self.idade print(f'{self.nome} nasceu em {ano}')
e76d821bf83cad07252a52fd9184058abff76da9
Jackroll/aprendendopython
/exercicios_udemy/Orientacao_Objetos/context_manager/context_manager_lib.py
839
3.890625
4
#método 02 de criar gerenciador de contexto - usando contextmanager, atraves da criação de uma função. from contextlib import contextmanager # é criado uma função normal, só que decorada com @contextmanager para virar gerenciador de contexto @contextmanager def abrir(arquivo, modo): try: print('Abrindo o arquivo') arquivo = open(arquivo, modo) #abre o arquivo yield arquivo # é igual o return, só que ao contrário do return, executa o código seguinte finally: arquivo.close() #fecha o arquivo with abrir('teste_02.txt', 'w') as arquivo: #para funcionar deve sempre ser usado com o with arquivo.write('linha 01 \n') arquivo.write('linha 02 \n') arquivo.write('linha 03 \n') arquivo.write('linha 04 \n')
2f18dce6db44f8cbde41683bccd3f16611aace20
Jackroll/aprendendopython
/exercicios_udemy/Modulos_uteis/Json/json_main.py
978
4.34375
4
""" trabalhando com json Documentação : https://docs.python.org/3/library/json.html json -> python = loads / load python -> json = dumps / dump """ from aprendendopython.exercicios_udemy.Modulos_uteis.Json.dados import * import json # convertendo dicionário para json dados_json = json.dumps(clientes_dicionario, indent =4) #usado ident=4 para dar a correta identação print(dados_json) #convertendo de json para pyhton (dicionário) print('xx'*50) dicionario_json = json.loads(clientes_json) for v,j in dicionario_json.items(): print(v) print(j) print('xx'*50) #convertendo, criando e gravando um dicionário em json with open('clientes.json', 'w') as arquivo: json.dump(clientes_dicionario, arquivo, indent=4) print('Conversão efetuada !') print('xx'*50) #convertendo e lendo um json em dicionário with open('clientes.json', 'r') as arquivo: dados = json.load(arquivo) for chave, valor in dados.items(): print(chave) print(valor)
1b139816100f6157c1492c44eb552c096fb8b32f
verma-rahul/CodingPractice
/Medium/InOrderTraversalWithoutRecursion.py
2,064
4.25
4
# Q : Given a Tree, print it in order without Traversal # Example: 1 # / \ # 2 3 => 4 2 5 1 3 # / \ # 4 5 import sys import random # To set static Seed random.seed(1) class Node(): """ Node Struct """ def __init__(self,val=None): self.val=val self.right=None self.left=None class BinaryTree(): def __init__(self,root=None): self.root=root def make_random_balnaced_tree(self,size): """ Constructs a random Balanced Tree & prints as an Array Ex: [1,2,3,4,5] => 1 / \ 2 3 / \ 4 5 """ val=random.randint(0, 100) self.root=Node(val) stack=[self.root];size=size-1;arr_tree=[val] while size>0: node=stack.pop(0) val=random.randint(0,100) left=Node(val) arr_tree.append(val) node.left=left stack.append(left) size=size-1 if size>0: val=random.randint(0,100) right=Node(val) node.right=right arr_tree.append(val) stack.append(right) size=size-1 print("Balanced Tree as Array: ", arr_tree) def print_inorder(self): """ Prints the Tree Inorder """ stack=[self.root] node=self.root print("Inorder Traversal of Tree: ") while len(stack)>0: if node!=None and node.left!=None: stack.append(node.left) node=node.left else: poped=stack.pop() print(poped.val) node=poped.right if node!=None: stack.append(node) def main(args): tree=BinaryTree() tree.make_random_balnaced_tree(10) tree.print_inorder() if __name__=='__main__': main(sys.argv[1:])
ffb8dd75a8a0fc099a0bdcdebf42df80831ef9ff
tistaharahap/woods.py
/woods.py
11,344
3.515625
4
import sys class OutOfTheWoods(object): def __init__(self): print chr(27) + "[2J" self.name = "John Doe" self.fragileObjectInFrontOfTree = "" self.fragileObjectCondition = "" self.wildAnimalSeen = "" self.takeTheWildAnimalWithMe = False self.stayWithGranny = False self.torchCarried = 0 self.jumpToPond = False self.askTheEntity = False self.fightBack = True self.beginStory() def beginStory(self): sys.stderr.write("\x1b[2J\x1b[H") print "Before we start, what is your name?", self.name = raw_input() print "\nOk", self.name, "let's start.." print "\n\n>> It is a sun shining brightly day and you are on your way climbing a mountain with your friends." print ">> As you are enjoying the views surrounding you, somehow you were separated from your friends." print ">> You find yourself now all alone where woods and forest is all around you." self.pressAnyKey() self.theFragilityOfYourHeart() def theFragilityOfYourHeart(self): self.clearScreen() print ">> Just when you thought things couldn't be any worse than this, you are shocked to see there's this fragile object in front of a big tree." self.thisIsYourHeart() self.yourHeartNow() print "\n>> You just stood there but it didn't take long to continue your way around the forest." self.pressAnyKey() self.whoAreYou() def yourHeartNow(self): print "\nHow is the condition of the %s? Is it broken, cracked or still whole?" % (self.fragileObjectInFrontOfTree), self.fragileObjectCondition = raw_input() if not (self.fragileObjectCondition == "broken" or self.fragileObjectCondition == "cracked" or self.fragileObjectCondition == "whole"): self.yourHeartNow() def thisIsYourHeart(self): print "\nWhat fragile object do you see in front of that big tree?", self.fragileObjectInFrontOfTree = raw_input() if self.fragileObjectInFrontOfTree == "": self.thisIsYourHeart() def whoAreYou(self): self.clearScreen() print ">> As you are walking, you are put into a narrow path." print ">> Out of nowhere, you see a wild animal right in front of you." self.thisIsYou() self.naturalBornLeader() self.pressAnyKey() self.areYouCautious() def areYouCautious(self): self.clearScreen() print ">> The sun is setting and darkness will follow, soon." print ">> You see some light not far from where you are, you follow the light." print ">> When you get there, you see a hut with an old fashioned water well just in front of it." print ">> In its frontyard, there's an old lady brooming the leaves away from her frontyard." print "\n>> You have 2 options: ask for directions or stay the night, it's dark." self.soAreYouCautious() self.pressAnyKey() self.theFidelity() def theFidelity(self): self.clearScreen() print ">> You are continuing your journey, no matter you asked or stayed, it's getting dark, again." print ">> Just in front of you, there's an abandoned cave with lots of torches lying around." print ">> Let's just say you have a lighter and you can light the torches." print "\nHow many torches are you taking with you?", self.torchCarried == raw_input() self.pressAnyKey() self.marvinStyle() def marvinStyle(self): self.clearScreen() print ">> With your torch lighted, you come across a river stream just ahead." print ">> The tide is gentle and you can see it's deep enough to get soakingly fresh." print "\n>> You have 2 options: you freshen things up a little or you get wet all in." self.barryIsThePapa() self.pressAnyKey() self.theEntity() def theEntity(self): self.clearScreen() print ">> You are refreshed and on your way through the woods." print ">> In a blink of an eye, there's an unknown entity in front of you, hovering from the ground!" print ">> You're really frustrated at this point." print "\n>> You have 2 options: run for your life or ask for directions" self.higherBeing() self.pressAnyKey() self.fightOrSurrender() def fightOrSurrender(self): self.clearScreen() print ">> The skies are getting its daily dose of light from the sun." print ">> It's early morning and you can see a way out from the woods." print ">> You reacted and started to walk faster towards the exit." print ">> When you got out, a war in the middle of nowhere has just started." print ">> One of the soldiers is pointing a gun on your forehead." print "\n>> You have 2 options: fight for your life or just surrender?" self.fight() self.pressAnyKey() self.concludeNow() def concludeNow(self): self.clearScreen() print ">> Thank you %s for answering all of the questions." % self.name print ">> Now is the time to know more about yourself." print "\n>> For every answer, the questions represent a part of your identity and of course your personality." print ">> Any conclusions you are about to read can change in the future depending on yourself." print ">> Some people struggle to change, some just change. It's your call." self.pressAnyKey() self.clearScreen() print ">> You saw a %s in front of a big tree" % self.fragileObjectInFrontOfTree print "\n>> That fragile object is your heart at the moment. The bigger the object, the bigger your heart is." print ">> Big or Small does not pertain to quality, this is your capacity at the moment." self.pressAnyKey() self.clearScreen() print ">> The fragile object is %s." % self.fragileObjectCondition print "\n>> A whole heart is a healthy heart, all the vitamins and nutrition to keep it whole are fed perfectly." print ">> If it's cracked or broken, you must find some way to heal or at least get some closure." print ">> Don't bleed your heart, no one deserves a bleeding heart." self.pressAnyKey() self.clearScreen() print ">> The wild animal you see is a %s." % self.wildAnimalSeen print "\n>> This wild animal is actually how you see yourself as in your character." print ">> You have your own subjectivity towards this animal and that's all right." print ">> The thing is, this animal is still wild. Your next answer is a defining one." if self.takeTheWildAnimalWithMe == True: print "\n>> You choose to tame and take the %s with you." % self.wildAnimalSeen print "\n>> Your answer shows that you are a Natural Born Leader." print ">> While people struggle to be leaders, you don't." print ">> The more the people around you struggle, the more obvious you are as a leader." print ">> Just to remember to have fun once in a while." else: print "\n>> You choose to run from the %s." % self.wildAnimalSeen print "\n>> You are best to function collectively." print ">> Your job is your job, that's just it, it's a job." print ">> A career is made of horizontal decisions." print ">> Try looking what's up there at the top, inspire yourself." self.pressAnyKey() self.clearScreen() print ">> You brought %d torch(es) with you." % self.torchCarried print "\n>> The more torch you carry, the more infidel you are with your love life." print ">> Be careful not to spread yourself too thin." print ">> Fidelity is like chivalry these days, rare and ideal." print ">> No matter how many torches, focus on 1, you can't light them all up anyways." self.pressAnyKey() self.clearScreen() action = "" if self.jumpToPond: action = "get wet" else: action = "freshen" print ">> You found a river stream and you choose to %s" % action print "\n>> If you choose to freshen, you are picky when it comes to bedding your sexual counterpart." print ">> On the contrary, if you choose to get wet, you're less picky, even not picky at all." print ">> No matter what you choose, play safe :)" self.pressAnyKey() self.clearScreen() if self.askTheEntity: action = "ask" else: action = "run" print ">> So there's this entity hovering in front of you. You choose to %s." % action print "\n>> If you choose to ask, you have a tendency of asking the Guy above first for His guidances when you run into problems." print ">> The other way around, if you choose to run, you tend to try the problem at hand first and ask for His guidances later." print ">> There is no wrong or right, it's just your own belief." self.pressAnyKey() self.clearScreen() if self.fightBack: action = "fight" else: action = "surrender" print ">> You found a way out of the woods only to find you have a gun pointing at you on your forehead. You %s." % action print "\n>> When you choose to fight, it's obvious that you don't go down easily. You are persistent and you will persevere what's needed to achieve your goals." print ">> If you surrender, you are more likely to accept logical reasonings beyond anything. Everything is in grey and there is no right or wrong, just logical or not logical." print ">> A combination of both is healthy, be open." self.pressAnyKey() self.clearScreen() def fight(self): print "\nFight or Surrender?", self.fightBack = raw_input() if self.fightBack == "fight" or self.fightBack == "surrender": if self.fightBack == "fight": self.fightBack = True elif self.fightBack == "surrender": self.fightBack = False else: self.fight() else: self.fight() def higherBeing(self): print "\nRun or Ask?", self.askTheEntity = raw_input() if self.askTheEntity == "run" or self.askTheEntity == "ask": if self.askTheEntity == "run": self.askTheEntity = False elif self.askTheEntity == "ask": self.askTheEntity = True else: self.higherBeing() else: self.higherBeing() def barryIsThePapa(self): print "\nFreshen or Wet?", self.jumpToPond = raw_input() if self.jumpToPond == "freshen" or self.jumpToPond == "wet": if self.jumpToPond == "freshen": self.jumpToPond = False elif self.jumpToPond == "wet": self.jumpToPond = True else: self.barryIsThePapa() else: self.barryIsThePapa() def soAreYouCautious(self): print "\nAsk or Stay?", self.stayWithGranny = raw_input() if self.stayWithGranny == "ask" or self.stayWithGranny == "stay": if self.stayWithGranny == "ask": self.stayWithGranny == False elif self.stayWithGranny == "stay": self.stayWithGranny == True else: self.soAreYouCautious() else: self.soAreYouCautious() def thisIsYou(self): print "\nWhat animal do you see?", self.wildAnimalSeen = raw_input() if self.wildAnimalSeen == "": self.thisIsYou() def naturalBornLeader(self): print "\n>> You are thinking of 2 things, either run away from it or instead you cautiously try to tame it and take it with you.", print "\n\nDo you run or tame?", self.takeTheWildAnimalWithMe = raw_input() if self.takeTheWildAnimalWithMe == "run" or self.takeTheWildAnimalWithMe == "tame": if self.takeTheWildAnimalWithMe == "tame": self.takeTheWildAnimalWithMe = True else: self.takeTheWildAnimalWithMe = False else: self.naturalBornLeader() def clearScreen(none): sys.stderr.write("\x1b[2J\x1b[H") def pressAnyKey(none): print "\nPress any key to continue >>", dummy = raw_input() me = OutOfTheWoods()
72e74e7dfbb1bc401f524e41e649fd8fc74da6dd
search-94/Genetic_algorithm
/inventario de carne.py
9,057
3.625
4
#ALGORITMO GENETICO INVENTARIO OPTIMO DE ALMACEN DE CARNE import random class algoritmoGenetico: def __init__(self): #creacion de variables self.poblacion = [] self.genotipo = [] self.bondad = [] self.cc = [] self.fprobabilidad = [] self.eliteq = [] self.elitecosto = [] self.npoblacion = 50 self.mayor = 0 print ("Cálculo de cantidad óptima de pedido 'Q*' para el manejo de inventario de productos cárnicos\n") self.d = int(input("Introduzca la demanda constante\n")) self.tiempo = int(input("Introduzca la cantidad de tiempo en dias requerida para satisfacer la demanda\n")) self.almacen = int(input("Introduzca la capacidad de las neveras \n")) self.c0 = int(input("Introduzca el costo de cada pedido Co \n")) self.mantenimiento = int(input("Introduzca el costo de mantenimiento por kilo\n")) self.depreciacion = int(input("Introduzca el costo de depreciación de un kilo por día\n")) self.ntramos = int(input("Introduzca la cantidad de tramos\n")) self.tramoinferior = [] self.tramosuperior = [] self.tramopreciocompra = [] print ("Introduzca el límite inferior del tramo 1") n = int(input()) self.tramoinferior.append(n) print ("Introduzca el límite superior del tramo 1") n = int(input()) self.tramosuperior.append(n) print ("Introduzca el costo de compra asociado al tramo 1") n = int(input()) self.tramopreciocompra.append(n) for i in range(1,self.ntramos): n = self.tramosuperior[i-1] + 1 self.tramoinferior.append(n) print ("Introduzca el límite superior del tramo ",i+1) n = int(input()) self.tramosuperior.append(n) print ("Introduzca el costo de compra asociado al tramo ",i+1) n = int(input()) self.tramopreciocompra.append(n) #Generación de población inicial if (self.almacen > self.tramosuperior[self.ntramos-1]): self.limitesuperior = self.tramosuperior[self.ntramos-1] else: self.limitesuperior = self.almacen self.limiteinferior = self.tramoinferior[0] a = bin(self.limitesuperior) self.posiciones = len(a)-2 secuencia = [] for i in range(self.limiteinferior, self.limitesuperior+1): secuencia.append(i) for i in range(self.npoblacion): a = random.choice(secuencia) self.poblacion.append(a) secuencia.remove(a) for i in range(self.npoblacion): a = bin(self.poblacion[i]) a = a.lstrip("0b") self.genotipo.append(a) while len(self.genotipo[i]) < self.posiciones: self.genotipo[i] = "0"+self.genotipo[i] for i in range (self.npoblacion): for j in range (self.ntramos): if self.poblacion[i] >= self.tramoinferior[j] and self.poblacion[i] <= self.tramosuperior[j]: self.cc.append(self.tramopreciocompra[j]) print ("Conjunto de Q* iniciales") print (self.poblacion,"\n") print ("Genotipo de la poblacion inicial") print (self.genotipo, "\n") print ("Costo de compra en kilos de cada pedido") print (self.cc,"\n") def evaluar(self): self.bondad = [] for i in range(self.npoblacion): #evaluar costo total de inventario cp = self.d/self.poblacion[i] p = self.tiempo/cp cua = self.mantenimiento + (self.depreciacion*p) ct = (self.c0 * self.d/self.poblacion[i]) + (cua * self.poblacion[i]/2) + self.cc[i]*self.d ct = round(ct,2) if ct > self.mayor: self.mayor = ct self.bondad.append(ct) def ruleta(self): totalbondad = 0 funcion = [] suma = 0 self.fprobabilidad = [] posicionmejor = 0 mejor = self.bondad[0] print ("Costo total para cada Q (bondad)") print (self.bondad,"\n") #sacar complemento self.mayor = self.mayor * 1.1 for i in range(self.npoblacion): n = self.mayor - self.bondad[i] totalbondad = totalbondad + n funcion.append(n) for i in range (self.npoblacion): #crear funcion de probabilidad con complemento suma = suma + funcion[i] n = (suma / totalbondad) * 100 n = round(n,2) self.fprobabilidad.append(n) print ("Función de probabilidad generada a partir de probabilidad de selección de cada Q") print (self.fprobabilidad) for i in range (self.npoblacion): if self.bondad[i] <= mejor: mejor = self.bondad[i] posicionmejor = i self.eliteq.append(self.poblacion[posicionmejor]) self.elitecosto.append(self.bondad[posicionmejor]) print("Q optimo de la generacion") print (self.eliteq) print ("Costo optimo de la generacion") print (self.elitecosto) aleatorio = [] for i in range (10000): #seleccion por ruleta aleatorio.append(i) nuevageneracion= [] s = "" while len(nuevageneracion) < self.npoblacion: esigual = True while esigual == True: a = random.choice(aleatorio) b = random.choice(aleatorio) if a!=b: esigual = False a = a/100 b = b/100 posiciona = 0 posicionb = 0 for j in range(self.npoblacion): #obtengo individuos a cruzar if j==0: if a <= self.fprobabilidad[j]: posiciona = j if b <= self.fprobabilidad[j]: posicionb = j else: if a <= self.fprobabilidad[j] and a > self.fprobabilidad[j-1]: posiciona = j if b <= self.fprobabilidad[j] and b > self.fprobabilidad[j-1]: posicionb = j #cruzar descendencia = [] padrea = self.genotipo[posiciona] padreb = self.genotipo[posicionb] for i in range(self.posiciones): descendencia.append(i) padrea = list(padrea) padreb = list(padreb) corte = random.randrange(self.posiciones) descendencia[:corte] = padrea[:corte] descendencia [corte:] = padreb[corte:] descendencia = s.join(descendencia) prueba = int(descendencia,2) if prueba <= self.limitesuperior and prueba >= self.limiteinferior: nuevageneracion.append(descendencia) self.genotipo = [] self.genotipo = nuevageneracion self.poblacion = [] for i in range (self.npoblacion): n = self.genotipo[i] n = int(n,2) self.poblacion.append(n) self.cc = [] for i in range (self.npoblacion): for j in range (self.ntramos): if self.poblacion[i] >= self.tramoinferior[j] and self.poblacion[i] <= self.tramosuperior[j]: self.cc.append(self.tramopreciocompra[j]) print ("poblacion nueva") print (self.poblacion) print ("Genotipo") print (self.genotipo) print ("Costo de compra") print (self.cc) def mutacion(self): for i in range(self.npoblacion): for j in range(self.posiciones): n = random.randint(0,99) if n == 0: aux = self.genotipo[i] aux = list(aux) if aux[j] == "0": aux[j] = "1" else: aux[j] = "0" s="" aux = s.join(aux) a = int(aux,2) if a>=self.tramoinferior[0] and a<= self.tramosuperior[self.ntramos-1]: print ("antes de mutacio ",self.genotipo[i]) self.genotipo[i] = aux print ("mutacion exitosa ",self.genotipo[i]) else: print("mutacion fallida") uno = algoritmoGenetico() uno.evaluar() for i in range (100): uno.ruleta() uno.mutacion() uno.evaluar() mejorq = uno.eliteq[0] mejorcosto = uno.elitecosto[0] for i in range(len(uno.eliteq)): if uno.elitecosto[i] < mejorcosto: mejorcosto = uno.elitecosto[i] mejorq = uno.eliteq[i] print ("El menor costo de inventario es ",mejorcosto," con una Q de ",mejorq)
14dc9c14dabdbc50f0924f6695e343c5832b4a4c
brunoatos/Aprendendo-programar-Python
/exercicio 16 com função del student pen test.py
368
3.9375
4
lista=['virus','notebook','desktop','S.O','Memoria'] print (lista) remover_lista=lista.pop() print (lista) print (remover_lista) #é simples, criei uma nova variavel e adicionei uma função pop() nela. depois printei a variavel lista depois de usar a função pop() e por ultimo printei a variavel que removi da lista.a função pop() remove o ultimo valor da lista.
2d3c4ff762249c691d6f3d6ac5831727a8b10856
brunoatos/Aprendendo-programar-Python
/exercicio 8 student pen test.py
248
4.03125
4
list=['maça','banana','pêra'] print (list[0]) '''nesse caso para imprimir uma lista de string , ela começa da esquerda para a direita com primeiro ordem 0 , tudo que está entre conchetes chama-se lista e cada string ou seja nomes com aspas .'''
9796ce266ad609f77291d57651f921f20800e65d
beenlyons/Ex_python
/Ex_collections/order_dict_test.py
264
3.515625
4
from collections import OrderedDict user_dict = OrderedDict() user_dict["asd"] = 0 user_dict["b"] = "2" user_dict["c"] = "3" user_dict["a"] = "1" # 删除第一个 print(user_dict.popitem(last=False)) # 移动到最后 user_dict.move_to_end("b") print(user_dict)
3ea969feb1deb687f7dd9e573bdb0c18d4a6bef1
maweefeng/baidubaikespider
/test/html_parse.py
1,309
3.609375
4
from bs4 import BeautifulSoup import re html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ soup = BeautifulSoup(html_doc,'html.parser',from_encoding='utf8') # 查找所有标签为a的节点 links = soup.find_all('a') for link in links: print(link.name,link['href'],link.get_text()) # 查找所有标签为a 链接符合http://example.com/lacie形式的节点 link_node = soup.find('a',href='http://example.com/lacie') print(link_node.name,link_node['href'],link_node.get_text()) # 正则表达式匹配 link_nodes = soup.find_all('a',href=re.compile(r'ill')) for link in link_nodes: print(link.name,link['href'],link.get_text()) #查找所有标签为div class 为abc 文字为python的节点 link_classnodes = soup.find_all('p',class_='story',text='...') for link in link_classnodes: print(link.name,link.get_text())
f6011e9bc0bbb8a46e698b872d66dce993462449
JarredAllen/EncryptionCracker---APCSP-Create-Task
/encryptions/dictionary.py
4,396
4.1875
4
''' The dictionary class, which handles verifying if something is a word, as well as how common the word is @author: Jarred ''' #from encryptions.base_class import base_class supported_languages=['english', 'french'] list_of_english_words=[] def build_list_of_english_words(): if list_of_english_words: return list_of_english_words #note: this file just contains a list of all English words with open('words.txt') as f: for line in f: list_of_english_words.append(line.strip()) return list_of_english_words list_of_common_english_words=[] def build_list_of_common_english_words(): if list_of_common_english_words: return list_of_common_english_words #note: This file contains a list of common English words (top 10K-ish) with open('common_words.txt') as f: for line in f: list_of_common_english_words.append(line.strip()) return list_of_common_english_words list_of_french_words=[] def build_list_of_french_words(): if list_of_french_words: return list_of_french_words #note: this file just contains a list of all French words with open('french_words.txt') as f: for line in f: list_of_french_words.append(line.strip()) return list_of_french_words list_of_common_french_words=[] def build_list_of_common_french_words(): if list_of_common_french_words: return list_of_common_french_words #note: This file contains a list of common French words (top 600-ish) with open('common_french_words.txt') as f: for line in f: list_of_common_french_words.append(line.strip()) return list_of_common_french_words class dictionary: def __init__(self, language='english'): """ Constructor for dictionary objects. Has one optional argument for the language that it is to decrypt in. If unspecified or left as None, it defaults to English. """ language=language.lower() if language==None or language=='english': self.words=build_list_of_english_words() self.common_words=build_list_of_common_english_words() elif language=='french': self.words=build_list_of_french_words() self.common_words=build_list_of_common_french_words() else: raise ValueError('Unrecognized or unsupported language') def get_words(self, reverse=False): if reverse: return self.reverse_words return self.words def get_common_words(self, reverse=False): if reverse: return self.reverse_common_words return self.common_words def is_word(self, word): return binary_search(word, self.words) def is_common_word(self, word): return binary_search(word, self.common_words) def get_score(self, word): word=word.strip() if self.is_common_word(word): return 2. if self.is_word(word): return 1. return -2 def binary_search(term, sequence): left=0 right=len(sequence) index=(left+right)//2 while left<right-1: if term==sequence[index]: return True elif term<sequence[index]: right=index else: left=index #print(sequence[index], left, right) index=(left+right)//2 return term==sequence[left] if __name__=='__main__': english=dictionary() french=dictionary('french') """ t=['a', 'b', 'c', 'd', 'f'] print(binary_search('a', t)) print(binary_search('b', t)) print(binary_search('c', t)) print(binary_search('d', t)) print(binary_search('e', t)) print(binary_search('f', t)) print(binary_search('ba', t)) """ """ def clear_dictionary_of_words_with_nonalphanumeric_characters(): words=[] with open('common_words.txt') as f: for line in f: line=line.strip() if not contains_nonalpha(line) and len(line)>0: words.append(line) words.sort() content='' for word in words: content+=word+'\n' #print(words) #print(content) with open('common_words.txt', 'w') as f: f.write(content) def contains_nonalpha(word): for i in word: if not i.isalpha(): return True return False clear_dictionary_of_words_with_nonalphanumeric_characters()"""
b9b33ab2d004d734e4c27fa5c53e2233dceb0589
agaevusal/base-of-python
/MyIterator.py
589
3.6875
4
class MyIterator: def __init__(self, lst): self.lst = lst self.i = 0 self.k = len(self.lst) - 1 def __next__(self): while True: if self.i <= self.k: if self.lst[self.i] % 2 != 0: self.i += 1 return self.lst[self.i - 1] else: self.i += 1 return 'not even' else: return 'the end!' def __iter__(self): return self x = MyIterator([1,2,3,4,5]) for i in x: print(i)
78d23605c09e0aff64a21f8fb8b8adc26ccd48ec
Fedor-Pomidor/primeri
/primer3.py
437
3.9375
4
import math x = float(input("Введите значение 'x'")) y = float(input("Введите значение 'y'")) z = float(input("Введите значение 'z'")) #вводите не меньше 4.4 if z >= 4.4: def primer1 (x, y, z): chislitel = math.sqrt(25 * ((x * y * math.sqrt(z - 4.4)) ** 2 + 5)) znamenatel = 8 + y return chislitel / znamenatel print(primer1(x, y, z))
b036a5e8f32b0b4921be8bd523a5ab5be07ed0f4
RyanTucker1/Tkinter
/playground.py
464
4.0625
4
from Tkinter import * #gives us access to everything in the Tkinter class root = Tk() #gives us a blank canvas object to work with root.title("Here Comes the Dong") button1 = Button(root, text="Button 1") button1.grid(row=1, column=1) entry1 = Entry(root) entry1.grid(row=1, column=0) label1 = Label(root, text="Owen Wilson", bg="pink",anchor=E) label1.grid(row=0, column=0, sticky=EW) mainloop() #causes the windows to display on the screen until program closes
da2230aea01a610ec306f52b65855d0fcc48d558
BenjaminSchubert/SysAdmin-scripts-for-linux
/pyDuplicate/filehandler.py
2,155
3.859375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ This file contains functions to handle files, list, order, and removing some """ from os import walk from os.path import join, isfile, getsize, isdir import logger import const def tree_walk_with_size(_dir): """ Takes a directory and returns a list of file with their weight :param _dir: the root directory where to list all files contained in it :return: list of tuple containing (file, file's size) """ files = [] for (dir_name, sub_dirs, file_names) in walk(_dir): sub_dirs[:] = [x for x in sub_dirs if x not in const.FOLDERS_NOT_TO_CHECK] for name in file_names: file_path = join(dir_name, name) if isfile(file_path) and not file_path.endswith(const.EXTENSIONS_NOT_TO_CHECK): files.append((file_path, getsize(file_path))) return files def order_files_by_size(weighted_files): """ Orders a list of files by their weight :param weighted_files: a list of tuples (file, file's size) :return: a dict with keys being file's size and values the file with that size """ dict_files = {} for file in weighted_files: if file[1] == 0: continue # we don't care about files of size 0 indices = file[1] if not indices in dict_files: dict_files[indices] = [file[0]] else: dict_files[indices].append(file[0]) return dict_files def handle_bad_folders(folders, force=False): """ Checks if every folder in the list given exists. If not : exits if force is false, else it is removed from the list :param folders: folders list to check :param force: boolean (default : False) :return: list of correct folders """ bad_folders = [str(x) for x in folders if not isdir(x)] if bad_folders and not force: logger().get_logger().error( "Some of the directories you gave are wrong, please check :\n {0}".format( '\n '.join(bad_folders))) exit(1) elif bad_folders and force: folders = [x for x in folders if x not in bad_folders] return folders
110e743b74b52c326956398c48bdcc4d5ef10902
kotsky/py-libs
/algorithms/merge/array_merge_algorithms.py
3,960
3.96875
4
"""Array Merge functions - merge_sorted_arrays(arrays) - to merge sorted arrays into one sorted """ # O(N*log(K) + K) Time / O(N + K) S # where N - total number of elements # K - number of subarrays def merge_sorted_arrays(arrays): if not len(arrays): return arrays # O(K) Time & Space def create_min_heap_from_first_element(arrays): min_heap = ModifiedMinHeap() for i in range(len(arrays)): # node_config = [initial_element, sub_array_idx, # initial_idx, sub_array_length] node_config = [arrays[i][0], i, 0, len(arrays[i])] min_heap.add_node(node_config) min_heap.head = min_heap.heap[0] return min_heap def merge_and_sort(arrays, min_heap): merged_array = [] while min_heap.head is not None: head = min_heap.head merged_array.append(head.value) head.idx += 1 if head.idx < head.limit: head.value = arrays[head.sub_array_idx][head.idx] min_heap.siftDown(0) min_heap.head = min_heap.heap[0] else: min_heap.removeHead() return merged_array class ModifiedMinHeap: class MinHeapNode: def __init__(self, config): value, sub_array_idx, idx, limit = config self.value = value self.sub_array_idx = sub_array_idx self.idx = idx self.limit = limit def __init__(self): self.heap = [] self.head = None def add_node(self, node_config): node = self.MinHeapNode(node_config) self.heap.append(node) self.sift_up(-1) def sift_down(self, start_index): heap = self.heap child_one_index = 2 * start_index + 1 child_two_index = 2 * start_index + 2 while child_one_index < len(heap): if child_two_index < len(heap): if heap[child_one_index].value <= heap[child_two_index].value and \ heap[start_index].value > heap[child_one_index].value: new_index = child_one_index elif heap[child_one_index].value > heap[child_two_index].value and \ heap[start_index].value > heap[child_two_index].value: new_index = child_two_index else: break else: if heap[start_index].value > heap[child_one_index].value: new_index = child_one_index else: break self.swap(start_index, new_index, heap) start_index = new_index child_one_index = 2 * start_index + 1 child_two_index = 2 * start_index + 2 def remove_head(self): if self.head is not None: if len(self.heap) > 1: self.swap(0, len(self.heap) - 1, self.heap) self.heap.pop() self.sift_down(0) self.head = self.heap[0] else: self.head = None self.heap.pop() def sift_up(self, idx): if idx < 0: idx = len(self.heap) + idx while idx > 0: parent_idx = (idx - 1) // 2 if self.heap[idx].value < self.heap[parent_idx].value: self.swap(idx, parent_idx, self.heap) idx = parent_idx else: break def swap(self, i, j, array): array[i], array[j] = array[j], array[i] search_heap = create_min_heap_from_first_element(arrays) merged_sorted_array = merge_and_sort(arrays, search_heap) return merged_sorted_array
c806d61916dedef457259a49a3a71b8a3d88479a
kotsky/py-libs
/data_structures/heaps/heaps_tree_implementation.py
4,503
4.0625
4
"""Min-Heap tree structure Thin Min-Heap implementation is based on pure binary tree structure with certain balancing optimisation by using additional attribute direction. Min-Heap methods: - class MinHeap() - Build Min-Heap from an any array with integers with a complexity O(N) Time / O(N) Space - peek() - check root of that heap - insert() - insert value - pop() - return and delete min head - is_empty() - check if heap is empty Example: INSERT = "insert" REMOVE = "remove" PEEK = "peek" BUILD = "build" def main(): min_heap = MinHeap() while 1: user_input = input() user_commands = user_input.split(" ") command = user_commands[0] try: value = int(user_commands[1]) except: value = None if command == INSERT: min_heap.insert(value) print("Added ", value) elif command == PEEK: print("Peek is ", min_heap.peek()) elif command == REMOVE: min_heap.pop() print("Removed. New peek is ", min_heap.peek()) elif command == BUILD: array = [48, 12, 24, 7, 8, -5, 24, 391, 24, 56, 2, 6, 8, 41] min_heap.build(array) min_heap.insert(9) min_heap.insert(-200) print(len(min_heap)) while not min_heap.is_empty(): output = min_heap.pop() print("Removed ", output) if __name__ == '__main__': # app.run(main) main() """ LEFT = 0 RIGHT = 1 class MinHeapNode: def __init__(self, value): self.value = value self.left = None self.right = None self.direction = LEFT def __str__(self): return repr(self.value) def flip_direction(self): self.direction = ~self.direction class MinHeap: def __init__(self, array=None): self.root = None self.count = 0 if array is not None: self.build(array) def build(self, array): for value in array: self.insert(value) def __len__(self): return self.count def __del__(self): pass def insert(self, value): def swap_values(node1, node2): node1.value, node2.value = node2.value, node1.value new_node = MinHeapNode(value) self.count += 1 if self.root is None: self.root = new_node return current_node = self.root is_completed = False while not is_completed: current_node.flip_direction() if current_node.value > new_node.value: swap_values(current_node, new_node) if current_node.direction == LEFT: if current_node.left is None: current_node.left = new_node is_completed = True else: current_node = current_node.left else: if current_node.right is None: current_node.right = new_node is_completed = True else: current_node = current_node.right def peek(self): return self.root def is_empty(self): return self.count == 0 def pop(self): if self.count == 0: return None self.count -= 1 value = self.root.value self.fix_tree() return value def fix_tree(self): def swap_values(node1, node2): node1.value, node2.value = node2.value, node1.value current_node = self.root parent_node = None current_node.value = None while current_node.left is not None or current_node.right is not None: if current_node.left is not None and current_node.right is not None: if current_node.left.value <= current_node.right.value: parent_node = current_node current_node = current_node.left else: parent_node = current_node current_node = current_node.right elif current_node.left is not None: parent_node = current_node current_node = current_node.left else: parent_node = current_node current_node = current_node.right swap_values(parent_node, current_node) if parent_node is None: self.root = None else: if parent_node.left == current_node: parent_node.left = None else: parent_node.right = None
a9aac54689126f3e08fe3fe9c1c751934a2704c5
kotsky/py-libs
/algorithms/sort/array_sort_algorithms.py
6,548
4.03125
4
""" In this sheet, sorted algorithms are implemented in the most optimal way. The following list: Merge Sort Heap Sort Quick Sort Selection Sort Insertion Sort Bubble Sort """ # Avg: Time O(N*log(N)) / Space O(N) # Worst: Time O(N*log(N)) / Space O(N) # Idea: # Create auxiliary array, where you can # store intermediate elements. # Recursively, divide array/subarrays until # you have only 1-2 elements, and then do # their swapping, and then merge (doMerge) # these subarrays on each recursive level. def mergeSort(array): def mergeSubarrays(merge_array, additional_array, start_idx, end_idx): if end_idx - start_idx < 1: return middle_idx = (end_idx + start_idx) // 2 mergeSubarrays(additional_array, merge_array, start_idx, middle_idx) mergeSubarrays(additional_array, merge_array, middle_idx + 1, end_idx) doMerge(merge_array, additional_array, start_idx, middle_idx + 1, end_idx) def doMerge(merge_array, additional_array, start_one, start_two, end_idx): p1 = start_one p2 = start_two p0 = p1 while p1 < start_two and p2 <= end_idx: if additional_array[p1] > additional_array[p2]: merge_array[p0] = additional_array[p2] p2 += 1 else: merge_array[p0] = additional_array[p1] p1 += 1 p0 += 1 while p1 < start_two: merge_array[p0] = additional_array[p1] p1 += 1 p0 += 1 while p2 <= end_idx: merge_array[p0] = additional_array[p2] p2 += 1 p0 += 1 if not len(array) or len(array) <= 1: return array else: merge_array = array additional_array = array.copy() mergeSubarrays(merge_array, additional_array, 0, len(array) - 1) return merge_array # Avg: Time O(N*log(N)) / Space O(1) # Worst: Time O(N*log(N)) / Space O(1) # Idea: # Convert array to min heap and use log(N) heap # property to find min N times of subarray N def heapSort(array): def buildHeap(array): for i in range(len(array) - 1, 0, -2): parent_idx = (i - 1) // 2 siftDown(array, parent_idx, len(array) - 1) return array def siftDown(array, parent_idx, end_idx): while parent_idx >= 0: child_one = 2 * parent_idx + 1 child_two = 2 * parent_idx + 2 if child_one > end_idx: break if child_two > end_idx: if array[parent_idx] < array[child_one]: swap(array, parent_idx, child_one) break if array[parent_idx] < max(array[child_one], array[child_two]): if array[child_one] >= array[child_two]: swap(array, parent_idx, child_one) parent_idx = child_one else: swap(array, parent_idx, child_two) parent_idx = child_two else: break if len(array) < 2: return array array = buildHeap(array) start_idx = 0 end_idx = len(array)-1 while (end_idx - start_idx) > 0: siftDown(array, start_idx, end_idx) swap(array, start_idx, end_idx) end_idx -= 1 return array # Avg: Time O(N*log(N)) / Space O(log(N)) # Worst: Time O(N^2) / Space O(log(N)) # Idea: # You have 3 pointers: pivot, left and right. # You compare left and right with pivot # and then swap left or right vs pivot accordingly, # depends on certain condition. Once you swapped, # you have subarrays from the left and from the # right respect to the pivot. Pivot element is in # a write order. Now, do quickSort for these # 2 subarrays. def quickSort(array): def sortHelper(array, start_idx, end_idx): if end_idx <= start_idx: return pivot = start_idx start_idx += 1 list_range = [pivot, end_idx] while end_idx >= start_idx: if array[start_idx] > array[pivot] > array[end_idx]: swap(array, start_idx, end_idx) if array[start_idx] <= array[pivot]: start_idx += 1 if array[end_idx] >= array[pivot]: end_idx -= 1 swap(array, pivot, end_idx) left_sub_isSmaller = list_range[0] - end_idx < end_idx+1, list_range[1] if left_sub_isSmaller: sortHelper(array, list_range[0], end_idx) sortHelper(array, end_idx+1, list_range[1]) else: sortHelper(array, end_idx+1, list_range[1]) sortHelper(array, list_range[0], end_idx) sortHelper(array, 0, len(array)-1) return array # Avg: Time O(N^2) / Space O(1) # Worst: Time O(N^2) / Space O(1) # Idea: # By traversing, we go through elements and do # swapping if the element before if greater than # the element after. If we do at least one swap, # then we do new traversing until there won't be # swaps. def bubbleSort(array): if not array: return None len_array = len(array) while True: was_swap = False index = 0 while index < (len_array - 1): if array[index] > array[index + 1]: swap(array, index, index + 1) was_swap = True index += 1 if was_swap is False: return array len_array -= 1 # Avg: Time O(N^2) / Space O(1) # Worst: Time O(N^2) / Space O(1) # Idea: # We try to insert elements before others, if they # are smaller. def insertionSort(array): for i in range(1, len(array)): second = i while second != 0: if array[second] < array[second - 1]: swap(array, second, second-1) second -= 1 else: break return array # Avg: Time O(N^2) / Space O(1) # Worst: Time O(N^2) / Space O(1) # Idea: # Every iteration we search for the smallest number # in remaining subarray, and then do swap with # respective place in the array. def selectionSort(array): for j in range(len(array) - 1): upper_pointer = j lower_pointer = j for i in range(lower_pointer, len(array)): if array[upper_pointer] > array[i]: upper_pointer = i swap(array, lower_pointer, upper_pointer) return array # Simple swap of elements inside of array def swap(array, idx_one, idx_two): array[idx_one], array[idx_two] = array[idx_two], array[idx_one]
6c9fc9c03b1d6ab243793f33bc481c57fae9b639
cardboardcode/pycrypt
/src/parserlib.py
4,209
3.9375
4
import sys import os def encryptFile(st, text): for letter in text: if (letter == 'a'): st+=str('1') if (letter == 'b'): st+=str('2') if (letter == 'c'): st+=str('3') if (letter == 'd'): st+=str('4') if (letter == 'e'): st+=str('5') if (letter == 'f'): st+=str('6') if (letter == 'g'): st+=str('7') if (letter == 'h'): st+=str('8') if (letter == 'i'): st+=str('9') if (letter == 'j'): st+=str('a') if (letter == 'k'): st+=str('b') if (letter == 'l'): st+=str('c') if (letter == 'm'): st+=str('d') if (letter == 'n'): st+=str('e') if (letter == 'o'): st+=str('f') if (letter == 'p'): st+=str('g') if (letter == 'q'): st+=str('h') if (letter == 'r'): st+=str('i') if (letter == 's'): st+=str('j') if (letter == 't'): st+=str('k') if (letter == 'u'): st+=str('l') if (letter == 'v'): st+=str('m') if (letter == 'w'): st+=str('n') if (letter == 'x'): st+=str('o') if (letter == 'y'): st+=str('p') if (letter == 'z'): st+=str('q') if (letter == ' '): st+=str(' ') #Capital Letters Lexicon start if (letter == 'A'): st+=str('Z') if (letter == 'B'): st+=str('Y') if (letter == 'C'): st+=str('X') if (letter == 'D'): st+=str('W') if (letter == 'E'): st+=str('V') if (letter == 'F'): st+=str('U') if (letter == 'G'): st+=str('T') if (letter == 'H'): st+=str('S') if (letter == 'I'): st+=str('R') if (letter == 'J'): st+=str('Q') if (letter == 'K'): st+=str('P') if (letter == 'L'): st+=str('O') if (letter == 'M'): st+=str('N') if (letter == 'N'): st+=str('M') if (letter == 'O'): st+=str('L') if (letter == 'P'): st+=str('K') if (letter == 'Q'): st+=str('J') if (letter == 'R'): st+=str('I') if (letter == 'S'): st+=str('H') if (letter == 'T'): st+=str('G') if (letter == 'U'): st+=str('F') if (letter == 'V'): st+=str('E') if (letter == 'W'): st+=str('D') if (letter == 'X'): st+=str('C') if (letter == 'Y'): st+=str('B') if (letter == 'Z'): st+=str('A') return st def decryptFile(st, text): for letter in text: if (letter == '1'): st+=str('a') if (letter == '2'): st+=str('b') if (letter == '3'): st+=str('c') if (letter == '4'): st+=str('d') if (letter == '5'): st+=str('e') if (letter == '6'): st+=str('f') if (letter == '7'): st+=str('g') if (letter == '8'): st+=str('h') if (letter == '9'): st+=str('i') if (letter == 'a'): st+=str('j') if (letter == 'b'): st+=str('k') if (letter == 'c'): st+=str('l') if (letter == 'd'): st+=str('m') if (letter == 'e'): st+=str('n') if (letter == 'f'): st+=str('o') if (letter == 'g'): st+=str('p') if (letter == 'h'): st+=str('q') if (letter == 'i'): st+=str('r') if (letter == 'j'): st+=str('s') if (letter == 'k'): st+=str('t') if (letter == 'l'): st+=str('u') if (letter == 'm'): st+=str('v') if (letter == 'n'): st+=str('w') if (letter == 'o'): st+=str('y') if (letter == 'p'): st+=str('z') if (letter == ' '): st+=str(' ') #Capital Letters Lexicon start if (letter == 'A'): st+=str('Z') if (letter == 'B'): st+=str('Y') if (letter == 'C'): st+=str('X') if (letter == 'D'): st+=str('W') if (letter == 'E'): st+=str('V') if (letter == 'F'): st+=str('U') if (letter == 'G'): st+=str('T') if (letter == 'H'): st+=str('S') if (letter == 'I'): st+=str('R') if (letter == 'J'): st+=str('Q') if (letter == 'K'): st+=str('P') if (letter == 'L'): st+=str('O') if (letter == 'M'): st+=str('N') if (letter == 'N'): st+=str('M') if (letter == 'O'): st+=str('L') if (letter == 'P'): st+=str('K') if (letter == 'Q'): st+=str('J') if (letter == 'R'): st+=str('I') if (letter == 'S'): st+=str('H') if (letter == 'T'): st+=str('G') if (letter == 'U'): st+=str('F') if (letter == 'V'): st+=str('E') if (letter == 'W'): st+=str('D') if (letter == 'X'): st+=str('C') if (letter == 'Y'): st+=str('B') if (letter == 'Z'): st+=str('A') return st
745d6348846a729ba22f518714f39d8f0deb861d
Vrndavana/Sprint-Challenge--Intro-Python
/src/cityreader/cityreader.py
872
3.859375
4
import csv cities = [] class City: def __init__(self, name,lat,lon): self.name = name self.lat = lat self.lon = lon def cityreader(cities=[]): with open("cities.csv") as p: city_parser = csv.DictReader(p, delimiter= ",", quotechar = "|") for row in city_parser: city = City(row["city"], float(row["lat"]), float(row["lng"])) cities.append(city) # TODO Implement the functionality to read from the 'cities.csv' file # For each city record, create a new City instance and add it to the # `cities` list # so call the csv function then pass dth a tex tfile i want to iterate teham ti aute #iterate the fucntion putting the for loop insife of the cities list. return cities cityreader(cities) # Print the list of cities (name, lat, lon), 1 record per line. for c in cities: print(c) print(c.name, c.lat, c.lon)
be5a272602da6854598512c0b5a9b34d80c39a7c
nicovandenhooff/project-euler
/solutions/p22.py
3,229
3.59375
4
# Project Euler: Problem 22 # Names scores # Author: Nico Van den Hooff # Github: https://github.com/nicovandenhooff/project-euler # Problem: https://projecteuler.net/problem=22 # Note: I implement a vectorized implementation with NumPy for this problem. # Specifically, I first create a vector for each name, where the vectors # shape is (26, 1). Each position in the vector is then filled with the # number of times a letter shows up in a given name. I then combine all # of the vectors into a names matrix, which is of shape (5163, 26). Next, # I simply multiply the matrix by a points vector of shape (26, 1), which # gives us a vector of shape (5163, 1) that represents the points value # for each persons name. Finally, I multiply the points value vector by # a "position" vector of shape (5163, 1) that represents each position a # name has in the list (element-wise multiplication here). To get the # answer, the sum is taken over the final vector. import string import numpy as np import csv # path to the names text file PATH = "./project-euler/data/p022_names.txt" def get_names_list(path): """Creates a sorted list of names and a "positions" vector. Parameters ---------- path : str The path of the names .txt file. Returns ------- names, positions : list of str, numpy array The names list and positions vector. The positions vector has shape (1, number of names). """ # the names list names = [] # read in names with open(path) as f: for row in csv.reader(f): names.extend(row) # sort names names.sort() # create positions vector positions = np.arange(1, len(names) + 1) return names, positions def create_names_matrix(names, vector_shape=(26,), start=1, stop=27): """Creates a names matrix and points vector. Parameters ---------- names : list of str The list of names. vector_shape : int, optional The shape of each name vector, by default (26,). start : int, optional Starting points value (inclusive), by default 1. stop : int, optional Ending points value (exclusive), by default 27. Returns ------- names_matrix, points : 2D numpy array, 1D numpy array The names matrix and points vector. """ # to store the vectorized names vectorized_names = [] # the points vector points = np.arange(start, stop) # dictionary mapping letters to points char_to_points = dict(zip(string.ascii_uppercase, range(start, stop))) # vectorize each name for name in names: vector = np.zeros(vector_shape) for char in name: # have to be careful with indexing here index = char_to_points[char] vector[index - 1] += 1 # append each name to vectorized names list vectorized_names.append(vector) # create names matrix from vectors names_matrix = np.array(vectorized_names) return names_matrix, points names, positions = get_names_list(PATH) names_matrix, points = create_names_matrix(names) print(np.sum(np.matmul(names_matrix, points) * positions))
f9fa0a430f651302cd9cce0092eaa8fadb18930e
nicovandenhooff/project-euler
/solutions/p48.py
1,016
3.703125
4
# Project Euler: Problem 48 # Self powers # Author: Nico Van den Hooff # Github: https://github.com/nicovandenhooff/project-euler # Problem: https://projecteuler.net/problem=48 DIGITS = 10 def self_powers_sum(start, stop): """Calculates the sum of a series of self powers. Parameters ---------- start : int The first number in the series. stop : int The last number in the series. Returns ------- total : int The sum of the series of self powers. """ total = 0 # calculate total for i in range(start, stop): total += i ** i return total def last_digits(n, length): """Returns the last k digits of a number. Parameters ---------- n : int The number. length : int The last k number of digits. Must be <= n Returns ------- [description] """ digits = str(total)[-length:] return digits total = self_powers_sum(1, 1001) digits = last_digits(total, DIGITS) print(digits)
0a5c041eb9e714cdda7ffc9df287233452add307
caiorss/OSlash
/oslash/applicative.py
1,383
3.96875
4
from abc import ABCMeta, abstractmethod class Applicative(metaclass=ABCMeta): """Applicative functors are functors with some extra properties. Most importantly, they allow you to apply functions inside the functor (hence the name). """ @abstractmethod def apply(self, something: "Applicative") -> "Applicative": """(<*>) :: f (a -> b) -> f a -> f b. Apply (<*>) is a beefed up fmap. It takes a functor value that has a function in it and another functor, and extracts that function from the first functor and then maps it over the second one. """ return NotImplemented def __mul__(self, something: "Applicative"): """(<*>) :: f (a -> b) -> f a -> f b. Provide the * as an infix version of apply() since we cannot represent the Haskell's <*> operator in Python. """ return self.apply(something) def lift_a2(self, func, b): """liftA2 :: (Applicative f) => (a -> b -> c) -> f a -> f b -> f c.""" return func % self * b @classmethod def pure(cls, x: "Callable") -> "Applicative": """The Applicative functor constructor. Use pure if you're dealing with values in an applicative context (using them with <*>); otherwise, stick to the default class constructor. """ return cls(x)
3169664c0f8cd32d7389d4dbb2a907fb916be13e
bogdanf555/randomNumberGuessingGame
/bin/functionalities.py
8,134
3.875
4
import ast # difficulty levels for the game difficultyPool = ("easy", "normal", "hard", "impossible") # dictionary that associates a level of difficulty to # the proper range of guess, the number of attempts and # the maximum value that a secret number can get # format of dictionary : difficulty - range, attempts, maximum number mode = { "easy" : (20, 4, 99), "normal" : (100, 6, 999), "hard" : (500, 8, 999), "impossible" : (1000, 9, 9999) } #displaying the default welcoming message def welcomingMessage(): try: welcomeFile = open("..\\data\\welcomingMessage.txt", "r") except: welcomeFile = open("data\\welcomingMessage.txt", "r") welcomeMessage = welcomeFile.read() welcomeFile.close() print(welcomeMessage) # record the play again decision def waitOnReplay(): retry = None while True: retry = input("Would you like to play again? (yes/no)\n") if retry == "yes": print("Great!") break elif retry == "no": print("Well, see ya then!") break else: print("I'm afraid I can't understand you, please tell me yes or no.") return retry # present the set of rules to the player def displayRules(): try: rulesFile = open("..\\data\\rules.txt", "r") except: rulesFile = open("data\\rules.txt", "r") rulesMessage = rulesFile.read() rulesFile.close() print(rulesMessage) #displayes the help guide of the the game def displayHelp(): try: helpFile = open("..\\help.txt", "r") except: helpFile = open("help.txt", "r") helpMessage = helpFile.read() print(helpMessage) helpFile.close() # displayes the Highscore table to the user def displayHighscoreBoard(): highscoreDict = readHighscoreFile() board = None while True: print("What leaderboard are you interested in?") difficultyRequested = input("(easy, normal, hard, impossible)\n") if difficultyRequested in ("easy", "normal", "hard", "impossible"): board = highscoreDict[difficultyRequested] break else: print("I'm afraid I did not get that.") if board[1][0] == '-': print("Nobody registered their highscore yet for this difficulty.") else: print("Place | Name | Attempts") for index in board: if board[index][0] == '-': break #print(str(index) + ".", board[index][0], str(board[index][1])) print("{:5.5} | {:16.16} | {}".format(str(index) + ".", board[index][0], str(board[index][1]))) # hints to display for the player # start and end represent the interval in which the number was choosen # attempts represents the number of trie to give to the player def generatedInformation(start, end, attempts): print("The number has been choosen. It is a natural number between {} and {}.".format(start, end)) print("You have {} attempts to guess the number.".format(attempts)) print("Now let's see if you can guess it.") # message to display when losing the game # number reveals the secret random number to the player def failureMessage(number): print("I'm sorry, maybe you need more training or luck.") print("The number to be guessed was {}.".format(number)) # sets the difficuly of the game based on player input def setDifficulty(): while True: print("Choose the desired difficulty to play:") difficulty = input("(easy, normal, hard, impossible)\n") if difficulty not in difficultyPool: print("Please try again, you misspelled the difficulty.") else: try: difficultyFile = open("..\\data\\difficulty.txt", "w") except: difficultyFile = open("data\\difficulty.txt", "w") difficultyFile.write(difficulty) difficultyFile.close() print("Difficulty successfully changed to {}.".format(difficulty)) break # gets the default difficulty from the difficulty.txt file def getDifficulty(): try: difficultyFile = open("..\\data\\difficulty.txt", "r") except: difficultyFile = open("data\\difficulty.txt", "r") difficulty = difficultyFile.read() difficultyFile.close() return difficulty # reads the highscore file and returns a dictionary containing # highscore information def readHighscoreFile(): try: highscoreFile = open("..\\data\\highscore.txt", "r") except: highscoreFile = open("data\\highscore.txt", "r") highscoreString = highscoreFile.read() highscoreFile.close() highscoreDict = ast.literal_eval(highscoreString) return highscoreDict # receives as input a dicitionary containing the highscore board # writes the new highscore board to the file def writeHighscoreFile(highscore): while True: try: highscoreFile = open("..\\data\\highscore.txt", "w") except: highscoreFile = open("data\\highscore.txt", "w") break if highscoreFile == None: print("Error : Please close the highscore.txt file on your computer.") print("Then retry to register your highscore.") while True: response = input("Ready? (yes, when you successfully closed the file)\n") if response == "yes": break highscoreFile.write(str(highscore)) highscoreFile.close() print("Congratulations, you're on the leaderboards!") # returns true if the comparison of the highscore file # and the template highscore file has as result an equality # false otherwise def isHighscoreFileEmpty(): try: highscoreFile = open("..\\data\\highscore.txt", "r") except: highscoreFile = open("data\\highscore.txt", "r") highscoreString = highscoreFile.read() highscoreFile.close() return len(highscoreString) == 0 # deletes all the highscores recorded in the highscore.txt # file by replacing its content with the template located # in the highscoreTemplate.txt def eraseHighscoreFile(display): try: try: template = open("..\\data\\highscoreTemplate.txt", "r") highscoreFile = open("..\\data\\highscore.txt", "w") except: template = open("data\\highscoreTemplate.txt", "r") highscoreFile = open("data\\highscore.txt", "w") templateString = template.read() highscoreFile.write(templateString) template.close() highscoreFile.close() if display: print("All recorded highscores have been removed successfully.") except: print("An error occured, please restart the game.") # the process in which the player tries to guess the secret number # returns a boolean that is used to check if the number was guessed # and a number which represents the score (number of attemps at guessing # used by the player) def guessingProcess(attempts, secretNumber): guessed = False tries = attempts for guess in range(1, attempts + 1): while True: try: numberGiven = int(input("Make your choice: ({} more attempts)\n".format(attempts + 1 - guess))) break except ValueError: print("Non numbers values are not accepted, please retry.") if numberGiven == secretNumber: print("Congratulations, you guessed it in {} attempts.".format(guess)) guessed = True tries = guess break elif guess < attempts: if numberGiven < secretNumber: print("The secret number is greater.") else: print("The secret number is lower.") return guessed, tries # this function copies the highscore file content into a dictionary # then modifies it in order to include the new record inside it # as parameters : difficulty will select which leaderboard needs to be modified # and attempts will be the new record established by the player # returns the hole new dictionary of highscores def recordHighscore(difficulty, attempts): highscoreBoards = readHighscoreFile() highscoreDict = highscoreBoards[difficulty] stack = [] key = 5 while key > 0 and attempts < highscoreDict[key][1]: if highscoreDict[key][0] != '-': stack.append(highscoreDict[key]) key -= 1 if key < 5: print("Your score is eligible for leaderboards recording.") while True: name = input("Please give me your name to put it in the hall of fame:\n(max 16 characters)\n") if name == "-" or len(name) > 16: print('The provided name is no a legal one, please input another.') else: break highscoreDict[key + 1] = (name, attempts) key += 2 while stack and key < 6: highscoreDict[key] = stack.pop(-1) key += 1 highscoreBoards[difficulty] = highscoreDict else: highscoreBoards = None del stack return highscoreBoards
237e8e64ed9f6967042daee49a8b0f72c64e63a0
moses4real/python
/Conditionals/For Loop.py
109
3.515625
4
Emails = ['Adewarasalavtion56@gmail.com','Oluwadamilare.m@yhaoo.com','Oluwadamilaremoses56@gmail.com'] for item in Emails: if 'gmail' in item: print(item)
3c1956e8a1f44ea31ff37e0a78e965bd4ae05b28
Menelaos92/Library-Management-System
/frontend.py
6,418
3.921875
4
from tkinter import * import backend def view_command(): list1.delete(0,END) # Deleting everything from start to end. for count, row in enumerate(backend.view_all()): list1.insert(END,(count+1,row)) # The first argument sets the position where its going to get settled the incoming string inside the view box, e.g. 0,1,2... END. # print(count+1) def search_command(): list1.delete(0,END) for row in backend.search(title_text_input.get(),author_text_input.get(),year_text_input.get(),isbn_text_input.get()): # Below, the arguments used in entries are defined as string objects using the method StringVar() and not as simple strings. So to get a simple string and use it in the backend.search() function as needed, there must be appended in the arguments the get() method which produces a simple string. list1.insert(END,row) def add_command(): backend.insert(title_text_input.get(),author_text_input.get(),year_text_input.get(),isbn_text_input.get()) # This inserts the inputed arguments inside the database table list1.delete(0,END) list1.insert(END,(title_text_input.get(),author_text_input.get(),year_text_input.get(),isbn_text_input.get())) # while this inserts them in to the view box of the app. # Also note that the arguments are inputed inside brackets as a single value, as a result in the output list we take one line of string and not many as the number of the imported arguments. def delete_command(): index_of_listbox=list1.curselection()[0] # Using this to get the number of the selected line of the listbox. index_of_database=list1.get(index_of_listbox)[1][0] # Using this to get the the number of line which is registered in the database. (content enumeration: database table different from listbox) backend.delete(index_of_database) list1.delete(0,END) for count, row in enumerate(backend.view_all()): # Updating the listbox after deleting list1.insert(END,(count+1,row)) # print(index_of_database) def update_command(): # list1.delete(0,END) index_of_listbox=list1.curselection()[0] # Using this to get the number of the selected line of the listbox. index_of_database=list1.get(index_of_listbox)[1][0] # Using this to get the the number of line which is registered in the database. (for content enumeration: database table different from listbox) backend.update(index_of_database,title_text_input.get(),author_text_input.get(),year_text_input.get(),isbn_text_input.get()) list1.delete(0,END) for count, row in enumerate(backend.view_all()): # Updating the listbox after updating the database. list1.insert(END,(count+1,row)) # print(index_of_database) def fill_entries(evt): # Fill entries with info form the selected row. Connected with list1.bind() method in Listbox sector below. # Note here that Tkinter passes an event object to fill_entries(). In this exapmle the event is the selection of a row in the listbox. try: index_of_listbox=list1.curselection()[0] index_of_database=list1.get(index_of_listbox) e1.delete(0,END) e1.insert(END, index_of_database[1][1]) # Here the use of try and except block, excepts the error produced when clicking inside an empty listbox. e2.delete(0,END) # The <<index_of_listbox=list1.curselection()[0]>> gives a list from which we took the first object. So when the listbox is empty we will take an empty list with no objects which produces an error. e2.insert(END, index_of_database[1][2]) e3.delete(0,END) e3.insert(END, index_of_database[1][3]) e4.delete(0,END) e4.insert(END, index_of_database[1][4]) # print(index_of_database[1][2]) except IndexError: pass def clean_entries_command(): e1.delete(0,END) e2.delete(0,END) e3.delete(0,END) e4.delete(0,END) ########################################### # Creation of GUI and its elements elements ########################################### # All the element alligning happens inside a grid. # Each element declares its own position inside the grid. # Creating a window object window=Tk() # window.create_window(height=100, width=100) # Window title window.wm_title('Book Library') # Labels l1=Label(window,text="Title") l1.grid(row=1,column=0) l2=Label(window,text="Author") l2.grid(row=2,column=0) l3=Label(window,text="Year") l3.grid(row=3,column=0) l4=Label(window,text="ISBN") l4.grid(row=4,column=0) #Entries title_text_input=StringVar() e1=Entry(window,textvariable=title_text_input) e1.grid(row=1,column=1) author_text_input=StringVar() e2=Entry(window,textvariable=author_text_input) e2.grid(row=2,column=1) year_text_input=StringVar() e3=Entry(window,textvariable=year_text_input) e3.grid(row=3,column=1) isbn_text_input=StringVar() e4=Entry(window,textvariable=isbn_text_input) e4.grid(row=4,column=1) #ListBox list1=Listbox(window,height=10,width=90,highlightcolor='green',selectbackground='green') list1.grid(row=1,column=2,rowspan=4,columnspan=6) list1.bind('<<ListboxSelect>>', fill_entries) # The fill_entries function is going to be executed when a row of the listbox is selected. Check for more http://www.tcl.tk/man/tcl8.5/TkCmd/event.htm#M41] #Scrollbars # sb1=Scrollbar(window) # sb1.grid(row=2,column=2,rowspan=6) # # list1.configure(yscrollcommand=sb1.set) # sb1.configure(command=list1.yview) #Buttons b1=Button(window,text="View All", width=14, command=view_command) # Using the function without brackets to execute it when the button is pushed without waiting this line of the script gets read. b1.grid(row=0,column=2) b2=Button(window,text="Search Entry", width=14, command=search_command) b2.grid(row=0,column=3) b3=Button(window,text="Add Entry", width=14, command=add_command) b3.grid(row=0,column=4) b4=Button(window,text="Update", width=14, command=update_command) b4.grid(row=0,column=5) b5=Button(window,text="Delete", width=14, command=delete_command) b5.grid(row=0,column=6) b6=Button(window,text="Close", width=4, command=window.destroy) b6.grid(row=0,column=0) b7=Button(window,text="Clean", width=15, command=clean_entries_command) b7.grid(row=0,column=1) # Show created window with its contained elements window.mainloop()
7c5abeb358b5790cff1bdfbf801c5093fa286443
SavinKumar/Python_lib
/Original files/Library.py
34,819
3.734375
4
from tkinter import * import sqlite3 import getpass from functools import partial from datetime import date conn = sqlite3.connect('orgdb.sqlite') cur = conn.cursor() def passw(): pa=getpass.getpass() passwo='seKde7sSG' print('Entered password is of ',len(pa),' characters, To continue press Enter otherwise Enter the passwords again') s=input() while s: print('Enter the correct password again: ') pa=getpass.getpass() print('Entered password is of ',len(pa),' characters, To continue press Enter otherwise Enter the passwords again') s=input() if pa==passwo: return 1; else: return 0; def p_exit(): exit() def p_add1(): add1=Tk() add1.title("Add records") add1.geometry("900x300") def p_ad(): i=int(E_2.get()) cur.execute('''INSERT OR IGNORE INTO Records('Roll_no') VALUES (?)''',(i,)) conn.commit() L_ = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = E_2.get()+" Added") L_.place(x=10,y=150) L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Roll Number to add: ") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=5,bg='Yellow',font=16, text = "Add",command = p_ad) B_1.place(x=350,y=100) add1.mainloop() def p_addrng(): add1=Tk() add1.title("Add records") add1.geometry("900x300") def p_ad(): i=int(E_2.get()) j=int(E_3.get()) for k in range(i,j+1): cur.execute('''INSERT OR IGNORE INTO Records('Roll_no') VALUES (?)''',(k,)) conn.commit() L_ = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = str(j-i+1)+" Recods Added") L_.place(x=10,y=250) L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Initial Roll number") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) L2 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Final Roll number") L2.place(x=50,y=100) E_3 = Entry(add1,font=16,textvariable = c) E_3.place(x=410,y=100) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=5,bg='Yellow',font=16, text = "Add",command = p_ad) B_1.place(x=350,y=190) add1.mainloop() def p_del1(): add1=Tk() add1.title("Delete records") add1.geometry("900x300") def p_ad(): i=int(E_2.get()) cur.execute('''DELETE FROM Records where Roll_no = ?''',(i,)) conn.commit() L_ = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = E_2.get()+" Deleted") L_.place(x=10,y=150) L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Roll Number to delete: ") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=5,bg='Yellow',font=16, text = "Delete",command = p_ad) B_1.place(x=350,y=100) add1.mainloop() def p_delrng(): add1=Tk() add1.title("Delete records") add1.geometry("900x300") def p_ad(): i=int(E_2.get()) j=int(E_3.get()) for k in range(i,j+1): cur.execute('''DELETE FROM Records where Roll_no = ?''',(k,)) conn.commit() L_ = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = str(j-i+1)+" Recods Deleted") L_.place(x=10,y=250) L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Initial Roll number") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) L2 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Final Roll number") L2.place(x=50,y=100) E_3 = Entry(add1,font=16,textvariable = c) E_3.place(x=410,y=100) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=5,bg='Yellow',font=16, text = "Delete",command = p_ad) B_1.place(x=350,y=190) add1.mainloop() def p_issue(): add1=Tk() add1.title("Issue Books") add1.geometry("900x900") def p_book(): i=int(E_2.get()) row =conn.execute('''select * from Records where Roll_no = ?''',(i,)) book1 = 0 book2 = 0 book3 = 0 book4 = 0 book5 = 0 for rec in row: book1=rec[1] book2=rec[2] book3=rec[3] book4=rec[4] book5=rec[5] break mpty=0 if book1==0: mpty+=1 if book2==0: mpty+=1 if book3==0: mpty+=1 if book4==0: mpty+=1 if book5==0: mpty+=1 tt='You can issue '+str(mpty)+' number of books only as per the rule.' def p_lock(): i=int(E_2.get()) row =conn.execute('''select * from Records where Roll_no = ?''',(i,)) book1 = 0 book2 = 0 book3 = 0 book4 = 0 book5 = 0 for rec in row: book1=rec[1] book2=rec[2] book3=rec[3] book4=rec[4] book5=rec[5] break b1=E_3.get() b2=E_4.get() b3=E_5.get() b4=E_6.get() b5=E_7.get() aaa=0 if b1=="": aaa+=1 if b2=="": aaa+=1 if b3=="": aaa+=1 if b4=="": aaa+=1 if b5=="": aaa+=1 L8 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Books for issue= "+str(5-aaa)) L8.place(x=50,y=510) aaa=5-aaa lst=[] if aaa==5: lst.append(b1) lst.append(b2) lst.append(b3) lst.append(b4) lst.append(b5) elif aaa==4: lst.append(b1) lst.append(b2) lst.append(b3) lst.append(b4) elif aaa==3: lst.append(b1) lst.append(b2) lst.append(b3) elif aaa==2: lst.append(b1) lst.append(b2) elif aaa==1: lst.append(b1) for j in range(len(lst)): aaa-=1 if book1==0: book1=lst[j] di=date.today().strftime("%d-%m-%Y") conn.execute('''UPDATE Records set book1=? where Roll_no=?''',(lst[j],i,)) conn.execute('''UPDATE Records set DdI1=? where Roll_no=?''',(di,i)) conn.commit() elif book2==0: book2=lst[j] di=date.today().strftime("%d-%m-%Y") conn.execute('''UPDATE Records set book2=? where Roll_no=?''',(lst[j],i,)) conn.execute('''UPDATE Records set DdI2=? where Roll_no=?''',(di,i)) conn.commit() elif book3==0: book3=lst[j] di=date.today().strftime("%d-%m-%Y") conn.execute('''UPDATE Records set book3=? where Roll_no=?''',(lst[j],i,)) conn.execute('''UPDATE Records set DdI3=? where Roll_no=?''',(di,i)) conn.commit() elif book4==0: book4=lst[j] di=date.today().strftime("%d-%m-%Y") conn.execute('''UPDATE Records set book4=? where Roll_no=?''',(lst[j],i,)) conn.execute('''UPDATE Records set DdI4=? where Roll_no=?''',(di,i)) conn.commit() elif book5==0: book5=lst[j] di=date.today().strftime("%d-%m-%Y") conn.execute('''UPDATE Records set book5=? where Roll_no=?''',(lst[j],i,)) conn.execute('''UPDATE Records set DdI5=? where Roll_no=?''',(di,i)) conn.commit() L9 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Books issued= "+str(len(lst))) L9.place(x=50,y=570) L2 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = tt) L2.place(x=50,y=180) L3 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book1") L3.place(x=50,y=260) E_3 = Entry(add1,font=16) E_3.place(x=410,y=260) L4 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book2") L4.place(x=50,y=310) E_4 = Entry(add1,font=16) E_4.place(x=410,y=310) L5 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book3") L5.place(x=50,y=360) E_5 = Entry(add1,font=16) E_5.place(x=410,y=360) L6 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book4") L6.place(x=50,y=410) E_6 = Entry(add1,font=16) E_6.place(x=410,y=410) L7 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book5") L7.place(x=50,y=460) E_7 = Entry(add1,font=16) E_7.place(x=410,y=460) B_2 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=5,bg='Yellow',font=16, text = "Book",command = p_lock) B_2.place(x=350,y=510) L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Roll number") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=10,bd=5,bg='Yellow',font=16, text = "Continue",command = p_book) B_1.place(x=350,y=100) def p_delete(): add1=Tk() add1.title("Return book") add1.geometry("900x900") def p_del(): i=int(E_2.get()) row =conn.execute('''select * from Records where Roll_no = ?''',(i,)) book1 = 0 book2 = 0 book3 = 0 book4 = 0 book5 = 0 for rec in row: book1=rec[1] book2=rec[2] book3=rec[3] book4=rec[4] book5=rec[5] break strr="" if book1!=0: strr=strr+str(book1)+',' if book2!=0: strr=strr+str(book2)+',' if book3!=0: strr=strr+str(book3)+',' if book4!=0: strr=strr+str(book4)+',' if book5!=0: strr=strr+str(book5) strr='You have these books issued '+strr def p_cal(): i=int(E_2.get()) row =conn.execute('''select * from Records where Roll_no = ?''',(i,)) book1 = 0 book2 = 0 book3 = 0 book4 = 0 book5 = 0 for rec in row: book1=rec[1] book2=rec[2] book3=rec[3] book4=rec[4] book5=rec[5] d1=rec[6] d2=rec[7] d3=rec[8] d4=rec[9] d5=rec[10] break b1=E_3.get() b2=E_4.get() b3=E_5.get() b4=E_6.get() b5=E_7.get() aaa=0 if b1=="": aaa+=1 if b2=="": aaa+=1 if b3=="": aaa+=1 if b4=="": aaa+=1 if b5=="": aaa+=1 aaa=5-aaa lst=[] if aaa==5: lst.append(int(b1)) lst.append(int(b2)) lst.append(int(b3)) lst.append(int(b4)) lst.append(int(b5)) elif aaa==4: lst.append(int(b1)) lst.append(int(b2)) lst.append(int(b3)) lst.append(int(b4)) elif aaa==3: lst.append(int(b1)) lst.append(int(b2)) lst.append(int(b3)) elif aaa==2: lst.append(int(b1)) lst.append(int(b2)) elif aaa==1: lst.append(int(b1)) dys_free=0 total=0 for j in range(len(lst)): if book1==lst[j]: r_dat=date.today() a=int(d1[6:]) b=int(d1[3:5]) c=int(d1[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>dys_free: dys=dys-dys_free else: dys=0 total+=0.50*dys elif book2==lst[j]: r_dat=date.today() a=int(d2[6:]) b=int(d2[3:5]) c=int(d2[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>dys_free: dys=dys-dys_free else: dys=0 total+=0.50*dys elif book3==lst[j]: r_dat=date.today() a=int(d3[6:]) b=int(d3[3:5]) c=int(d3[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>dys_free: dys=dys-dys_free else: dys=0 total+=0.50*dys elif book4==lst[j]: r_dat=date.today() a=int(d4[6:]) b=int(d4[3:5]) c=int(d4[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>dys_free: dys=dys-dys_free else: dys=0 total+=0.50*dys elif book5==lst[j]: r_dat=date.today() a=int(d5[6:]) b=int(d5[3:5]) c=int(d5[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>dys_free: dys=dys-dys_free else: dys=0 total+=0.50*dys def p_conf(): i=int(E_2.get()) row =conn.execute('''select * from Records where Roll_no = ?''',(i,)) book1 = 0 book2 = 0 book3 = 0 book4 = 0 book5 = 0 for rec in row: book1=rec[1] book2=rec[2] book3=rec[3] book4=rec[4] book5=rec[5] d1=rec[6] d2=rec[7] d3=rec[8] d4=rec[9] d5=rec[10] break b1=E_3.get() b2=E_4.get() b3=E_5.get() b4=E_6.get() b5=E_7.get() aaa=0 if b1=="": aaa+=1 if b2=="": aaa+=1 if b3=="": aaa+=1 if b4=="": aaa+=1 if b5=="": aaa+=1 aaa=5-aaa lst=[] if aaa==5: lst.append(int(b1)) lst.append(int(b2)) lst.append(int(b3)) lst.append(int(b4)) lst.append(int(b5)) elif aaa==4: lst.append(int(b1)) lst.append(int(b2)) lst.append(int(b3)) lst.append(int(b4)) elif aaa==3: lst.append(int(b1)) lst.append(int(b2)) lst.append(int(b3)) elif aaa==2: lst.append(int(b1)) lst.append(int(b2)) elif aaa==1: lst.append(int(b1)) for j in range(len(lst)): if book1==lst[j]: conn.execute('''UPDATE Records set 'book1'=? where Roll_no=?''',(0,i,)) conn.execute('''UPDATE Records set 'DdI1'=? where Roll_no=?''',('00-00-0000',i,)) conn.commit() elif book2==lst[j]: conn.execute('''UPDATE Records set 'book2'=? where Roll_no=?''',(0,i,)) conn.execute('''UPDATE Records set 'DdI2'=? where Roll_no=?''',('00-00-0000',i,)) conn.commit() elif book3==lst[j]: conn.execute('''UPDATE Records set 'book3'=? where Roll_no=?''',(0,i,)) conn.execute('''UPDATE Records set 'DdI3'=? where Roll_no=?''',('00-00-0000',i,)) conn.commit() elif book4==lst[j]: conn.execute('''UPDATE Records set 'book4'=? where Roll_no=?''',(0,i,)) conn.execute('''UPDATE Records set 'DdI4'=? where Roll_no=?''',('00-00-0000',i,)) conn.commit() elif book5==lst[j]: conn.execute('''UPDATE Records set 'book5'=? where Roll_no=?''',(0,i,)) conn.execute('''UPDATE Records set 'DdI5'=? where Roll_no=?''',('00-00-0000',i,)) conn.commit() L9 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "done") L9.place(x=350,y=720) L8 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Total fine: "+str(total)) L8.place(x=50,y=580) B_2 = Button(add1,activebackground='Green',activeforeground='Red',width=7,bd=5,bg='Yellow',font=16, text = "Confirm",command = p_conf) B_2.place(x=350,y=650) L2 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = strr) L2.place(x=50,y=180) L3 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book1") L3.place(x=50,y=260) E_3 = Entry(add1,font=16) E_3.place(x=410,y=260) L4 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book2") L4.place(x=50,y=310) E_4 = Entry(add1,font=16) E_4.place(x=410,y=310) L5 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book3") L5.place(x=50,y=360) E_5 = Entry(add1,font=16) E_5.place(x=410,y=360) L6 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book4") L6.place(x=50,y=410) E_6 = Entry(add1,font=16) E_6.place(x=410,y=410) L7 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book5") L7.place(x=50,y=460) E_7 = Entry(add1,font=16) E_7.place(x=410,y=460) B_2 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=7,bg='Yellow',font=16, text = "Return",command = p_cal) B_2.place(x=350,y=510) L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Roll number") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=10,bd=5,bg='Yellow',font=16, text = "Continue",command = p_del) B_1.place(x=350,y=100) def p_mail(): add1=Tk() add1.title("Mail to students") add1.geometry("700x300") import smtplib row =conn.execute('''select * from Records''') lst1=[] for rec in row: mpty=0 book1=rec[1] d1=rec[6] book2=rec[2] d2=rec[7] book3=rec[3] d3=rec[8] book4=rec[4] d4=rec[9] book5=rec[5] d5=rec[10] if book1!=0: mpty+=1 if book2!=0: mpty+=1 if book3!=0: mpty+=1 if book4!=0: mpty+=1 if book5!=0: mpty+=1 total=0 free_days=0 for i in range(mpty): if book1 !=0: r_dat=date.today() a=int(d1[6:]) b=int(d1[3:5]) c=int(d1[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>free_days: dys=dys-free_days else: dys=0 total+=0.50*dys elif book2 !=0: r_dat=date.today() a=int(d2[6:]) b=int(d2[3:5]) c=int(d2[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>free_days: dys=dys-free_days else: dys=0 total+=0.50*dys elif book3 !=0: r_dat=date.today() a=int(d3[6:]) b=int(d3[3:5]) c=int(d3[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>free_days: dys=dys-free_days else: dys=0 total+=0.50*dys elif book4 !=0: r_dat=date.today() a=int(d4[6:]) b=int(d4[3:5]) c=int(d4[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>free_days: dys=dys-free_days else: dys=0 total+=0.50*dys elif book5 == lst1[i]: r_dat=date.today() a=int(d5[6:]) b=int(d5[3:5]) c=int(d5[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>free_days: dys=dys-free_days else: dys=0 total+=0.50*dys if total!=0: lst1.append(rec[0]) lst2=[] for rrol in lst1: row =conn.execute('''select * from RecordsEmail where Roll_no=?''',(rrol,)) for rec in row: eme=rec[1] lst2.append(eme) lstt=lst2 L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text =str(len(lstt))+" are number of students whose fine started.") L1.place(x=10,y=10) sender = "systemlibrary567@gmail.com" recipient = lstt password = getpass.getpass() # Your SMTP password for Gmail subject = "UIET KUK LIBRARY" text = ''' Dear student, This is gentle remainder from uiet kuk library that we have started fine. This is automatic mailing so don't reply. This is only for uiet kuk student. If you are not student so please ignore it. ''' smtp_server = smtplib.SMTP_SSL("smtp.gmail.com", 465) smtp_server.login(sender, password) message = "Subject: {}\n\n{}".format(subject, text) if len(lstt)>0: smtp_server.sendmail(sender, recipient, message) smtp_server.close() L2 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text ="Done mailed.") L2.place(x=10,y=110) def p_details(): def p_show(): rol=int(E_2.get()) row =conn.execute('''select * from Records where Roll_no = ?''',(rol,)) row1=conn.execute('''select * from RecordsEmail where Roll_no = ?''',(rol,)) for rec in row1: L2 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Email of student: "+rec[1]) L2.place(x=50,y=160) break lst1=[] total=0 mpty=0 for rec in row: book1=rec[1] d1=rec[6] book2=rec[2] d2=rec[7] book3=rec[3] d3=rec[8] book4=rec[4] d4=rec[9] book5=rec[5] d5=rec[10] break if book1!=0: mpty+=1 lst1.append(book1) L3 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book Number= "+str(book1)+" Issue Date: "+ d1) L3.place(x=50,y=220) if book2!=0: mpty+=1 lst1.append(book2) L4 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book Number= "+ str(book2)+" Issue Date: "+ d2) L4.place(x=50,y=280) if book3!=0: mpty+=1 lst1.append(book3) L5 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book Number= "+str(book3)+" Issue Date: "+ d3) L5.place(x=50,y=340) if book4!=0: mpty+=1 lst1.append(book4) L6 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book Number= "+str(book4)+" Issue Date: "+ d4) L6.place(x=50,y=400) if book5!=0: mpty+=1 lst1.append(book5) L7 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text ="Book Number= "+ str(book5)+" Issue Date: "+ d5) L7.place(x=50,y=460) days_free=0 for i in range(len(lst1)): if book1 == lst1[i]: r_dat=date.today() a=int(d1[6:]) b=int(d1[3:5]) c=int(d1[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>days_free: dys=dys-days_free else: dys=0 total+=0.50*dys elif book2 == lst1[i]: r_dat=date.today() a=int(d2[6:]) b=int(d2[3:5]) c=int(d2[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>days_free: dys=dys-days_free else: dys=0 total+=0.50*dys elif book3 == lst1[i]: r_dat=date.today() a=int(d3[6:]) b=int(d3[3:5]) c=int(d3[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>days_free: dys=dys-days_free else: dys=0 total+=0.50*dys elif book4 == lst1[i]: r_dat=date.today() a=int(d4[6:]) b=int(d4[3:5]) c=int(d4[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>days_free: dys=dys-days_free else: dys=0 total+=0.50*dys elif book5 == lst1[i]: r_dat=date.today() a=int(d5[6:]) b=int(d5[3:5]) c=int(d5[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>days_free: dys=dys-days_free else: dys=0 total+=0.50*dys L8 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Total fine= "+str(total)) L8.place(x=50,y=520) add1=Tk() add1.title("Show Details") add1.geometry("900x900") L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Roll Number") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=5,bg='Yellow',font=16, text = "Show",command = p_show) B_1.place(x=350,y=100) add1.mainloop() def p_mail_change(): add1=Tk() add1.title("Edit Details") add1.geometry("900x900") def p_changeg(): i=int(E_2.get()) row1=conn.execute('''select * from RecordsEmail where Roll_no = ?''',(i,)) ssa='' for rec in row1: ssa='Email for rollno '+str(i)+' is '+rec[1] def p_change_conf(): rol=int(E_2.get()) newEmail=E_3.get() conn.execute('''UPDATE RecordsEmail set 'Email'=? where Roll_no=?''',(newEmail,rol,)) conn.commit() L4 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = 'Done') L4.place(x=150,y=360) L2 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = ssa) L2.place(x=50,y=160) L3 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = 'New Email: ') L3.place(x=50,y=220) E_3 = Entry(add1,font=16) E_3.place(x=410,y=220) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=8,bd=5,bg='Yellow',font=16, text = "Change",command = p_change_conf) B_1.place(x=350,y=300) L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Roll Number") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=5,bg='Yellow',font=16, text = "Edit",command = p_changeg) B_1.place(x=350,y=100) add1.mainloop() if not(passw()): exit() root = Tk() root.title("Library_Management") root.geometry("900x900") a='''UNIVERSITY INSTITUTE OF ENGINEERING AND TECHNOLOGY KURUKSHETRA UNIVERSITY KURUKSHETRA''' c= StringVar() b = StringVar() rol = StringVar() L = Label(root,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text =a) L.place(x=150,y=10) b1="Enroll 1 or more student(s) having different roll numbers" B_1 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b1,command = p_add1) B_1.place(x=150,y=100) b2="Enroll students in a range" B_2 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b2, command=p_addrng) B_2.place(x=150,y=160) b3 = "Delete 1 or more students(s) having different roll numbers" B_3 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b3,command = p_del1) B_3.place(x=150,y=220) b4="Delete students in a range" B_4 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b4, command=p_delrng) B_4.place(x=150,y=280) b5="Issue book(s) for a roll number" B_5 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b5, command=p_issue) B_5.place(x=150,y=340) b6="Return book(s) by any student using roll number" B_6 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b6, command=p_delete) B_6.place(x=150,y=400) b7="To get mail those students whose fine already started" B_7 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b7, command= p_mail) B_7.place(x=150,y=460) b8="To get all details related to any student" B_8 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b8,command= p_details) B_8.place(x=150,y=520) b9="Edit the details i.e. change Email of any student" B_9 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b9, command=p_mail_change) B_9.place(x=150,y=580) B_10 = Button(root,activebackground='Green',activeforeground='Red',width=10,bd=5,bg='Yellow',font=16, text ="Exit",command = p_exit) B_10.place(x=400,y=640) root.mainloop()
b0670e3cdb4f9647102f477224de46ad97ff78d3
nsc1114/comp110-21f-workspace
/exercises/ex02/repeat_beat.py
378
3.96875
4
"""Repeating a beat in a loop.""" __author__ = "730394272" beat: str = input("What beat do you want to repeat?") num: str = input("How many times do you want to repeat it?") total: str = beat if int(num) <= 0: print("No beat...") else: runtime: int = int(num) while runtime > 1: total = total + " " + beat runtime = runtime - 1 print(total)
8b859bf457f2da415c393ea7f56d62495e778835
MarynaNogtieva/mipt
/practice1/spider.py
280
3.609375
4
import turtle import math t = turtle.Turtle() t.shape('turtle') legs_angle = 360 / 12 for i in range(12): t.forward(100) t.stamp() t.left(180) # turn to face center on the way back t.forward(100) t.right(180) # turn to face border on the way forward t.right(legs_angle)
d9d7f6302c0c7c3721bd63c6b2866c6f111ee243
MarynaNogtieva/mipt
/practice1/10_indended_sqares.py
373
4.09375
4
import turtle import math t = turtle.Turtle() t.shape('turtle') side_size = 50 def draw_square(t, side_size): for i in range(4): t.forward(side_size) t.left(90) for i in range(10): draw_square(t,side_size) # t.forward(side_size) side_size += 20 t.penup() # lift turtle # move turtle outside t.backward(10) t.right(90) t.forward(10) t.left(90) t.pendown()
81eba7d41e0f8962458519751b02c21dc52c88a5
Sreenidhi220/IOT_Class
/CE8OOPndPOP.py
1,466
4.46875
4
#Aum Amriteshwaryai Namah #Class Exercise no. 8: OOP and POP illustration # Suppose we want to model a bank account with support for 'deposit' and 'withdraw' operations. # One way to do that is by Procedural Programming # balance = 0 # def deposit(amount): # global balance # balance += amount # return balance # def withdraw(amount): # global balance # balance -= amount # return balance #The above example is good enough only if we want to have just a single account. #Things start getting complicated if we want to model multiple accounts. # Have multiple accounts as list or dictionary or separate variables? def deposit(name, amount): Accounts[name] += amount return Accounts[name] def withdraw(name, amount): Accounts[name] -= amount return balance Accounts = {} Accounts["Arya"] = 2000 Accounts["Swathi"] = 2000 Accounts["Urmila"] = 2000 print("Arya's balance is %d" % deposit("Arya", 200)) class BankAccount: def __init__(self): self.balance = 0 def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance Arya = BankAccount() Swathi = BankAccount() Urmila = BankAccount() Swathi.deposit(400) Urmila.deposit(700) print(Urmila.balance) #Referece :https://anandology.com/python-practice-book/object_oriented_programming.html
85b42725e82771c0e8e6e04f84e2c5e1fbec0606
sisinflab/Perceptual-Rec-Mutation-of-Adv-VRs
/src/utils/__init__.py
904
3.515625
4
import sys import os import socket def cpu_count(): """ Returns the number of CPUs in the system """ if sys.platform == 'win32': try: num = int(os.environ['NUMBER_OF_PROCESSORS']) except (ValueError, KeyError): num = 0 elif 'bsd' in sys.platform or sys.platform == 'darwin': comm = '/sbin/sysctl -n hw.ncpu' if sys.platform == 'darwin': comm = '/usr' + comm try: with os.popen(comm) as p: num = int(p.read()) except ValueError: num = 0 else: try: num = os.sysconf('SC_NPROCESSORS_ONLN') except (ValueError, OSError, AttributeError): num = 0 if num >= 1: return num else: raise NotImplementedError('cannot determine number of cpus') def get_server_name(): return socket.gethostname()
cd6b3802242956ea0c86e3ca72e844c80484ccc6
arcann/mstr_python_api
/microstrategy_api/task_proc/bit_set.py
262
3.515625
4
from enum import Enum class BitSet(set): def combine(self): result = 0 for entry in self: if isinstance(entry, Enum): result |= entry.value else: result |= entry return result
c79f3df4eb01631e73363cd6e5e6546e15380b30
edran/ProjectsForTeaching
/Classic Algorithms/sorting.py
2,073
4.28125
4
""" Implement two types of sorting algorithms: Merge sort and bubble sort. """ def mergeMS(left, right): """ Merge two sorted lists in a sorted list """ llen = len(left) rlen = len(right) sumlist = [] while left != [] and right != []: lstack = left[0] while right != []: rstack = right[0] if lstack < rstack: sumlist.append(lstack) left.pop(0) break else: sumlist.append(rstack) right.pop(0) if left == []: sumlist += right else: sumlist += left return sumlist def mergeSort(l): """ Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted). Repeatedly merge sublists to produce new sorted sublists until there is only 1 sublist remaining. This will be the sorted list. """ # I actually implemented without reading any of the formal algorithms, # so I'm not entirely sure I did a good job. I have to read up and compare # my solution with a standard one. if len(l) == 1: return l split = len(l) / 2 a = mergeMS(mergeSort(l[:split]), mergeSort(l[split:])) return a def bubbleSort(l): """ simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order """ n = list(l) swapped = True k = len(n) - 1 while swapped: swapped = False i = k while i > 0: u = n[i] d = n[i - 1] if u < d: n[i] = d n[i -1] = u swapped = True i -= 1 return n def main(): t = raw_input("List of numbers> ") t = eval("[" + t + "]") r = mergeSort(t) b = bubbleSort(t) print "MergeSort: ", r print "BubbleSort: ", b if __name__ == "__main__": main()
4b41489f518c4cbca1923440c3416cdfef345f88
edran/ProjectsForTeaching
/Numbers/factprime.py
657
4.28125
4
""" Have the user enter a number and find all Prime Factors (if there are any) and display them. """ import math import sys def isPrime(n): for i in range(2,int(math.sqrt(n)) + 1): # premature optimization? AH! if n % i == 0: return False return True def primeFacts(n): l = [] for i in range(1,int(math.ceil(n/2))+1): if n % i == 0 and isPrime(i): l.append(i) if n not in l and isPrime(n): l.append(n) # for prime numbers return l def main(): i = int(raw_input("Factors of which number? ")) print primeFacts(i) if __name__ == "__main__": while 1: main()
05acb3ccc06473b83b430816bd688b410a97871f
edran/ProjectsForTeaching
/Numbers/alarm.py
2,457
3.671875
4
""" A simple clock where it plays a sound after X number of minutes/seconds or at a particular time. """ import time import pyglet def passedTime(t, typetime): """ Returns time passed since t (seconds) typetime can be <m> or <s> to specify the returning type (minutes or seconds) """ try: passed = time.time() - t except TypeError: "Argument is not a time" if typetime == "m": # minutes return passed / 60.0 elif typetime == "s": # seconds return passed else: print "Type not valid" mario = pyglet.media.load("oneup.wav", streaming=False) def playSound(): mario.play() def cronometer(t, typetime): start = time.time() flag = True # for counter while 1: p = passedTime(start, typetime) if flag: # get first p r = p flag = False if int(r) != int(p): print "Remaining " + str(int(t) - int(p)) + typetime r = p if t < p: print "END of cronometer!" break playSound() time.sleep(1) def alarm(hours, minutes): h = int(hours) m = int(minutes) if not (h in range(24) and m in range(60)): print "Wrong time values" return flag = True while 1: t = time.localtime() # gmtime is UTC if t.tm_hour == int(h) and t.tm_min == int(m): break if flag: # get first p past_hr = t.tm_hour past_min = t.tm_min flag = False if past_hr != t.tm_hour or past_min != t.tm_min: remaining = ((h - t.tm_hour) * 60) + (m - t.tm_min) # mmm print "Remamining minutes: " + str(remaining) past_hr = t.tm_hour past_min = t.tm_min playSound() time.sleep(1) def main(): inp = raw_input("Cronometer or Alarm? [c/a] ") if inp == "C" or inp == "c": typetime = raw_input("Minutes or seconds? [s/m] ") t = float(raw_input("How many minutes/seconds? ")) cronometer(t, typetime) elif inp == "A" or inp == "a": print "When would you like the alarm to go off?" hours = raw_input("Hours[0-23]> ") minutes = raw_input("Minutes[0-59]> ") alarm(hours, minutes) if __name__ == "__main__": main()
9f7f047dbb43adc3798df7b33e7de4554a64c0ac
DanielWillim/AoC2019
/day1.py
354
3.609375
4
def fuel_cost(mass): mass_fuel = (mass // 3) - 2 if mass_fuel <= 0: return 0 return mass_fuel + fuel_cost(mass_fuel) inp = open('inp_day1', "r") lines = inp.readlines() total_cost = 0 print(fuel_cost(14)) print(fuel_cost(100756)) for line in lines: total_cost += fuel_cost(int(line)) print(total_cost) inp.close()
bafd57196a0350f468390680e923c9fe9541e77a
keyman9848/bncgit
/xmjc_analysis/dataDeal/dataCollection/txtCollection.py
609
3.515625
4
import pymysql # 打开数据库连接 db = pymysql.connect(host='172.16.143.66',port = 3306,user='kjt', passwd='kjt$',db ='kjt',charset='utf8') # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql = "SELECT VERSION()" sql1= "select * from users" cursor.execute(sql1) # 获取所有记录列表 results = cursor.fetchall() for row in results: fname = row[0] lname = row[1] age = row[2] sex = row[3] income = row[4] # 打印结果 print (fname, lname, age, sex, income) # 关闭数据库连接 db.close()
d0659e52a363d340934df53c5ae71b1e9fd16209
ClayMav/BPlus-Tree
/bplustree/bplustree.py
8,164
3.890625
4
""" This is a group project, to be worked on and completed in collaboration with the group to which you were assigned in class. One final report is due per group. A number of groups, selected randomly, will be asked to demonstrate the correctness of your program for any input data. Your task is to develop and test a program that generates a B+ tree of order 4 for a sequence of unique index values. In addition, it must support insert and delete operations. 1) Input is: a. a sequence of numeric key values (three digits at most) for initial generation of B+ tree, and b. a sequence of insert and delete commands. 2) For initial sequence of key values, your program should generate and print out the generated index tree. In addition, for each insert and delete command it should also generate and print out the resulting index tree. 3) Test data will be made available on April 5. Your report should show that your program operates correctly for this test data. 4) Your final technical report should include: a. a description of your overall approach and the logic of your program, b. pseudo code for your program, c. output as explained in (2), and d. a hard copy of your program. 5) Please note that the deadline is firm and will not change under any circumstances. """ import math from graphviz import Digraph, nohtml from node.node import Node class BPlusTree(object): DEFAULT_ORDER = 3 def __init__(self, order=DEFAULT_ORDER): self.order = order self.root = Node(order=order) @property def order(self): """An integer denoting the order of the tree""" return self._order @order.setter def order(self, value): """Set the order of the tree""" self._order = value @property def root(self): """The root node of the tree""" return self._root @root.setter def root(self, value): """Set the root node of the tree""" self._root = value def _insert(self, value, root=None): root = self.root if root is None else root if not root.is_leaf_node: split = self._insert(value, root.find_child(value)) if split is not None: new_node, split_value = split if not root.is_split_imminent: root.insert(split_value) root.add_child(new_node) else: second_new_node, second_split_value = root.insert(split_value) if root.find_child(new_node.max) is None: root.add_child(new_node) else: second_new_node.add_child(new_node) parent_node = root.parent if parent_node is None: parent_node = Node(values=[second_split_value], order=self.order, is_internal=True) parent_node.add_child(root) parent_node.add_child(second_new_node) self.root = parent_node else: return second_new_node, second_split_value else: if not root.is_split_imminent: root.insert(value) else: new_node, split_value = root.insert(value) parent_node = root.parent if parent_node is None: parent_node = Node(values=[split_value], order=self.order, is_internal=True) parent_node.add_child(root) parent_node.add_child(new_node) self.root = parent_node else: return new_node, split_value def _connect_leaves(self): queue = [self.root] leaves = [] while queue: root = queue.pop(0) if root.is_leaf_node: leaves.append(root) if len(leaves) > 1: leaves[-2].next = leaves[-1] leaves[-1].prev = leaves[-2] for i, child in enumerate(root.children): if child is not None: queue.append(child) def insert(self, value): self._insert(value) self._connect_leaves() def _render_node_str(self, node): values = [' ']*(self.order-1) f_idx = 0 buffer = [] for i, value in enumerate(node.values): values[i] = str(value) for i, value in enumerate(values): buffer.append('<f%d> |<f%d> %s|' % (f_idx, f_idx+1, value)) f_idx += 2 buffer.append('<f%d>' % (f_idx,)) return ''.join(buffer) def _render_graph(self, g): queue = [self.root] while queue: root = queue.pop(0) g.node('%s' % (id(root),), nohtml(self._render_node_str(root))) if root.next is not None: g.edge('%s' % (id(root),), '%s' % (id(root.next),), constraint='false') for i, child in enumerate(root.children): if child is not None: queue.append(child) g.edge('%s:f%d' % (id(root), i*2), '%s:f%d' % (id(child), self.order)) def render(self, filename='btree.gv'): g = Digraph('g', filename=filename, node_attr={'shape': 'record', 'height': '.1'}) self._render_graph(g) g.view() def _delete(self, val, root=None): """Deletes specified value""" root = self.root if root is None else root if not root.is_leaf_node: merged = self._delete(val, root.find_child(val)) if merged: if len(root.values) != root.num_children-1: if root.parent: return root.merge(val) else: if root.num_children == 1: root = self.root self.root = root.children[0] root.remove_child(self.root) else: root.values.pop(-1) else: if val in root.values: success = root.remove(val) if not success: if not root.redistribute(val): return root.merge(val) def delete(self, val, root=None): self._delete(val, root) def find(self, val, root=None): """Determines if value exists in tree""" # Technically this function works, but it doesn't take advantage of the # Optimizations of the B+ Tree. Will fix later. # TODO FIX root = self.root if root is None else root # Stopping Conditions if val in root.values: # If val is in this node return True if root.num_children == 0: # If val is not in node, and there are no children return False # Recursion if val <= root.values[0]: # If val smaller or equal to first value in the root # Go to first child print("LESS THAN OR EQUAL TO FIRST", val, root.values[0]) return self.find(val, root.children[0]) if val > root.values[-1]: # If val greater than the last value in the root # Go to last child print("GREATER THAN LAST", val, root.values[-1]) return self.find(val, root.children[len(root.values)]) for index, value in enumerate(root.values): if not index == len(root.values) - 1 and val > value and \ val <= root.values[index + 1]: # If in between two values in the root, go to child in between # Go to child at root.children[index + 1] print("BETWEEN", value, "<", val, "<=", root.values[index + 1]) return self.find(val, root.children[index + 1]) def __str__(self): return "order={}, root={}".format(self.order, self.root)
2b7c6bb7e8405efe52a594d97bc7c7ac1584417c
kujaku11/mt_metadata
/mt_metadata/utils/list_dict.py
7,082
3.578125
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 16 11:08:25 2022 @author: jpeacock """ # ============================================================================= # Imports # ============================================================================= from collections import OrderedDict # ============================================================================= class ListDict: """ Hack together an object that acts like a dictionary and list such that a user can get an item by index or key. This is the first attempt, seems to work, might think about inheriting an OrderedDict and overloading. """ def __init__(self, values={}): self._home = OrderedDict(values) def __str__(self): lines = ["Contents:", "-" * 12] for k, v in self._home.items(): lines.append(f"\t{k} = {v}") return "\n".join(lines) def __repr__(self): return self._home.__repr__() def __eq__(self, other): return self._home.__eq__(other._home) def __len__(self): return self._home.__len__() def _get_key_from_index(self, index): try: return next(key for ii, key in enumerate(self._home) if ii == index) except StopIteration: raise KeyError(f"Could not find {index}") def _get_index_from_key(self, key): try: return next(index for index, k in enumerate(self._home) if k == key) except StopIteration: raise KeyError(f"Could not find {key}") def _get_key_from_object(self, obj): """ Get the key from the metadata object :param obj: DESCRIPTION :type obj: TYPE :return: DESCRIPTION :rtype: TYPE """ if hasattr(obj, "id"): return obj.id elif hasattr(obj, "component"): return obj.component else: raise TypeError("could not identify an appropriate key from object") def __deepcopy__(self, memodict={}): """ Need to skip copying the logger need to copy properties as well. :return: DESCRIPTION :rtype: TYPE """ copied = type(self)() for key, value in self.items(): if hasattr(value, "copy"): value = value.copy() copied[key] = value return copied def copy(self): """ Copy object """ return self.__deepcopy__() def _get_index_slice_from_slice(self, items, key_slice): """ Get the slice index values from either an integer or key value :param items: DESCRIPTION :type items: TYPE :param key_slice: DESCRIPTION :type key_slice: TYPE :raises TypeError: DESCRIPTION :return: DESCRIPTION :rtype: TYPE """ if key_slice.start is None or isinstance(key_slice.start, int): start = key_slice.start elif isinstance(key_slice.start, str): start = self._get_index_from_key(key_slice.start) else: raise TypeError("Slice start must be type int or str") if key_slice.stop is None or isinstance(key_slice.stop, int): stop = key_slice.stop elif isinstance(key_slice.stop, str): stop = self._get_index_from_key(key_slice.stop) else: raise TypeError("Slice stop must be type int or str") return slice(start, stop, key_slice.step) def __getitem__(self, value): if isinstance(value, str): try: return self._home[value] except KeyError: raise KeyError(f"Could not find {value}") elif isinstance(value, int): key = self._get_key_from_index(value) return self._home[key] elif isinstance(value, slice): return ListDict( list(self.items())[ self._get_index_slice_from_slice(self.items(), value) ] ) else: raise TypeError("Index must be a string or integer value.") def __setitem__(self, index, value): if isinstance(index, str): self._home[index] = value elif isinstance(index, int): try: key = self._get_key_from_index(index) except KeyError: try: key = self._get_key_from_object(value) except TypeError: key = str(index) self._home[key] = value elif isinstance(index, slice): raise NotImplementedError( "Setting values from slice is not implemented yet" ) def __iter__(self): return iter(self.values()) def keys(self): return list(self._home.keys()) def values(self): return list(self._home.values()) def items(self): return self._home.items() def append(self, obj): """ Append an object :param obj: DESCRIPTION :type obj: TYPE :return: DESCRIPTION :rtype: TYPE """ try: key = self._get_key_from_object(obj) except TypeError: key = str(len(self.keys())) self._home[key] = obj def remove(self, key): """ remove an item based on key or index :param key: DESCRIPTION :type key: TYPE :return: DESCRIPTION :rtype: TYPE """ if isinstance(key, str): self._home.__delitem__(key) elif isinstance(key, int): key = self._get_key_from_index(key) self._home.__delitem__(key) else: raise TypeError("could not identify an appropriate key from object") def extend(self, other, skip_keys=[]): """ extend the dictionary from another ListDict object :param other: DESCRIPTION :type other: TYPE :return: DESCRIPTION :rtype: TYPE """ if isinstance(skip_keys, str): skip_keys = [skip_keys] if isinstance(other, (ListDict, dict, OrderedDict)): for key, value in other.items(): if key in skip_keys: continue self._home[key] = value else: raise TypeError(f"Cannot extend from {type(other)}") def sort(self, inplace=True): """ sort the dictionary keys into alphabetical order """ od = OrderedDict() for key in sorted(self._home.keys()): od[key] = self._home[key] if inplace: self._home = od else: return od def update(self, other): """ Update from another ListDict """ if not isinstance(other, (ListDict, dict, OrderedDict)): raise TypeError( f"Cannot update from {type(other)}, must be a " "ListDict, dict, OrderedDict" ) self._home.update(other)
dc4e1a66e05f8db95dda9efbdc9c4dfc3748b791
IDSF21/assignment-2-samarthgowda
/main.py
4,335
3.5625
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import streamlit as st @st.cache def load_songs(): df = pd.read_csv("./data.csv") df = df.drop_duplicates(["id", "name"], keep="last") df = df.dropna(how="any") df["year"] = df["year"].astype(int) return df songs = load_songs() @st.cache def get_years(songs): return list(np.sort(songs["year"].unique())) years = get_years(songs) @st.cache def calculate_songs_agg(songs): songs_agg = songs.groupby("year").agg( { "acousticness": np.mean, "danceability": np.mean, "duration_ms": np.mean, "energy": np.mean, "instrumentalness": np.mean, "liveness": np.mean, "loudness": np.mean, "popularity": np.mean, "speechiness": np.mean, "tempo": np.mean, "valence": np.mean } ) songs_agg.index = pd.to_datetime(songs_agg.index, format="%Y") return songs_agg songs_agg = calculate_songs_agg(songs) with st.container(): """ # 🎶 How Music has Changed from 1921-2020 Information about these songs are from Spotify Web API. Dataset provided from [Kaggle](https://www.kaggle.com/ektanegi/spotifydata-19212020). """ if st.checkbox("Show raw dataframe of Spotify 1921-2020 Songs Dataset"): songs if st.checkbox("Show dataframe of average values for different columns in Spotify Songs grouped by Year"): songs_agg with st.container(): """ ### 📅 Understanding how different aspects of songs have changed over time Overtime, song attributes have changed a lot. Take a look at how certain attributes are very similar overtime from 1921 to 2020 and how other attributes change drastically over the last century. """ overall_variable_select = st.selectbox( "Select the variable that you would like to explore.", [ "acousticness", "danceability", "duration_ms", "energy", "instrumentalness", "liveness", "loudness", "speechiness", "tempo", "valence" ], key="overall_variable", ) songs_agg_data = songs_agg[[overall_variable_select]] songs_agg_data["year"] = songs_agg_data.index fig, ax = plt.subplots() ax.plot("year", overall_variable_select, data=songs_agg_data) ax.set_xlabel("Release Year") ax.set_ylabel(overall_variable_select) ax.set_title(f"{overall_variable_select} vs Release Year for Spotify Song Data 1921-2021") st.pyplot(fig) with st.container(): """ ### 🔊 Understanding the distribution of aspects of songs for a given release year range Select a start year, end year, and a song attribute and observe the distribution of the song attribute's distribution over the date range. There are interesting differences between certain attributes as you change the start and end years. """ col1, col2 = st.columns(2) with col1: start_year, end_year = st.select_slider("Select a range of years to explore", options=years, value=[years[0], years[-1]]) with col2: year_variable_select = st.selectbox( "Select the variable that you would like to explore", [ "acousticness", "danceability", "duration_ms", "energy", "instrumentalness", "liveness", "loudness", "speechiness", "tempo", "valence" ], key="year_variable", ) with st.container(): after_start = songs["year"] >= start_year before_end = songs["year"] <= end_year between_years = after_start & before_end songs_data = songs.loc[between_years] songs_data = songs_data[["year", year_variable_select]] fig, ax = plt.subplots() ax.hist(songs_data[year_variable_select]) ax.set_ylabel(f"Frequency") ax.set_xlabel(year_variable_select) ax.set_title(f"Frequency of {year_variable_select} for Spotify Song Data {start_year} to {end_year}") st.pyplot(fig)
1ab87bc5c2863c90dea96185241b0869f2259f30
sonusbeat/intro_algorithms
/Recursion/group_exercise2.py
489
4.375
4
""" Group Exercise Triple steps """ def triple_steps(n): """ A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Count how many possible ways the child can run up the stairs. :param n: the number of stairs :return: The number of possible ways the child can run up the stairs. """ if n <= 2: return n return triple_steps(n-1) + triple_steps(n-2) + triple_steps(n-3) print(triple_steps(3))
916e2aa4bc23a717c6ba3d196b26cb44a02e6c78
sonusbeat/intro_algorithms
/7.Loops/01.exercise.py
469
4.21875
4
# Exercises # 1. Write a loop to print all even numbers from 0 to 100 # for num in range(101): # if num % 2 == 0: # print(num) # list comprehension # [print(i) for i in range(101) if i % 2 == 0] # 2. Write a loop to print all even numbers from 0 to 100 # for i in range(0, 101): # if i % 2 == 1: # print(i, end=" ") # print() # print("*" * 40) # for ch in "hello": # print(ch) # for ch in ["hello", "Hola", "Konichiwa"]: # print(ch)
ec45e6109ddd2f2f3b9984404f015b828f0ca4f1
sonusbeat/intro_algorithms
/SearchingAlgorithms/2.binary_search.py
1,037
4.28125
4
""" Binary Search - how you look up a word in a dictionary or a contact in phone book. * Items have to be sorted! """ alist = [ "Australia", "Brazil", "Canada", "Denmark", "Ecuador", "France", "Germany", "Honduras", "Iran", "Japan", "Korea", "Latvia", "Mexico", "Netherlands", "Oman", "Philippines", "Qatar", "Russia", "Spain", "Turkey", "Uruguay", "Vietnam", "Wales", "Xochimilco", "Yemen", "Zambia" ] def binary_search(collection, target): start = 0 end = len(collection) - 1 steps = 0 while start <= end: mid = (start + end) // 2 steps += 1 if collection[mid] == target: steps_message = "s" if steps > 1 else "" return F"\"{collection[mid]}\" is at position {str(mid)} and it took {str(steps)} step{steps_message}" elif collection[mid] < target: start = mid + 1 else: end = mid - 1 return F"Your country \"{target}\" is not on the list!" print(binary_search(alist, input("What's your country? ")))
07f7fc0b352b9919350390eab9eba036b89fba66
sonusbeat/intro_algorithms
/Labs/Lab0.py
492
3.84375
4
import turtle screen = turtle.Screen() screen.bgcolor("#90ee90") t = turtle.Turtle() t.pensize(5) t.shape('turtle') t.color("blue") t.stamp() for _ in range(12): t.penup() t.forward(100) t.pendown() t.forward(10) t.penup() t.forward(20) t.pendown() t.stamp() t.penup() t.backward(130) t.left(30) screen.exitonclick() # the pensize (thickness) = 5 # from center to the tick = 100 # the length of the tick = 10 # from the tick to turtle = 10
d7d7dddc18064c4b24885e0caa07872f3fcde5d3
CavHack/Manhattanite-
/EM-GMM/k_clustering.py
2,969
3.9375
4
############################################################################################################## # Author: Karl Whitford # # Manhattanite- Multi-disciplinary Machine Learning/A.I Toolkit with Python # # Extracted from project description: # WHAT YOUR PROGRAM OUTPUTS # # You should write your K-means and EM-GMM codes to learn 5 clusters. Run both algorithms for 10 iterations. # You can initialize your algorithms arbitrarily. We recommend that you initialize the K-means centroids by # randomly selecting 5 data points. For the EM-GMM, we also recommend you initialize the mean vectors in the # same way, and initialize pi to be the uniform distribution and each Sigma_k to be the identity matrix. ############################################################################################################## import sys import numpy as np def load_data(input_file): """ Load the dataset. Assumes a *.csv is fed without header, and the output variable in the last column """ data = np.genfromtxt(input_file, delimiter=',', skip_header=0, names=None) return data def KMeans(X, K=5, maxit=10, saveLog=true): """ Apply KMeans for clustering a dataset given as input, and the number of clusters (K). Input: x1, ..., xn where x in R^d, and K Output: Vector c of cluster assignments, and K mean vectors mu """ #Sample size N = X.shape[0] #Initialize output variable c = np.zeros(N) mu = X[np.random.choice(N, K, replace=False), :] for i in xrange(N): kmin = 1 minDist = float('Inf') for k in xrange(K): dist = np.linalg.norm(X[i, :] - mu[k, :]) if dist < minDist: minDist = dist kmin = k c[i] = kmin + 1 cNew = np.zeros(N) it = 1 while it <= maxit and not all (c==cNew): #write the output file if required if saveLog: with open('centroids-'+ str(it) + '.csv', 'w') as f: for mu_i in mu: for j in xrange(len(mu_i)-1): f.write(str(mu_i[j]) + ',') f.write(str(mu_i[len(mu_i) -1 ]) + '\n') c = np.copy(cNew) for i in xrange(N): kmin = 1 minDist = float('Inf') for k in xrange(K): dist = np.linalg.norm(X[i, :]-mu[k, :]) if dist < minDist: minDist = dist kmin = k cNew[i] = kmin + 1 for k in xrange(1, K+1): Xk = X[cNew ==k, :] mu[k - 1] = np.sum(Xk, axis=0) / Xk.shape[0] it += 1 return (c, mu, it) def gauss(mu, cov, x): """ Computes gaussian parametrized by mu and cov, given x. Make sure x dimensions are of correct size """ d = len(x) den = np.sqrt(np.linalg.det(cov))*(2*np.pi)**(0.5*d) num = np.exp(-0.5 * np.dot(x-mu, np.linalg.solve(cov, np.transpose(x-mu)))) return num/den
42a61c3c43eaa30894aeb3bd7980dfc679b34475
the-economancer/Project-Euler
/Problem003.py
789
4
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 16 15:53:11 2016 Functions to compute largest prime factor of a given number @author: michael """ import math import time def isPrime(x): for y in range(2,int(math.sqrt(x))+1): if x % y == 0: return False return True def factors(x): factors = [] for y in range (2,int(math.sqrt(x))+1): if y in factors: return factors if x % y == 0: factors.append(y) return factors def primefactors(x): facts = factors(x) pfact = [] for fact in facts: if isPrime(fact): pfact.append(fact) return pfact def maxprime(x): a = time.time() maxprim = max(primefactors(x)) print(time.time() - a) return maxprim
e4c980515428ad2e3bb23d9cf104d9ebf30a2780
molweave532/IntroToProg-Python-Mod07
/HW07-Error-Handling/Assignment07-error-handling-MW.py
1,010
4.03125
4
# ------------------------------------------------- # # Title: HW07 - error handling # Description: A brief description of error handling # ChangeLog: (Who, When, What) # Molly Weaver, 02/27/21, Created Script # ------------------------------------------------- # try: # write a test case here intOne = int(input("Please enter an integer from 1 to 10: ")) except ValueError: # then tell the user there was an error print("That's not what I'm looking for! I need an integer.") except Exception as error: print("That was unexpected!") print(error) else: try: # look to see if the integer is outside the expected range if intOne < 1 or intOne > 10: raise Exception except Exception: # tell the user there was an error (print("That is outside the expected range!")) else: # no errors encountered! print("You entered: ", intOne) finally: # do this every time print("Goodbye!")
8738e0b40f3dd5bd03454d4190fd660bbab6bd43
jameskowalski97/plotting-library
/assignment_4.py
1,273
3.609375
4
#!/bin/python # Import the libraries we are using. It is good practice to import all necessary # libraries in the first lines of a file. import numpy as np import matplotlib.pyplot as plt import pandas as pd #test comment # Create an array (a multi-dimensional table) out of our data file, full of text all_data = np.genfromtxt("data/1302_susc_data.csv", delimiter=',',skip_header=3) #print(all_data) #to divide the data sets in output print("~~~~~~~~~~~~~~~~~~~~~") # Select the data range we are interested in, convert it into a new array, full of numbers susc_data = np.array(all_data[:,:], dtype=float) #print(susc_data) #Create a figure of the processed data susc_figure = plt.figure() susc_plot = plt.scatter (susc_data[:,0],susc_data[:,1]) plt.title ("IODP Expedition 303, Site U1302-03") plt.xlabel ("Meters Composite Depth") plt.ylabel ("Magnetic Susceptibility") plt.show(block=True) susc_figure.savefig('results/susceptibility-with-depth.png') #let script write pandas dataset into .json file all_data = pd.read_csv("data/1302_susc_data.csv", header=2) all_data.info() all_data.to_json("results/data_output.json") print(all_data.loc['0.3':'1',:]) json_data = pd.read_json("results/data_output.json") json_data.info() print(json_data.loc['0.3':'1',:])
795353bbba095affade0e5933b63a0e3fbec7a6e
low101043/final-year-13-project
/final_Game_File.py
3,848
3.703125
4
# Main Game from tkinter import * #This means I can use tkinter #import gamePrototype4 ###################################################################################################################################################################################################################################### def instructions(): """Made By Nathaniel Lowis. 1st Edit: 17/10/18. Latest Edit: 17/10/18 Inputs - None Outputs - None Displays the instructions for how to play the game""" instructionScreen = Tk() #Makes a window instructionScreen.title("Bullet Game") #Name of the window instructionScreen.geometry("500x500") #Size of the window #menu.wm_iconbitmap("favicon.ico") instructionScreen.configure(background = ("navy")) #Background of the window instructionsToDo= Label(instructionScreen, text = "To play the game click on the screen. Controls (Do not have caps lock on) \n q: Fires a horizontal Bullet. Powerful however the enemy will shoot \n w: Fires a Parabolic Bullet. Not so powerful \n Aim: Get to the red block as fast as you can using the least amount of bullets possible and having the most health at the end. \nCyan Block - Enemy\nDark Blue Block - You", bg = "grey", fg = "black") #This will output all the instructions onto the window so the user can see how to play the game instructionsToDo.pack() #Sends the label to the screen ###################################################################################################################################################################################################################################### def play_Game(): """Made By Nathaniel Lowis 1st Edit: 17/10/18 Latest Edit: 17/10/18 Inputs - None Outputs - None Plays the game""" import main_Game #Goes to file named gamePrototype4 and runs it. This will run the game #exec(open("gamePrototype4.py").read()) #Testing ###################################################################################################################################################################################################################################### def database_To_Display(): """Made By Nathaniel Lowis 1st Edit: 18/10/18 Latest Edit: 18/10/18 Inputs - None Outputs - None Will go to the file which ouputs the leaderboard""" import displaying_Database #Goes to file called displaying_Database and runs the code ###################################################################################################################################################################################################################################### #main window = Tk() #Makes a window for the GUI window.title("Bullet Game") #Names the window window.geometry("500x500") #The size of the window #window.wm_iconbitmap("favicon.ico") window.configure(background = ("navy")) #Sets the background colour labelWelcome =Label(window, text = "Bullet Shot", bg = "green", fg = "white") #This is the welcome label saying the name of the game (Bullet Shot) labelWelcome.pack() #Sends it to the main screen buttonInstructions = Button(window, text = "Instructions", bg = "green", fg = "white", command = instructions ) #This is the button to Go to the instructions buttonInstructions.pack() #Sends button to window buttonGame = Button(window, text = "Game", bg = "green", fg = "white", command = play_Game) #This is the button to play the game buttonGame.pack() #Sends button to the screen buttonLeaderboard = Button(window, text = "Leaderboard", bg = "green", fg = "white", command = database_To_Display) #This is the button to go to the leaderboard buttonLeaderboard.pack() #Sends button to the screen window.mainloop() #Infinte loop.
80582061e8c52501b90a818218215639ef8cbdcb
Lackman-coder/collection
/argsandkwargs.py
661
3.5625
4
# *args methods: def name(*args): name(a) print("denser","anitha","lackman","drikas","rakshana" "\n") def animal(*bets): animal(b) print("cat","dog","parrot","fish" "\n") def item(*home): for items in home: print(items) item("tv","fridge","ac","electronics" "\n") #if u not using *args then u cannot give moore arguments on function call example below: ''' def frd(a,b,c): print(a,b,c) frd("frd1","frd2","frd3","frd4")''' #uncmd above code and check error. # **kwargs method: def data(**kwargs): for key , value in kwargs.items(): print("{} is {}".format (key,value)) data(name = "lackman", age=28, gender = "male", occupation = "seaman")
5c70c82b051ae0d488a4562748e5fd235202534c
corinnelhh/data-structures
/Graph/graph_directional.py
3,337
3.75
4
class Node(object): def __init__(self, data): self._data = data self._visited = False class Graph(object): def __init__(self, *data): self._edges = {} self._nodes = [] for node in data: self._nodes.append(Node(node)) def add_node(self, data): a = Node(data) self._nodes.append(a) return a def has_edge(self, n1, n2): return (n1, n2) in self._edges def add_edge(self, n1, n2, w1=None): if not self.has_edge(n1, n2): if n1 not in self._nodes: self._nodes.append(n1) if n2 not in self._nodes: self._nodes.append(n2) self._edges[(n1, n2)] = w1 def delete_edge(self, n1, n2): try: self._edges.pop((n1, n2)) except(KeyError): raise KeyError def delete_node(self, n): if n not in self._nodes: raise IndexError for i in self._nodes: if self.has_edge(n, i): self.delete_edge(n, i) elif self.has_edge(i, n): self.delete_edge(i, n) self._nodes.remove(n) def has_node(self, n): return n in self._nodes def has_neighbors(self, n): neighbors = [] if n not in self._nodes: raise IndexError for i in self._nodes: if self.has_edge(n, i): neighbors.append(i) return neighbors def adjacent(self, n1, n2): if not self.has_node(n1) or not self.has_node(n2): raise IndexError return self.has_edge(n1, n2) def df_traversal(self, n, df): if not self.has_node(n): raise IndexError if not n._visited: n._visited = True df.append(n) neighbors = self.has_neighbors(n) for i in neighbors: self.df_traversal(i, df) def bf_traversal(self, n): if not self.has_node(n): raise IndexError bf = [n] n._visited = True for i in bf: for child in self.has_neighbors(i): if not child._visited: bf.append(child) child._visited = True return bf # def find_shortest_path(self, n1, n2): # if (not self.has_node(n1)) or (not self.has_node(n2)): # raise IndexError # pass def visit_reset(self): for i in self._nodes: i._visited = False if __name__ == '__main__': import random g = Graph() for i in range(10): a = random.randint(10,99) g.add_node(a) for i in range(40): a = random.randint(0,9) b = random.randint(0,9) g.add_edge(g._nodes[a], g._nodes[b]) for i in g._nodes: result = "Node "+str(i._data)+": | " for x in g.has_neighbors(i): result += str(x._data)+" | " print result df = [] g.df_traversal(g._nodes[0] ,df) result = "\nDepth First Search: \n\t" for i in df: result += str(i._data) +" | " g.visit_reset() print result + "\n" bf = g.bf_traversal(g._nodes[0]) result = "\nBreadth First Search: \n\t" for i in bf: result += str(i._data) +" | " print result + "\n" g.visit_reset()
1cc74b32a7fc70815377e099434dc908ee962da7
corinnelhh/data-structures
/Queue/queue.py
935
4
4
class Node(object): def __init__(self, data, next_node=None): self.data = data self.next = next_node self.last = None class Queue(object): def __init__(self, data=None): self.head = None self.tail = None self.size = 0 if data: for val in data: self.enqueue(val) def enqueue(self, data): self.last_node = self.head self.head = Node(data, self.head) if self.last_node: self.last_node.last = self.head if self.tail is None: self.tail = self.head self.size += 1 def dequeue(self): if self.tail is None: print "Sorry, the queue is empty!" raise IndexError our_returned_value = self.tail.data self.tail = self.tail.last self.size -= 1 return our_returned_value def size_me(self): return self.size
0ea7ceffc8365b8d61d10608a240a6c59a05247e
corinnelhh/data-structures
/Heap/binary_heap.py
1,959
3.859375
4
#!/usr/bin/env python #import math, random class BinaryHeap(object): def __init__(self, max_heap="max", *data): self._list = [] self._size = 0 self.max_heap = True if max_heap == "min": self.max_heap = False elif max_heap != "max" and max_heap is not None: self.push(max_heap) if data: for i in data: self.push(i) def push(self, value): self._list.append(value) child = parent = self._size self._size += 1 while parent > 0: parent = (child - 1) // 2 if self.compare(child, parent): break self.swap(child, parent) child = parent def pop(self): if not self._size: print "Yo, this is an empty heap." raise IndexError val = self._list[0] self._list[0] = self._list[-1] self._list.pop() self._size -= 1 parent, left, right = 0, 1, 2 while right < self._size: if (self.compare(left, parent) and self.compare(right, parent)): break if self.compare(right, left): self.swap(parent, left) parent = left else: self.swap(parent, right) parent = right left = parent * 2 + 1 right = left + 1 if left < self._size: if self.compare(parent, left): self.swap(parent, left) return val def swap(self, x, y): self._list[x], self._list[y] = self._list[y], self._list[x] def compare(self, x, y): if self.max_heap: return self._list[x] < self._list[y] else: return self._list[x] > self._list[y] """ #DEBUGGING for x in range(10): a = BinaryHeap(1,*[random.randint(0,100) for i in range(11)]) print str(a._list) """
6954f9970b9f32aa4de9e42e0964ca73a1b1cf88
corinnelhh/data-structures
/Stack/stack.py
542
3.71875
4
class Node(object): def __init__(self, data, next_node=None): self.data = data self.next = next_node class Stack(object): def __init__(self, data=None): self.head = None if data: for val in data: self.push(val) def push(self, data): self.head = Node(data, self.head) def pop(self): if self.head is None: raise IndexError our_returned_value = self.head.data self.head = self.head.next return our_returned_value
2d5ff47ae292ccb66d00aeea9471839310bae822
vamsikrishna6668/python
/class8.py
827
3.859375
4
class Employee: emp_desgination=input("Enter a Employee Desgination:") emp_work_loaction=input("Enter a Employee Work Location:") def fun1(self): print("Iam a function1") def assign(self,idno,name,sal): print("The idno of the Employee:",idno) print("The Name of the Employee:",name) print("The Salary of the Employee:",sal) def show(self,emp_add,emp_wiki): self.emp_add=emp_add self.emp_wiki=emp_wiki print(self.emp_wiki) print(self.emp_add) def display(self,age,cno): self.age=age self.cno=cno print("Iam a Display") #call e1=Employee() e1.fun1() e1.assign(101,"Ismail",96000000) a=input("Enter a Employee address:") b=input("Enter a Employee Wiki:") e1.show(a,b) e1.display(25,8500580594)
4bb0736d12da8757a76839f242d902fb08afc461
vamsikrishna6668/python
/class2.py
559
4.3125
4
# w.a.p on class example by static method and static variables and take a local variable also print without a reference variable? class student: std_idno=101 std_name="ismail" @staticmethod def assign(b,c): a=1000 print("The Local variable value:",a) print("The static variable name:",student.std_name) print("The static variable idno: ",student.std_idno) print("Iam a static method") print(b*c) #call student.assign(50,60) print(student().std_idno) print(student().std_name)
2435e4af4414429c2bc3b66ee1475829799b01d6
seraht/AmazonScraper
/Scraping/laptop_features_class.py
2,267
3.546875
4
""" Define an OOP Features, with the corresponding attributes and functions for the features of the laptop Authors: Serah """ from Createdb import connect_to_db from datetime import datetime import config from Logging import logger import sys sys.path.append('../') DB_FILENAME = config.DB_FILENAME class Features: def __init__(self, screen_size='', max_screen_resolution='', chipset_brand='', card_description='', brand='', item_weight='', operating_system='', computer_memory_type='', batteries='', date_first_available=''): self.screen_size = screen_size self.max_screen_resolution = max_screen_resolution self.brand = chipset_brand self.card_description = card_description self.brand_name = brand self.item_weight = item_weight self.operating_system = operating_system self.computer_memory_type = computer_memory_type self.batteries = batteries self.date = date_first_available # Check if we didn't get empty values from the scraping. # If valid is 0, I will retry the scraping. if self.screen_size != '' or self.max_screen_resolution != '' or self.brand != '' \ or self.card_description != '' or self.brand_name != '' or self.item_weight != '' \ or self.operating_system != '' or self.computer_memory_type != '' or self.batteries != '': self.valid = 1 else: self.valid = 0 self.con = connect_to_db() self.cur = self.con.cursor() def add_to_db(self, laptop_id, link): """Add the Features to the table laptop_features of the db""" try: query = config.QUERY_INSERT_FEATURES records = (laptop_id, link, self.screen_size, self.max_screen_resolution, self.brand, self.card_description, self.brand_name, self.item_weight, self.operating_system, self.computer_memory_type, self.batteries, self.date, datetime.now(), self.valid) self.cur.execute(query, records) self.con.commit() logger.info('Table features laptop: added -> ' + str(laptop_id)) except Exception as e: logger.error(f'Adding Laptop features: {e}')
8425d06717614c9e3d0a34e0c253cf1f6eebf8d3
svi-lab/general_programs
/slice_of_pie.py
3,391
3.53125
4
import numpy as np from warnings import warn def slice_of_pie(matrix, phi_1, phi_2, r_1=0, r_2=np.inf, center=False): """isolates the sclice of an image using polar coordinates Prerequisites: numpy Parameters: matrix:2D ndarray: input matrix as 2D numpy array (your input image) r_1:float: the length in pixels of the min radius r_2:float: the length in pixels of the max radius center:(float, float): tuple of coordinates of the center phi_1:float: start value in degrees phi_2:float: end value in degrees (the angle is measured from 0 to 360, starting from 6 o'clock counter clockwise) Note: You have to remember that numpy matrix indexes start from upper left corner Consequently, our positive quadrant is on the lower right Output: slice:masked 2D ndarray: the same imput matrix with all the values but the slice masked Example: Say you want to keep only the values of the given matrix inside the area 10°-45°, r<60: # initialize some basic matrix: my_matrix = np.zeros((150,200)) # define the slice: my_slice = slice_of_pie(my_matrix, 10, 45, r_max=60) # show the result: plt.imshow(my_slice) """ # Transforming negative angles into positive: if phi_1 < 0: phi_1 += 360 if phi_2 == 0: phi_2 = 360 if phi_2 < 0: phi_2 += 360 def _angle_condition(alpha, phi_1=phi_1, phi_2=phi_2): '''specifies the condition to be satisfied by the angle value depending on the relative input values of phi_1 and phi_2 Example: phi_1 = -20 phi_2 = 20 We suppose that the user wanted to isolate the 40° slice and not the 320° slice. ''' if phi_1 > phi_2: return ((alpha > phi_1) | (alpha < phi_2)) # bitwise logical OR else: return ((alpha > phi_1) & (alpha < phi_2)) # bitwise logical AND M, N = matrix.shape if type(center) == tuple and ((center[0] <= M) & (center[1] <= N)): img_cen = center elif center: raise ValueError('Your center needs to be a tuple of coordinates inside the image') elif center == False: img_cen = ((M-1)/2, (N-1)/2) # IMPORTANT: The center of the image furthest_point = np.sqrt((max(img_cen[0], M-img_cen[0]))**2 + (max(img_cen[1], N-img_cen[1]))**2) # Checking if the values are valid: if not ((r_2 > r_1) and (r_1 >= 0)): raise ValueError('You must have "0 <= r_1 < r_2"') if r_1 > furthest_point: warn("Check your r_1 value, you risk getting an empty image") x, y = np.mgrid[0:M, 0:N] X = x - img_cen[0] # New X from the center of the image Y = y - img_cen[1] Z = X + 1j*Y PHI = np.angle(Z, deg=True) # in order to have values from 0 to 360 instead from -180 to +180 as given by default: PHI += 180 * (1 - np.sign(PHI)) # here follows the definition of the radius condition: R = np.abs(Z) def _radius_condition(radius, r_1=r_1, r_2=r_2): return ((radius < r_2) & (radius > r_1)) slice_mask = _angle_condition(PHI) & _radius_condition(R) # combining the conditions on angle and radius return np.ma.masked_array(matrix, mask=np.logical_not(slice_mask))
3a5908b10e1eb651085ac4dee75e344b8bb9cc83
singzinc/PythonTut
/basic/tut2_string.py
785
4.3125
4
# ====================== concat example 1 =================== firstname = 'sing' lastname = 'zinc ' print(firstname + ' ' + lastname) print(firstname * 3) print('sing' in firstname) # ====================== concat example 2 =================== foo = "seven" print("She lives with " + foo + " small men") # ====================== Concat example 3 =================== x = 'apples' y = 'lemons' z = 'In the basket are %s and %s' % (x,y) print(z) #=============== example 2 =================== firstname = 'Christopher Arthur Hansen Brooks'.split(' ')[0] # [0] selects the first element of the list lastname = 'Christopher Arthur Hansen Brooks'.split(' ')[-1] # [-1] selects the last element of the list print(firstname) print(lastname) # this is incorrect example # x = 'Chris' + 2 # print(x) x = 'Chris' + str(2) print(x)
57d256f05332980e76360dc99e3f2693905a8b60
giacomofi/DijkstraAlgorithmR
/heapdijkstra.py
2,818
3.515625
4
from graph import Graph from node import Node import time class HeapDijkstra: def __init__(self): pass nodeLinkAndCost = [] heaps = [] finalHeap = [] def createGraph(self): nodes = [] g = Graph(nodes) f = open("GeneratedGraph.txt", "r") lines = f.readlines() linesSize = len(lines) f.close() numberOfNodes = int(lines[0]) allNodeLinks = [] for i in range(0, numberOfNodes): for j in range(1, numberOfNodes): nodeAndLinks = lines[j].split("->") links = nodeAndLinks[1].split(",") allNodeLinks.append(links) n = Node(i, i + 1, allNodeLinks[i]) g.getNodes().append(n) for j in range(numberOfNodes, linesSize): arcAndCost = lines[j].split("=") arcElements = arcAndCost[0].split(",") self.heaps.append((int(arcElements[0]), int(arcElements[1]), int(arcAndCost[1]))) finalHeaps = [] actual = self.heaps[0][0] for i in range(0, len(self.heaps)): y = self.heaps[i][0] if (actual == y): finalHeaps.append(self.heaps[i]) if (actual != y): actual = y self.nodeLinkAndCost.append(finalHeaps) finalHeaps = [] finalHeaps.append(self.heaps[i]) if (i == len(self.heaps) - 1): self.nodeLinkAndCost.append(finalHeaps) for i in range(0,len(self.nodeLinkAndCost)): self.finalHeap.append((sorted(self.nodeLinkAndCost[i], key=lambda tup: tup[2]))) for i in range(0, numberOfNodes): if i == 0: g.getNodes()[i].setWeight(0) else: g.getNodes()[i].setWeight(999999) return g def dijkstraWithHeap(self): graph = self.createGraph() nodes = graph.getNodes() temporaryNodes = nodes selected = temporaryNodes[0].getNodeId() print("Init " + str(selected)) sink = nodes[len(nodes) - 1].getNodeId() print("The sink is " + str(sink)) predecessors = [] trigger = selected next = 0 start = time.clock() while trigger != sink: print("Node actually selected is: " + str(selected)) trigger = selected if selected != sink: tupleInExam = (self.finalHeap[next])[0] elementInExam = tupleInExam[1] next = elementInExam-1 predecessors.append(selected) selected = elementInExam predecessors.append(sink) print("Dijkstra Algorithm performed in " + str((time.clock() - start))) return predecessors
9e59cf888a34263475acad0a8dd3543d5352a105
gbmhunter/AdventOfCode2017
/day12/day12.py
1,361
3.65625
4
connections = [] with open('input.txt', newline='') as file: for line in file: connPrograms = line[line.index('>') + 2:] connPrograms = [x.strip() for x in connPrograms.split(',')] connPrograms = list(map(int, connPrograms)) connections.append(connPrograms) def FindGroup(startProgram): group = [] WalkPipes(startProgram, group) return group def WalkPipes(index, group): group.append(index) connPrograms = connections[index] for connProgram in connPrograms: # Make sure we havn't already visited this program! if not connProgram in group: WalkPipes(connProgram, group) group0 = FindGroup(0) print('num of programs in group 0 (part 1 answer) = ' + str(len(group0))) def FindNumGroups(): groups = [] for index, connection in enumerate(connections): # First, check if this program (index) is already part # of a group alreadyInGroup = False for group in groups: if index in group: alreadyInGroup = True break if not alreadyInGroup: group = FindGroup(index) groups.append(group) return len(groups) numGroups = FindNumGroups() print('numGroups (part 2 answer) = ' + str(numGroups))
bb3d93729ebf17b23e6af471a3165371da9715fc
gbmhunter/AdventOfCode2017
/day5/day5.py
973
3.640625
4
input = open('input.txt') inputLines = input.readlines() instrList = [] for line in inputLines: instrList.append(int(line)) canExit = False index = 0 steps = 0 while True: if index < 0 or index >= len(instrList): break instr = instrList[index] # print('instr = ' + str(instr)) # Increment current instruction by 1 instrList[index] = instr + 1 # Update index index += instr steps += 1 print('answer (part 1) = ' + str(steps)) instrList = [] for line in inputLines: instrList.append(int(line)) canExit = False index = 0 steps = 0 while True: if index < 0 or index >= len(instrList): break instr = instrList[index] # print('instr = ' + str(instr)) # Perform instruction update rules if instr >= 3: instrList[index] = instr - 1 else: instrList[index] = instr + 1 # Update index index += instr steps += 1 print('answer (part 2) = ' + str(steps))
cb8589722606e8fa69a9db8c49f7a55080f8a8cc
talhaibnaziz/projects
/pi3ddemos/CollisionBalls.py
1,902
3.65625
4
#!/usr/bin/python from __future__ import absolute_import, division, print_function, unicode_literals """ Example of using the loop control in the Display class with the behaviour included in the pi3d.sprites.Ball class """ import random import sys import math import demo import pi3d MAX_BALLS = 25 MIN_BALL_SIZE = 5 MAX_BALL_SIZE = 40 MAX_BALL_VELOCITY = 10.0 KEYBOARD = pi3d.Keyboard() LOGGER = pi3d.Log(__name__, level='INFO') BACKGROUND_COLOR = (1.0, 1.0, 1.0, 0.0) DISPLAY = pi3d.Display.create(background=BACKGROUND_COLOR) WIDTH, HEIGHT = DISPLAY.width, DISPLAY.height ZPLANE = 1000 fov = 2.0 * math.degrees(math.atan(HEIGHT/2.0/ZPLANE)) CAMERA = pi3d.Camera((0, 0, 0), (0, 0, -1.0), (1, 1100, fov, WIDTH / float(HEIGHT))) SHADER = pi3d.Shader('uv_flat') TEXTURE_NAMES = ['textures/red_ball.png', 'textures/grn_ball.png', 'textures/blu_ball.png'] TEXTURES = [pi3d.Texture(t) for t in TEXTURE_NAMES] def random_ball(b): """Return a ball with a random color, position and velocity.""" return pi3d.Ball(shader=SHADER, texture=TEXTURES[int(3 * b / MAX_BALLS) % 3], radius=random.uniform(MIN_BALL_SIZE, MAX_BALL_SIZE), x=random.uniform(-WIDTH / 2.0, WIDTH / 2.0), y=random.uniform(-HEIGHT / 2.0, HEIGHT / 2.0), z=ZPLANE, vx=random.uniform(-MAX_BALL_VELOCITY, MAX_BALL_VELOCITY), vy=random.uniform(-MAX_BALL_VELOCITY, MAX_BALL_VELOCITY)) SPRITES = [random_ball(b) for b in range(MAX_BALLS)] DISPLAY.add_sprites(*SPRITES) LOGGER.info('Starting CollisionBalls') while DISPLAY.loop_running(): for i, ball1 in enumerate(SPRITES): for ball2 in SPRITES[0:i]: ball1.bounce_collision(ball2) if KEYBOARD.read() == 27: DISPLAY.stop()
1a8b164a526e8a1cde7fc6617f1caf31f95c7cb3
antoniogi/HPC
/Python/TACC_HPC/3_matplotlib/bars_color.py
590
4.03125
4
#!/usr/bin/env python # # Creates and displays a bar plot. Changes the bar color depending on # the y value # # # agomez (at) tacc.utexas.edu # 30 Oct 2014 # # --------------------------------------------------------------------- import matplotlib.pyplot as plt import numpy as np x = np.arange(5) yvals = [-100, 200, -25, 50, 10] bars = plt.bar(x, yvals) #change color of bars when y<0 for idx, val in enumerate(yvals): if (val<0): bars[idx].set_color('r') plt.xticks(x+0.5, ('x1', 'x2', 'x3', 'x4', 'x5')) #add a horizontal line at y=0 plt.axhline(0, color='black') plt.show()
21edae2f34df0c3b13ec7a37bdbfcfce357fe524
jgramm/altfactsbot
/textToMarkov.py
5,144
3.609375
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 11 15:35:37 2017 @author: James """ import re import random def textTo2GramMarkov(text, wordsTo=dict(), count=0): #text = re.sub(r'\W+', '', text) #words = text.split() words = "".join((char if char.isalpha() else " ") for char in text).split() # wordsTo is a dictionary of dictionaries. The first key is the word we are # going to markov from. The second key is the word we are going to. The # value is the frequency of key1 to key2 for i in range(len(words) - 1): w = words[i] w1 = words[i+1] if w in wordsTo.keys(): if w1 in wordsTo[w].keys(): wordsTo[w][w1] += 1 else: wordsTo[w][w1] = 1 else: wordsTo[w] = {w1: 1} return (wordsTo, count + len(words) - 1) def allTextTo2GramMarkov(lines): wordsTo = dict() count = 0 count2 = 0 for line in lines: print('finished %i of %i' % (count2, len(lines))) count2 += 1 (wordsTo, tempCount) = textTo2GramMarkov(line.lower(), wordsTo) count += tempCount #wordsTo = normalize2GramMarkov(wordsTo, count) print('done generating markov') print(wordsTo) return wordsTo def sampleMarkov(markov, w): if w in markov.keys(): probs = markov[w] total = 0 for val in probs.values(): total += val ind = random.randrange(total) for key in probs.keys(): ind -= probs[key] if ind <= 0: return key return 'oops' #def normalize2GramMarkov(markov, count): # for k1 in markov.keys(): # for k2 in markov[k1].keys(): # markov[k1][k2] /= count def textTo3GramMarkov(text, wordsTo=dict()): #text = re.sub(r'\W+', '', text) #words = text.split() words = "".join((char if char.isalpha() else " ") for char in text).split() # wordsTo is a dictionary of dictionaries. The first key is the word we are # going to markov from. The second key is the word we are going to. The # value is the frequency of key1 to key2 for i in range(len(words) - 2): w = words[i] w1 = words[i+1] w2 = words[i+2] if w in wordsTo.keys(): if (w1,w2) in wordsTo[w].keys(): wordsTo[w][(w1,w2)] += 1 else: wordsTo[w][(w1,w2)] = 1 else: wordsTo[w] = {(w1,w2): 1} return wordsTo def allTextTo3GramMarkov(lines): wordsTo = dict() count2 = 0 for line in lines: print('finished %i of %i' % (count2, len(lines))) count2 += 1 wordsTo = textTo3GramMarkov(line.lower(), wordsTo) print('done generating markov') print(wordsTo) return wordsTo def textTo3GramMarkov2(text, wordsTo=dict()): #text = re.sub(r'\W+', '', text) #words = text.split() words = "".join((char if char.isalpha() else " ") for char in text).split() # wordsTo is a dictionary of dictionaries. The first key is the word we are # going to markov from. The second key is the word we are going to. The # value is the frequency of key1 to key2 if len(words) < 3: return wordsTo for i in range(len(words) - 2): w = words[i] w1 = words[i+1] w2 = words[i+2] if w in wordsTo.keys(): if w2 in wordsTo[(w,w1)].keys(): wordsTo[(w,w1)][w2] += 1 else: wordsTo[(w,w1)][w2] = 1 else: wordsTo[(w,w1)] = {w2: 1} return wordsTo def allTextTo3GramMarkov2(lines): wordsTo = dict() count2 = 0 for line in lines: print('finished %i of %i' % (count2, len(lines))) count2 += 1 wordsTo = textTo3GramMarkov2(line.lower(), wordsTo) print('done generating markov') print(wordsTo) return wordsTo def sample3Markov2(markov, w, w1): if (w,w1) in markov.keys(): probs = markov[(w,w1)] total = 0 for val in probs.values(): total += val ind = random.randrange(total) for key in probs.keys(): ind -= probs[key] if ind <= 0: return key return 'oops' def main(): lines = [] with open('trumpSpeeches.txt', 'r', encoding='UTF8') as f: lines = f.readlines() m = allTextTo3GramMarkov2(lines) w = 'build' w1 = 'a' print(w) for i in range(100): print(w1) s = sample3Markov2(m, w, w1) w = w1 w1 = s #print(sampleMarkov(m,'warned')) if __name__=='__main__': main()
efc04c2b1660461fb8321fa29699e5d73ffd6285
oliviervos/python_workbook_174_Solution
/IntroductionToProgramming/E14.py
169
3.734375
4
height_us = map(float,raw_input("please input your height with feet and inches, sep by ,").split(',')) print "your height in cm is", 2.54*(height_us[0]*12+height_us[1])
79b4b968d475c29c3a99f4a85724ca9a3d05f4c9
oliviervos/python_workbook_174_Solution
/IntroductionToProgramming/E13.py
1,132
3.6875
4
# the solution in the book is optimal but too simple, here we give the optimal dynamic programming solution coins = input("input a number of cents in integer\n") pennies = 1 nickels = 6 #in order to make it harder, we make nickles to be 6 dimes = 10 quarters = 25 #limit the denominations to only 4 types from collections import Counter def reconstructCoins(pre_ls,cur): count = Counter() if pre_ls[cur] == -1: count[cur] += 1 return count else: count[cur - pre_ls[cur]] += 1 return count + reconstructCoins(pre_ls, pre_ls[cur]) def makeChange(coin,deno): ls = [0]*(coin+1) pre_ls = [0]*(coin+1) #print pre_ls for de in deno: if de <= coin: ls[de] = 1 pre_ls[de] = -1 for i in range(2,coin+1): if pre_ls[i] != -1: temp_min = [] for de in deno: if i - de >= 0: temp_min.append((ls[i-de]+1,i-de)) min_tuple = min(temp_min) ls[i] = min_tuple[0] pre_ls[i] = min_tuple[1] count = reconstructCoins(pre_ls,len(pre_ls)-1) print ls[-1] #print pre_ls print count # print "The minimum number of coins is {0}, combination is {1}" deno = [1,6,10,25] makeChange(coins,deno)
590b4ee6898e35551b8059ef9256d307a8bcce59
markvakarchuk/ISAT-252
/Python/Rock, Paper, Scissors - Linear.py
1,891
4.1875
4
import time import random # defining all global variables win_streak = 0 # counts how many times the user won play_again = True # flag for if another round should be played game_states = ["rock", "paper", "scissors"] #printing the welcome message print("Welcome to Rock, Paper, Scissors, lets play!") time.sleep(0.5) input("Press Enter to continue... \n") # this function is promted at the beginning and after every round if the user won # def play_round(): while play_again: # define local variables user_move = input("Enter 'rock','paper', or 'scissors': ") # computers turn to generate move comp_move = random.choice(game_states) # see if user won # user can win with 3 different combinations # 1) Scissors beats Paper5 # 2) Rock beats Scissors # 3) Paper beats Rock if comp_move == user_move: # first check if it was a time print("Tie! Go again! \n") play_again = True elif comp_move == 'paper' and user_move == 'scissors': # check for combo 1 print("Scissors beats paper! Go again! \n") win_streak += 1 play_again = True elif comp_move == 'scissors' and user_move == 'rock': # check for combo 2 print("Rock beats scissors! Go again! \n") win_streak += 1 play_again = True elif comp_move == 'rock' and user_move == 'paper': # check for combo 3 print("Paper beats rock! Go again! \n") win_streak += 1 play_again = True else: # means computer won, print how computer won and end round print("\n" + str(comp_move) + " beats your move of " + str(user_move)) print("Better luck next time! \n") play_again = False print("********************************") print("Win streak: " + str(win_streak)) print("********************************") print("\n") print("Thanks for playing!") print("\n") print("\n")
b47c6a6383e857ea7ca8e93cc0c24f43a59c7516
piyushsharma161/Detect-and-count-differnet-products
/training/copy_dir.py
1,122
3.515625
4
import os, shutil import argparse ''' Creating the output directory if not already exists Doing the copy directory by recursively calling my own method. When we come to actually copying the file I check if the file is modified then only we should copy. ''' parser = argparse.ArgumentParser() def copy_dir(src, dst, symlinks=False, ignore=None): if not os.path.exists(dst): os.makedirs(dst) for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) if os.path.isdir(s): copy_dir(s, d, symlinks, ignore) else: if not os.path.exists(d) or os.stat(s).st_mtime - os.stat(d).st_mtime > 1: shutil.copy2(s, d) def main(): parser.add_argument('src', help='description for source file') parser.add_argument('dst', help='description for destination file') args = parser.parse_args() if not os.path.exists(args.src): os.makedirs(args.src) shutil.rmtree(args.dst) copy_dir(args.src, args.dst) shutil.rmtree(args.src) os.mkdir(args.src) if __name__ == '__main__': main()
c07f63c3755581aca8eb2c7adf3024aaf422ea60
eclansky/scriptPlayground
/looping.py
301
3.9375
4
#looping #for loops #Make a for loop that prints out dictionary stuff #items returns list of dictionaries key:value pairs # dict.items format # Putting sep separator equal to empty string makes it delete the spaces between for name, price in menu_prices.items(): print(name, ':', price, sep='')
51d1da533af29e0a438cfa46ab22b85054e3eeb4
alexng96/ECE143Team6
/analysis_modules.py
3,095
4.40625
4
import pandas as pd def make_pandas(fname): """Makes a pandas dataset from the given csv file name. Changes data-types of numeric columns Arguments: fname {string} -- the csv files with CAPE data """ assert fname == 'engineering.txt' or 'humanities.txt' or 'socialSciences.txt' or 'ucsd.txt', "Not a correct input file" colNames = ['Course Name', 'Summer?', 'Term', 'Enrolled', 'Evals Made', 'Recommend Class %', 'Recommend Prof %', 'Hrs/Week', 'GPA Expected', 'GPA Received'] data = pd.read_csv(fname, names = colNames) data.apply(pd.to_numeric, errors='ignore') return data def average_GPA(data, summer = True, year = 'all', expected = False): """Returns the average GPA either from all summer or non-summer courses. Can be cumulative or only courses from a certain year. Example: average_GPA(data, False, '09', True) will return the average expected GPA of all non-summer courses from 2009 Arguments: data {DataFrame} -- DataFrame of CAPE data Keyword Arguments: summer {bool} -- True if average from summer courses, False if non-summer courses (default: {True}) year {str} -- Year of GPA average desired (default: {'all'}) expected {bool} -- True if expected GPA, False if Received GPA (default: {False}) """ temp = df_trim_term(data, summer, year) if expected: return temp["GPA Expected"].mean() return temp["GPA Received"].mean() def average_enrollment(data, summer = True, year = 'all'): """Returns the average enrollment number from all summer or non-summer courses. Can be cumulative or only courses from a certain year. Example: average_enrollment(data, True, '10') will return the average enrollment of all summer courses from 2010 Arguments: data {DataFrame} -- DataFrame of CAPE data Keyword Arguments: summer {bool} -- True if average from summer courses, False if non-summer courses (default: {True}) year {str} -- Year of average enrollment desired (default: {'all'}) """ temp = df_trim_term(data, summer, year) return temp['Enrolled'].mean() def df_trim_term(data, summer, year): """Returns a DataFrame with only courses determined by the given parameters Arguments: data {DataFrame} -- DataFrame of CAPE data summer {bool} -- True if summer courses, False if non-summer courses year {str} -- Year desired """ assert year == 'all' or '11' or '12' or '13' or '14' or '15' or '16' or '17', "Possible Years: 11-17" assert isinstance(data, pd.DataFrame), 'Given Data is not a Pandas DataFrame' assert isinstance(summer, bool), 'Incorrect Parameter (Boolean): Determines summer or non-summer courses' if year == 'all' and summer: temp = data[(data['Summer?'] == 'S')] elif year == 'all': temp = data[(data['Summer?'] == 'NS')] elif summer: temp = data[(data['Term'].str.contains(year)) & (data['Summer?'] == 'S')] else: temp = data[(data['Term'].str.contains(year)) & (data['Summer?'] == 'NS')] return temp
3a784950aad8f17238f9aa4ca346ae1491f77b92
rebondy/barbot
/algorithm.py
5,373
3.75
4
Margarita = ["Tequila", "Cointreau", "Lime Juice"] MintJulep = ["Wiskey", "Angostura Bitters", "Sugar Syrup"] PlantersPunch = ["White Rum", "Lime Juice", "Sugar Syrup", "Angostura Bitters"] Cosmopolitan = ["Vodka", "Cointreau", "Lime Juice", "Cranberry Juice"] Vodkatini = ["Vodka", "Vermouth"] Fitzgerald = ["Lemon Juice", "Sugar Syrup", "Angostura Bitters", "Gin"] DryMartini = ["Gin", "Vermouth"] VodkaSour = ["Vodka", "Lemon Juice", "Sugar Syrup"] Gimlet = ["Gin", "Lime Juice"] LemonDaiquiri = ["Cointreau", "White Rum", "Lemon Juice"] CranberryVodka = ["Cranberry Juice", "Vodka"] Manhattan = ["Angostura Bitters", "Vermouth", "Wiskey"] Daiquiri = ["White Rum", "Sugar Syrup", "Lime Juice"] WiskeySour = ["Wiskey", "Lemon Juice", "Sugar Syrup"] CapeCodder = ["Vodka", "Cranberry Juice"] OldFashioned = ["Wiskey", "Angostura Bitters", "Sugar Syrup"] Mojito = ["Sugar Syrup", "White Rum"] #print("the length is", len(masterSet)) #print(masterSet) def sort (): # This function uses the randomly ordered set (masterSet) to place an ingredient at a servo # initialize variables masterList = Margarita + MintJulep + PlantersPunch + Cosmopolitan + Vodkatini + Fitzgerald + DryMartini + VodkaSour + Gimlet + LemonDaiquiri + CranberryVodka + Manhattan + Daiquiri + WiskeySour + CapeCodder + OldFashioned + Mojito masterSet = set(masterList) servo1 = ['first', 'second', 'third'] servo2 = ['first', 'second', 'third'] servo3 = ['first', 'second', 'third'] servo4 = ['first', 'second', 'third'] n = 0 overlapCounter = 0 # place ingredient at each servo for i in masterSet: if n < 3: servo1[n] = i n = n +1 elif n < 6: servo2[n-3] = i n = n + 1 elif n < 9: servo3[n-6] = i n = n + 1 elif n < 12: servo4[n-9] = i n = n + 1 # write what ingredient is randomly placed in which servo's position # print("Servo 1 is : ", servo1,"Servo 2 is : ", servo2,"Servo 3 is : ", servo3,"Servo 4 is : ", servo4) # check each drink recipe to see if there is overlap at each servo overlapCounter = overlap(servo1, servo2, servo3, servo4, Margarita) overlapCounter = overlapCounter + overlap(servo1, servo2, servo3, servo4, MintJulep) overlapCounter = overlapCounter + overlap(servo1, servo2, servo3, servo4, PlantersPunch) overlapCounter = overlapCounter + overlap(servo1, servo2, servo3, servo4, Cosmopolitan) overlapCounter = overlapCounter + overlap(servo1, servo2, servo3, servo4, Vodkatini) overlapCounter = overlapCounter + overlap(servo1, servo2, servo3, servo4, Fitzgerald) overlapCounter = overlapCounter + overlap(servo1, servo2, servo3, servo4, DryMartini) overlapCounter = overlapCounter + overlap(servo1, servo2, servo3, servo4, VodkaSour) overlapCounter = overlapCounter + overlap(servo1, servo2, servo3, servo4, Gimlet) overlapCounter = overlapCounter + overlap(servo1, servo2, servo3, servo4, LemonDaiquiri) overlapCounter = overlapCounter + overlap(servo1, servo2, servo3, servo4, CranberryVodka) overlapCounter = overlapCounter + overlap(servo1, servo2, servo3, servo4, Manhattan) overlapCounter = overlapCounter + overlap(servo1, servo2, servo3, servo4, Daiquiri) overlapCounter = overlapCounter + overlap(servo1, servo2, servo3, servo4, WiskeySour) overlapCounter = overlapCounter + overlap(servo1, servo2, servo3, servo4, CapeCodder) overlapCounter = overlapCounter + overlap(servo1, servo2, servo3, servo4, OldFashioned) overlapCounter = overlapCounter + overlap(servo1, servo2, servo3, servo4, Mojito) # print("Overlap on this one was: ", overlapCounter) # while overlapCounter > 5: # main() # if overlapCounter <= 5: # print("Overlap on this one was: ", overlapCounter) # print("Servo 1 is : ", servo1,"Servo 2 is : ", servo2,"Servo 3 is : ", servo3,"Servo 4 is : ", servo4) print("Overlap on this one was: ", overlapCounter) print("Servo 1 is : ", servo1,"Servo 2 is : ", servo2,"Servo 3 is : ", servo3,"Servo 4 is : ", servo4) def overlap (servo1 : list, servo2 : list, servo3 : list, servo4 : list, drinkRecipe : list): overlap = 0 for i in range(len(drinkRecipe)): overlap = overlap + checkServo(i, drinkRecipe, servo1) overlap = overlap + checkServo(i, drinkRecipe, servo2) overlap = overlap + checkServo(i, drinkRecipe, servo3) overlap = overlap + checkServo(i, drinkRecipe, servo4) return overlap def checkServo (i : int, drinkRecipe : list, servoToCheck : list): overlap = 0 if drinkRecipe[i] in servoToCheck: if i+1 < len(drinkRecipe): if drinkRecipe[i+1] in servoToCheck: overlap = overlap + 1 #print('Overlap occured at: ', servoToCheck) if i+2 < len(drinkRecipe): if drinkRecipe[i+2] in servoToCheck: overlap = overlap + 1 #print('Overlap occured at: ', servoToCheck) if i+3 < len(drinkRecipe): if drinkRecipe[i+3] in servoToCheck: overlap = overlap + 1 #print('Overlap occured at: ', servoToCheck) return overlap def main(): sort() main()
2f0f16f52d149b8420c44326c81b66f24be427e3
rudrut/developing-python-applications-2020
/Week7_tasks.py
4,921
3.65625
4
#---------------------------------------------------------------- #Task 1 #class Complex: # def __init__(self, real = 0, imaginary = 0): # self.real = real # self.imaginary = imaginary # # def getReal(self): # return self.real # # def getImaginary(self): # return self.imaginary # # def setReal(self, a): # self.real = a # # def setImaginary(self, b): # self.imaginary = b # # def __str__(self): # return "{} {} {}i".format(self.real, '+' if self.imaginary >= 0 else '-', abs(self.imaginary)) # # def __add__(self, other): # return Complex(self.real + other.real, self.imaginary + other.imaginary) # # def __sub__(self, other): # return (self.real - other.real, self.imaginary - other.imaginary) # # def conjugate(self): # return Complex(self.real, -self.imaginary) # # def __neg__(self): # return Complex(-self.real, -self.imaginary) # # def __mul__(self, other): # real = self.real * other.real - self.imaginary * other.imaginary # imaginary = self.imaginary * other.real + self.real * other.imaginary # return Complex(real, imaginary) # # def __truediv__(self, other): # conjugate = other.conjugate() # # den = other * conjugate # den = den.real # # number = self / conjugate # return Complex(number.real/den, number.imaginary/den) #---------------------------------------------------------------- #Task 2 #class Clock: # def __init__(self, hours, minutes, seconds): # self.hours = hours # self.minutes = minutes # self.seconds = seconds # # def __str__(self): # return "{0:02d}:{1:02d}:{2:02d}".format(self.hours, self.minutes, self.seconds) # # def tick(self): # self.seconds += 1 # if self.seconds == 60: # self.seconds = 0 # self.minutes += 1 # # if self.minutes == 60: # self.minutes = 0 # self.hours += 1 # # if self.hours == 24: # self.hours = 0 #class AlarmClock(Clock): # def __init__(self, hours, minutes, seconds): # super().__init__(hours, minutes, seconds) # # def soundAlarm(self, alarmHour, alarmMinute): # if self.hours == alarmHour and self.minutes == alarmMinute and self.seconds == 0: # print("AAAAALLLLLEEEEERRRRRRTTTTTT") #---------------------------------------------------------------- #Task 3 #class Bird: # def __init__(self, name, amountOfEggs = 1): # self.name = name # if amountOfEggs < 1: # self.amountOfEggs = 1 # elif amountOfEggs > 10: # self.amountOfEggs = 10 # else: # self.amountOfEggs = amountOfEggs # # def getName(self): # return self.name # # def setName(self, desiredName): # self.name = desiredName # # def getAmountOfEggs(self): # return self.amountOfEggs # # def setAmountOfEggs(self, desiredAmount): # if desiredAmount >= 1 and desiredAmount <= 10: # self.amountOfEggs = desiredAmount # # def __str__(self): # return "Bird's name is: " + str(self.name) + ", and it has " + str(self.amountOfEggs) + " egg(s)." # #class Migratory(Bird): # def __init__(self, name, amountOfEggs, country, month): # super().__init__(name, amountOfEggs) # # if len(country) < 5 and len(country) > 20: # print("Please specify country with capital first letter and with 5 to 20 characters!") # # elif country[0].isupper() == False: # self.country = country.capitalize() # else: # self.country = country # # if month < 1: # self.month = 1 # elif month > 12: # self.month = 12 # else: # self.month = month # # def getCountry(self): # return self.country # # def getMonth(self): # return self.month # # def setCountry(self, desiredCountry): # if (len(desiredCountry) >= 5 and len(desiredCountry) <= 20 and desiredCountry[0].isupper()): # self.country = desiredCountry # # def setMonth(self, desiredMonth): # if (desiredMonth >= 1 and desiredMonth <= 12): # self.month = desiredMonth # # def __str__(self): # return "Migratory is called " + str(self.name) + ", and it has " + str(self.amountOfEggs) + " egg(s). It's destination is " + str(self.country) + " and it migrates there in month " + str(self.month) + '.' #---------------------------------------------------------------- #Bonus Task 1 #---------------------------------------------------------------- #Bonus Task 2 #----------------------------------------------------------------
92d4b3e00f461d9582d502d56ae028f3297f6c90
arqcenick/SRMNIST
/contrib_homework.py
7,549
3.5
4
# CS 559 homework template # Instructor: Gokberk Cinbis # # Adapted from # https://www.tensorflow.org/get_started/mnist/pros # License: Apache 2.0 License # # Homework author: <Your name> ######################################################### # preparations (you may not need to make changes here) ######################################################### import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import matplotlib.pyplot as plt # prepare data and TensorFlow mnist = input_data.read_data_sets('data/MNIST_data', one_hot=True) sess = tf.InteractiveSession() LOW_RES_SZ = 7 # low-resolution input image size (constant) beta = 0.001 # define input and down-sampler layers x = tf.placeholder(tf.float32, shape=[None, 28*28], name='x') # groundtruth x_image = tf.reshape(x, [-1,28,28,1]) x_lr = tf.image.resize_images(x_image, [LOW_RES_SZ,LOW_RES_SZ]) # low-resolution version of x keep_prob = tf.placeholder(tf.float32) # unused unless you have dropout regularization ######################################################### # Define your super-resolution network here. The network # should take 7x7 images as input (x_lr), and predict 28x28 super-resolution images (x_sr), # (without using the 28x28 groundtruth image "x", or its class label). # Below is a simple example that consists of a single linear layer. ######################################################### def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) def conv2d(x, W, shape): reshaped = tf.reshape(x, [-1,shape[0], shape[1],W.get_shape().as_list()[2]]) conv = tf.nn.conv2d(reshaped, W, strides=[1, 1, 1, 1], padding='SAME') flattened = tf.reshape(conv, [-1, shape[0]*shape[1]]); return tf.nn.relu(flattened); def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def upsample_2d(x, size): a=x.get_shape().as_list() height = a[1]*size[0] width = a[2]*size[1] output_size = [height, width] return tf.image.resize_images(x, output_size,method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) def dense_batch_relu(x, out, phase, scope): with tf.variable_scope(scope): print(x.get_shape()) h1 = tf.contrib.layers.fully_connected(x, out, activation_fn=None, scope='dense', weights_initializer=tf.contrib.layers.initializers.xavier_initializer()) h2 = tf.contrib.layers.batch_norm(h1, center=True, scale=True, is_training=phase, scope='bn') return tf.nn.relu(h2, 'relu') tf.reset_default_graph() #x_lr_vec = tf.reshape(x_lr, [-1,LOW_RES_SZ*LOW_RES_SZ]) x = tf.placeholder(tf.float32, shape=[None, 28*28], name='x') x_image = tf.reshape(x, [-1,28,28,1]) x_lr = tf.image.resize_images(x_image, [LOW_RES_SZ,LOW_RES_SZ]) # low-resolution version of x x_lr_vec = tf.reshape(x_lr, [-1,LOW_RES_SZ*LOW_RES_SZ]) phase = tf.placeholder(tf.bool, name='phase') h1 = dense_batch_relu(x_lr_vec, 28*28, phase, 'layer1') W_conv1 = weight_variable([3, 3, 1, 32]) W_conv3 = weight_variable([3, 3, 32, 1]) h_conv1 = conv2d(h1, W_conv1, [28,28]); x_sr = conv2d(h_conv1, W_conv3,[28,28]); ''' W1 = tf.Variable(tf.random_normal([LOW_RES_SZ*LOW_RES_SZ,28*28], stddev=0.1)) b1 = tf.Variable(tf.zeros([28*28])) fc1 = tf.nn.relu(tf.matmul(x_lr_vec, W1) + b1) keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(fc1, keep_prob) fcr1 = tf.reshape(h_fc1_drop, [-1, 28, 28, 1]) W_conv1 = weight_variable([3, 3, 1, 16]) W_conv3 = weight_variable([3, 3, 16, 1]) b_conv1 = bias_variable([16]) b_conv3 = bias_variable([1]) h_conv1 = tf.nn.relu(conv2d(fcr1, W_conv1) + b_conv1) h_conv3 = tf.nn.relu(conv2d(h_conv1, W_conv3) + b_conv3) x_sr = tf.reshape(h_conv3,[-1, 28*28]) ''' ''' W_conv1 = weight_variable([3, 3, 1, 32]) W_conv2 = weight_variable([3, 3, 32, 32]) W_conv3 = weight_variable([3, 3, 32, 1]) W_conv4 = weight_variable([3, 3, 64, 1]) b_conv1 = bias_variable([32]) b_conv2 = bias_variable([32]) b_conv3 = bias_variable([1]) b_conv4 = bias_variable([1]) x_image_low = tf.reshape(x_lr, [-1,7,7,1]) print(x_image_low.get_shape()) h_conv1 = tf.nn.relu(conv2d(x_image_low, W_conv1) + b_conv1) h_upsample1 = upsample_2d(h_conv1, (2,2)); h_conv2 = tf.nn.relu(conv2d(h_upsample1, W_conv2) + b_conv2) h_upsample2 = upsample_2d(h_conv2, (2,2)); h_conv3 = tf.nn.relu(conv2d(h_upsample2, W_conv3) + b_conv3) print(h_conv2.get_shape()) x_sr = tf.reshape(h_conv3,[-1, 28*28]) ''' print(x_sr.get_shape(), x.get_shape()) ######################################################### # train on the train subset of MNIST ######################################################### # (write your training code here. here, we are just using the initial random weights) ######################################################### # evaluate your model on the train and validation sets. # use these two results when designing your architecture # and tuning your optimization method. ######################################################### with tf.name_scope('loss'): reconstruct_error = tf.reduce_mean((x_sr-x)**2) loss = reconstruct_error; ######################################################### def train(): update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) with tf.control_dependencies(update_ops): # Ensures that we execute the update_ops before performing the train_step train_step = tf.train.AdamOptimizer(1e-4).minimize(loss) sess = tf.Session() sess.run(tf.global_variables_initializer()) history = [] iterep = 200 epochs = 100 for i in range(iterep * epochs): x_train = mnist.train.next_batch(64) sess.run(train_step, feed_dict={'x:0':x_train[0], 'phase:0': 1}) if (i + 1) % iterep == 0: epoch = (i + 1)/iterep t = sess.run([loss], feed_dict={x: mnist.test.images, 'phase:0': 0}) history += [[epoch] + t] print history[-1] return history, sess history, sess = train() ######################################################### # plot an example result ######################################################### image_index = 21 # image index print("showing %d-th validation image and the super-resolution output for it" % image_index) for i in range(12): tmp_in = mnist.validation.images[image_index+i:image_index+1+i,:] tmp_lr = x_lr.eval(feed_dict={x:tmp_in, 'phase:0': 0},session=sess) tmp_out = x_sr.eval(feed_dict={x:tmp_in, 'phase:0': 0}, session=sess) plt.subplot(6,6,i*3+1) plt.imshow(tmp_in.reshape([28,28]), cmap='gray') plt.subplot(6,6,i*3+2) plt.imshow(tmp_lr.reshape([7,7]), cmap='gray') plt.subplot(6,6,i*3+3) plt.imshow(tmp_out.reshape([28,28]), cmap='gray') ######################################################### # once you finalize the model, evaluate on the test set # (only once, at the end, using the best model according the validation set error) ######################################################### print("test error %g" % reconstruct_error.eval(feed_dict={ x: mnist.test.images, 'phase:0':0}, session=sess)) plt.show()
cb8efd3255f3b5a4c19a93b4efb02de49c4c0a84
Clay190/Unit-5
/warmup13.py
265
3.640625
4
#Clay Kynor #11/16/17 #warmup13.py from random import randint words = [] for i in range(1,21): num = randint(1,100) words.append(num) words.sort() print(words) print("The maximum is", words[19]) print("The minimum is", words[0]) print("Sum", sum(words))