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
61a293256dff4c87004e8627f0afadd9a9d202ca
shea7073/More_Algorithm_Practice
/2stack_queue.py
1,658
4.15625
4
# Create queue using 2 stacks class Stack(object): def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def size(self): return len(self.items) def pop(self): return self.items.pop() def push(self, item): self.items.append(item) # Works only if entire set is passed during enqueue before any dequeueing class Queue2Stacks(object): def __init__(self): self.stack1 = Stack() self.stack2 = Stack() def enqueue(self, element): for item in element: self.stack1.push(item) while not self.stack1.isEmpty(): current = self.stack1.pop() self.stack2.push(current) return self.stack2 def dequeue(self): return self.stack2.pop() # Works better if enqueueing is happening randomly # instead of all at once at the beginning class Queue2Stacks2(object): def __init__(self): self.stack1 = Stack() self.stack2 = Stack() def enqueue(self, element): self.stack1.push(element) def dequeue(self): while not self.stack1.isEmpty(): current = self.stack1.pop() self.stack2.push(current) answer = self.stack2.pop() while not self.stack2.isEmpty(): current = self.stack2.pop() self.stack1.push(current) return answer queue = Queue2Stacks2() queue.enqueue(1) queue.enqueue(2) print(queue.dequeue()) queue.enqueue(5) queue.enqueue(6) print(queue.dequeue()) print(queue.dequeue()) print(queue.dequeue())
273a7556156975ad82607dd09ebed43e79e785c3
legacy72/suicide_analysis
/prepare_text.py
4,605
3.515625
4
import re from stemmer_porter_algorithm import Stemmer class TextPreparation: def __init__(self, text): self._st = Stemmer() self._text = text def strip_and_convert_to_lower(self): self._text = self._text.lower().strip() def remove_non_letter_characters(self): self._text = re.sub(r'([^\s\w]|_)+', '', self._text) def stemmer(self): words = self._text.split() self._text = '' for word in words: new_word = self._st.stem(word) self._text += new_word + ' ' def prepare_text(self): self.strip_and_convert_to_lower() self.remove_non_letter_characters() self.stemmer() return self._text if __name__ == '__main__': text = 'Привет читатели. Я рад то что ты читаешь мой текст. Я хотел бы рассказать тебе про свою жизнь. Знаешь, ' \ 'началась она не так поздно, всего лишь 17 лет назад. В середине декабря 9 класса угораздило мне влюбиться' \ ' по уши. Я дышал ей, я любил её больше своей жизни. Она мне сказала, что она не общалась со своими ' \ 'ровесниками, я первый, и то что она ни с кем не общалась дольше двух недель. Я подумал, что я не они, и ' \ 'она будет со мной встречаться долго, очень долго. Правда я и не рассчитывал, что свяжу с ней свою ' \ 'жизнь, так как я был простым деревенским пацанчиком, а она "принцессой". Ну есть такой закон, который ' \ 'называется "законом подлости". Я общался с ней всего лишь две с половиной недели. Я считал эти дни, ' \ 'так как они для меня очень важны. Она изменила меня, я с ней стал иначе смотреть на эту жизнь. ' \ 'Я расстался с ней по своей вине, я был очень город и ревнив. Я не поверил ей и написал ей очень ' \ 'плохое сообщение, и сожалею об этом до сих пор. После моего сообщения она написала так: "Знаешь что? ' \ 'Ты дебил! Верь своим фактам! А мне больше не пиши и не звони!" Вот это сообщение было последним от ' \ 'её "лица". После этого все зимние каникулы я употреблял спиртное. И тут всё началось. Я сначала ' \ 'выпивал, потом стал курить, летом, я не ценил свою жизнь и хотел умереть. И когда несколько бед' \ ' сразу легли на мои плечи, я решил наглотаться таблеток и сдохнуть. Но вы не поверите, меня не взяли на' \ ' тот свет! Я встал и пошёл на учёбу, хотя прошло уже два часа, я даже не чувствовал эффект, хотя съел' \ ' 20 таблеток анальгина. Последующие пол года я тупо убивал свой организм. Я стал принимать наркотики. ' \ 'Я первый раз в своей жизни попробовал спайс, и понял что это как любовь. Хорошо душе и постепенно ' \ 'убивает меня. Ведь всё так начинается: неудачная любовь, алкоголь, сигареты, наркотики' \ ' и смерть!Этот текст я написал тоже под кайфом, так что прошу не обращайте внимание ' \ 'на мои ошибки. Может быть меня сейчас' \ ' и нет. Пока...07.05.2013 Автор: 47' tp = TextPreparation(text) new_text = tp.prepare_text() print(new_text)
893f87c55d4e80e667be34e5caacc39c5dc1d81f
luizhsriva/solutions-to-CS50
/minpay.py
1,223
4
4
""" Donald Steinert MIT Intro to CS and Programming pset2a -- minpay.py requests starting cc balance, interest rate and monthly payment rate and prints monthly payment amount and remaining balance for 12 months, as well as total paid for the year interest charged on first day of next month rounds printed results to two decimal places using round() note: MIT appears to be rounding some results, but not others in its solution; this only rounds printed results, as specified in instructions """ bal = float(raw_input('What is your starting balance: ')) ann_int = float(raw_input('What is the annual interest rate: ')) mnth_min_pmnt_rt = float(raw_input('What is the minimum monthly payment rate: ')) / 100 print '\n' mnth = 1 mnth_int_rt = ann_int / 12.0 / 100 total_pmnt = 0 while mnth <= 12: print 'Month: {}'.format(mnth) mnth_min_pmnt = mnth_min_pmnt_rt * bal print 'Minimum monthly payment: {}'.format(round(mnth_min_pmnt, 2)) bal = (bal - mnth_min_pmnt) + (bal * mnth_int_rt) print 'Remaining balance: {}\n'.format(round(bal, 2)) mnth += 1 total_pmnt = total_pmnt + mnth_min_pmnt print 'Total paid: {}'.format(round(total_pmnt, 2)) print 'Remaining balance: {}\n'.format(round(bal, 2))
29436d6802295d6eb8992d2f510427219d29f35b
Mark9Mbugua/Genesis
/chatapp/server.py
1,892
4.125
4
import socket #helps us do stuff related to networking import sys import time #end of imports ### #initialization section s = socket.socket() host = socket.gethostname() #gets the local hostname of the device print("Server will start on host:", host) #gets the name of my desktop/host of the whole connection(when I run the program) port = 8080 #make sure the port is on my local host(my computer) s.bind((host,port)) #binds the socket with the host and the port print("") print("Server done binding to host and port successfully") print("") print("Server is waiting for incoming connections") print("") #we can now start listening to incoming connections s.listen(1) #we accept only one connection conn,addr = s.accept() print("") #conn is assigned to the socket itself which is the physical socket (s?) coming from the client #addr is assigned to the IP address of the client that we'll be connecting print(addr, "Has connected to the server and is now online...") #prints the IP Address/Hostname of the client that is connected to us print("") #now move on to the client side. #we're back! while 1: message = input(str(">>"))#for a decoded message message = message.encode()#to change this message into bytes since s/w interface only supports bytes conn.send(message)#conn is the client that is connected to us print("message has been sent..") print("") #piece of code that will accept the message and display it incoming_message = conn.recv(1024) #when you type a message and press enter, it is going to be stored here. #we need to decode the message since we had encoded it incoming_message = incoming_message.decode() print("Server: ", incoming_message) print("") #so far we have a one-sided chat #we need to therefore put it in a loop
8a621e39c673f20545eb7b4301c5d968fd57581c
parul21/Python-Programs
/try_except.py
157
3.515625
4
text="" try: text=input("Enter something") except EOFError: print "Eof" except KeyboardInterrupt: print "Keyboard interrupt" else: print text
43b9fe070547cf97ba59e181f6aad74505e84d04
parul21/Python-Programs
/objvar.py
909
3.96875
4
#!/usr/bin/python #filename objvar.py class Robot: population=0 def __init__(self,name): self.__name=name print "Initializing {0}".format(self.__name) Robot.population+=1 def say_hi(self): print "Greetings, my master calls me {0}".format(self.__name) def __del__(self): print "{0} is being destroyed".format(self.__name) Robot.population-=1 if(Robot.population==0): print ("{0} was the last one ".format(self.__name)) else: print ("There are still {0} robots left".format(Robot.population)) def how_many(): print "We have {0} robots left".format(Robot.population) how_many=staticmethod(how_many) r1=Robot("R1") r1.say_hi() Robot.how_many() r2=Robot("R2") r2.say_hi() Robot.how_many() #print r1.name del r1 del r2 Robot.how_many()
704274669bc30218e8dba7341167906e28969761
parul21/Python-Programs
/binarysearch.py
1,882
3.921875
4
"""def binarysearch(slist, value, last_index): length = len(slist) if(length==0): return -1 if(length==1): return 0 if slist[0]==value else -1 index = length/2 if(slist[index]==value): return last_index elif(value<slist[index]): if(length%2==0): last_index = last_index-length/2 else: last_index = last_index-1-length/2 return binarysearch(slist[:index], value, last_index) else: return binarysearch(slist[index:], value, last_index)""" not_found = -1 import unittest class TestBinS(unittest.TestCase): def test_empty(self): lst = [] key = 0 self.assertEquals(binsearch(lst, 0,), -1) """def test_equal(self): lst = [0, 0, 0, 0] self.assertEquals(binsearch(lst, 0,), 0)""" def test_negs(self): lst = [-10, -1, 0, 1 , 10] self.assertEquals(binsearch(lst, 0,), 2) def test_randoms(self): import random size = random.randint(0, 10) lst = sorted([random.randint(0, 10) for i in range(size)]) lst = list(set(lst)) #we are already aware of bug in case there are duplicates if lst: #lst can be an empty list and then lst[0] will be an error self.assertEquals(binsearch(lst, lst[0],), 0) def binsearch(slist, value, left=0, right=None): if not right: right = len(slist)-1 return binarysearch(slist, value, left, right) def binarysearch(slist, value, left, right): while(left<=right): mid = (left+right)/2 if slist[mid]==value: return mid elif value<slist[mid]: right = mid-1 return binarysearch(slist, value, left, right) else: left = mid+1 return binarysearch(slist, value, left, right) return -1 if __name__=="__main__": unittest.main()
783aaf4e6527d5defcf0a4583268032f72a8205c
lipk/pyzertz
/pyzertz/table.py
2,094
3.59375
4
import copy class Tile: def __init__(self , type : int, col : int, row : int): self.type=type #(-1) - does not exists, 0 - empty, 1 - white, 2 - gray, 3 - black self.col=col self.row=row def __str__(self): return str(self.type) def coord(self): return("col: " + str(self.col) + " row: " + str(self.row)) def copy(self): t=Tile(self.type,self.col,self.row) return t class Table: size = 0 def __init__(self, size : int): self.size=size self.tiles=[] self.marbles=[6,8,10] #white, gray, black for i in range(self.size+1): row1 = [] row2 = [] for j in range(i+self.size+1): row1.append(Tile(0,j-i,i-self.size)) if i != self.size: row2.append(Tile(0,j-self.size,self.size-i)) if i != self.size: self.tiles.insert(i,row2) self.tiles.insert(i,row1) def copy(self): t = Table(3) t.size=self.size for i in range(0,len(t.tiles)): for j in range(0,len(t.tiles[i])): t.tiles[i][j]=self.tiles[i][j].copy() t.marbles = copy.deepcopy(self.marbles) return t def __str__(self): #return '\n'.join([' '.join(map(str,row) for row in self.tiles]) #return '\n'.join(map(lambda row:map(str,row),self.tiles)) s="" for row in self.tiles: for t in row: s+=str(t) s+=' ' s+="\n" s+="white(1):"+str(self.marbles[0])+" gray(2):"+str(self.marbles[1])+" black(3):"+str(self.marbles[2])+'\n' return s def get(self , col : int , row : int): if col+row > -self.size-1 and col+row < self.size+1: return self.tiles[row+self.size][col+self.size+min(0,row)] else: pass
bb8089e56f29132ff9702bb3013a3a1b27794250
GANESH0080/Python-WorkPlace
/StringReplaceMethod/StringCharUpper.py
70
3.53125
4
name = "Ganesh Salunkhe" newString = name.replace('a', 'A') print(newString)
cda9abb1f52c06bd79b34f1fd08c0c80fe95b3da
GANESH0080/Python-WorkPlace
/GetPathOfFile/GetFilepath.py
376
3.546875
4
import os import shutil from os import path # Created file w = open("getPathFileone.txt", "w+") w.close() # Store the file path in the variable src If txt file exist if(path.exists("getPathFileone.txt")): src = path.realpath("getPathFileone.txt"); # Use src variable to split the path & filename haid, tail = path.split(src) print ("Path :", haid) print ("File :", tail)
80192a8c2357a805072936ccb99b9dabc8e27778
GANESH0080/Python-WorkPlace
/ReadFilePractice/ReadDataOne.py
291
4.25
4
# Created an File file = open("ReadFile.txt" ,"w+") # Enter string into the file and stored into variable file.write("Ganesh Salunkhe") # Open the for for reading file = open("ReadFile.txt" ,"r") # Reading the file and store file date into variable re= file.read() # Printing file data print(re)
4945dc24aafe8f9066734a23642c0cad79c6654a
GANESH0080/Python-WorkPlace
/Loops/StringForLup.py
151
3.53125
4
def sampleSTRForLoop(): str = ["Apple", "Banana", "Grapes", "Mango", "Chiku"] for x in range(2, 5): print(str[x]) sampleSTRForLoop()
d88fef56d6c618ca183bb1be662f23dc19b19c76
GANESH0080/Python-WorkPlace
/CheckingFileorDirectory/ChkFileDirectory.py
412
3.734375
4
import os.path from os import path # Created an file w = open("file.txt","w+") m = open("D:\PythonWorkPlace\samplefile.txt","w+") # Checking file exist in directory or not print("file exist:" + str(path.exists("guru99.txt"))) print("file exists:" + str(path.exists("file.txt"))) print("Directory exists:" + str(path.exists("D:\PythonWorkPlace"))) print("Directory exists:" + str(path.exists("samplefile.txt")))
24bead458694a8a5cc7138d3f074d052fdfbdec4
GANESH0080/Python-WorkPlace
/Loops/BreakInForLup.py
182
3.625
4
def sampleForLoop(): number = [2, 12, 14, 28, 9, 27, 35, 44, 78] for x in range(2, 7): print(number[x]) if (number[x]==9): break sampleForLoop()
06b1e2900a7e3aa036053b98920ae6d1776c5d7d
GANESH0080/Python-WorkPlace
/TupleInpython/CompareTupleTwo.py
90
3.78125
4
a = (5, 3) b = (5, 4) if (a > b): print("a is bigger") else: print("b is bigger")
7bcbda4e4e0d4da74cdc4dc8ed7e197d37e778c9
GANESH0080/Python-WorkPlace
/ConditionalStatements/IfElseStatementOne.py
165
3.828125
4
def SampleIfElse(): num, num1 = 25, 35 st = (num, "Is less than num1") if (num < num1) else print(num, "Is greater than num1") print(st) SampleIfElse()
74dc8724b152731c57394e5626197592e472c040
GANESH0080/Python-WorkPlace
/TupleInpython/CompareTupleOne.py
90
3.671875
4
a = (0, 5) b = (1, 4) if (a > b): print("a is bigger") else: print("b is bigger")
de3cf5eec6681b391cddf58e4f48676b8e84e727
KapsonLabs/CorePythonPlayGround
/Decorators/instances_as_decorators.py
660
4.28125
4
""" 1. Python calls an instance's __call__() when it's used as a decorator 2. __call__()'s return value is used as the new function 3. Creates groups of callables that you can dynamically control as a group """ class Trace: def __init__(self): self.enabled = True def __call__(self, f): def wrap(*args, **kwargs): if self.enabled: print('Calling {}'.format(f)) return f(*args, **kwargs) return wrap tracer = Trace() @tracer def rotate_list(l): return l[1:] + [l[0]] l = [1,2,3] t = rotate_list(l) print(t) #disable the tracer tracer.enabled = False t = rotate_list(l) print(t)
b0f164e5a063ff4078bcfeac39870eccd52bf964
BartKeulen/smartstart
/smartstart/environments/generate_gridworld.py
4,963
3.96875
4
"""Random GridWorld Generator module Defines methods necessary for generating a random gridworld. The generated gridworld is a numpy array with dtype int where each entry is a state. Attributes in the gridworld are defined with the following types: 0. State 1. Wall 2. Start state 3. Goal state States will have a grid size of 3x3. States are separated by a 1x3 of 3x1 wall that can be turned in to a state. """ import random from collections import deque import numpy as np random.seed() def _fill_cell(gridworld, pos, type=0): """Fill cell with type Cell at position pos and surrounding it is filled with type. Resulting in a 3x3 grid with center pos. Parameters ---------- gridworld : :obj:`np.ndarray` numpy array of the gridworld pos : :obj:`np.ndarray` 2D position to be filled type : :obj:`int` type to fill with (Default value = 0) """ gridworld[pos[0] - 1: pos[0] + 2, pos[1] - 1: pos[1] + 2] = type def _fill_wall(gridworld, cur_pos, new_pos, type=0): """Fill a wall between two cells Parameters ---------- gridworld : :obj:`np.ndarray` numpy array of the gridworld cur_pos : :obj:`np.ndarray` 2D position to be filled new_pos : :obj:`np.ndarray` 2D position to be filled type : :obj:`int` (Default value = 0) Raises ------ Exception Something went wrong with the wall, not possible """ pos = np.asarray((cur_pos + new_pos) / 2, dtype=np.int32) orientation = np.where(new_pos - cur_pos == 0)[0] if orientation == 0: gridworld[pos[0] - 1: pos[0] + 2, pos[1]] = type elif orientation == 1: gridworld[pos[0], pos[1] - 1: pos[1] + 2] = type else: raise Exception("Something went wrong with the wall, not possible") def _check_free_cell(gridworld, pos, location): """Check if cell is free The cell at location to move relative of pos is checked for availability. Where location is defined as 0. right 1. down 2. left 3. up Parameters ---------- gridworld : :obj:`np.ndarray` numpy array of the gridworld pos : :obj:`np.ndarray` 2D position to be filled location : :obj:`int` location to move relative of pos Returns ------- :obj:`np.ndarray` location relative of pos after applying location :obj:`bool` True if the cell is free """ pos = pos.copy() if location == 0: pos += np.array([4, 0]) elif location == 1: pos += np.array([0, -4]) elif location == 2: pos += np.array([-4, 0]) elif location == 3: pos += np.array([0, 4]) else: raise Exception("Choose from available locations: [0, 1, 2, 3]") free = False if np.sum(gridworld[pos[0] - 1: pos[0] + 2, pos[1] - 1: pos[1] + 2]) == 9: free = True return pos, free def generate_gridworld(size=None): """Generate a random GridWorld Generates a random GridWorld using a depth-first search (see `Wikipedia`_). .. _Wikipedia: https://en.wikipedia.org/wiki/Maze_generation_algorithm\ #Depth-first_search Parameters ---------- size : :obj:`tuple` size of the GridWorld (default = (100, 100)) Returns ------- :obj:`str` name (= `Random`) :obj:`~smartstart.environments.gridworld.GridWorld` new GridWorld object :obj:`int` scale (= 1) """ if size is None: size = (100, 100) if size[0] > 100 or size[1] > 100: print("\033[1mMaximum size is (100, 100). Maximum size is used for the generated maze.\033[0m") gridworld = np.ones(size, dtype=np.int32) start = np.random.randint(1, min(size), size=2) _fill_cell(gridworld, start, 2) stack = deque() cur_cell = start while True: available_cells = [] for i in range(4): cell, available = _check_free_cell(gridworld, cur_cell, i) if available: available_cells.append(cell) if not available_cells: if not stack: break cur_cell = stack.pop() else: new_cell = random.choice(available_cells) stack.append(cur_cell) _fill_wall(gridworld, cur_cell, new_cell) _fill_cell(gridworld, new_cell) cur_cell = new_cell possible_goals = np.array(np.where(gridworld == 0)) goal_idx = np.random.randint(possible_goals.shape[1]) goal = possible_goals[:, goal_idx] _fill_cell(gridworld, goal, 3) return "Random", gridworld, 1 if __name__ == "__main__": from smartstart.environments.gridworldvisualizer import GridWorldVisualizer maze = generate_gridworld() render = True visualizer = GridWorldVisualizer("RandomGridWorld") while render: render = visualizer.render(maze)
365e560f1b26ed46120f028b8655bfc643fba827
ashleyjohnson590/CS162Python-Project8b
/sort_timer.py
3,268
4.25
4
#Author: Ashley Johnson #Date: 5/20/2021 #Description: Program uses time module and decorator function to time the number of seconds it #takes the decorator function to run and the wrapper function returns the elapsed time. The #compare sorts function generates a list of 1000 numbers and makes a separate copy of the list. # Function times how long it takes bubble sort to sort the copy of the list of numbers. Function # does the same for a list of 2000, 3000, and up to 10,000 numbers. Program generates a graph using # matlib that plots number of elements being sorted on the x axis, and time in seconds to sort on # the y axis. import random from functools import wraps import time import matplotlib.pyplot as plt import matplotlib as mat def list_generator(size, low=1, high=10000): """generates a list of random numbers from 1 to 10,000""" print("\n\nGenerating list of size {}".format(size)) randomlist = [random.randint(low, high) for x in range(size)] return randomlist def sort_timer(sort_function): """decorator function that times how many seconds it takes the function to run. The wrapper function returns the elapsed time.""" @wraps(sort_function) def wrapper(list): begin = time.perf_counter() sort_function(list) end = time.perf_counter() runtime = end-begin return runtime return wrapper def compare_sorts(b_sort,i_sort): """generates a list of 1000 numbers using list_generator helper function and makes a separate copy of the list. Function times how long it takes for insertion sort to sort the copy and how long it takes bubble sort to sort the copy. Function repeats the same procedure for 2000, 3000 and up to 10,000 random numbers. """ #config = mat.get_configdir() #print(config) x_vals = [] y_vals_bubble = [] y_vals_insert = [] i = 1000 while i <= 10000: my_list = list_generator(i) my_list2 = list(my_list) x_vals.append(i) print("Getting time for bubble_sort...") y_vals_bubble.append(b_sort(my_list)) print("Getting time for insert_sort...") y_vals_insert.append(i_sort(my_list2)) i += 1000 plt.plot(x_vals, y_vals_bubble,'go--',label='Bubble Sort') plt.plot(x_vals, y_vals_insert, 'ro--', label='Insertion Sort') plt.legend(loc="upper left") plt.show() @sort_timer def bubbleSort(a_list): """ Sorts a_list in ascending order """ for pass_num in range(len(a_list) - 1): for index in range(len(a_list) - 1 - pass_num): if a_list[index] > a_list[index + 1]: temp = a_list[index] a_list[index] = a_list[index + 1] a_list[index + 1] = temp # Function to do insertion sort @sort_timer def insertion_sort(a_list): """ Sorts a_list in ascending order """ for index in range(1, len(a_list)): value = a_list[index] pos = index - 1 while pos >= 0 and a_list[pos] > value: a_list[pos + 1] = a_list[pos] pos -= 1 a_list[pos + 1] = value def main(): compare_sorts(bubbleSort,insertion_sort) if __name__ == "__main__": main()
f37b8ea7b9cffb3006fcd3a5179b4bd29f1599f4
KrishPagarSchool/Python
/countdigit.py
175
4.125
4
number=int(input("Enter The Number : ")) count = 0 while number > 0: count=count+1 number = number//10 print ("Number of digits in the given number is ", count)
e2ac7012c5b67f134a848d68cdbd969da8f2a6e3
mohamed-okasha/teccamp2020
/Python assignment/AS3.py
1,010
3.734375
4
# a program that allowes u to enter a Name and Grade of tenth student,to know thier mark whether it's excellent, very-good, good, or poor. #with open("AS3.txt") as fabj: # bio = fabj.read() # print(bio) i = 0 while i < 11 : n = input("Pls, Enter ur Name :") grade = int(input("whats ur Grade in %")) if grade>=85 and grade<=100: print(f" Name of Student : {n} Grade is {grade} % Rate : Excellent") Rate = "Excellent" elif grade>=70 and grade<85: print(f" Name of Student : {n} Grade is {grade} % Rate : Very-good") Rate = "Very-good" elif grade>=50 and grade<70: print(f" Name of Student : {n} Grade is {grade} % Rate : Good") Rate = "Good" elif grade>=0 and grade<50: print(f" Name of Student : {n} Grade is {grade} % Rate : Maybe naext time") Rate = "Poor" else: print("Unkown Result") i +=1 else: print("We Done") #x = open("AS3.txt" , "w") #x.write("AS3.py") #x.close()
ea2dc66303ac5f4c2a141f604fb396bc84583099
sakhayadeep/Guvi-sessions
/stack.py
477
3.859375
4
''' Implementation of stack in python ''' class stack: st = list() def push(self, i): self.st.append(i) print("pushed : ", i) def pop(self): if(self.st): print("popped : ", self.st.pop()) else: print("nothing to pop!!") def main(): ll = stack() for i in range(3): x = (i+1)*10 ll.push(x) print() for i in range(4): ll.pop() if __name__ == "__main__": main()
ee9cf22dae8560c6ee899431805231a107b8f0e6
smalbec/CSE115
/conditionals.py
1,110
4.4375
4
# a and b is true if both a is true and b is true. Otherwise, it is false. # a or b is true if either a is true or b is true. Otherwise, it is false. # # if morning and workday: # wakeup() # # elif is when you need another conditional inside an if statement def higher_lower(x): if x<24: return("higher") elif x>24: return("lower") else: return("correct u dumb") print(higher_lower(24)) def categorize(x): if x<20: return("low") elif x>=20 and x<36: return("medium") else: return("high") #or the more optimal one def categorize2(x): if x<15: return("low") elif 15<=x<=24: return("medium") else: return("high") print(categorize2(60)) def categorizelen(x): if len(x)<5: return("short") elif 5<=len(x)<=14: return("medium") else: return("long") def compute_xp(x,y): if y==False: return(92884) else: return(92884 + x) def replacement(x): x = x.replace("a", "j") return(x) print(replacement("alalala"))
2dc085cea228f8f6cfc3f6e022b0efd7665fb991
smalbec/CSE115
/math imports.py
513
3.609375
4
import math a = 3.14 y = math.pi y = round(y, 2) b = math.pi b = pow(b, 10) leo = "tonto" leo = leo.replace("tonto", "wea") print("weon " + str(a) + " qlao " + str(y) + " la " + str(b) + " " + str(leo)) import math import math def distance(x,y): euclidian = math.sqrt(((12.5 - x)**2) + (-7.3 - y)**2) return euclidian def printSequence(seq): for x in seq: print(x) printSequence(['a', 'b', 'c']) def explode(str): x = [] for v in str: x.append(v) return x
36fc1c1937694434e1a9212261f0191d5898d2c3
mfilipelino/codewars-py
/codewars/balance_parathenses.py
908
3.90625
4
class Stack: def __init__(self): self.lst = [] def is_empty(self): return len(self.lst) == 0 def top(self): if self.is_empty() is False: return self.lst[-1] else: return None def append(self, value): self.lst.append(value) def pop(self): self.lst.pop() def balanced(s): stack = Stack() for c in s: if c == ")" and stack.is_empty(): return False elif c == ")" and stack.top() == "(": stack.pop() elif c == "(": stack.append("(") return stack.is_empty() def recursive_balanced(s, index=0, open=0): if index == len(s): return open == 0 if open < 0: return False if s[index] == "(": return recursive_balanced(s, index + 1, open + 1) else: return recursive_balanced(s, index + 1, open - 1)
68d7d0e94fdaf221a57846f1811f0023e09eb9f6
mfilipelino/codewars-py
/codewars/linkedlist_operations.py
1,037
3.875
4
from codewars.linkedlist import LinkedList def union(list1, list2): list3 = LinkedList() node = list1.get_head() while node is not None: list3.insert_at_tail(node.data) node = node.next_element node = list2.get_head() while node is not None: list3.insert_at_tail(node.data) node = node.next_element list3.remove_duplicates() return list3 # Returns a list containing the intersection of list1 and list2 def intersection(list1, list2): list3 = LinkedList() hashmap = dict() node = list1.get_head() while node is not None: hashmap[node.data] = True node = node.next_element node = list2.get_head() while node is not None: if node.data in hashmap: list3.insert_at_tail(node.data) node = node.next_element return list3 def find_nth(lst, n): node = lst.get_head() size = lst.length() index = 0 for _ in range(0, size - n, 1): node = node.next_element return node.data
bac850544d06862dd117d75f6d51d9a9ae4bd9a3
mfilipelino/codewars-py
/tests/test_linkelistalt.py
477
3.75
4
from codewars.linkelistalt import LinkedList, Node, rotate_list def test_print_all(): linked_list = LinkedList() for i in range(1, 6, 1): linked_list.add(Node(i)) linked_list.print_all() rotate_list(linked_list, 2) linked_list.print_all() def test_print_all_2(): linked_list = LinkedList() for i in range(1, 6, 1): linked_list.add(Node(i)) linked_list.print_all() rotate_list(linked_list, -2) linked_list.print_all()
c5c573f1b2e173b46d60837861d222fabd44df2d
dwang2010/sudoku
/sudoku_classes.py
5,156
3.59375
4
from typing import List, Tuple # single square on board that can hold value from 1-9 class Cell: def __init__(self, i: int, j: int, val: int=0, lock: bool=False): self.pos = (i, j) self.val = val self.lock = lock def set_val(self, val: int) -> None: self.val = val def set_lock(self, lock: bool) -> None: self.lock = lock def get_val(self) -> int: return self.val def get_lock(self) -> bool: return self.lock # group of nine cells on the board # no need to separate per row / column / block # load in appropriate cells in board init class Region: def __init__(self): self.cells = [] # add board cell to region during init def add_cell(self, c: Cell) -> None: self.cells.append(c) # check that region only holds unique values def validate(self) -> Tuple[bool, int]: res, s = 0, set() for cell in self.cells: if cell.val > 0: res += 1 s.add(cell.val) return (res == len(s), len(s)) # holds all the cells / regions class Board: N = 9 # grid of NxN cells def __init__(self): rows, cols, blks = self.N, self.N, self.N # init grid of cells self.g = [[Cell(r,c) for c in range(cols)] for r in range(rows)] # init row / col / blk regions self.r_reg = [Region() for _ in range(rows)] self.c_reg = [Region() for _ in range(cols)] self.b_reg = [Region() for _ in range(blks)] # populate regions with grid cells for r in range(rows): for c in range(cols): self.r_reg[r].add_cell(self.g[r][c]) # row self.c_reg[c].add_cell(self.g[r][c]) # col blk_ind = 3*(r//3) + c//3 self.b_reg[blk_ind].add_cell(self.g[r][c]) # blk # check all board regions for sudoku 1-9 uniqueness def chk_board(self) -> Tuple[bool, bool]: r_nums = 0 for r in self.r_reg: uniq, nums = r.validate() if not uniq: return (False, False) r_nums += nums c_nums = 0 for c in self.c_reg: uniq, nums = c.validate() if not uniq: return (False, False) c_nums += nums b_nums = 0 for b in self.b_reg: uniq, nums = b.validate() if not uniq: return (False, False) b_nums += nums return (True, r_nums + c_nums + b_nums == 243) # load in board configuration # TBD: make this load from file? def load_board(self, grid: List[List[int]]) -> bool: rows, cols = len(grid), len(grid[0]) if rows != self.N and cols != self.N: return False for r in range(rows): for c in range(cols): lock = True if grid[r][c] else False self.g[r][c].set_val(grid[r][c]) self.g[r][c].set_lock(lock) return True # clear all board cells to zero value def clear_board(self) -> None: zero_grid = [[0 for _ in range(self.N)] for __ in range(self.N)] self.load_board(zero_grid) # set all cells with non-zero value to locked def lock_board(self) -> None: for r in range(self.N): for c in range(self.N): if self.g[r][c].get_val(): self.g[r][c].set_lock(True) # return current board state def _print_board(self) -> None: self.test = [[None for _ in range(self.N)] for __ in range(self.N)] for r in range(self.N): for c in range(self.N): self.test[r][c] = self.g[r][c].val for r in range(self.N): print (self.test[r]) # return board cell def get_cell(self, i: int, j: int) -> Cell: return self.g[i][j] # update board cell with new value def update_cell(self, i: int, j: int, val: int) -> Cell: self.g[i][j].set_val(val) return self.g[i][j] # find solution for starting board condition def solve_board(self) -> bool: # clear existing non-locked cells # recursive dfs: try all board combos at each unlocked position # helper function takes index (i, j) returns bool # inserts starting from 1 at specified position # if board valid and recursive step into next step valid, return true # else if either fails, increments current val up to 9 for i in range(self.N): for j in range(self.N): if not self.g[i][j].get_lock(): self.g[i][j].set_val(0) if not self.chk_board()[0]: return False def hlpr(i: int, j: int) -> bool: if i == self.N: return True cell = self.g[i][j] lock = cell.get_lock() ni = i+1 if j == 8 else i nj = (j+1) % 9 if lock: return hlpr(ni, nj) for k in range(1, self.N+1): cell.set_val(k) if self.chk_board()[0] and hlpr(ni, nj): return True cell.set_val(0) return False return hlpr(0,0)
2a766709a615d59e92ba87839db761a0eec029c7
maxsch3/keras-batchflow
/keras_batchflow/base/batch_transformers/feature_dropout.py
3,385
3.5
4
import numpy as np import pandas as pd from .base_random_cell import BaseRandomCellTransform class FeatureDropout(BaseRandomCellTransform): """ A batch transformation for randomly dropping values in the data to some pre-defined values **Parameters** - **n_probs** - a *list*, *tuple* or a *one dimensional numpy array* of probabilities $p_0, p_1, p_2, ... p_n$. $p_0$ is a probability for a row to have 0 augmented elements (no augmentation), $p_1$ - one random cells, $p_2$ - two random cells, etc. A parameter must have at least 2 values, scalars are not accepted - **cols** - a *list*, *tuple* or *one dimensional numpy array* of strings with columns names to be transformed Number of columns must be greater or equal the length of **n_probs** parameter simply because there must be enough columns to choose from to augment n elements in a row - **col_probs** - (optional) a *list*, *tuple* or *one dimensional numpy array* of floats $p_{c_0}, p_{c_1}, ... p_{c_k}$ where k is the number of columns specified in parameter cols. $p_{c_0}$ is the probability of column 0 from parameter *cols* to be selected in when only one column is picked for augmentation. $p_{c_1}$ is the same for column 1, etc. It is important to understand that when two or more columns, are picked for a row, actual frequencies of columns will drift towards equal distribution with every new item added. In a case when number of columns picked for augmentation reaches its max allowed value (number of columns available to choose from parameter **cols**), there will be no choice and the actual counts of columns will be equal. This means the actual distribution will turn into a uniform discrete distribution. **Default: None** - **drop_values** - (optional) a *list*, *tuple* or *one dimensional numpy array* of values. If not set, `None` will be used for all columns. If single value is set, it will be used for all columns. If a list of items is set, it must be the same length as cols parameter. In this case, values specified in drop_values will be used to fill dropped values in corresponding columns """ def __init__(self, n_probs, cols, col_probs=None, drop_values=None): super(FeatureDropout, self).__init__(n_probs, cols, col_probs) self._drop_values = self._validate_drop_values(drop_values) def _validate_drop_values(self, drop_values): if (type(drop_values) is str) or not hasattr(drop_values, '__iter__'): drop_values = [drop_values] elif type(drop_values) not in [tuple, list, np.ndarray]: raise ValueError('Error: parameter cols must be a single value or list, tuple, numpy array of values') dv = np.array(drop_values) if dv.ndim > 1: raise ValueError('Error: drop_values must be a vector of one dimension or a scalar value') if (len(dv) == 1) and (len(self._cols) > 1): dv = np.repeat(dv, len(self._cols)) if len(dv) != len(self._cols): raise ValueError('Error: drop_values and cols parameters must have same dimensions') return dv def _make_augmented_version(self, batch): return pd.DataFrame(np.tile(self._drop_values, (batch.shape[0], 1)), columns=self._cols, index=batch.index)
31973482ec85f4fd929f8a2ab5f99828a157e2e7
abasnfarah/IP_Algo_DS
/Algo_DS_Python/Algo_DS_Python/algorithms/graphAlgorithms/graphs.py
1,585
3.546875
4
""" Author: Abas Farah This is code for graphs.py This file has some prebuilt graphs using the: --> Adjecency List --> Adjecency Matrix --> Adjecency List with edge weights --> Object oriented graph with edge weights """ import sys import os dirpath = os.path.dirname(os.path.abspath(__file__)) sys.path.append('.') sys.path.append(dirpath + '/../../data_structures/linkedList/') # A Undirected graph with 7 nodes and edge weigths # if nodes aren't connected it has a None value adjecencyMatrix = [[None, 5, 7, 3, None, None, None, None], [ 5, None, None, None, 2, 10, None, None], [ 7, None, None, None, None, None, 1, None], [ 3, None, None, None, None, None, None, 11], [None, 2, None, None, None, None, None, 9], [None, 10, None, None, None, None, None, 4], [None, None, 1, None, None, None, None, 6], [None, None, None, 11, 9, 4, 6, None]] # generating adjecencyList to match adjecency Matrix def genAdjecencyList(): adjecencyList = [None]*8 for i in range(0,8): adjecencyList[i] = [] for i in range(0,8): for j in range(0,8): if adjecencyMatrix[i][j] != None: adjecencyList[i].append(j) return adjecencyList adjecencyList = genAdjecencyList() dag = {'A':['C'], 'B':['C','E'], 'C':['D'], 'E':['F'], 'D':['F'], 'F':['G'], 'G':[]}
8ee4c7cdf6ce11084256045ad39df86fa0222125
abasnfarah/IP_Algo_DS
/Algo_DS_Python/Algo_DS_Python/data_structures/AVL_Trees/AVL_Trees.py
5,391
3.828125
4
""" This is the class definition for a AVL_BST (Adelson-Velsky-Landis Binary Search Tree) INVARIANT: all elements in the right sub tree are < root and all elements in the left sub tree are > then the root node. Also, for every node the left and right children's heights differ by at most +-1. This BST maintains a balanced structure using rotations. Sample BST's: Perfect Balanced non-Perfect Balanced AVL Tree 4 4 / \ / \ 2 6 2 6 / \ / \ / \ 1 3 5 7 1 3 """ #importing Copy for compy operations import copy class AVL_Node(): def __init__(self, val): self.val = val self.right = None self.left = None self.height = 0 class AVL_BST(): def __init__(self, val=None): self.tree = None if val is None else AVL_Node(val) def getTree(self): return self.tree def heightIfExists(self, node): if node is None: return -1 else: return node.height # This method gets the new height of parent based off children heights def newHeight(self, node): l = self.heightIfExists(node.left) r = self.heightIfExists(node.right) return max(l,r) + 1 def getDifference(self, node): l = self.heightIfExists(node.left) r = self.heightIfExists(node.right) return abs(l - r) # This function returns 0 if left heavy and 1 if right Heavy and -1 if equal def rightOrLeftHeavy(self, root): if(root == None): return -1 else: # need childrens heights l = self.heightIfExists(root.left) r = self.heightIfExists(root.right) if l == r: return -1 elif( l > r): return 0 else: return 1 # This does a right Rotation of sub trees at root x def right_Rotation(self, x): y = x.left b = y.right # Rotating Variables y.right = x x.left = b #Updating Heights x.height = self.newHeight(x) y.height = self.newHeight(y) return y def left_Rotation(self, x): y = x.right b = y.left # rotating y.left = x x.right = b #updating Heights x.height = self.newHeight(x) y.height = self.newHeight(y) return y def wInsert(self, root, val): # The actual inserting just like our BST Class # base case if(root == None): root = AVL_Node(val) elif((val > root.val) and root.right == None): root.right = AVL_Node(val) elif((val > root.val) and root.right != None): self.wInsert(root.right, val) elif((val < root.val) and root.left == None): root.left = AVL_Node(val) elif((val < root.val) and root.left != None): self.wInsert(root.left, val) # now need to reGet Height after insert root.height = self.newHeight(root) # Getting differences of sub tree heights and if root is right or left heavy d = self.getDifference(root) h = self.rightOrLeftHeavy(root) # now we have four cases to rotate, 1.left, 2.right, 3.leftRight, 4.rightLeft #Case 1 0r 3 if( d > 1 and h == 1): # now we need to check if its a left or leftRight case # w is equal to -1,0,1 depending if root.right w = self.rightOrLeftHeavy(root.right) # if w = 0 or -1 then just left heavy and leftrotate # if w = 1 then right heavy and need a rightRotate(root.right) then leftRotate if(w == 1 or w == -1): root = self.left_Rotation(root) elif(w == 0): root.right = self.right_Rotation(root.right) root = self.left_Rotation(root) # Now we need to check for a right or rightLeft case if( d > 1 and h == 0): # now we nned to right or left case # w is equal to -1 0 1 depending if root.right w = self.rightOrLeftHeavy(root.left) # if w = 1 then just right heavy and right_rotate # if w = 0 or -1 then left heavy and left rotate(root.right) then right rotate if(w == -1 or w == 0): root = self.right_Rotation(root) elif(w == 1): root.left = self.left_Rotation(root.left) root = self.right_Rotation # This takes a val inserts it then as it ascedes to top it rotates to keep balance def insert(self, val): if(self.tree== None): self.tree= AVL_Node(val) else: self.wInsert(self.tree, val) # prints Tree using inOrder traversal def printTree(self,node): if( node != None): self.printTree(node.left) print(node.val) self.printTree(node.right) def main(): x = AVL_BST() x.insert(20) x.insert(4) x.insert(3) x.insert(1) x.insert(2) x.insert(29) x.insert(41) x.insert(50) x.printTree(x.getTree()) main()
f6c88e028ceef2d200a812d55e5e17621ac6669e
abasnfarah/IP_Algo_DS
/Algo_DS_Python/Algo_DS_Python/data_structures/stacks/stacks.py
11,480
3.65625
4
""" Author: Abas Farah This is code for the arrayStack class. And the listStack class: The Properties of the arrayStack Class: Atributes: stack, top, size. Methods: push, pop, peek, resize, The properties of the listStack class: Atributes: stack, size Methods: push, pop, peek Functions utilizing the Stack data Structure: reverseString() checkForBalancedParentheses() infixToPrefix() infixToPostfix() prefix() postfix() """ # Using linkedList python implementation import sys import os # Getting directory of script being run dirpath = os.path.dirname(os.path.abspath(__file__)) sys.path.append('.') # Adding dependency module to our python PATH sys.path.append(dirpath + "/../") from linkedList.linkedList import LinkedList # Class definition of arrayStack class ArrayStack: # Initilizer Function def __init__(self, data=None): self.stack = [None] * 10 if data is None else [data] + [None] * 9 self.size = 1 if data is not None else 0 self.top = 0 if data is not None else -1 def isEmpty(self): if(self.size == 0): return True else: return False # resize Method. This resizes the array to 2*len(Array) when array size is exhausted # Complexity O(2n), linear def resize(self): newArr = [None] * (len(self.stack)*2) for i in range(0, len(self.stack)): newArr[i] = self.stack[i] self.stack = newArr # push method this pushes elements on to the array and resizes it if array size is reached # Best case O(1), worst case O(n) due to resizing, Average case O(1). def push(self, data): # This checks if we need to resize the array if (self.size + 1 == len(self.stack)): self.resize() # Otherwise we can just add to the stack self.top += 1 self.stack[self.top] = data self.size += 1 # This returns the top element and decrements our stack by 1 # Complexity is O(1), constant def pop(self): if(self.size == 0): print("Stack is Empty. ") return None else: element = self.stack[self.top] self.top -= 1 self.size -= 1 return element # This returns the element at the top without poping it out of stack # Complexity is O(1), constant def peek(self): if(self.size == 0): print("Stack is Empty. ") return None else: element = self.stack[self.top] return element # This is function for testing in terminal def printStack(self): for i in range(0, self.size): print(self.stack[i]) class ListStack: def __init__(self, data=None): self.stack = LinkedList(data) self.size = self.stack.size def isEmpty(self): if(self.size == 0): return True else: return False # This takes O(1) time since inserting at head of linkedList def push(self, data): self.stack.insert(data,0) self.size += 1 # This takes O(1) time since deleting from head of linkedlist # If stack is empty will raise ValueError def pop(self): element = self.stack.getHead() self.stack.delete(0) self.size -= 1 return element def peek(self): return self.stack.getHead() def getList(self): return self.stack def printStack(self): self.stack.printList() # O(n) time def reverseString(x): s = ArrayStack(); for i in x: s.push(i) w = "" for i in range(0, len(x)): w += s.pop() return w # O(N) time # This function checks if a given string has balanced paren (), {}, []. return boolean def checkBalancedParentheses(inputString): strStack = ListStack() # Looping through string for i in inputString: # if we have a opening paren then push to stack if(i == '(' or i == '{' or i == '[' ): strStack.push(i) # Once a closing paren is given we need to check if it is balanced # if our input matches then we keep going or return false elif(i == ')' or i =='}' or i == ']'): if(strStack.isEmpty()): return False x = strStack.pop() if(i == ')' and x != '('): return False if(i == ']' and x != '['): return False if(i == '}' and x != '{'): return False if(strStack.isEmpty()): return True else: return False # This function takes two operands x and s and returns true if s has lower precedence then x def lowerPrecedence(x, s): if ((x == '*' and s == '+') or (x == '*' and s == '-')): return True elif ((x == '/' and s == '+') or (x == '/' and s == '-')): return True else : return False # This method takes a infix expression: (1 + 2) * 5 --> 1 2 5 + * # The order of operants never change A + b * C --> A B C + * def infixToPostfix(s): strStack = ArrayStack() postfix = '' # Check if infix has balanced paren if(checkBalancedParentheses(s) == False): print("infix expression not balanced") return s for x in s: if (x == '*' or x == '+' or x == '-' or x == '/' or x == '(' or x == ')'): # need to check if stack is empty if(strStack.isEmpty()): strStack.push(x) # If whats on the stack has lower precedence then we can just push elif( lowerPrecedence(x, strStack.peek()) ): strStack.push(x) # Now x is either above a opening paren or lowerPrecedence elif( strStack.peek() == '('): strStack.push(x) elif( x == '(' ): strStack.push(x) # Since we hit a closing paren we need to pop and write all operators elif( x == ')'): operatorString = '' # now we need to traverse the stack till we hit a closing paren while((strStack.isEmpty() == False) and strStack.peek() != '('): operatorString += strStack.pop() # After the loop we hit a opening bracket and need to pop once more to get rid of it postfix += operatorString strStack.pop() # now we know that x is lowerPrecedence then whats on the stack # not surrounded by a paren. in this case we pop the stack till # it's empty or we hit a opening paren and write to our return string else: while((strStack.isEmpty() == False) and strStack.peek() != '('): postfix += strStack.pop() strStack.push(x) # if x doesn't equal a space, operator or paren then we can just push elif( x != ' '): postfix += x # now we want to push whats left in the stack to the return string while(strStack.isEmpty() == False): postfix += strStack.pop() return postfix # This method takes a infix expression: (1 + 2) * 5 --> *+125 # The order of operants never change A + b * C --> *+ABC def infixToPrefix(s): strStack = ArrayStack() prefix = '' # Check if infix has balanced paren if(checkBalancedParentheses(s) == False): print("infix expression not balanced") return s for x in s: if (x == '*' or x == '+' or x == '-' or x == '/' or x == '(' or x == ')'): # need to check if stack is empty if(strStack.isEmpty()): strStack.push(x) # If whats on the stack has lower precedence then we can just push elif( lowerPrecedence(x, strStack.peek()) ): strStack.push(x) # Now x is either above a opening paren or lowerPrecedence elif( strStack.peek() == '('): strStack.push(x) elif( x == '(' ): strStack.push(x) # Since we hit a closing paren we need to pop and write all operators elif( x == ')'): operatorString = '' # now we need to traverse the stack till we hit a closing paren while((strStack.isEmpty() == False) and strStack.peek() != '('): operatorString = strStack.pop() + operatorString # After the loop we hit a opening bracket and need to pop once more to get rid of it prefix = operatorString + prefix strStack.pop() # now we know that x is lowerPrecedence then whats on the stack # not surrounded by a paren. in this case we pop the stack till # it's empty or we hit a opening paren and write to our return string else: while((strStack.isEmpty() == False) and strStack.peek() != '('): prefix = strStack.pop() + prefix strStack.push(x) # if x doesn't equal a space, operator or paren then we can just push elif( x != ' '): prefix += x # now we want to push whats left in the stack to the return string while(strStack.isEmpty() == False): prefix = strStack.pop() + prefix return prefix # This evaluates a prefix expression x and returns an integer value # Assume that the string passed is a valid postfix expression def postfix(s): # create a stack to hold operants operantStack = ListStack() value = 0 # Now we will go through the string and evaulate the expression for x in s: # we'll check for operant if (x == '*' or x == '/' or x == '-' or x == '+'): # now we need to pop last two values A = operantStack.pop() B = operantStack.pop() if(x == '*'): value = B * A operantStack.push(value) elif(x == '/'): value = B / A operantStack.push(value) elif(x == '-'): value = B - A operantStack.push(value) elif(x == '+'): value = B + A operantStack.push(value) elif (x != ' '): y = int(x) operantStack.push(y) return operantStack.pop() # This function evaluates a prefix expression and returns a integer value # Assume that the string passed is a valid postfix expression def prefix(s): # Create a stack to hold operants operantStack = ArrayStack() value = 0 # Now we will go through the string and evaluate the expression for x in reversed(s): # We will check for operant if (x == '*' or x == '/' or x == '-' or x == '+'): B = operantStack.pop() A = operantStack.pop() if(x == '*'): value = B * A operantStack.push(value) elif(x == '/'): value = B / A operantStack.push(value) elif(x == '-'): value = B - A operantStack.push(value) elif(x == '+'): value = B + A operantStack.push(value) elif (x != ' '): y = int(x) operantStack.push(y) return operantStack.pop()
db20e2e0738b81a45ec1685f4e485418d072b0c5
sithu/cmpe255-spring19
/lab5/linear_algebra.py
470
3.640625
4
import math def vector_subtract(v, w): """subtracts two vectors componentwise""" return [v_i - w_i for v_i, w_i in zip(v,w)] def dot(v, w): """v_1 * w_1 + ... + v_n * w_n""" return sum(v_i * w_i for v_i, w_i in zip(v, w)) def sum_of_squares(v): """v_1 * v_1 + ... + v_n * v_n""" return dot(v, v) def squared_distance(v, w): return sum_of_squares(vector_subtract(v, w)) def distance(v, w): return math.sqrt(squared_distance(v, w))
7f942c56a2d9e4a495aba97960e4b99ba04a6552
DEKHTIARJonathan/IMA-Deep-Learning
/deepsix/download/flickr.py
1,275
3.546875
4
import flickrapi def session(filename): """Open an instance of the Flickr API given an API key.""" with open(filename) as f: api_keys = f.readlines() api_key = api_keys[0].rstrip() api_secret = api_keys[1].rstrip() session = flickrapi.FlickrAPI(api_key, api_secret) return session def urls_tagged(keywords, api_key): """Return a generator over images with a given tag on Flickr. Args: keywords (str): A comma-separated list of Flickr tags. api_key (str): The path to a valid Flickr API key. Yields: Pairs photo_id, photo_url for each photo returned from the Flickr API. The photo_id is the unique ID assigned by Flickr to each photo, and the photo_url is the url to download the image file. """ flickr = session(api_key) url_template = 'https://farm{}.staticflickr.com/{}/{}_{}.jpg' for photo in flickr.walk(tag_mode='all', tags=keywords): photo_id = photo.get('id') secret = photo.get('secret') farm_id = photo.get('farm') server = photo.get('server') # info = flickr.photos.getInfo(photo_id=photo_id) photo_url = url_template.format(farm_id, server, photo_id, secret) yield photo_id, photo_url
4c403bd4174b1b71461812f9926e6dac87df2610
JasmanPall/Python-Projects
/lrgest of 3.py
376
4.46875
4
# This program finds the largest of 3 numbers num1 = float(input(" ENTER NUMBER 1: ")) num2 = float(input(" ENTER NUMBER 2: ")) num3 = float(input(" ENTER NUMBER 3: ")) if num1>num2 and num1>num3: print(" NUMBER 1 is the greatest") elif num2>num1 and num2>num3: print(" NUMBER 2 is the greatest") else: print(" NUMBER 3 is the greatest")
c8b69c1728f104b4f308647cc72791e49d84e472
JasmanPall/Python-Projects
/factors.py
370
4.21875
4
# This program prints the factors of user input number num = int(input(" ENTER NUMBER: ")) print(" The factors of",num,"are: ") def factors(num): if num == 0: print(" Zero has no factors") else: for loop in range(1,num+1): if num % loop == 0: factor = loop print(factor) factors(num)
9718066d59cdbd0df8e277d5256fd4d7bb10d90c
JasmanPall/Python-Projects
/Swap variables.py
290
4.25
4
# This program swaps values of variables. a=0 b=1 a=int(input("Enter a: ")) print(" Value of a is: ",a) b=int(input("Enter b: ")) print(" Value of b is: ",b) # Swap variable without temp variable a,b=b,a print(" \n Now Value of a is:",a) print(" and Now Value of b is:",b)
87dfe7f1d78920760c7e1b7131f1dd941e284e5a
JasmanPall/Python-Projects
/odd even + - 0.py
557
4.375
4
# This program checks whether number is positive or negative or zero number=float(input(" Enter the variable u wanna check: ")) if number < 0: print("THIS IS A NEGATIVE NUMBER") elif number == 0: print(" THE NUMBER IS ZERO") else: print(" THIS IS A POSITIVE NUMBER") if number%2 == 0: print("The number %i is even number" %number) else: print("The Number %i is odd" % number) #loop=float(input(" DO U WISH TO CONTINUE: ")) #if loop == "Y" or "y": #elif loop == "N" or "n": # break:
12c2dfa1a418daf8de31c22a394d4e1465ae2724
ameeshaS11/Greedy-1
/jumpgame.py
515
3.546875
4
#Time Complexity : O(n) #Space Complexity : O(1) # Did this code successfully run on Leetcode : Yes #Any problem you faced while coding this : No class Solution: def canJump(self, nums: List[int]) -> bool: if nums[0]>= len(nums)-1: return True idx = len(nums)-2 dest = len(nums)-1 while idx >= 0: if nums[idx] >= dest-idx: dest = idx if dest == 0: return True idx -= 1 return False
17739c9ef743a4eea06fc2de43261bfc72c21678
elijahwigmore/professional-workshop-project-include
/python/session-2/stringfunct.py
1,612
4.21875
4
string = "Hello World!" #can extract individual characters using dereferencing (string[index]) #prints "H" print string[0] #prints "e" print string[1] #print string[2] #Slicing #of form foo[num1:num2] - extract all elements from and including num1, up to num2 (but not including element at num2) #all of the below prints World print string[-6:-1] print string[6:-1] print string[6:11] #print everything before the space: prints Hello print string[:5] #print everything after the space: World! print string[6:] sentence = "I am a teapot!" print sentence.split(" ") #***LISTS*** myList = ["a word", 3, 3, 4.6, "end"] print myList print myList[0] print myList[1:] print myList + [5, 4, 5, 67] myList.append([1, 2, 3, 4]) print myList myList.remove('end') print myList print len(myList) myList[1] = 'one' print myList nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in nums: if ((i % 2) == 1): nums.remove(i) print nums nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in nums: if ((i % 2) == 1): nums = nums[0:i-1] + nums[i+1:] print nums #***DICTIONARIES*** myDict = {'one':1, 'two':2, 'three':3, 'four':4} print myDict['two'] myDict['five'] = 5 print myDict for i in myDict: print myDict[i] months = {'jan':1, 'feb':2, 'mar':3, 'apr':4, 'may':5, 'jun':6, 'jul':7, 'aug':8, 'sep':9, 'oct':10, 'nov':11, 'dec':12} print ('apr' in months) #PRACTICE: #Input: "A man a plan a canal Panama" -> {'A':1, 'a':2, 'man':1, 'plan':1, 'Panama':1, 'canal':1}
8716e46d6a1e1d119c070dfcd94226473d5c7302
xxxhol1c/PTA-python
/programming/4-13.py
227
3.71875
4
from math import factorial error = float(input()) res = 0 i = 0 while True: res += 1/factorial(i) if 1/factorial(i+1) <= error: res += 1/factorial(i+1) break else: i += 1 print(f'{res:.6f}')
8e2ea8cfb6475161e2c188540a7a79c1e2a96f69
xxxhol1c/PTA-python
/programming/4-6.py
382
3.59375
4
""" timeout def fib(n): if n == 1 or n == 2: return 1 return fib(n - 1) + fib(n - 2) """ def fib(n): pre , cur = 0, 1 for _ in range(1, n): pre , cur = cur, pre + cur return cur n = int(input()) if n < 1: print('Invalid.') else: for i in range(1, n+1): print(f'{fib(i):11}', end='') if i % 5 == 0: print('')
66f3b04df297736341fed29bb2e6c323eb536c5a
xxxhol1c/PTA-python
/programming/5-2.py
221
3.515625
4
n = int(input()) count = 0 sum = 0 for i in range(n): dic = eval(input()) for item in dic: path = dic[item] for key in path: count += 1 sum += path[key] print(n, count, sum)
e17447bfdb6c35860de087bdb5780a3d6569535e
xxxhol1c/PTA-python
/programming/3-17.py
150
3.859375
4
str = input().strip() chr_remove = input().strip() str = str.replace(chr_remove.upper(), '').replace(chr_remove.lower(), '') print(f'result: {str}')
42a8eee49d3119b284903aa38289d33e36acfc0c
xxxhol1c/PTA-python
/programming/4-29.py
263
3.921875
4
lst1 = list(input().split())[1:] lst2 = list(input().split())[1:] res = [] for num in lst1: if num not in lst2 and num not in res: res.append(num) for num in lst2: if num not in lst1 and num not in res: res.append(num) print(' '.join(res))
3d430df61055e0d3dbc68c8f270c964b89b9b3b8
xxxhol1c/PTA-python
/programming/4-26.py
124
3.921875
4
from math import factorial n = int(input()) res = 0 for i in range(1,n+1,2): res += factorial(i) print(f'n={n},s={res}')
8f7136a85530c671e188d90fcf7ef5f51e68412d
sowmyakrishnaraj91/byte_python
/ds_using_list.py
497
3.828125
4
shop_list = ['apple', 'mango','banana'] print('I have',len(shop_list),'items') print('These items are:', end=' ' ) for items in shop_list: print(items, end=' ') print('items', shop_list) print('adding rice') shop_list.append('rice') print('updated: ',shop_list) print('Sorting list') shop_list.sort() print('sorted list',shop_list) print('buying first item', shop_list[0]) olditem = shop_list[0] del shop_list[0] print('item bought', olditem) print('remaining items', shop_list)
8023d34f620beec2928e834869c35acdcb258dea
sowmyakrishnaraj91/byte_python
/control_flow.py
192
3.75
4
number = 19 guess = int(input('Enter an int:')) if guess == number: print('Spot on') elif guess < number: print('A little higher') else: print('A öittle lower') print('Done')
547bd9ea976fa5b783a27d8474fcc83f883c6b98
akjadon/Deep-Learning
/ANN/1-1-regression.py
1,504
3.890625
4
from keras.datasets import boston_housing from keras.models import Sequential from keras.layers import Activation, Dense from keras import optimizers (X_train, y_train), (X_test, y_test) = boston_housing.load_data() model = Sequential() # Keras model with two hidden layer with 10 neurons each model.add(Dense(10, input_shape = (13,))) # Input layer => input_shape should be explicitly designated model.add(Activation('sigmoid')) model.add(Dense(10)) # Hidden layer => only output dimension should be designated model.add(Activation('sigmoid')) model.add(Dense(10)) # Hidden layer => only output dimension should be designated model.add(Activation('sigmoid')) model.add(Dense(1)) # Output layer => output dimension = 1 since it is regression problem ''' This is equivalent to the above code block >> model.add(Dense(10, input_shape = (13,), activation = 'sigmoid')) >> model.add(Dense(10, activation = 'sigmoid')) >> model.add(Dense(10, activation = 'sigmoid')) >> model.add(Dense(1)) ''' sgd = optimizers.SGD(lr = 0.01) # stochastic gradient descent optimizer model.compile(optimizer = sgd, loss = 'mean_squared_error', metrics = ['mse']) # for regression problems, mean squared error (MSE) is often employed model.fit(X_train, y_train, batch_size = 50, epochs = 100, verbose = 1) results = model.evaluate(X_test, y_test) print('loss: ', results[0]) print('mse: ', results[1])
2244fcdea5ed252a02782ef5fb873fbb5c91b411
lohitbadiger/interview_questions_python
/3_prime_number.py
403
4.25
4
# given number is prime or not def prime_num_or_not(n): if n>1: for i in range(2,n): if (n%i)==0: print('given number is not prime') print(i,"times",n//i,"is",n) break else: print('given number is prime') else: print('given number is not prime') # n=input('enter the number') n=3 prime_num_or_not(n)
84f0b4335f058c440ac748f165fd7e87ef1e08b2
lohitbadiger/interview_questions_python
/6_letter_reverse.py
724
4.1875
4
#letters reverse in strings def reverse_letters(string): if len(string)==1: return string return reverse_letters(string[1:]) + (string[0]) # string=input('enter string') string='lohit badiger' print(reverse_letters(string)) print('----------------------------') def reverse_letter2(string): string = "".join(reversed(string)) print(string) string='lohit badiger' reverse_letter2(string) print('----------------------------') def reverse_letetr(string): string=string[::-1] print(string) string='lohit badigers' reverse_letetr(string) print('----------------------------') def reverse_string(string): ss='' for s in string: s=s+ss print(ss) reverse_string('im going')
039d14e75813ac6601cd9ba752e39fce2ccbf982
gautamgitspace/leetcode_30-day_challenge
/81_single_number.py
1,967
3.71875
4
class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: List[int] """ allnumsxor = nums[0] """ this will basically give us the XOR of those two target nums which appear just once in nums note that for 2 nums to be different, they differ in their some set bit position otherwise their XOR would yield 0 Here let's say that different bit is the Ith bit and can be found by using 1(bit_set) ANDing with allnumsxor """ bit_set = 1 for num in nums[1:]: allnumsxor ^= num while (allnumsxor & bit_set) == 0: bit_set <<= 1 """ now we know that Ith position. Now since all numbers occur twice and 2 numbers occur once, these numbers can be divided into groups where one group has Ith bit set as 0 and other has ith bit set as 1 in this case these groups are: G1 (1,1,5) with i = 2 [001,001,101] => 2nd bit is 0 G2 (2,2,3) with i = 2 [010,010,110] => 2nd bit is 1 since we know the different bit position is 2, from above, we take each num and check in which G it falls. For a num to fall in G1 we want to check if bit 2 is 0 so we AND 2 with the num and expect 0 to be the output For a num to fall in G2 we want to check if bit 2 is 1 so we AND 2 with the num and expect 1 to be the output Once we know which belongs where, we just xor them all as this by nature of numnber distribution, bound to have 1 unique numer. This way we find both n1 and n2 """ n1, n2 = 0, 0 for num in nums: if num & bit_set: n1 ^= num else: n2 ^= num return [n1, n2]
80c6c7fdad232dbd8d28c2df8084a303357b9132
gautamgitspace/leetcode_30-day_challenge
/46_find_all_anagrams.py
1,327
3.53125
4
class Solution(object): def findAnagrams(self, s, p): """ :type s: str :type p: str :rtype: List[int] """ res, d = [], {} begin, end = 0, 0 for item in p: d[item] = d.get(item, 0) + 1 counter = len(d) while end < len(s): # WINDOW EXPANSION c = s[end] if c in d: d[c] = d.get(c) - 1 if d[c] == 0: counter -= 1 end += 1 """ counter value reaching 0 means: - we have exhausted all keys, check if we have encountered an anagram until now - make keys available again by evaulating the begin ptr and incrementing counter accordingly """ while counter == 0: # WINDOW CONTRACTION temp_c = s[begin] if temp_c in d: d[temp_c] = d.get(temp_c) + 1 if d[temp_c] > 0: # we bail out as soon as # counter becomes > 0 counter += 1 if end - begin == len(p): res.append(begin) begin += 1 return res
9b697012de1a21ec58ae88d1df69c39c2f486333
gautamgitspace/leetcode_30-day_challenge
/113_single_number_iii.py
1,394
3.640625
4
class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: List[int] """ xorian = nums[0] for item in nums[1:]: xorian ^= item bit_set = 1 while xorian & bit_set == 0: bit_set <<= 1 """ now we know the Ith bit which would be diff for those two numbers that occur once now we need to for two groups. One of the two that occur only once would fall in one of these two groups. these groups will have numbers from nums whose Ith bit will be either 1 or 0. For the givrn testcase, it will be: G1 {1,1,5} and G2 {2,2,3} whether the bit is 0 or 1 can be evaulated by ANDing bit_set with number and checking for 1 or 0. Once we have determined these groups, we just do xorian for a group and find the odd one out, just like simple num1 problem. So we have: """ n1, n2 = 0, 0 for num in nums: if num & bit_set: # xorian for all in say G1 # off one out will stick to n1 n1 ^= num else: # xorian for all in say G2 # off one out will stick to n2 n2 ^= num return [n1, n2]
1743d3608dc8a99cfeb1257aee77c8c8c676e93e
gautamgitspace/leetcode_30-day_challenge
/98_max_width_bt.py
1,397
3.734375
4
tion for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def widthOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int - if tree were to be represented as an array the indices would have been this way for node i: i, left child (2*i), right child(2*i + 1).. - at each node we maintain a list like this: lst[(node, position)] where node will be the node being visited and position will be based on the calculation of left child or right child and i - at any level, width then would be: last elem pos in lst - first elem pos in lst + 1 """ width = 0 level = [(root, 0)] while level: next_level = [] width = max(width, level[-1][1] - level[0][1] + 1) # traverse the level lst now # for each node we scan L & R for node, pos in level: if node.left: next_level.append((node.left, pos * 2)) if node.right: next_level.append((node.right, pos * 2 + 1)) level = next_level return width
a38ec022c6b48c0dd8d2f57add5ab5e1da39cda3
sirisha-8/Array-1
/spiral_matrix.py
1,307
3.75
4
#Time Complexity : O(mn) #Space Complexity : O(1) #Did this code successfully run on Leetcode : yes #Any problem you faced while coding this : no class Solution(object): def spiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ rows = len(matrix) cols = len(matrix[0]) result = [] top = 0 bottom = rows-1 left =0 right = cols-1 while((top<=bottom) and (left <= right)): #left to right for i in range(left,right+1,1): result.append(matrix[top][i]) top=top+1 #top to bottom for i in range(top,bottom+1,1): result.append(matrix[i][right]) right = right-1 #right to left if (top<=bottom): for i in range(right,left-1,-1): result.append(matrix[bottom][i]) bottom = bottom-1 #bottom to top if (left <=right): for i in range(bottom,top-1,-1): result.append(matrix[i][left]) left = left+1 return result
0d6b5af34daf68d5dd0b9df6dd8e9b4d632ea230
debjava/external-ping
/main.py
1,922
3.515625
4
import argparse from ping import PingUtil def hello(): argParser = argparse.ArgumentParser() argParser.add_argument('-p', '--ping', nargs= "+", help="Ping IP Addresses.") argParser.add_argument('-t', '--telnet', nargs="+", help="Telnet command") args = argParser.parse_args() # print('Result:', vars(args)) # All passed arguments paramDict = args.__dict__ commandName = None # print("Now Ping values : ",paramDict.get("ping")) # print("Arguments passed: ",paramDict.keys()) if args.ping: print("It is ping") commandName = "ping" argList = paramDict.get(commandName) ipString = argList[0]; ips = ipString.split(',') print("All IPs: ", ips) PingUtil.pingAllIPs(ips) # print("Now Ping values : ", paramDict.get("ping")) # for arg in argList: # print("Argument value: ", arg) elif args.telnet: print("It is Telnet") commandName = "telnet" # print("Now Telnet values : ", paramDict.get("telnet")) # argList = paramDict.get(commandName) # for arg in argList: # print("Argument value: ", arg) # if "ping" in paramDict: # print('you have to ping IP address') # print(vars(args).values()) # print("Now Actual Passed Ping values : ", paramDict.get("ping")) # elif "telnet" in paramDict: # print("You have to perform telenet validations") # argList = vars(args).values() # for val in argList: # print("Value as argument: ", val) # if args.ping == 'someip': # print("=====================") # print('you have to ping IP address') # print(vars(args).values()) # # for arg in vars(args): # # print("Argument passed: ", arg) # print("Hello World") if __name__ == '__main__': hello()
50a3e1da1482569c0831227e0e4b5ead75433d43
PatrickKalkman/pirplepython
/homework01/main.py
1,872
4.59375
5
""" Python Is Easy course @Pirple.com Homework Assignment #1: Variables Patrick Kalkman / patrick@simpletechture.nl Details: What's your favorite song? Think of all the attributes that you could use to describe that song. That is: all of it's details or "meta-data". These are attributes like "Artist", "Year Released", "Genre", "Duration", etc. Think of as many different characteristics as you can. In your text editor, create an empty file and name it main.py. Now, within that file, list all of the attributes of the song, one after another, by creating variables for each attribute, and giving each variable a value. """ # Favorite Song: Tennessee Whiskey by Chris Stapleton Artist = "Chris Stapleton" ArtistGender = "Male" Title = "Tenessee Whiskey" Album = "Traveller" NumberOfSongsOnAlbum = 14 Year = 2015 Genre = "Country" DurationInSeconds = 293 OriginalAutor = "David Allan Coe" Country = "United States" TimesPlayedOnSpotify = 287881875 PriceInDollars = 2.75 Bio = "Christopher Alvin Stapleton is an American singer-songwriter, " + \ "guitarist, and record producer.x He was born in Lexington, Kentucky," + \ " and grew up in Staffordsville, Kentucky, until moving to Nashville, " + \ "Tennessee, in 2001 to pursue a career in music writing songs. " + \ " Subsequently, Stapleton signed a contract with Sea Gayle Music to " + \ "write and publish his music." WikipediaLink = "https://en.wikipedia.org/wiki/Chris_Stapleton" print(f"Title: {Title}") print(f"Artist: {Artist}") print(f"Gender: {ArtistGender}") print(f"Album: {Album}") print(f"Number of songs on album: {NumberOfSongsOnAlbum}") print(f"Year: {Year}") print(f"Genre: {Genre}") print(f"Country: {Country}") print(f"Duration: {DurationInSeconds} s") print(f"Original autor: {OriginalAutor}") print(f"Number of plays on Spotify: {TimesPlayedOnSpotify}") print(f"Price: ${PriceInDollars}") print(f"Bio: {Bio}") print(f"Wikipedia link: {WikipediaLink}")
0f5cf4e36e1a01173be26cc50f468368bb2a3e87
PatrickKalkman/pirplepython
/project03/main.py
5,870
4.21875
4
""" Python Is Easy course @Pirple.com Project #3: Pick a Card Game! Patrick Kalkman / patrick@simpletechture.nl Details: Everyone has their favorite card game. What's yours? For this assignment, choose a card game (other than Blackjack), and turn it into a Python program. It doesn't matter if it's a 1-player game, or a 2 player game, or more! That's totally up to you. A few requirements: It's got to be a card game (no board games, etc) When the game starts up, you should ask for the players' names. And after they enter their names, your game should refer to them by name only. ("It's John's turn" instead of "It's player 1's turn). At any point during the game, someone should be able to type "--help" to be taken to a screen where they can read the rules of the game and instructions for how to play. After they're done reading, they should be able to type "--resume" to go back to the game and pick up where they left off. Extra Credit: Want to make this much much harder on yourself? Okay, you asked for it! For extra credit, allow 2 players to play on two different computers that are on the same network. Two people should be able to start identical versions of your program, and enter the internal IP address of the user on the network who they want to play against. The two applications should communicate with each other, across the network using simple HTTP requests. Try this library to send requests: http://docs.python-requests.org/en/master/ http://docs.python-requests.org/en/master/user/quickstart/ And try Flask to receive them: http://flask.pocoo.org/ The 2-player game should only start if one person has challenged the other (by entering their internal IP address), and the 2nd person has accepted the challenge. The exact flow of the challenge mechanism is up to you. """ from enum import Enum from game import Deck, Player, Rules, Stack class GameEngine: class States(Enum): INIT = 1 PLAYING = 2 FINISHED = 3 def __init__(self): self.state = self.States.INIT self.current_player_index = 0 self.players = [] self.deck = Deck() self.rules = Rules() self.stack = Stack() self.cheat_card = "" def initialize_game(self): self.deck.build() self.deck.shuffle() self.rules.read_rules() def create_players(self): number_players = int(input("Enter the number of players? ")) for player_number in range(1, number_players + 1): player_question = f"Enter the name of player{player_number}? " name = input(player_question) self.players.append(Player(name)) def current_player(self): return self.players[self.current_player_index] def deal_cards(self): player_index = 0 for card in self.deck.cards: self.players[player_index].hand.append(card) player_index += 1 if player_index >= len(self.players): player_index = 0 def next_player(self): if self.current_player().no_more_cards(): print(f"{self.current_player().name} won the game!!!!!") self.state = self.States.FINISHED self.current_player_index += 1 if self.current_player_index >= len(self.players): self.current_player_index = 0 def previous_player(self): if self.current_player_index > 0: return self.players[self.current_player_index - 1] else: return self.players[len(self.players) - 1] def print_rules(self): print(self.rules) def game_loop(self): while self.state != self.States.FINISHED: if self.state == self.States.INIT: self.create_players() self.deal_cards() self.state = self.States.PLAYING print(f"{self.current_player().name} it is your turn") print(self.stack) print(self.current_player()) command = input((f"What do you want to do?" " (help, playcard, cheater) ")) if command == "help": self.print_rules() elif command == "playcard": call_card = input("Which card do you want to play? ") if self.current_player().has_card(call_card): card = self.current_player().get_card(call_card) self.stack.add_card(card) self.cheat_card = input( ("What card do you " "want to say you " "played? ") ) self.next_player() else: print("You don't have that card") elif command == "cheater": lastcard = self.stack.get_last_card() print(f"Last card was: {lastcard}") if self.cheat_card == str(lastcard): print( ( f"No, {self.previous_player().name} did not cheat, " "you will get all the played cards" ) ) played_cards = self.stack.get_cards() self.current_player().add(played_cards) self.stack.clear() else: print( ( f"Yes, you are right {self.previous_player().name} " f"cheated. {self.previous_player().name} will get " "all played cards" ) ) played_cards = self.stack.get_cards() self.previous_player().add(played_cards) self.stack.clear() def start_game(self): self.initialize_game() self.game_loop() game = GameEngine() game.start_game()
60f8df2f7560e7e6004db05b582521e44f9c6291
alexadusei/DataStructures
/Binary-vs-Trinary.py
5,817
4.15625
4
#------------------------------------------------------------------------------- """ Purpose: To test the complexities of a binary and trinary search. Simply run the program to see the results. Preset values: 5 lists with different lengths (n), and 3 values for k, per experiment. Values use constant k for ALL lists, then will redo the experiment with a new k-value (change of divisibility of n). All sizes of n have been hardcoded and can be changed on lines 24. Values of k will be decided within the 'd' list, found on line 29. """ #------------------------------------------------------------------------------- import time, random def main(): n = [50000, 75000, 100000, 500000, 10000000] statements = ["--- BINARY SEARCH ---", "--- TRINARY SEARCH ---", \ "--- BINARY SEARCH (not in list) ---", \ "---TRINARY SEARCH (not in list) ---"] lists = [] d = [10, 5, 2] print 'Sorting lists...\n' for i in range(len(n)): lists.append(randomList(n[i])) qsort(lists[i]) print 'Begin search\n' for m in range(len(d)): size = n[0]/d[m] for i in range(4): k = defineK(lists[i], i, size, n) print statements[i] for j in range(len(n)): if i % 2 == 0: #Binary search(lists[j], k, i) else: #Trinary search(lists[j], k, i) print "" def bin_search(A, first, last, target): #returns index of target in A, if present #returns -1 if target is not present in A if first > last: return -1 else: mid = (first + last)/2 if A[mid] == target: return mid elif A[mid] > target: return bin_search(A, first, mid-1, target) else: return bin_search(A, mid+1, last, target) def trin_search(A, first, last, target): #returns index of target in A, if present #returns -1 if target is not present in A if first > last: return -1 else: one_third = first + (last - first)/3 two_thirds = first + 2*(last - first)/3 if A[one_third] == target: return one_third elif A[one_third] > target: #search the left-hand third return trin_search(A, first, one_third-1, target) elif A[two_thirds] == target: return two_thirds elif A[two_thirds] > target: #search the middle third return trin_search(A, one_third+1, two_thirds-1, target) else: #search the right-hand third return trin_search(A, two_thirds+1, last, target) def qsort(lis, lowIndex=0, highIndex=None): """ An in-place version of quick sort. Sorts lis[lowIndex:highIndex+1] in place. If highIndex is None, we use the highest index in the list. No return value. """ if highIndex == None: highIndex = len(lis)-1 if lowIndex >= highIndex: # list segment has 0 or 1 elements, already sorted return # swap the middle value into the first position in the list to use # as the partition value, to avoid worst-case behavior midIndex = (lowIndex+highIndex)//2 lis[lowIndex],lis[midIndex] = lis[midIndex],lis[lowIndex] pval = lis[lowIndex] # indexes i and j divide A into sections. The invariant is: # lis[lowIndex] == pval # if lowIndex<index<=i: lis[lowIndex] < pval # if i<index<=j: lis[lowIndex] >= pval i = lowIndex j = lowIndex while j < highIndex: j += 1 if lis[j] < pval: # swap this value into the section that is < pval i += 1 lis[i],lis[j] = lis[j],lis[i] # swap the partition value into its proper position lis[lowIndex],lis[i] = lis[i],lis[lowIndex] # sort each of the two sections of the list and we're done qsort(lis,lowIndex,i) qsort(lis,i+1,highIndex) def randomList(length): """ Helper function: creates a list of random numbers Parameter: the length for the list """ randList = [] for i in range(length): randList.append(random.randint(0, length)) return randList def defineK(lis, iteration, size, n): """ Function that starts the process of randomizing values of k. Takes a list, an iteration based on the for loop starting this function (the last two iterations cause different results in this function and 'search'. If the iteration is greater than 1, then it will assume we are dealing with k-values and searches NOT within the list). """ k = [] #First if-statement deals with randomizing k values not in the list. It #randomizes from the max size to two times the max size (guarantees #nonexistence in lists) for i in range(size): if iteration > 1: #For values not in list (last pair of experiments) k.append(random.randint(n[-1], 2*n[-1])) else: #For values in list (first pair of experiments) k.append(random.randint(0, len(lis)-1)) return k def search(lis, k, iteration): """ Function that processes the searches. The parameter iteration determines whether to do a search with k values in/out of the list, and also, based on its divisibility with 2, determines whether to start a binary search or a trinary search """ t = time.clock() for i in range(len(k)): if iteration % 2 == 0: #Binary bin_search(lis, 0, len(lis)-1, k[i]) else: #Trinary trin_search(lis, 0, len(lis)-1, k[i]) print "N =", len(lis), "| k =", len(k), ": ", round(time.clock() - t, 6),\ "seconds process time" main()
b7ae64773830e76ff884fc1f1b9f0c8422ca99e3
manuelalfredocolladocenteno/NotebooksAI
/Práctica 4/fitness/tsp2d-rect-graph.py
1,770
3.828125
4
#!/usr/bin/python # -*- coding: iso-8859-1 -*- import matplotlib.pyplot as plt # Generate N cities import random cities = [] N2 = 10 for i in range(N2): for j in range(N2): c = [i/float(N2-1), j/float(N2-1)] cities.append(c) N = len(cities) print(N) print(cities) def dist (x, y): return ( (x[0]-y[0])**2 + (x[1]-y[1])**2 ) ** 0.5 def globaldist (chromosome): acum = 0.0 for i in range(len(chromosome)): acum += dist(cities[chromosome[i-1]],cities[chromosome[i]]) # -1 is the last element return acum # how to use genetics library # first, define a fenotype function: given a chromosome returns an individual # init graphics plt.ion() fig = plt.figure() axes = fig.add_subplot(111) xlim = axes.set_xlim(-0.05,1.05) ylim = axes.set_ylim(-0.05,1.05) x = [] y = [] l1, = axes.plot(x, y,'g') l2, = axes.plot(x, y,'ro') def orderedcities (chromosome): res = [] x = [] y = [] for g in chromosome: res.append(cities[g]) x.append(cities[g][0]) y.append(cities[g][1]) x.append(x[0]) y.append(y[0]) l1.set_data(x, y) l2.set_data(x, y) return res def phenotype (chromosome): orderedcities(chromosome) s = 'Length=%5.3f' % globaldist(chromosome) plt.title(s) return s # second, define a fitness function: given an chromosome, returns a number indicating the goodness of that chromosome def fitness (chromosome): # priorize ordered genes score = globaldist(chromosome) return (1.0+N*0.1)/(1.0+score) # asume un promedio de distancia de 0.1 entre dos ciudades adyacentes en el óptimo para que en esas condiciones el optimo sea aprox. 1.0 # third: if desired, force parameters in UI # valid parameters: alphabet, type, chromsize, elitism, norm, pmut, pemp, popsize parameters = { 'alphabet':list(range(N)), 'type':'permutation' }
4bd162dc975f4838dd3b5c8aab8735067432f7f8
Emmanuel289/pandas-python
/index_select_assign.py
2,135
3.90625
4
import pandas as pd iris = pd.read_csv('./Iris_Data.csv', index_col =0) print('The iris species include: \n {}'.format(iris.head())) #print('The length of the sepals are: \n{}'.format(iris.sepal_length)) #use dot notation followed by the name of a column to access its entries #print('The length of the sepals are: \n{}'.format(iris['sepal_length'])) #second method possible if object is a dictionary print('The sepal_length of Iris-setosa is: {}'.format(iris['sepal_length'][1])) #retrieve a row entry using its integer index #Pandas-specific indexing #print('The {} has the following properties: \n{}'.format(iris.iloc[0,-1],iris.iloc[0])) #index-based selection. Selects first row of dataset #print('The sepal_lengths of all the species of iris flowers are: \n{}'. format(iris.iloc[:,0])) #syntax for iloc is row first and colum second. Passing a colon retrieves all values in that row or column dimension print('The sepal_lengths of the first five species of iris flowers are: \n{}'. format(iris.iloc[:5,0])) #print('The sepal length of the first species of iris flowers is: {}'.format(iris.loc[1, 'sepal_length'])) #label-based selection print('The sepal length of the all the species of iris flowers are: {}'.format(iris.loc[:, 'sepal_length'])) #label-based selection iris.set_index('sepal_length','sepal_lengths') print(iris) #Conditional Selection #print(iris.sepal_length ==5.1) #true for all lengths equal to 5.1 and false otherwise #print(iris.loc[iris.sepal_length ==5.1]) #can be used inside loc to select the relevant data that meets the condition #print(iris.loc[(iris.sepal_length ==4.8)&(iris.sepal_width ==3.0)]) #can check if multiple conditions are satisfied & #print(iris.loc[(iris.sepal_length >4.8)|(iris.sepal_width <=3.0)]) #can check if any of the conditions are satisfied using | #print(iris.loc[iris.species.isin(['Iris-setosa', 'Iris-virginica'])]) #check the data under a particular column whose value is in a list of values #print(iris.loc[iris.sepal_width.isnull()]) #print sepal_widths that are empty or NaN print(iris.loc[iris.sepal_width.notnull()]) #print sepal_widths that are not empty
51d4e80ffcf2fbcd5caa7bff1ca60d9c25933854
schneiderson/ars1
/bot/kalman.py
2,324
3.859375
4
""" Kalman Filter """ import numpy as np __author__ = "Olve Drageset, Andre Gramlich" def kalman_filter(mu_t_minus_1, sigma_t_minus_1, u_t, z_t): """ Given as input a previous believed pose, previous covariance matrix, control input, and sensor correction on pose, determine a new believed pose and covariance. mu_t_minus_1 is the believed pose at the previous frame sigma_t_minus_1 is the covariance matrix from the previous frame u_t is the change in position [delta_x, delta_y, delta_theta] since t-1 according to our knowledge of our wheels z_t is the position as predicted by the sensor data """ # A_t is the Identity matrix because we have 0 change in position depending on our previous position # B_t is the Identity matrix because our input u_t is already the delta in position due to control # C_t is the Identity matrix because we want to make it simple A_t = B_t = C_t = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) C_t_transpose = np.transpose(C_t) # Q_t is the covariance for the sensor error, R_t is for the odometry error Q_t = np.array([[.01, 0, 0], [0, .01, 0], [0, 0, .01]]) R_t = np.array([[.05, 0, 0], [0, .05, 0], [0, 0, .05]]) # PREDICTION # Set our predicted position according to our old position, velocity, and estimated change due to control mu_bar_t = np.matmul(A_t, mu_t_minus_1) + np.matmul(B_t, u_t) mu_bar_t[2] = mu_bar_t[2] % 360 # Increase our covariance based on our estimated error in u_t sigma_bar_t = np.matmul(np.matmul(A_t, sigma_t_minus_1), np.transpose(A_t)) + R_t # CORRECTION K_t = np.matmul( np.matmul(sigma_bar_t, C_t_transpose), np.linalg.inv(np.matmul(np.matmul(C_t, sigma_bar_t), C_t_transpose) + Q_t)) # Correct our predicted position due to our sensor observation mu_t = mu_bar_t + np.matmul(K_t, z_t - np.matmul(C_t, mu_bar_t)) mu_t[2] = mu_t[2] % 360 # Correct our covariance matrix (decrease covariance) due to the sensor data sigma_t = np.matmul(np.identity(3) - np.matmul(K_t, C_t), sigma_bar_t) return mu_t, sigma_t # Prediction of pose at time t, covariance at time t
b85b30bba76aa6351247482ef8a98044e3958679
schneiderson/ars1
/bot/trigonometry.py
8,034
4.21875
4
''' TRIGONOMETRY MODULE ''' import math __author__ = 'Camiel Kerkhofs' def triangulate_beacons(beacons): """ Given a set of beacons and the distance to each beacon, finds the point where they all intersect. We assume the real position of each beacon is known from an internal map. All other information is relative to the robot and is noisy (distance and bearing to each beacon). input: [(beacon_1.x, beacon_1.y, bearing, distance), ..., (beacon_n.x, beacon_n.y, bearing, distance)] By triangulating the beacons using their known location and the robots orientation towards them we can find a noisy estimate of the real x, y and theta values of the robot. returns tuple (x, y, theta) """ if len(beacons) < 3: return False # Triangulate connected beacons inner_points = [] for index, beacon in enumerate(beacons): # Triangulate the beacon with all other beacons for index_2, beacon_2 in enumerate(beacons): if index_2 > index: # Distance between beacon 1 and robot d1 = beacon.distance # Distance between beacon 2 and robot d2 = beacon_2.distance # Angle between d1 and d2 relative to the robot angle = abs(beacon_2.bearing - beacon.bearing) if angle > 180: angle = 360-angle # Distance between the 2 beacons a = law_of_cosines(d1, d2, angle) # Robot position relative to the 2 beacons x = (a**2 + d1**2 - d2**2) / (2*a) y = math.sqrt(d1**2 - x**2) # We assume the position of the beacons is derived from an internal map. # We use the position of beacon 1 and beacon 2 to get the angle between these beacons # Real angle of the 2 beacons beacon_angle = line_angle((beacon_2.x, beacon_2.y), (beacon.x, beacon.y)) # Get the 2 possible robot positions from x, y, beacon1 and the angle between the 2 beacons x_endpoint = line_endpoint((beacon.x, beacon.y), beacon_angle, x) xy_endpoint_pos = line_endpoint(x_endpoint, beacon_angle+90, y) xy_endpoint_neg = line_endpoint(x_endpoint, beacon_angle-90, y) # Append the possible endpoints to the list inner_points.append([(round(xy_endpoint_pos[0]), round(xy_endpoint_pos[1])), (round(xy_endpoint_neg[0]), round(xy_endpoint_neg[1]))]) # Filter all possible inner points. # Determine whether X or X' is valid given all other beacon observations (this is why we need at least 3 beacons) believe_point = None believe_points = [] for i in range(len(inner_points)): # First loop execution: find initial believe point using the first 2 beacon pairs if len(believe_points) == 0 and i+1 < len(inner_points): p1 = inner_points[i] p2 = inner_points[i+1] # The 2 points that are closest to each other in the 2x2 matrix are the correct X/X' point dist_diffs = [ line_distance(p1[0], p2[0]), line_distance(p1[0], p2[1]), line_distance(p1[1], p2[0]), line_distance(p1[1], p2[1]) ] temp = dist_diffs.index(min(dist_diffs)) if temp < 2: believe_point = p1[0] believe_points.append(p1[0]) if temp == 0: believe_points.append(p2[0]) elif temp == 1: believe_points.append(p2[1]) elif temp < 4: believe_point = p1[1] believe_points.append(p1[1]) if temp == 2: believe_points.append(p2[0]) elif temp == 3: believe_points.append(p2[1]) # Compare other beacon observations to the believe point else: if line_distance(inner_points[i][0], believe_point) < line_distance(inner_points[i][1], believe_point): believe_points.append(inner_points[i][0]) else: believe_points.append(inner_points[i][1]) # Average the believe points # Due to noisy distance measures, our position estimates can vary. # We take the middle of this area; more beacons = higher accuracy center = get_polygon_center(believe_points) # Get the robots real angle using the known beacons and the calculated robot position theta_real = line_angle((beacons[0].x, beacons[0].y), (center[0], center[1])) # angle between beacon 1 and robot theta = (theta_real - beacons[0].bearing) % 360 # Actual robot pose given its relative angle to beacon 1 return (center[0], center[1], theta) def line_intersect(a_p1, a_p2, b_p1, b_p2, tolerance = 0.001): """ Finds the intersection between two lines a and b defined by their respective endpoints p1 and p2 """ # Check if lines intersect if a_p1[0] > b_p1[0] and a_p1[0] > b_p2[0] and a_p2[0] > b_p1[0] and a_p2[0] > b_p2[0]: return False if a_p1[0] < b_p1[0] and a_p1[0] < b_p2[0] and a_p2[0] < b_p1[0] and a_p2[0] < b_p2[0]: return False if a_p1[1] > b_p1[1] and a_p1[1] > b_p2[1] and a_p2[1] > b_p1[1] and a_p2[1] > b_p2[1]: return False if a_p1[1] < b_p1[1] and a_p1[1] < b_p2[1] and a_p2[1] < b_p1[1] and a_p2[1] < b_p2[1]: return False # Get diffs along each axis x_diff = (a_p1[0] - a_p2[0], b_p1[0] - b_p2[0]) y_diff = (a_p1[1] - a_p2[1], b_p1[1] - b_p2[1]) def det(a, b): return a[0] * b[1] - a[1] * b[0] # Find the intersection div = det(x_diff, y_diff) if div == 0: return False d = (det(*(a_p1, a_p2)), det(*(b_p1, b_p2))) x = det(d, x_diff) / div y = det(d, y_diff) / div # Check if intersection exceeds the segments if x < min(a_p1[0], a_p2[0]) - tolerance: return False if x > max(a_p1[0], a_p2[0]) + tolerance: return False if y < min(a_p1[1], a_p2[1]) - tolerance: return False if y > max(a_p1[1], a_p2[1]) + tolerance: return False if x < min(b_p1[0], b_p2[0]) - tolerance: return False if x > max(b_p1[0], b_p2[0]) + tolerance: return False if y < min(b_p1[1], b_p2[1]) - tolerance: return False if y > max(b_p1[1], b_p2[1]) + tolerance: return False return x, y def line_endpoint(start, angle, distance): """ Return the endpoint of a line that goes from point 'start' at angle 'angle' for distance 'distance' """ x = start[0] + distance * math.cos(math.radians(angle)) y = start[1] + distance * math.sin(math.radians(angle)) return x, y def law_of_sines(a, b, c): """ Return the angle of the corner opposite to side c in a triangle given by its 3 sides a, b and c (Law of sines) """ return math.degrees(math.acos((c**2 - b**2 - a**2)/(-2.0 * a * b))) def law_of_cosines(a, b, angle): """ Return the side of a triangle given its sides a, b and the angle between them (Law of cosines) """ return math.sqrt( a**2 + b**2 - 2*a*b*math.cos(math.radians(angle)) ) def line_distance(p1, p2): """ Return the distance between 2 points p1 and p2 """ return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) def line_angle(p1, p2): """ Return the angle of the line that goes from p1 to p2 Clockwise in pygame window Counter clockwise in xy-space """ angle = math.atan2((p1[1]-p2[1]), (p1[0]-p2[0])) * 180.0/math.pi return (angle + 360) % 360 def get_polygon_center(points): """ Returns the center of a set of points """ center = [0, 0] num = len(points) for i in range(num): center[0] += points[i][0] center[1] += points[i][1] center[0] /= num center[1] /= num return center
4740e2d4ae6d57bbd0c63ab34cc6d62a5cb1de34
dcasanova82/uni-python
/tarea-1-2.py
516
4.0625
4
""" Ejercicio 2 =========== """ try: n1 = float(input('Enter the first number: ')) n2 = float(input('Enter the second number: ')) op = str(input('Enter the operator (+,-,*,/): ')) if op == '+': res = n1 + n2 elif op == '-': res = n1 - n2 elif op == '*': res = n1 * n2 elif op == '/': res = n1 / n2 else: print('Invalid operator selected') print('The final result is {}'.format(res)) except ValueError: print('Invalid numbers selected!')
e72fbf0a96b198fd4ab47611bd8968c91d304186
quqixun/Hackerrank_Python
/30 Days of Code/day25_running_time_and_complexity.py
364
3.890625
4
import math def is_prime(n): if n < 2: return False elif n < 4: return True else: for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True T = int(input().strip()) for t in range(T): n = int(input().strip()) print("Prime" if is_prime(n) else "Not prime")
a6c5ac6798a6f24c69270c940be8689d2f25a58b
quqixun/Hackerrank_Python
/Algorithm/Implementation/electronics_shop.py
657
3.953125
4
#!/bin/python3 import sys def getMoneySpent(keyboards, drives, s): # Complete this function max_price = 0 for k in keyboards: for d in drives: if k + d > max_price and k + d <= s: max_price = k + d return max_price if max_price > 0 else -1 s, n, m = input().strip().split(' ') s, n, m = [int(s), int(n), int(m)] keyboards = list(map(int, input().strip().split(' '))) drives = list(map(int, input().strip().split(' '))) # The maximum amount of money she can spend on a keyboard and USB drive, # or -1 if she can't purchase both items moneySpent = getMoneySpent(keyboards, drives, s) print(moneySpent)
f5de6bd64442266303e1fb3ee192218827b6e0c4
quqixun/Hackerrank_Python
/Algorithm/Implementation/day_of_programmer.py
858
3.5625
4
#!/bin/python3 import sys def solve(year): # Complete this function days_in_months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if year == 1918: days_in_months[1] = 15 elif year >= 1700 and year <= 1917: if year % 4 == 0: days_in_months[1] = 29 else: if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0): days_in_months[1] = 29 days_num, day, month = 0, 0, 0 for i in range(len(days_in_months)): days_num += days_in_months[i] if days_num > 256: month = i + 1 break day = 256 - sum(days_in_months[:month - 1]) day_str = str(day).zfill(2) month_str = str(month).zfill(2) year_str = str(year) return ".".join([day_str, month_str, year_str]) year = int(input().strip()) result = solve(year) print(result)
ff2a1544c7998056d5983fca1d65e254226d2b82
jmart047/DrinkRink
/integrationTest.py
5,252
3.65625
4
#!/usr/bin/python3 from tkinter import * from tkinter import messagebox import sqlite3 conn = sqlite3.connect('DrinkRink1.db') c = conn.cursor() top = Tk() top.title("welcome") top.configure(background="#a1dbcd") photo = PhotoImage(file="dr_logo2.png") w = Label(top, image=photo) w.pack() def start(): #main screen mainScreen=Toplevel(top) mainScreen.title("Main Screen") mainScreen.geometry("200x200") def getDrink(): #user inputs ingredient, returns all drinks with that ingredient. inputScreen=Toplevel(mainScreen) inputScreen.title("Ingredients") enterIng= Label(inputScreen,text="enter ingredient") entry1= Entry(inputScreen, bd = 5) #using user input to get data from sqlite database ing= entry1.get() def getIng(): result =c.execute("SELECT DRDESC FROM Drinks WHERE DRDRID IN " "(SELECT DTDRID FROM Detail WHERE INGID " "=(SELECT INGID FROM Ingredients WHERE INDESC LIKE ?))", (ing,)) resultrow = c.fetchall() print(resultrow) if resultrow is not None: #for result in resultrow: #result = ' '.join(result) #print("\n\t", result) answerScreen=Toplevel(inputScreen) answerScreen.title("Drinks") mess= Message(answerScreen, text=resultrow) mess.pack() leave=Button(answerScreen, text="Go Back", command=answerScreen.destroy) leave.pack() else: errorScreen=Toplevel(inputScreen) errlabel=Label(errorScreen,text="Not an Ingredient") goback = Button(errorScreen, text="Go Back", command=errorScreen.destroy) errlabel.pack() goback.pack() getAnswer= Button(inputScreen, text="Enter", command= getIng) enterIng.pack() entry1.pack() getAnswer.pack() goBack = Button(inputScreen, text="Dismiss", command=inputScreen.destroy) goBack.pack() def myBar(): #user inputs multiple ingredients, returns the IDs. Work on returning drinks using multiple Ingredients barScreen=Toplevel(mainScreen) barScreen.title("MyBar") enterIng1= Label(barScreen,text="enter ingredient") enterIng2= Label(barScreen,text="enter ingredient") enterIng3= Label(barScreen,text="enter ingredient") entry1= Entry(barScreen, bd = 5) entry2= Entry(barScreen, bd = 5) entry3= Entry(barScreen, bd = 5) def getmyBar(): #search database for Ingredient IDs ing1= entry1.get() ing2= entry2.get() ing3= entry3.get() res1 =c.execute("SELECT ININID FROM Ingredients WHERE INDESC = ?", (ing1,)) result1 = c.fetchone() res2 =c.execute("SELECT ININID FROM Ingredients WHERE INDESC = ?", (ing2,)) result2 = c.fetchone() res3 =c.execute("SELECT ININID FROM Ingredients WHERE INDESC = ?", (ing3,)) result3 = c.fetchone() finalresult= result1 + result2 + result3 answerScreen=Toplevel(barScreen) messa = Message(answerScreen, text= finalresult) messa.pack() leave=Button(answerScreen, text="Go Back", command=answerScreen.destroy) leave.pack() getAnswer= Button(barScreen, text="Enter", command= getmyBar) goBack= Button(barScreen, text="Go Back", command= barScreen.destroy) enterIng1.pack() entry1.pack() enterIng2.pack() entry2.pack() enterIng3.pack() entry3.pack() getAnswer.pack() goBack.pack() def drinklist(): #returns a list of all the drinks in database dlScreen=Toplevel(mainScreen) dlScreen.title("Drink List") mylist=list() showAll = c.execute("SELECT DRDESC FROM Drinks ORDER BY 1") resultset = c.fetchall() for result in resultset: result=' '.join(result) mylist.append(result) msg = Message(dlScreen, text=mylist) msg.pack() button = Button(dlScreen, text="Dismiss", command=dlScreen.destroy) button.pack() #main screen buttons one = Button(mainScreen, text = "Enter Ingredients", command = getDrink) two = Button(mainScreen, text = "MyBar", command=myBar) three = Button(mainScreen, text = "Full Drink List", command=drinklist) four = Button(mainScreen, text = "Leave", command= mainScreen.destroy) one.place(x=75,y=10) two.place(x=75,y=60) three.place(x=75,y=110) four.place(x=75,y=160) #start screen buttons start= Button(top, text="Enter Drinkrink",command=start) start.place(x=200,y=200) start.pack end= Button(top, text="Leave Drinkrink",command=top.destroy) end.place(x=350, y=200) top.mainloop()
9aabee0c1e71af2689f37aa9ee2112cf3c77e9d2
varshitha8142/Binarysearch.io
/23_binary_search_io_programs.py
567
3.875
4
""" Given a list of strings words, concatenate the strings in camel case format. Example 1 Input words = ["java", "beans"] Output "javaBeans" Example 2 Input words = ["Go", "nasa"] Output "goNasa" """ # paste your solution class Solution: def solve(self, words): # Write your code here s = '' l=[] for i in range(len(words)): if(i>0): t = words[i].capitalize() else: t = words[i].lower() l.append(t) for p in l: s = s+p return s
14ddce893102b8e7752e32d28f36c4c267c33100
varshitha8142/Binarysearch.io
/03.py
2,403
4
4
# pylint: disable=invalid-name """ Unique Occurrences Given a list of integers nums, return true if the number of occurrences of every value in the array is unique, otherwise return false. Note: Numbers can be negative. Example 1 Input nums = [5, 3, 1, 8, 3, 1, 1, 8, 8, 8] Output True Explanation Yes, there is 1 occurrence of 5, 2 occurrences of 3, 3 occurrences of 1, and 4 occurrences of 8. All number of occurrences are unique. Example 2 Input nums = [-3, -1, -1, -1, -2, -2] Output True Explanation There's 1 occurrence of -3, 2 occurrences of -2, and 3 occurrences of -1. All number of occurrences are unique. Example 3 Input nums = [3, 1, 1, 2, 2, 2, 3] Output False Explanation There are 2 occurrences of 1, and 2 occurrences of 3. So the number of occurrences here is not unique. """ import unittest from collections import Counter # Implement the below function and run this file # Return the output, No need read input or print the ouput def unique_occurrences(nums): nums=sorted(nums) counts = dict(Counter(nums)) a = counts.values() return len(a) == len(set(a)) class TestUniqueOccurrences(unittest.TestCase): def test_01(self): self.assertEqual(unique_occurrences( [5, 3, 1, 8, 3, 1, 1, 8, 8, 8]), True) def test_02(self): self.assertEqual(unique_occurrences([-3, -1, -1, -1, -2, -2]), True) def test_03(self): self.assertEqual(unique_occurrences([3, 1, 1, 2, 2, 2, 3]), False) def test_04(self): self.assertEqual(unique_occurrences([1, 2]), False) def test_05(self): self.assertEqual(unique_occurrences([1, 1, 2, 2, 1]), True) def test_06(self): self.assertEqual(unique_occurrences( [1000, 5, 5, 3333, 1000, 1000]), True) def test_07(self): self.assertEqual(unique_occurrences( [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]), False) def test_08(self): self.assertEqual(unique_occurrences( [-3, 5, 1, -3, 1, 1, 1, -3, 10, 5]), True) def test_09(self): self.assertEqual(unique_occurrences( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), False) def test_10(self): self.assertEqual(unique_occurrences( [3, 1, 1, 3, 3, 1, 3, 1, 3, 3, 1, 3]), True) if __name__ == '__main__': unittest.main(verbosity=2)
6e72005b59e6d8de3ca35d2e030b76959b013c91
gordongreeff/MITx600
/Lec2.5.4.py
121
4.25
4
## Example from lecture 2.5 slide 4 x = 3 x = x * x print (x) y = float (raw_input ('Pick a number: ')) print (y * y)
6e653a649f753a20b94d9226df98f8caaebdcb0c
weitrue/note
/python/leetcode/linear/list/remove_nth_node_from_end_of_list.py
1,457
3.5625
4
""" Module Description: 19-删除链表的倒数第 N 个结点 Solution: Date: 2021-03-11 13:39:13 Author: Wang P Problem:# 给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。 # # 进阶:你能尝试使用一趟扫描实现吗? # 示例 1: # 输入:head = [1,2,3,4,5], n = 2 # 输出:[1,2,3,5] # # 示例 2: # 输入:head = [1], n = 1 # 输出:[] # # 示例 3: # 输入:head = [1,2], n = 1 # 输出:[1] # # 提示: # 链表中结点的数目为 sz # 1 <= sz <= 30 # 0 <= Node.val <= 100 # 1 <= n <= sz # # Related Topics 链表 双指针 # 👍 1264 👎 0 """ # leetcode submit region begin(Prohibit modification and deletion) # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: hair = ListNode(next=head) slow, fast = hair, head; while n > 0: fast = fast.next n -= 1 while fast: fast = fast.next slow = slow.next slow.next = slow.next.next return hair.next # leetcode submit region end(Prohibit modification and deletion)
45b89c4fab9e1e0bdd87117b5b0dd4543914bbef
weitrue/note
/python/leetcode/linear/list/reverse_linked_list_ii.py
1,392
3.5625
4
""" Module Description: 92-反转链表 II Solution: Date: 2021-03-15 19:06:58 Author: Wang P Problem:# 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。 # # 说明: # 1 ≤ m ≤ n ≤ 链表长度。 # # 示例: # # 输入: 1->2->3->4->5->NULL, m = 2, n = 4 # 输出: 1->4->3->2->5->NULL # Related Topics 链表 # 👍 709 👎 0 """ # leetcode submit region begin(Prohibit modification and deletion) # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode: cur = hair = ListNode(next=head) n = right - left + 1 while left > 1: cur = cur.next left -= 1 cur.next = self.reverse(cur.next, n) return hair.next def reverse(self, head: ListNode, n: int) -> ListNode: if not head: return None pre, cur, nex = ListNode(), head, None while n > 0: nex = cur.next cur.next = pre.next pre.next = cur cur = nex n -= 1 head.next = cur return pre.next # leetcode submit region end(Prohibit modification and deletion)
d3621efc07a922a54442e79b08cbb227aaeb9bf9
weitrue/note
/python/algorithm/search/binary_search.py
549
3.984375
4
""" Module Description: 二分查找算法 Problem: Solution: Date: 2020/1/20 Author: Wang P """ def binary_search(arr, target): n = len(arr) left = 0 right = n - 1 while left <= right: mid = (left + right) // 2 if arr[mid] < target: left = mid + 1 elif arr[mid] > target: right = mid - 1 else: print(f"index: {mid}, value:{arr[mid]}") return True return False if __name__ == "__main__": l = [1, 3, 4, 5, 6, 7, 8] binary_search(l, 8)
8007fe45185f608a628b204a7694d2f6d1aa5c94
calebhews/Ch.07_Graphics
/7.2_Picasso.py
4,515
4.40625
4
''' PICASSO PROJECT --------------- Your job is to make a cool picture. You must use multiple colors. You must have a coherent picture. No abstract art with random shapes. You must use multiple types of graphic functions (e.g. circles, rectangles, lines, etc.) Somewhere you must include a WHILE or FOR loop to create a repeating pattern. Do not just redraw the same thing in the same location 10 times. You can contain multiple drawing commands in a loop, so you can draw multiple train cars for example. Please use comments and blank lines to make it easy to follow your program. If you have 5 lines that draw a robot, group them together with blank lines above and below. Then add a comment at the top telling the reader what you are drawing. IN THE WINDOW TITLE PLEASE PUT YOUR NAME. When you are finished Pull Request your file to your instructor. ''' import arcade arcade.open_window(625, 625, "The USS Enterprise") arcade.set_background_color(arcade.color.BLACK) x=30 y=30 circle=13 radius=110 angle=0 arcade.start_render() arcade.draw_rectangle_filled(240,360, 25,100,arcade.color.GRAY,30) arcade.draw_rectangle_filled(240, 240, 25, 100, arcade.color.GRAY, -30) arcade.draw_rectangle_filled(340,300,80,60,arcade.color.GRAY) arcade.draw_rectangle_filled(255,300,100,30,arcade.color.GRAY) arcade.draw_rectangle_filled(240, 240, 100, 6, arcade.color.AERO_BLUE, 60) arcade.draw_rectangle_filled(240,360,100,6,arcade.color.AERO_BLUE,-60) arcade.draw_rectangle_filled(255,315,100,20,arcade.color.GRAY,7) arcade.draw_rectangle_filled(255, 285, 100, 20, arcade.color.GRAY, -7) arcade.draw_circle_filled(205,300,19,arcade.color.GRAY) arcade.draw_rectangle_filled(340,300,60,50,arcade.color.LIGHT_GRAY) arcade.draw_rectangle_filled(260,310,105,20,arcade.color.LIGHT_GRAY,7) arcade.draw_rectangle_filled(260, 290, 105, 20, arcade.color.LIGHT_GRAY, -7) arcade.draw_circle_filled(210,300,15,arcade.color.LIGHT_GRAY) arcade.draw_lrtb_rectangle_filled(310,400,305,295,arcade.color.GRAY) arcade.draw_circle_filled(480,300,120,arcade.color.LIGHT_GRAY) arcade.draw_circle_outline(480,300,120,arcade.color.GRAY) for i in range(7): arcade.draw_circle_outline(480,300,radius, arcade.color.GRAY) radius -= circle for i in range(16): arcade.draw_line(480,332,480,420,arcade.color.GRAY,.5) arcade.draw_line(505,322,565,385,arcade.color.GRAY,.5) arcade.draw_line(512,300,600,300,arcade.color.GRAY,.5) arcade.draw_line(505,278,565,215,arcade.color.GRAY,.5) arcade.draw_line(480,268,480,180,arcade.color.GRAY,.5) arcade.draw_line(457,278,394,215,arcade.color.GRAY,.5) arcade.draw_line(457, 322, 394, 385, arcade.color.GRAY, .5) arcade.draw_line(450, 300, 420,300,arcade.color.GRAY,.5) arcade.draw_circle_filled(420,300,5,arcade.color.GRAY) arcade.draw_rectangle_filled(412,300,15,8,arcade.color.GRAY) arcade.draw_circle_filled(390,300,15,arcade.color.LIGHT_GRAY) arcade.draw_rectangle_filled(370,300,40,30,arcade.color.LIGHT_GRAY) arcade.draw_rectangle_filled(370,300,38,28,arcade.color.GRAY) arcade.draw_circle_filled(390, 300, 14, arcade.color.GRAY) arcade.draw_circle_filled(490,300,15,arcade.color.GRAY) arcade.draw_circle_filled(470,300,10,arcade.color.GRAY) arcade.draw_rectangle_filled(480,310,18,7,arcade.color.GRAY,15) arcade.draw_rectangle_filled(480,290,18,7,arcade.color.GRAY,-15) arcade.draw_circle_filled(490,300,10,arcade.color.LIGHT_GRAY) arcade.draw_rectangle_filled(200,195,20,300,arcade.color.LIGHT_GRAY,90) arcade.draw_rectangle_filled(200,405,20,300,arcade.color.LIGHT_GRAY,90) arcade.draw_triangle_filled(15, 405, 50, 395, 50, 415, arcade.color.LIGHT_GRAY) arcade.draw_triangle_filled(15, 195, 50, 185, 50, 205, arcade.color.LIGHT_GRAY) arcade.draw_circle_filled(350, 195, 10, arcade.color.LIGHT_GRAY) arcade.draw_circle_filled(350, 405, 10, arcade.color.LIGHT_GRAY) arcade.draw_circle_filled(390,300,8,arcade.color.CAPRI) arcade.draw_rectangle_filled(200,195, 16, 290, arcade.color.GRAY,90) arcade.draw_rectangle_filled(200,405,16,290,arcade.color.GRAY,90) arcade.draw_circle_filled(348,195,8,arcade.color.GRAY) arcade.draw_circle_filled(348,405,8,arcade.color.GRAY) arcade.draw_triangle_filled(25,405,55,397,55, 413,arcade.color.GRAY) arcade.draw_triangle_filled(25,195,55,187,55,203,arcade.color.GRAY) arcade.draw_circle_filled(310,195,3,arcade.color.CAPRI) arcade.draw_circle_filled(310, 405, 3, arcade.color.CAPRI) arcade.finish_render() arcade.run()
898063b188e360577a48bd0246b7eccdea9c442f
huangty1208/Data-Challenge
/Customer Cliff/RLS.py
1,563
3.734375
4
# Generate 'random' data np.random.seed(0) X = 2.5 * np.random.randn(100) + 1.5 # Array of 100 values with mean = 1.5, stddev = 2.5 res = 0.5 * np.random.randn(100) # Generate 100 residual terms y = 2 + 0.3 * X + res # Actual values of Y # Create pandas dataframe to store our X and y values df = pd.DataFrame( {'X': X, 'y': y} ) # Calculate the mean of X and y xmean = np.mean(X) ymean = np.mean(y) # Calculate the terms needed for the numator and denominator of beta df['xycov'] = (df['X'] - xmean) * (df['y'] - ymean) df['xvar'] = (df['X'] - xmean)**2 # Calculate beta and alpha beta = df['xycov'].sum() / df['xvar'].sum() alpha = ymean - (beta * xmean) print(f'alpha = {alpha}') print(f'beta = {beta}') # use statsmodel for OLS import statsmodels.formula.api as smf # Initialise and fit linear regression model using `statsmodels` model = smf.ols('y ~ X', data=df) model = model.fit() model.summary() # Predict values x_pred = model.predict() # Plot regression against actual data plt.figure(figsize=(12, 6)) plt.plot(X, y, 'o') # scatter plot showing actual data plt.plot(X, x_pred, 'r', linewidth=2) # regression line plt.xlabel('x') plt.ylabel('y') plt.title('xy') plt.show() from sklearn.linear_model import LinearRegression # Build linear regression model using TV and Radio as predictors # Split data into predictors X and output Y # Initialise and fit model lm = LinearRegression() model = lm.fit(X.reshape(-1, 1), y) print(f'alpha = {model.intercept_}') print(f'betas = {model.coef_}')
85d5f1a121d86144e786bb60a2c938e8a0e251e7
seyerspython/shiyanlou
/apple_analysis.py
288
3.65625
4
# -*- coding:utf8 -*- import pandas as pd def quarter_volume(): data=pd.read_csv('apple.csv',header=0,parse_dates=['Date'],index_col=[0]) data_3m=data.resample('Q-DEC').sum() second_volume=data_3m.sort_values(by='Volume')['Volume'][-2] return second_volume print(quarter_volume)
667ace0a8cdbb1ee12acb9282ed7006c18cc107f
phamous2day/courseraChallenges
/UdemyPythonPostgreSQL/makeMethod.py
626
3.8125
4
import random def ask_user_and_check_number(): user_number=int(input("Enter a number between 0 and 9: ")) if user_number in magic_numbers: print("You got the number correct!!") if user_number not in magic_numbers: print("You totally got the number WRONG!") magic_numbers = [random.randint(0,9), random.randint(0,9)] def run_program_x_times(chances): for attempt in range(chances): #range(changes) is [0,1,2] print("This is attempt{}".format(attempt)) ask_user_and_check_number() user_attempts = int(input("Enter number of attempts: ")) run_program_x_times(user_attempts)
66bd26baa04365307e68a0cdc57d8f8676c87589
DrunkenAlcoholic/PythonScripts
/Ancient.Ciphers.py
2,353
3.5
4
#!/usr/bin/env python3 """ Description: Ancient implementation of Caesar/ROTxx/Vigenere ciphers. Author: DrunkenAlcoholic Date: June 2019 """ # Custom Alphabet used for Caesar or Vigenre or Both sAlphabet = 'aBcDeFgHiJkLmNoPqRsTuVwXyZAbCdEfGhIjKlMnOpQrStUvWxYz0123456789' iAlphaBet = len(sAlphabet) def caesar(sSource, iShift, bDecrypt = False): sResult = '' for cChar in sSource: try: if bDecrypt: sResult += sAlphabet[((sAlphabet.index(cChar) + iAlphaBet) - iShift) % iAlphaBet] else: sResult += sAlphabet[(sAlphabet.index(cChar) + iShift) % iAlphaBet] except ValueError: sResult += cChar return sResult def vigenere(sSource, sKey, bDecrypt = False, iTableSize = 94): # Create a table, can also use custom table(sAlphabet) i = 32 sTable = '' while i < (iTableSize + 32): sTable += chr((i)) i += 1 # Set key length equal or greater than Source length sFinalKey = sKey while len(sFinalKey) <= len(sSource): sFinalKey += sKey # Remove feedline & Carrage return from Source for cChar in sSource: if (cChar == chr(10)) or (cChar == chr(13)): del(sSource[cChar]) # Vigenere Encrypt / Decrypt i = 0 sResult = '' while i <= (len(sSource) -1): if sTable.index(sSource[i]) == -1: sResult += sSource[i] iPosText = sTable.index(sSource[i]) iPosKey = sTable.index(sFinalKey[i]) if bDecrypt: sResult += sTable[(((iPosText + iTableSize) - iPosKey) % iTableSize)] else: sResult += sTable[((iPosText + iPosKey) % iTableSize)] i += 1 return sResult + " : " + sTable # Example Caesar print("Caesar cipher example") sInput = input("enter string: ") iShift = int(input("enter shift number: ")) print("original string: ", sInput) sCaesar = caesar(sInput, iShift) print("after cipher: ", sCaesar) sCaesar = caesar(sCaesar, iShift, True) print("after decipher: ", sCaesar) # Example Vigenere print("\n Vigenere cipher example") sInput = input("enter string: ") sInputKey = input("enter key: ") print("Original String: ", sInput) sVigenere = vigenere(sInput, sInputKey) print("after Vigenere cipher: ", sVigenere) sVigenere = vigenere(sVigenere, sInputKey, True ) print("after Vigenere decipher: ", sVigenere)
7e0c61f3130987cc8bec0408489de75bb194695f
agusaldasoro/gen_tests
/TP1/workspace-autotest/tp1/examples/encryption.py
1,772
3.5625
4
# # Relative letter frequencies for the french and english languages. # First item is letter 'A' _frequency and so on. # ENGLISH = (0.0749, 0.0129, 0.0354, 0.0362, 0.1400, 0.0218, 0.0174, 0.0422, 0.0665, 0.0027, 0.0047, 0.0357, 0.0339, 0.0674, 0.0737, 0.0243, 0.0026, 0.0614, 0.0695, 0.0985, 0.0300, 0.0116, 0.0169, 0.0028, 0.0164, 0.0004) FRENCH = (0.0840, 0.0106, 0.0303, 0.0418, 0.1726, 0.0112, 0.0127, 0.0092, 0.0734, 0.0031, 0.0005, 0.0601, 0.0296, 0.0713, 0.0526, 0.0301, 0.0099, 0.0655, 0.0808, 0.0707, 0.0574, 0.0132, 0.0004, 0.0045, 0.0030, 0.0012) FREQUENCIES = (ENGLISH, FRENCH) # This program can be used to decipher Caesar encoding as produced by the # function bellow def cipher(s, key): r = '' ASC_A = ord('a') for c in s.lower(): if 'a'<=c<='z': r += chr(ASC_A+(ord(c)-ASC_A+key)%26) else: r += c return r #compute letter frequencies delta def _delta(source, dest): N = 0.0 for f1,f2 in zip(source, dest): N += abs(f1-f2) return N # compute letter frequencies from a text def _frequency(s): D = dict([(c,0) for c in 'abcdefghijklmnopqrstuvwxyx']) N = 0.0 for c in s: if 'a'<=c<='z': N += 1 D[c] += 1 L = D.items() L.sort() return [f/N for (_,f) in L] # deciphering caesar code by letter frequencies analysis def decipher(s): deltamin = 1000 bestrot = 0 freq = _frequency(s) for key in range(26): d = min([_delta(freq[key:]+freq[:key], x) for x in FREQUENCIES]) if d<deltamin: deltamin = d bestrot = key return cipher(s, -bestrot) def _typeHint(): cipher('', 0) decipher('')
f736d12f3cbce12040c58d2cedd7e20586485334
agusaldasoro/gen_tests
/TP1/workspace-autotest/tp1/examples/persons.py
563
3.75
4
''' Created on Sep 1, 2016 @author: galeotti ''' def youngest(ages): if len(ages) == 0: return None min_age = None for name in ages.keys(): age = ages[name] if age < min_age: min_age = age return min_age def oldest(ages): if len(ages) == 0: return None max_age = None for name in ages.keys(): age = ages[name] if age > max_age: max_age = age return max_age def _typeHint(): youngest({"Michael": 12, "John":10}) oldest({"Michael": 12, "John":10})
5979f5f1eba5eb8fb3706dd8023f5429ae5f2ef2
bulboushead/AtBS
/CoinFlip.py
1,140
3.53125
4
def CoinFlipStreaks(): import random, sys trials = 100000 numberOfStreaks = 0 minStreak = 6 for experimentNumber in range(trials): #Create 100 HT values flips = 100 flipList = [] for i in range(flips): if random.randint(0,1) == 0: flipList += 'H' else: flipList += 'T' #print(flipList) #Check for streaks and incr numberOfStreaks counter = 0 done = False for i in range(len(flipList)): while i < len(flipList)-1: if done: break if flipList[i] == flipList[i+1]: counter += 1 if counter == 5: numberOfStreaks += 1 done = True else: counter = 0 break print('\n\n') print('Number of streaks = ' + str(numberOfStreaks)) trials = float(trials) print('Chance of streak: %s%%' % ((numberOfStreaks / (trials / 100)))) CoinFlipStreaks()
1c6321b991aabf63764f2e65f1b4ea0d1f1a537e
Ardrake/PlayingWithPython
/drawstar.py
225
3.84375
4
'''this program draws a five corner star''' # ntoehunt import turtle wn = turtle.Screen() dstar = turtle.Turtle dstar.pencolor('blue') angle = 40 for i in range(5): dstar.right(angle) dstar.forward(100)
b884cc6e8e590ef59a9c3d69cad3b5d574368916
Ardrake/PlayingWithPython
/string_revisited.py
1,674
4.21875
4
str1 = 'this is a sample string.' print('original string>>', str1,'\n\n') print('atfer usig capitalising>>',str1.capitalize()) #this prints two instances of 'is' because is in this as well print('using count method for "is" in the given string>>', str1.count('is')) print('\n\n') print('looking fo specfic string literal with spaces>>', str1.count(' is '),'\n') print('using find method for "amp" in the string>>', str1.find('amp'),'\n') print('checkin if sring.isupper()>>',str1.isupper(),'\n') print(bin(255)) #prints in binary stru = str1.upper() print('making string upper case>>',stru,'\n\n') print('now testing new string.isupper()>>', stru.isupper(),'\n\n') print(str1.upper().isupper()) print('lower string "',stru.lower(),'"') print('\n\nTitle method', str1.title()) ##working with spaces in the string str2 = ' five taps of the SPACEBAR ' print('\n\n',str2) print('using s.lstrip() to remove all the whitespaces from the left\n\ ', str2.lstrip(),'\n') print('now on the right\n', str2.rstrip(),'next letter \n') print('this is about removing whitespaces from both sides\n',str2.strip()) # replacing text in a string print(str1.replace('sample', 'testing')) #replaces the first instance in the string #splitting string into a list str3 = str1.split(' ') print(str3) #joining it back together str4 = ' '.join(str3) #because lists don't have join() method quoted string is necessary print(str4) ##formatting a string ## there are two ways to do that s = '%s is %d years old' % ('Harry', 29) #old c style still supported by python3 print(s) t= '{0} is {1} years old and can pass {2} string data'.format('Harry', 29, 'third') print(t)
e385e84609ec8ac97b67310992bf9a74b9f2fa03
skanel/pykhmer-docs
/Dictionaries.py
1,801
3.578125
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 28 16:46:57 2019 @author: Kanel.Soeng """ my_dict = { "key1":"value1", "key2": "value2" } my_dict my_dict["key1"] fruits = {"Apple": 3, "Banna": 1.75, "Cherry": 2} fruits fruits["Cherry"] # 2) Dictionaries with all data type's new_dict = { "k1":147, "k2":[15, 25, 35], "k3":{"Apple":3} } new_dict new_dict["k2"] new_dict["k2"][1] new_dict["k3"] new_dict["k3"]["Apple"] # PRACTISE customer_info = { "salary": 300, "age": 40, "children": {"name": "sopheak", "sex": "male"}, "account_start_date": 20190130, "family_number":["Mr.A", "M.B", "Miss.C"], #........ #........ #....etc... } d = {"students": ["a", "b","c","d"]} d d["students"][1] d["students"][1].upper() d["students"][1].lower() # 3) Add values d = {"k1":100, "k2":200} d["k0"] = 300 d # 4) Replace values d["k1"] = "New One" d d.keys() d.values() d.items # 1) Define a Dictionary # 2) Dictionaries with all data type's # 3) Add values # 3) Replace values # 5) Keys, Values and Item's retrieval # Exercise: 30min str = "awesome This is an awesome occation. This has never happend before." char_occurances = {} #empty dict for char in str: char_occurances[char] = char_occurances.get(char, 0)+1 print(char_occurances) word_occurances = {} for word in str.split(): word_occurances[word] = word_occurances.get(word, 0)+1 print(word_occurances) for (key, value) in char_occurances.items(): print(f"{key} {value}") for key in char_occurances.keys(): print(key) for val in char_occurances.values(): print(val)
6b8534e3bfa2a2511fffca47f90fbcdbc4b879fd
skanel/pykhmer-docs
/Boolean.py
993
3.859375
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 13 07:03:54 2019 @author: Kanel.Soeng """ # Boolean's ## True true False false type(True) 10 > 9 3 == 2 7 < 5 #example 1: l = [1,2,3,4, -1,-3] #control flow , if else => boolean to control the flow logic of the programs. for i in l: if -3 >= 1 : print(i) else: print("none") #example 2: number = 23 guess = int(input('Enter an integer : ')) if guess == number: # is it true or false? # New block starts here print('Congratulations, you guessed it.') print('(but you do not win any prizes!)') # New block ends here elif guess < number: # Another block print('No, it is a little higher than that') # You can do whatever you want in a block ... else: print('No, it is a little lower than that') # you must have guessed > number to reach here print('Done') # This last statement is always executed, # after the if statement is executed. #REMEMBER Write in 'True' not 'true'
26afd30edfecaeb3b79bd8fccf0bdb63a114e421
skanel/pykhmer-docs
/fx2.py
2,091
3.59375
4
# -*- coding: utf-8 -*- """ Created on Mon Apr 29 19:03:48 2019 @author: Kanel.Soeng """ from math import sqrt print("ស្រាយ​សមីការដឹក្រេទី 2: ax^2 + bx + c = 0") a = float(input("បញ្ចូល a: ")) b = float(input("បញ្ចូល b: ")) c = float(input("បញ្ចូល c: ")) if a == 0: if b == 0: if c == 0: print("​សមីការមាន​ឬសច្រើន​រាប់​មិនអស់!") else: print("​សមីការគ្មានឬស!") else: if c == 0: print("​សមីការមាន​ឬស x = 0") else: print("​សមីការមាន​ឬស មួយ x = ", -c / b) else: delta = b ** 2 - 4 * a * c if delta < 0: print("សមីការគ្មានឬស!") elif delta == 0: print("សមីការមាន​ឬស មួយ x = ", -b / (2 * a)) else: print("សមីការមាន​ឬស មួយ ពីរ​ផ្សេងគ្នា") print("x1 = ", float((-b - sqrt(delta)) / (2 * a))) print("x2 = ", float((-b + sqrt(delta)) / (2 * a))) # WRITE IN FUNCITON WAY #coding:utf-8 #Program by Kanel import math def quadratic(a,b,c): delta = b*b - 4*a*c if delta > 0 : x1 = (-b + math.sqrt(delta))/(2*a) x2 = (-b - math.sqrt(delta))/(2*a) print("សមីការដឺក្រេទី 2 មាន​ឬសពីរ​ផ្សេងគ្នា") print("x1= %3.2f x2= %3.2f " %(x1,x2)) elif delta ==0 : print ("សមីកាមាន​ឬស​ឌុប x1=x2= %3.2f" %(-b/2*a)) else : print ("សមីការគ្មាន​ឬស" ) print("ដាក់បញ្ចូលតាម​លំដាប់លំដោយ មេគុណ a,b,c របស់​សមីការ​ដឹក្រេទី២ ") a = float(input('មេគុណ a:')) b = float(input('មេគុណ b:')) c = float(input('មេ c:')) quadratic(a,b,c)
88e075ee41de693ffac1d3ead9078941d7cb7ab1
bombero2020/python_tools
/euromill.py
2,891
3.5
4
import pandas as pd # Use this function on premise if there is no data# def actualizarlista(): '''Función que toma todos los números, incluido el último, de los resultados de los sorteos y los mete en Resultados_base.csv''' print("Recuperando datos de Google spreadsheet") ref = "https://docs.google.com/spreadsheet/pub?key=0AhqMeY8ZOrNKdEFUQ3VaTHVpU29UZ3l4emFQaVZub3c&amp" tabla = pd.read_html(ref, header=0, parse_dates=True) t = pd.DataFrame(tabla[0]) print(t.head(5)) t.drop(t.index[0], inplace=True, axis=0) # quitamos la fila 0, ya que no hay datos t.drop(['Unnamed: 0'], inplace=True, axis=1) # quitamos la columna 1, no necesario t.drop(['Unnamed: 7'], inplace=True, axis=1) # quitamos la columna 7, no necesaria enca = ['FECHA', 'N1', 'N2', 'N3', 'N4', 'N5', 'Star1', 'Star2'] t.columns = enca # redefinimos las columnas # falta pasarlos a enteros print(t.head()) t.drop(t.index[0], inplace=True, axis=0) t.to_csv('Resultados_base.csv') print("\nGuardado en Resultados_base.csv\n") class EuroMill: def __init__(self): self.data_frame = self.get_data() def version(self): print('version 09/11/2019') def get_data(self): '''Función para cargar los datos en un Dataframe''' datos = pd.read_csv("Resultados_base.csv", parse_dates=True) df = pd.DataFrame(datos) df.set_index('FECHA', inplace=True, drop=True) df.drop(['Unnamed: 0'], inplace=True, axis=1) return df def BackUp_datos(self): '''Función para guardar los datos en un backup de respaldo''' print("Actualizando datos...") self.get_data() print("Cargando datos...") dataframe = self.get_data() dataframe.to_csv("ResultadosBackup.csv") print("\nGuardado en ResultadosBackup.csv\n") def analise_data(self): ''' Función para saber el peso de cada número en cada columna''' n1 = self.data_frame.N1.values n2 = self.data_frame.N2.values n3 = self.data_frame.N3.values n4 = self.data_frame.N4.values n5 = self.data_frame.N5.values st1 = self.data_frame.Star1.values st2 = self.data_frame.Star2.values print(st2, type(st2), len(st2)) numero = st2 l = len(numero) if max(numero) <= 12: n = [i for i in range(1, 13)] else: n = [i for i in range(1, 51)] popu = [] weights = [] for i in n: count = 0 for j in numero: if i == j: count += 1 w = 100 * (count / float(l)) # print(i,'encontrado',count,'times','weight',w) popu.append(i) weights.append(round(w)) print(popu, weights) def test(): eur1 = EuroMill() df = eur1.get_data() print(eur1.analise_data()) test()
93f34502472cddeb27d9d3404fb0f4f5269bb920
ladipoore/PythonClass
/hass4.py
1,239
4.34375
4
""" I won the grant for being the most awesome. This is how my reward is calculated. My earnings start at $1 and can be doubled or tripled every month. Doubling the amount can be applied every month and tripling the amount can be applied every other month. Write a program to maximize payments given the number of months by user. """ #Introducing the program Welcome = "Congratulations!" Welcome2 = "If you are using this program, that means you won the You-Are-Awesome award!" print (100*"*") print(format(Welcome,'^100s')) print(format(Welcome2,'^100s')) print (100*"*") print("\n") print("I am sure you are dying to know how much you won, let's compute!") print("\n") #Calculating and printing out the results. amount = 1 months = int(input("For how many months did they say you will receive payments? ")) print("\n") print("Here are the monthly installment amounts:") print("\n") for strategy in range(1,months+1,1): if strategy == 1: payment = "$"+str(amount) print("Month ",strategy, ":", payment.rjust(50)) elif strategy %2 == 0: amount *= 2 payment = "$"+str(amount) print("Month ",strategy, ":", payment.rjust(50)) else: amount *= 3 payment = "$"+str(amount) print("Month ",strategy, ":", payment.rjust(50))
a059707c56ec6ca5511f685ae678f8d7938feafc
Chaitainya/Python_Programs
/hello.py
197
3.5625
4
# def greet(names): # for name in names: # print("Hello", name) # greet("monica") def greet(*names): for name in names: print("Hello", name) greet("monica","leon","sheema")
dd6bd262bba20f8b9cbbed4e81f51312986f1440
Chaitainya/Python_Programs
/class_3.py
204
3.890625
4
class Add: num_1 = 4 num_2 = 5 def __init__(self,num_3): self.num_3 = num_3 def num(self): return self.num_1 + self.num_2 + self.num_3 add = Add(6) print(add.num())
f6b533e909b813218b187015c4e36bb8b4b22c86
Chaitainya/Python_Programs
/reverse.py
163
4
4
my_list = [1,2,3,4,5,6,7,8,9,10] print(my_list[::-1]) my_tuple = (1,2,3,4,5,6,7,8,9,10) print(my_tuple[::-1]) my_str = "1,2,3,4,5,6,7,8,9,01" print(my_str[::-1])
18892e6ba25a7f3ec491f1cb5c23f6f3278f0432
mahmutkamalak/word-letter-counter
/char counter.py
3,201
4.0625
4
from tkinter import Tk,Button,Label,StringVar,Entry,DoubleVar ##tkinter window =Tk() #get a new window window.title('Character&word counter') # window.configure(background='red') #windowun değişkenlerini ayarladık window.geometry('320x220') window.resizable(width=True,height=True) ## kullanıcı boyutu değiştiremesin diye ayar yaptık ######First FUNCTION####### word_count=0 char_count=0 def calculatee (): value=str(ft_entry.get()) #get kullanılmasının sebebi uygulamaya girilen değeri fonsiyon için buraya almak split_string=value.split() word_count=len(split_string) mt_value.set(word_count) #yüzde 4f ile 4 atne decimal point olsun dedik. for w in split_string: global char_count char_count += len(w) mt_value2.set(char_count) return word_count,char_count def clear(): ft_value.set("") mt_value.set("") mt_value2.set("") ft_lbl= Label(window,text="TEXT",bg="purple",fg="white",width=14) # label oluşturduk ,renklerini ne yazağını belirledik ft_lbl.grid(column=0,row=0,padx=15,pady=15) #oluşturulan labelın konumunu belirledik winndowdaki ft_value = StringVar() #aslında değerin tipini belirttik tüm sayılar ve decimal sayılar yazılabilir ft_entry=Entry(window,textvariable=ft_value,width=14) # ft_entry.grid(column=1,row=0) ft_entry.delete(0,'end') #uygulama 0 dan başlaması için temizledik ft_lbl = Label(window,text="Character",bg="black",fg="white",width=14) ft_lbl.grid(column=0,row=2,padx=15,pady=15) mt_lbl = Label(window,text="Word",bg="brown",fg="white",width=14) mt_lbl.grid(column=0,row=1) mt_value = DoubleVar() mt_entry = Entry(window,textvariable=mt_value,width=14) mt_entry.grid(column=1,row=1,pady=30) mt_entry.delete(0,'end') mt_value2 = DoubleVar() mt_entry2 = Entry(window,textvariable=mt_value2,width=14) mt_entry2.grid(column=1,row=2,pady=30) mt_entry2.delete(0,'end') convert_btn=Button(window,text='calculate',bg='blue',fg='white',width=14,command=calculatee) #command butonun hangi fonk çağırıcağını gösterir convert_btn.grid(column=0,row=3,padx=15) clear_btn = Button(window,text="Clear",bg="black",fg="white",width=14,command=clear) clear_btn.grid(column=1,row=3,padx=15) window.mainloop() # prpgramın çalışmasını sağlar #https://www.codevscolor.com/python-count-words-characters-string/ ###KAYNAK1
6e0a0d84763e65fc5b8161a432874cf245fe4b5f
Pawtang/learn-py
/Through Section 5/number_lists.py
181
4.1875
4
even = [2, 4, 6, 8] odd = [1, 3, 5, 7, 9] #Nested List numbers = [even, odd] for number_list in numbers: print(number_list) for value in number_list: print(value)
a46b0b613c55afe16054daab51880a610d5c64ca
aja2000/imbot1
/test.py
301
3.671875
4
swears = open("swears.csv", "r") key = swears.read() split = key.split(",") # print(split) message = 'poop' def bad_word_test(): for word in split: if message == word: return True return False if bad_word_test(): print('bad word') else: print("child of god")
e8490f5d83ca0755a3cb07269a5fff76746a7b58
divij234/python-programs
/python programs/FactorsUsingWhile.py
188
3.984375
4
num=int(input("Enter a number : ")) i=1 print("The factors of ",num,"are :-") while i<=num: if num%i==0: print(i) i+=1
34a526561a96ff912b365dd9a62f92f607f51d9f
divij234/python-programs
/python programs/ForExample.py
151
4.25
4
str=input("Enter a string : ") for x in range(len(str)): print(str[x]) #we can also do it like this:- for element in str: print(element)
9963f40ed9b635d430c35b57695116416ef91654
divij234/python-programs
/python programs/list1.py
213
4.09375
4
#WAP to search for an elemnt in a given list li=[] for i in range(0,6): val=input("enter the elements") li.append(val) if 12 in li: print("it is present") else: print("it is not present")