blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
71611f767f80e3e7e1078a6c663c039a0812396a
mschultz4/practice
/answers/old/python/fibonacci.py
321
4.03125
4
''' Fibonnacci sequence @param {number} n Value of sequence to return Assumptions 1. Series starts at 1 2. n a positive integer ''' def fib(n): a, b = (1, 1) # start sequence at 3 i = 3 # process sequence while(i <= n): a, b = (b, a + b) i += 1 return b print(fib(5))
010f4caaef35a6ec577b0bb5ef77a125278ea6b7
chvjak/hr-practice
/list_insertion_sort.py
1,327
3.921875
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def __repr__(self): return str(self.val) class Solution: # @param A : head node of linked list # @return the head node in the linked list def insertionSortList(self, A): cur_sorted = A stack = [cur_sorted] while cur_sorted.next is not None: cur_to_insert = cur_sorted.next while len(stack): maybe_smaller = stack.pop() if maybe_smaller.val > cur_to_insert.val: greater = maybe_smaller # swap greater.val, cur_to_insert.val = cur_to_insert.val, greater.val cur_to_insert = greater else: stack.append(maybe_smaller) break # restore stack cur_stack = cur_to_insert while cur_stack != cur_sorted.next: stack.append(cur_stack) cur_stack = cur_stack.next stack.append(cur_stack) cur_sorted = cur_sorted.next return A l = ListNode(9) l.next = ListNode(7) l.next.next = ListNode(8) l.next.next.next = ListNode(5) S = Solution() res = S.insertionSortList(l)
e05a55c5f64861bb85ba42ad77db7b08f119e785
mayraahmad65/PythonProjects
/date_and_time.py
206
3.75
4
# -*- coding: utf-8 -*- """ Created on Tue May 5 10:46:02 2020 @author: Mayra """ import datetime now = datetime.datetime.now() print("Current date and time : ") print(now.strftime("%y-%m-%d %H:%M:%S"))
18d1300a06a6b7c408f4f382eb8431ccb3b0e50f
syedaali/python
/exercises/46_web_requests.py
1,392
4.28125
4
__author__ = 'syedaali' ''' An alternade is a word in which its letters, taken alternatively in a strict sequence, and used in the same order as the original word, make up at least two other words. All letters must be used, but the smaller words are not necessarily of the same length. For example, a word with seven letters where every second letter is used will produce a four-letter word and a three-letter word. Here are two examples: "board": makes "bad" and "or". "waists": makes "wit" and "ass". Using the word list at http://www.puzzlers.org/pub/wordlists/unixdict.txt, write a program that goes through each word in the list and tries to make two smaller words using every second letter. The smaller words must also be members of the list. Print the words to the screen in the above fashion. ''' import requests r = requests.get('http://www.puzzlers.org/pub/wordlists/unixdict.txt') if r.raise_for_status: print 'got url' else: print 'could not get url' s = str(r.text) s = s.split() s = list(s) word1 = '' word2 = '' words = [] for item in s: word1 += item[::2] word2 += item[1::2] print 'item {0} makes {1} and {2}'.format(item, word1, word2) if word1 in s: words.append(word1) print '{0} exists'.format(word1) if word2 in s: words.append(word2) print '{0} exists'.format(word2) word1 = '' word2 = ''
05cbd1e07212c009fa813bb02e88240bf6a43378
v1nnyb0y/Coursera.BasePython
/Coursera/Week.1/Task.6.py
81
3.890625
4
''' Last digit of number ''' number = int(input()) print(number % 10, end='\n')
605b1d703a80356b3bd168c718f5468290e18041
Hgonzalez/PythonClass201901
/Python Class/Capitalization.py
881
3.921875
4
user_input = input("Enter a word to begin, to quit type 'quit': \n> ") def character(x): chars = ("?",".","!") if x in chars: return True else: return False def character_replace(x): word = " " for i in range(len(x)-2): if character(x[i]): #print("hgjhhj",x[i],i) newindex = i+2 #print("nnnn",newindex) first_letter = x[newindex].upper() #print(capital_letter) #print(replaced_string[0:newindex]) #print(replaced_string[newindex+1:]) word = replaced_string[0:newindex]+ first_letter + replaced_string[newindex+1:] #print ("KKK",word) # else: # newindex = i+2 # capital_letter = x[newindex].capitalize() # word = replaced_string[0:newindex]+ capital_letter + replaced_string[newindex+1:] print (word) replaced_string = user_input.replace(" i ", " I ") replaced_string = replaced_string.capitalize() character_replace(user_input)
2c73636f1d00b9138cacd46e5f31c3b565f9dffe
paige0701/algorithms-and-more
/projects/inflearn/python_algorithm/dfs_beginner.py
6,258
3.515625
4
class One: def to_binary(self, n): if n == 1: print(n, end='') else: self.to_binary(n // 2) print(n % 2, end='') def to_binary2(self,n): if n== 0: return else: self.to_binary2(n//2) print(n%2, end='') class Two: def pre_order_traversal(self, v): if v > 7: return else: print(v, end='') self.pre_order_traversal(v*2) self.pre_order_traversal(v*2 +1) def in_order_traversal(self, v): if v > 7: return else: self.in_order_traversal(v * 2) print(v, end='') self.in_order_traversal(v * 2 + 1) def post_order_traversal(self, v): if v > 7: return else: self.post_order_traversal(v * 2) self.post_order_traversal(v * 2 + 1) print(v, end='') class Three: n = 3 ch = [0] * (n + 1) def DFS(self, v): if v == self.n+1: for i in range(1, self.n+1): if self.ch[i] == 1: print(i, end='') print() else: self.ch[v] = 1 self.DFS(v+1) self.ch[v] = 0 self.DFS(v+1) class Four: n = 6 a = [1, 3, 5, 6, 7, 10] total = sum(a) my_sum = 0 def DFS(self, v, total): print('sum ch = ', total) print('sum total = ', self.total) if total > self.total//2: return if v == self.n: if total == (self.total - total): print('Yes') import sys sys.exit(0) else: self.DFS(v + 1, total + self.a[v]) self.DFS(v + 1, total) class Five: total = 100000000 a = [27, 567,999,234, 50, 567, 123,4734, 754, 84, 35,1353, 76, 464,4634, 65, 89 , 3553, 59, 38, 4135] diff = -21167888 def solution(self, n, tot, tsum): if tot + (sum(self.a)-tsum) < self.diff: # this is important less time return if n == len(self.a): if self.total > tot > self.diff: self.diff = tot else: self.solution(n+1, tot + self.a[n], tsum+self.a[n]) self.solution(n+1, tot, tsum+self.a[n]) class Six: n, m = 3, 2 result = [0] * n cnt = 0 def solution(self, l): if l == self.m: for i in range(self.m): print(self.result[i], end=' ') print() self.cnt += 1 else: for i in range(1, self.n+1): self.result[l] = i self.solution(l+1) class Eight: m = 2 n = 3 res = [0] * n ch = [0] * (n+1) def solution(self, L): if L == self.m: for i in range(L): print(self.res[i], end='') print() else: for i in range(1, self.n+1): if self.ch[i] == 0: self.ch[i] = 1 self.res[L] = i self.solution(L+1) self.ch[i] = 0 class Nine: n = 4 m = 16 res = [0] * n ch = [0] * (n+1) t = [1, 3, 3, 1] def solution(self, L): if L == self.n: t = 0 for i in range(len(self.res)): t += (self.res[i] * self.t[i]) if t == self.m: print(''.join([str(i) for i in self.res])) import sys sys.exit(0) else: for i in range(1, self.n+1): if self.ch[i] == 0: self.ch[i] = 1 self.res[L] = i self.solution(L+1) self.ch[i] = 0 n, f = 4, 16 p = [0] * n b = [1] * n ch = [0] * (n+1) # TODO: 1,3,3,1 이항계수 구하는 법 !! 주용함 for i in range(1, n): b[i] = b[i - 1] * (n - i) // i # TODO: itertools.permutaions def solution2(self, L, sum): if L == self.n and sum == self.f: for x in self.p: print(x, end=' ') import sys sys.exit(0) else: for i in range(1, self.n+1): if self.ch[i] == 0: self.ch[i] = 1 self.p[L] = i self.solution2(L+1, sum + (self.p[L] * self.b[L])) self.ch[i] = 0 class Ten: n, m = 4, 2 res = [0] * m cnt = 0 def solution(self, L, s): if L >= m: for i in self.res: print(i, end='') print() self.cnt+=1 else: for i in range(s, self.n+1): self.res[L] = i self.solution(L+1, i+1) class Eleven: n, k, m = 5, 3, 6 a = 2, 4, 5, 8, 12 res = [0] * n cnt = 0 # find combinations using itertools import itertools # combinations # for x in itertools.combinations(a, k): def solution(self, L, s, total): if L == self.k: if total % self.m == 0: self.cnt += 1 else: for i in range(s, self.n): self.res[L] = self.a[i] self.solution(L+1, i+1, total+self.a[i]) if __name__ == '__main__': one = One() # one.to_binary2(11) two = Two() # two.pre_order_traversal(1) # print() # two.in_order_traversal(1) # print() # two.post_order_traversal(1) three = Three() # three.DFS(1) four = Four() # four.DFS(0, 0) # five = Five() # five.solution(0,0, 0) # print(five.diff) six = Six() # six.solution(0) # print(six.cnt) # seven = Seven() a = [419, 408, 186, 83] a.sort(reverse=True) money = 6249 res = 21470000 # print(seven.solution(len(a)-1)) # seven.DFS(0,0) # print(res) # print(seven.coinChange([186,419,83,408], 6249)) m = 2 # n = 3 # eight = Eight() # eight.solution(0) nine = Nine() # nine.solution(0) # nine.solution2(0,0) ten = Ten() # ten.solution(0,1) # print(ten.cnt) el = Eleven() el.solution(0, 0, 0) print(el.cnt)
52d2425578854b88b6afd37f1643044ce12bce5d
sabharee/python-scripts
/python/20170223find_function/20170223find_function.py
207
3.796875
4
def find(str,ch): index = 0 while index<len(str): if str[index] == ch: return index index=index+1 return -1 position = find("furniture","r") print "position of the element is",position
d62a6d338b8d2e768faa366e10e84b9c8f720461
igortereshchenko/amis_python
/km73/Hnidak_Maryna/4/task2.py
508
4.1875
4
''' Умова: Вивести результат функції sign(x), що визначається наступним чином: sign(x) = 1, if x > 0, sign(x) = -1, if x < 0, sign(x) = 0, if x = 0.. Вхідні дані: користувач вводить дійсне число. Вихідні дані: вивести результат sign. ''' x = float(input(' x = ')) if x>0: answer = 1 elif x<0: answer = -1 else: answer = 0 print('sign(x)', '=', answer)
52922dcaa154ca16e53817ab768a2faf63014ae8
jacksonludwig/ticBotTwo
/board.py
1,399
3.765625
4
class Board: MAGIC_SQUARE = [4, 9, 2, 3, 5, 7, 8, 1, 6] def __init__(self): self.board = [1, 2, 3, 4, 5, 6, 7, 8, 9] def format_board(self): row1 = f"{self.board[0]} | {self.board[1]} | {self.board[2]}" row2 = f"{self.board[3]} | {self.board[4]} | {self.board[5]}" row3 = f"{self.board[6]} | {self.board[7]} | {self.board[8]}" return f"```{row1}\n{row2}\n{row3}```" def is_spot_open(self, position): return isinstance(self.board[position], int) def take_move(self, symbol, position): position = int(position) - 1 self.board[position] = symbol def is_tie(self): for i in range(len(self.board)): if self.is_spot_open(i): return False return True def __magic_square_check(self, board, symbol, i, j, k): MAGIC_SQUARE = self.MAGIC_SQUARE if i != j and i != k and j != k: if (board[i], board[j], board[k]) == (symbol, symbol, symbol): if MAGIC_SQUARE[i] + MAGIC_SQUARE[j] + MAGIC_SQUARE[k] == 15: return True return False def is_win(self, symbol): for i in range(0, 9): for j in range(0, 9): for k in range(0, 9): if self.__magic_square_check(self.board, symbol, i, j, k): return True return False
4c7f9be6e5eb21e835b215ccd48a7113ceac6025
maverick51/word-frequency
/word_frequency.py
1,391
4.21875
4
import re #import for re.sub def word_frequency(mystring): '''This function counts the number of words in the passed in string''' freq = {} #the dictionary of words and number of appearances #change string to a list to make it easier to pull out words mylist = mystring.split(' ') #find number of times words appear in string for word in mylist: if word not in freq: #add word for first time freq[word] = 1 else: #word appears already so add one to total freq[word] += 1 freq = dict(freq) #change list of words/total to dictionary return freq #return list of words/total as dictionary if __name__ == "__main__": #do whatever when the file is run directly #open file and read in whole text with open("sample.txt") as sample: data = repr(sample.readlines()) #make data lower case data = data.lower() #strip all punctuation and commands data = re.sub(r'[^A-Za-z]', r' ', data) #call word_frequency to find out how many times words appear mydict = word_frequency(data) #call sorted to make a list of sorted words by accurance mydictsorted = sorted(mydict.items(), key=lambda x: x[1], reverse=True) #print out the top 20 most used words count = 0 while count <= 19: (x, y) = mydictsorted[count] print(x, y) count += 1
74c9df4dd20637fd93efa5a87503c8f22da0d6b4
sagarm4224/python
/PycharmProjects/First/InputOutput.py
1,083
3.921875
4
str = input("Enter the input \n") print("received input is", str) #file creation mode in PYTHON file = open("foo1.csv","w+") file.write("Python is so good nowadays, isn't it\n") file = open("foo1.csv","r+") str = file.read() print("the read string is ", str) position = file.tell() print("the current position of the file is " , position ) file.close() import os; os.rename("foo1.csv","foo2.csv") os.remove("foo2.csv") os.rmdir("New DIrectory") os.mkdir("New Directory") print(os.getcwd()) file = open("foo.txt","r") for index in range(5): line = file.__next__() print(index,line) file.close() file = open("foo.txt","r") line = file.read(10) print("the number of byte read is ", line) file.close() file = open("foo.txt","r") for i in range(6): line1 = file.readline() print("the number of byte read is" , line1) file.close() file = open("foo.txt","r") line = file.read() print("the line read is ",line) file.seek(7,0) line = file.read() print("after the seek the line read is ",line)
a9a9c90fbf223f6c913cf641824dbeb5062d662d
ankitkumar174/QSTP-ROS-2021-Ass-1
/Ankit ROS ass-1.py
2,281
4.09375
4
#!/usr/bin/env python # coding: utf-8 # In[4]: """Week I Assignment by Ankit Kumar Simulate the trajectory of a robot approximated using a unicycle model given the following start states, dt, velocity commands and timesteps State = (x, y, theta); Velocity = (v, w) 1. Start=(0, 0, 0); dt=0.1; vel=(1, 0.5); timesteps: 25 2. Start=(0, 0, 1.57); dt=0.2; vel=(0.5, 1); timesteps: 10 3. Start(0, 0, 0.77); dt=0.05; vel=(5, 4); timestep: 50 Upload the completed python file and the figures of the three sub parts in classroom """ import numpy as np import matplotlib.pyplot as plt class Unicycle: def __init__(self, x: float, y: float, theta: float, dt: float): self.x = x self.y = y self.theta = theta self.dt = dt # Store the points of the trajectory to plot self.x_points = [self.x] self.y_points = [self.y] def step(self, v: float, w: float, n:int): for i in range(n): self.theta += w *(self.dt) self.x += v*np.cos(self.theta) self.y += v*np.sin(self.theta) self.x_points.append(self.x) self.y_points.append(self.y) return self.x, self.y, self.theta def plot(self, v: float, w: float,i:int): plt.title(f"Unicycle Model: {v}, {w}") plt.title(f" Ankit's ROS ass-1 graphs - {i}") plt.xlabel("x-Coordinates") plt.ylabel("y-Coordinates") plt.plot(self.x_points, self.y_points, color="red", alpha=0.75) plt.grid() plt.show() if __name__ == "__main__": print("Unicycle Model Assignment") # ploting multiple trajectories trajec = [ {'x':0,'y': 0,'theta': 0,'dt': 0.1, 'v':1,'w': 0.5,'step': 25}, {'x':0,'y': 0,'theta': 1.57,'dt' :0.2,'v': 0.5, 'w':1,'step': 10}, {'x':0,'y': 0,'theta': 0.77, 'dt':0.05, 'v': 5,'w': 4, 'step': 50} ] for i in range(len(trajec)): x = trajec[i]['x'] y = trajec[i]['y'] theta = trajec[i]['theta'] dt = trajec[i]['dt'] v = trajec[i]['v'] w = trajec[i]['w'] n = trajec[i]['step'] project=Unicycle(x, y, theta, dt) cordinates = project.step(v, w, n) x, y, theta = cordinates project.plot(v, w, i+1)
6733908a98800eb74354ebb5c249a97add1e65f9
macoyulloa/holbertonschool-machine_learning
/math/0x00-linear_algebra/4-line_up.py
260
4.09375
4
#!/usr/bin/env python3 """ adding array """ def add_arrays(arr1, arr2): """ adding array """ if len(arr1) is not len(arr2): return None result = [] for i in range(len(arr1)): result.append(arr1[i] + arr2[i]) return result
3d5609257b7a31b8a1684599aa8eb6b7f39d337f
artkpv/code-dojo
/_algos/math/permutations/permutations2.py
524
3.8125
4
#!python3 class Solution: def permutation(nums): if not nums: yield [] # to start combining for i in range(len(nums)): for p in Solution.permutation(nums[:i] + nums[i+1:]): yield [nums[i]] + p def permute(self, nums): return list(Solution.permutation(nums)) if __name__ == '__main__': s = Solution() res = s.permute([1,2,3]) print('Result', res) assert res == [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
5117130ea3dcde0101c85b1bab04777ad8e85e2d
vamsitallapudi/Coderefer-Python-Projects
/programming/leetcode/linkedLists/medium/SplitLLToParts.py
1,594
3.71875
4
# Definition for singly-linked list. from typing import List from leetcode.linkedLists.medium.LinkedListComponents import initializeLinkedList class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def splitListToParts(self, root, k): # Count the length of the linked list curr, length = root, 0 while curr: curr, length = curr.next, length + 1 # Determine the length of each chunk chunk_size, longer_chunks = length // k, length % k res = [chunk_size + 1] * longer_chunks + [chunk_size] * (k - longer_chunks) # Split up the list prev, curr = None, root for index, num in enumerate(res): if prev: prev.next = None res[index] = curr # skipping these many number of items to get ready for next split for i in range(num): prev, curr = curr, curr.next return res # find the length to split def initializeLinkedListWith11(): a = ListNode(0) b = ListNode(1) c = ListNode(2) d = ListNode(3) e = ListNode(4) # f = ListNode(5) # g = ListNode(6) # h = ListNode(7) # i = ListNode(8) # j = ListNode(9) # k = ListNode(10) a.next = b b.next = c c.next = d d.next = e # e.next = f # f.next = g # g.next = h # h.next = i # i.next = j # j.next = k return a if __name__ == "__main__": a = initializeLinkedListWith11() Solution().splitListToParts(a, 3)
953b8836a6c25fd271ac10a993175a487b501e66
FalconFX9/WRO2019--GitHub_Python
/block_algorithm.py
1,458
3.703125
4
from time import sleep blocks = [] white_blocks_seen = 0 pick_up_block = False def first_scan(): global blocks, white_blocks_seen def blocks_list(): if int(input('Give input')) == 17: blocks.append(False) else: blocks.append(True) sleep(1) while not len(blocks) == 3: blocks_list() pass for i in range(0, len(blocks)): print(blocks[i]) if not blocks[i]: white_blocks_seen += 1 if white_blocks_seen == 2: blocks.append(True) blocks.append(True) blocks.append(True) def second_scan(): global white_blocks_seen, pick_up_block while len(blocks) < 6: if white_blocks_seen < 2: if not int(input('Give value')) == 17: blocks.append(True) # Go pick up the block else: blocks.append(False) white_blocks_seen = 0 for i in range(0, len(blocks)): if not blocks[i]: white_blocks_seen += 1 else: print("All white blocks have been seen") blocks.append(True) # Go pick up all the next blocks def pick_up_blocks(): global pick_up_block count = 0 if blocks[count]: # Code to pick up the block pass else: # Follow to next line pass count += 1 first_scan() second_scan() print(blocks)
9056fe0b5503c5ea74cb6c86f9565dfd9acfc68d
gerald-odonnell7/LearningToProgram
/PFAB/2014-09-18/grade.py
194
4.09375
4
grade = input("Please enter a numeric grade (0-100)") if (grade >= 90): print "A" elif (grade >= 80): print "B" elif (grade >= 70): print "C" elif (grade >= 60): print "D" else: print "F"
c9b675eaea154296a09187a53ec5bc2d811f220f
y-usuzumi/survive-the-course
/random_questions/单向链表/main.py
791
3.875
4
class Node: def __init__(self, n, next_node=None): self._n = n self._next_node = next_node @property def value(self): return self._n @property def next_node(self): return self._next_node def __str__(self): if self._next_node is None: return "(%s)" % self._n else: return "(%s) -> %s" % (self._n, self._next_node) def linked_list_from_list(l): # [1, 4, 7, 2, 9, 5, 3] # 1 -> 4 -> 7 -> 2 -> 9 -> 5 -> 3 node = None for i in reversed(l): node = Node(i, next_node=node) return node if __name__ == '__main__': l = [1, 4, 7, 2, 9, 5, 3] ll = linked_list_from_list(l) print(ll) print("Head is: %s" % ll.value) print("Tail is: %s" % ll.next_node)
125177dcedd2bf6ab15fa8c597cdb0b206c09a0f
tz0531/EECS-349-Final-Project
/bjutils.py
456
3.765625
4
from Card import * def valHand(hand): val = 0 aces = [] for card in hand: if "Ace" in card.name: #if val <= 10: # val += 11 #else: # val += 1 # card.value = 1 aces.append(card) else: val += card.value for card in aces: if val + 11 > 21: val += 1 card.value = 1 else: val += 11 return val def flippedAce(hand): for card in hand: if card.value == 1: print("Has a flipped ace!") return True return False
6699c275fbb46a805c31bdd11cfa01f1abf88bb4
garenporter/OSU_Assignments_And_Projects
/CS_372/program_1/serversample.py
2,238
3.53125
4
import sys from socket import * def chat(newConnection, clientName, userName): message = "" #Hold the message while 1: #Run until we no longer want to chat receive = newConnection.recv(501)[0:-1] #Receive message if receive == "": #If nothing is received. Wait for new connection print "End of connection" print "Waiting..." break print "{}> {}".format(clientName, receive) #Puts the prompt in the propert format sending = "" while len(sending) > 500 or len(sending) == 0: sending = raw_input("{}> ".format(userName)) if sending == "\quit": #Per assignment specs, must be able to quit when you type in \quit print "End of connection" print "Waiting..." break newConnection.send(sending) def infoSave(connection, userName): clientName = connection.recv(1024) connection.send(userName) return clientName if __name__ == "__main__": if len(sys.argv) != 2: #First check if the user put in the right number of arguments. If not, print the usage statement print "Usage: python chatServer.py [port]" exit(1) portNumber = sys.argv[1] newSocket = socket(AF_INET, SOCK_STREAM) #Taken from here https://docs.python.org/2/howto/sockets.html newSocket.bind(('128.193.54.182', int(portNumber))) #Also from this link https://docs.python.org/2/howto/sockets.html newSocket.listen(1) #Start listening userName = "" while len(userName) > 10 or len(userName) == 0: #Get the user name, estabish connection, call chat function and finally close when we're ready userName = raw_input("Enter a username that is 10 characters or less. ") print "Server is ready for messages." while 1: connection, address = newSocket.accept() print "Connected on address {}".format(address) chat(connection, infoSave(connection, userName), userName) connection.close()
5dbb38b363779ddde46801cde6f995f6291d5337
agk79/Python
/project_euler/problem_01/sol1.py
431
4.21875
4
''' Problem Statement: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3,5,6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below N. ''' from __future__ import print_function try: raw_input # Python 2 except NameError: raw_input = input # Python 3 n = int(raw_input().strip()) print(sum([e for e in range(3, n) if e % 3 == 0 or e % 5 == 0]))
b8ad2a9dfecb88e288d1b2279979e5bb743908e4
Chepexz/EJEPS2
/assignments/05Trapecio/src/exercise.py
315
3.78125
4
import math import os def main(): os.system("clear") a = float(input("ingrese el valor para el cateto 'A' cateto: ")) b = float(input("ingrese el valor para el cateto 'B' cateto: ")) c = math.sqrt((a*a+b*b)) print(str(F"El valor de la Hipotenusa es: {c}")) if __name__=='__main__': main()
cfc6a20d4fb7f2efef6c31a1a6adcb1fc9d46077
thisismsp78/PythonCodsLearn
/p1/FactorialDemo/FactorialDemo.py
115
4
4
number=int(input("Enter number : ")) result=1 while number>1: result*=number number-=1 print(result)
faaddb1d14cf9009540ee2783561a798cd00ba01
wnsgur1198/python_practice
/ex18.py
214
3.75
4
# 파일을 읽어 데이터 분리해서 출력하기 infile=open("test.txt","r") for line in infile: line=line.rstrip() word_list=line.split() for word in word_list: print(word) infile.close()
188f40751d81ea50ccd4575e6a0bf1b09c31ab49
zaeemyousaf/zaeem
/softDevelopement/memoryTest_1.0_python/MemoryTest_Functions.py
7,346
3.96875
4
''' Author: Zaeem Yousaf Email: quaidzaeem@gmail.com Date: 01-02-2017 version: 1.0 python: 3 Teacher: Sir Naghman at PakTurk ''' ''' Function list 1): mkCards(n,types) returns an array of size n, contains 'types' types of data 2): mkGrid(cardsArray,rows,cols) returns two dimensional array of size 'rows' and 'columns' 3): shuffle(grid,nplaces) returns shuffled two dimensional array, nplaces=1 means suffle only one card and so on 4): areSame(usc) boolean predicates whether user selected card are same. 5): cardsAtPos(grid,pos) returns cards array at positions 6): gridDisplay(grid,faceUp=False,except) provides user's interface 7): removeCards(grid,pos,replace) replaces cards at pos from grid with user defined value 8): contains(boxArray,elements) boolean predicates whether 'element list' is in boxArray ''' def mkCards(n,types): ''' it makes n virtual cards of different types it is ordered list''' identicals=int(n/types) Deck=[] for t in range(types): for identical in range(identicals): Deck.append(t) return Deck deck=mkCards(64,32) #-------------------------------------------- def mkGrid(cardsList,rows,cols): ''' makes two dimension grid into rows and columns ''' grid=[] #loops=len(cardsList)+1 loops=(rows*cols)+1 rowElements=[] for l in range(1,loops): if l % cols !=0: rowElements.append(cardsList[l-1]) else: rowElements.append(cardsList[l-1]) grid.append(rowElements) rowElements=[] return grid grid=mkGrid(deck,8,8) #print(grid) #---------------------------------------------- def shuffle(grid,nplaces): ''' it rearranges the cards nplaces tries to swap n cards to eachother's place''' shuffledGrid=grid # preserve the original grid m=len(grid) # number of rows n=len(grid[0]) # number of columns from random import random for i in range(nplaces): # select one random coordinate rRow1=int((m)*random()) #print(" random row1 is: {} ".format(rRow1)) # random row rCol1=int((n)*random()) #print(" random col1 is: {} ".format(rCol1)) #print(rCol1) # random column vAtCoordinate1=(grid[rRow1])[rCol1] #print(" value at {} is {} ".format((rRow1,rCol1),vAtCoordinate1)) # value At Coodinate 1 #------------------------- # select second random coordinate rRow2=int((m)*random()) #print(" random row2 is: {} ".format(rRow2)) #print(rRow2) rCol2=int((n)*random()) #print(" random col2 is: {} ".format(rCol2)) #print(rCol2) vAtCoordinate2=(grid[rRow2])[rCol2] #print(" value at {} is {} ".format((rRow2,rCol2),vAtCoordinate2)) #print(" value at {}".format(vAtCoordinate1)) #------------------------- swaping temp=vAtCoordinate1 vAtCoordinate1=vAtCoordinate2 vAtCoordinate2=temp # print(" after swaping value at {} is {} ".format((rRow2,rCol2),vAtCoordinate2)) #------------------------- updating grid ((shuffledGrid[rRow2])[rCol2])=vAtCoordinate2 ((shuffledGrid[rRow1])[rCol1])=vAtCoordinate1 return shuffledGrid sGrid=shuffle(grid=grid,nplaces=20) #print(sGrid) #------------------------------------- test whether all are same def areSame(usc): # User's Selected Cards ''' if first matchs all other then all are same ''' first=usc[0] loops=len(usc) same=True for remaining in range(1,loops): if first != usc[remaining]: same=False if same == True: return True else: return False # print(areSame((1,1,1,1))) #---------------------------------- def contains(boxArray,elements): ''' boxArray: array from which you are comparing elements: array that you are comparing note: order matters ''' # for exceptions only loops=int(len(boxArray)/2) found=False for first in range(loops): block=[] row=2*first for others in range(2): block.append(boxArray[row+others]) #print(block) if block==elements: found=True if found==True: return True else: return False #print(contains(boxArray=[1,2,1,3,3,7],elements=[1,3])) #print(contains(boxArray=[1,2,1,3,3,7],elements=[3,2])) #---------------------------------- def cardsAtPos(grid,pos): ''' pos=(row1,col1,row2,col2....) starting index from 1 each consective pair is position of a card grid''' # assumes first index =1 cards=[] loops=int(len(pos)/2) for i in range(loops): i=i*2 row=pos[i] card=(grid[row-1])[pos[i+1]-1] cards.append(card) return cards #print(cardsAtPos(grid,(1,1,8,8,0,5))) #-------------------------------------------- def gridDisplay(grid,faceUp=False,exception=[]): ''' Display grid either faces up are layed down except those cards at positions in except list ''' # Top border print("__________ Game for Memory Testing Designed at PakTurk School _______________\n\n") print("",end="\t\t") cloops=len(grid[0]) rloops=len(grid) for cols in range(cloops): print("{}".format(cols+1),end="\t") for rows in range(1,rloops+1): print("\n") print("",end="\t") print("{}".format(rows),end="\t") if faceUp==True: # lay cards with their faces up except a list give for columns in range(cloops): if (grid[rows-1])[columns] =="empty": print(" ",end="\t") # in case of empty #-------------------- elif contains(boxArray=exception,elements=[rows,columns+1]) ==True: # in case of exception print("#",end="\t") else: # show elements print("{}".format((grid[rows-1])[columns]),end="\t") else: # lay cards with their faces down except a list given for columns in range(cloops): # in case, a card has been removed if (grid[rows-1])[columns] =="empty": print(" ",end="\t") elif contains(boxArray=exception,elements=[rows,columns+1]) ==True: print("{}".format((grid[rows-1])[columns]),end="\t") # show card at this pos else: # mask with this sign print("#",end="\t") print("\n") # return nothing if it runs successfully return 0 #gridDisplay(grid,faceUp=False,exception=[1,1,1,2]) #gridDisplay(sGrid,show=True) #-------------------------------------------- select cards at pos #usc=input("Enter cards pos coma separated: ") #pos=eval(usc) # users selected cards #cards=cardsAtPos(sGrid,pos) #if areSame(cards): # print("congratulation! your guess is right") #print(cards) #--------------------------------------------- def removeCards(grid,pos,replace="empty"): loops=int(len(pos)/2) for i in range(loops): i=i*2 row=pos[i] (grid[row-1])[pos[i+1]-1]=replace #print(grid) #removeCards(grid,pos=[1,1,2,2]) #print(grid) #=============================== user input functions
5195cb3490ddaf3c0c95e29c02c8267d466d4c36
EricGronda/cmsc-classes
/201/Homeworks/hw6/hw6_part5.py
2,331
4.40625
4
# File: hw6_part5.py # Author: Eric Gronda # Date: 11/18/2017 # Section: 06 # E-mail: gt32930@umbc.edu # Description: # Non-Recursively generate the levels of Pascal's triangle ######################################################################## # getValidInput() verifies that an int entered is greater than zero # Input: num; an int to validate # Output: num; a validated integer def getValidInput(prompt): num = int(input(prompt)) # use boolean flag to verify number validNum = False while validNum == False: validNum = True # reprompt if the number is less than 0 if num <= 0: validNum = False print("Your number must be positive (greater than zero).") num = int(input(prompt)) return num ######################################################################## # pascal() creates each level of Pascal's # triangle, reaching the requested height # Input: levelsToMake; an int, the number of levels requested # Output: None (the levels are printed from the function) def pascal(levelsToMake): # print the first and second levels print("1") print("1 1") # make 2D List of levels levelList = [ [1 ,1] ] # until all levels are printed for level in range(1 , levelsToMake): levelList.append([1]) # until all numbers in level are created for pascNums in range(level): # create new number col = len(levelList[level]) num = levelList[level - 1][col - 1] num += levelList[level - 1][col] # append new number to the list levelList[level].append(num) # end level with 1 levelList[level].append(1) # print out level of numbers for j in range(len(levelList[level]) - 1): print(levelList[level][j] , end=" ") print(levelList[level][len(levelList[level]) - 1]) def main(): # display opening statement print("Welcome to the Pascal's triangle generator.") # get number of levels to generate prompt = ("Please enter the number of levels to generate: ") levelsToMake = getValidInput(prompt) # display Pascal's triangle pascal(levelsToMake) main()
da57b24c3d68ce895b34283b4faafacc1b2eba4d
junlyyouny/python
/voice/testSpeech.py
342
3.734375
4
# -*- coding: UTF-8 -*- # thread模块导入方式修改为 import _thread as thread # input方法中 print prompt 改为 return prompt 以返回输入的文件 import speech speech.say('语音识别已开启 ') while True: phrase = speech.input() speech.say('您说的是%s' %phrase) if phrase == "退出程序": break
730c1a5d89ae2bc4931a3e8c4bcd980592394e5f
YaqianQi/Algorithm-and-Data-Structure
/Python/Leetcode Daily Practice/Array/487. Max Consecutive Ones II.py
906
3.53125
4
""" Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at most one 0. Example 1: Input: [1,0,1,1,0] Output: 4 Explanation: Flip the first zero will get the the maximum number of consecutive 1s. After flipping, the maximum number of consecutive 1s is 4. Note: The input array will only contain 0 and 1. The length of input array is a positive integer and will not exceed 10,000 """ class Solution(object): def findMaxConsecutiveOnes(self, nums): """ :type nums: List[int] :rtype: int """ from collections import deque k = 1 queue = deque() l = 0 res = 0 for i, num in enumerate(nums): if num == 0: queue.append(i) if len(queue) > k: l = queue.popleft() + 1 res = max(res, i - l + 1) return res
adc26bdef42283aed4113688d439b10f280e6b04
aamnah/100daysOfPython
/day2.py
888
4.375
4
# 1000 Days of Python - Day 2 # Data Types print("Hello"[1]) # e print("123" + "456") # 123456 print(123 + 456) # 579 print(123_456_789) # Type checking with type() print(type("Hello")) # <class 'str'> print(type(123)) # <class 'int'> print(type(123_000_000)) # <class 'int'> print(type(13.4)) # <class 'float'> print(type(True)) # <class 'bool'> # Type casting myNumber = 123 print(type(str(myNumber))) # <class 'str'> print(type(float(myNumber))) # <class 'float'> myString = "567" print(myNumber + float(myString)) # 690.0 # Math print(3 + 5) # 8 -add print(9 - 4) # 5 - subtract print(3 * 9) # 27 - multiply print(7 / 2) # 3.5 - divide (returns a float) print(7 // 2) # 3 - floor (returns an int) print(13 % 5) # 3 - modulus (remainder after division) print(2 ** 3) # 8 - exponent print(2 ** 3 ** 2) # 512 - exponent #P-E-MD-AS (Left to Right) print( 3 + 3 - 3 / 3 * 3 ) # 3.0
f54ca390934ba5b5e249d1da48c1ed96c9e0f97b
JoalisonMatheuss/ExercicioFILA
/Questao 2.py
354
3.59375
4
class queue: def __init__(self): self.itens = [] def enqueue(self, valor): self.itens.append(valor) def dequeue(self): if (not(self.isEmpty())): self.itens.pop(0) def lenght(self): return len(self.itens) def isEmpty(self): return len(self.itens) == 0
1362061200c10057ae96ebedfaa07ede1a3f966d
MattSegal/poker-bot
/logReg.py
3,014
3.765625
4
import numpy as np import matplotlib.pyplot as plt # =============================================================================== # def logisticRegression(X,y,plotResults=False): """ X is expected to come with Xo already added ie X of dim (m,n+1) """ numFeat = X.shape[1] # including bias # use gradient descent to find theta initialTheta = np.zeros(numFeat) alpha = 1 lam = 1 numIters = 100 theta = gradientDescent(X, y, initialTheta, alpha, lam, numIters, plotResults) return theta # =============================================================================== # def gradientDescent(X, y, theta, alpha, lam, numIters, plotResults = False): """ m is number of training examples n is number of features """ # Initialize some useful values [m,n] = X.shape J_history = np.zeros(numIters) dJ = np.zeros(n) for itr in range(numIters): (J,dJ) = costFunction(theta,X,y,lam) theta = theta - alpha * dJ; J_history[itr] = J if plotResults: plt.plot(J_history) plt.ylabel('Cost Function') plt.xlabel('Number of Iterations') plt.show() return theta # =============================================================================== # def costFunction(theta,X,y,lam): m = len(y) # number of training examples mf = float(m) n = theta.size # number of parameters # output variables J = 0 grad = np.zeros(n); # compute gradient of cost function z = np.dot(X,theta) hx = sigmoid(z) for j in range(n): grad[j] = ((1/mf)*(hx - y)*X[:,j] ).sum() if j > 0: grad[j] += lam*theta[j]/mf # compute cost of theta pos = - y*np.log(hx) neg = - (1-y)*np.log(1-hx) J = ( (1/mf)*(pos + neg) ).sum() + (lam/2/mf)*(theta[1:]*theta[1:]).sum() return J , grad # =============================================================================== # def sigmoid(z): return 1.0/(1.0+np.exp(-z)) # =============================================================================== # def featureNormalize(X): """ X is of dimensions (m,n) with m examples and n features normalizes X and returns mu and sigma for each feature returns X, mu, sigma with n+1 rows, with first row being bias """ [m,n] = X.shape X_norm = np.zeros((m,n+1)) mu = np.zeros(n+1) sigma = np.zeros(n+1) X_norm[:,1:] = X.copy() # X1 to Xn X_norm[:,0] = 1 # Xo = 1 for all examples mu[0] = 0 # mu0 = 0 sigma[0] = 1 # sigma0 = 0 for feat in range(1,n+1): mu[feat] = np.mean(X[:,feat-1]) sigma[feat] = np.std(X[:,feat-1]) for i in range(m): X_norm[i,feat] = (X[i,feat-1] - mu[feat]) / sigma[feat] return X_norm, mu, sigma # =============================================================================== #
89c4d518077c648cfb6b589e08f5b973320c315d
aash-beg/PythonTraining
/01_ListExamples/07. Remove Words.py
213
3.921875
4
text_1 = 'Python is a programming language' text_1 = text_1.split() print(text_1) stopwords = ['is', 'a'] text_2 = [] for items in text_1: if items not in stopwords: text_2.append(items) print(text_2)
be9bc7a996ed633a36419a3ff9f85839a5ea0a96
vslve/python
/algo_and_ds/factorize_number.py
318
4.21875
4
def factorize_number(number): """Раскладывает число на множители""" divisor = 2 while (number > 1): if (number % divisor == 0): print(divisor, end=" ") number /= divisor else: divisor += 1 factorize_number(int(input()))
cd144c6866d5e67920901f8ba0b45b4663b45268
yamgent/cs5250-assignment4
/simulator.py
16,991
3.734375
4
import sys NO_JOB = -1 class Process: ''' A process, as represented in a particular line inside the input text file. ''' def __init__(self, id, arrival_time, burst_time): assert arrival_time >= 0 assert burst_time >= 0 self.id = id self.arrival_time = arrival_time self.burst_time = burst_time def __repr__(self): ''' For printing purposes. ''' return '[id %d: arrival_time %d, burst_time %d]' % (self.id, self.arrival_time, self.burst_time) def spawn_job(self, current_time): ''' Create a new job associated with this process. ''' assert current_time >= self.arrival_time return Job(self.id, self.arrival_time, self.burst_time, current_time - self.arrival_time, self.burst_time) class Job: ''' Describes a job scheduled for the CPU. ''' def __init__(self, id, arrival_time, remaining_time, waiting_time, burst_time): assert arrival_time >= 0 assert remaining_time >= 0 assert waiting_time >= 0 assert burst_time >= 0 self.id = id self.arrival_time = arrival_time self.remaining_time = remaining_time self.waiting_time = waiting_time self.burst_time = burst_time def add_waiting_time(self, waiting_duration): ''' Called when this job is NOT the current active one, add the waiting time by the waiting duration. ''' assert waiting_duration >= 0 self.waiting_time += waiting_duration def substract_remaining_time(self, processing_duration): ''' Called when this job is the current active one, substract the remaining time by the processing duration. ''' assert processing_duration >= 0 self.remaining_time -= min(processing_duration, self.remaining_time) def is_done(self): ''' Is the job completed? ''' return self.remaining_time <= 0 class JobReceiver: ''' When probed, returns the new list of jobs that have arrived at the particular current time. Note: process_list must be in order of arrival time! ''' def __init__(self, process_list): assert process_list is not None self.process_list = process_list self.next_new_job_index = 0 def all_jobs_received(self): ''' Are there no more jobs in the queue? ''' return self.next_new_job_index >= len(self.process_list) def peek_next_process(self): ''' Peek at the next process in the queue (Note: it may not have arrived yet! Need to check arrival_time <= current_time). ''' if self.all_jobs_received(): return None return self.process_list[self.next_new_job_index] def receive_new_jobs(self, current_time): ''' Returns the list of new jobs at the current time. Note: There could be multiple jobs 'arriving' if the current_time value skips (i.e. receive_new_jobs() is not religiously called at current_time = 0, 1, 2, 3, ..., instead the number is in increasing order but not called in fixed intervals, such as 1, 5, 11, ...). ''' result = [] if self.all_jobs_received(): # no more jobs return result while (not self.all_jobs_received()) and self.peek_next_process().arrival_time <= current_time: # a new job has arrived result.append(self.peek_next_process().spawn_job(current_time)) self.next_new_job_index += 1 return result class Cpu: ''' Maintains the state of a simulated CPU. ''' def __init__(self, process_list): self.current_time = 0 self.remaining_jobs = [] self.completed_jobs = [] self.current_running_job_index = NO_JOB self.job_receiver = JobReceiver(process_list) self.schedule = [] self.job_completed_event_callback = None def set_job_completed_event_callback(self, callback): ''' Set the callback function that we should call when a job is completed. This callback should accept a parameter for a job object. ''' self.job_completed_event_callback = callback def get_current_running_job(self): ''' Get the current job. ''' if self.current_running_job_index == NO_JOB: return None return self.remaining_jobs[self.current_running_job_index] def switch_to_job_with_index(self, new_job): ''' Switch to the new job (given its index). ''' # don't bother switching if it is the same job if self.current_running_job_index == new_job: return self.current_running_job_index = new_job if self.current_running_job_index != NO_JOB: self.schedule.append((self.current_time, self.get_current_running_job().id)) def switch_to_job_with_object(self, new_job_object): ''' Switch to the new job (given the particular object representation of the job). ''' assert new_job_object in self.remaining_jobs # find the corresponding job index for the given new_job_object for i in range(0, len(self.remaining_jobs)): if self.remaining_jobs[i] == new_job_object: self.switch_to_job_with_index(i) return assert False # cannot find the object's index, something gone VERY wrong def wait_until_new_job_arrives(self): ''' Called when there's no job in the CPU, wait until the new job arrives from JobReceiver. ''' assert len(self.remaining_jobs) == 0 assert not self.job_receiver.all_jobs_received() next_arrival_time = self.job_receiver.peek_next_process().arrival_time self.move_current_time_to(next_arrival_time) def increment_current_time(self, duration): ''' Increment current time by given amount. ''' self.move_current_time_to(self.current_time + duration) def move_current_time_to(self, new_time): ''' Move the current time forward to new_time. What happens when time is moved forward? 1. update all waiting job's waiting time 2. update the current running job's remaining time 3. put the current running job to the completed queue if it is done 4. receive new jobs (if any) 5. update current_time to be the new_time ''' assert self.current_time <= new_time delta = new_time - self.current_time current_running_job = self.get_current_running_job() # 1. update all waiting job's waiting time for job in self.remaining_jobs: if job == current_running_job: continue job.add_waiting_time(delta) # 2. update the current running job's remaining time if current_running_job is not None: current_running_job.substract_remaining_time(delta) # 3. put the current running job to the completed queue if it is done if current_running_job.is_done(): self.remaining_jobs.remove(current_running_job) self.completed_jobs.append(current_running_job) if self.job_completed_event_callback is not None: self.job_completed_event_callback(current_running_job) self.switch_to_job_with_index(NO_JOB) current_running_job = None # 4. receive new jobs (if any) new_jobs = self.job_receiver.receive_new_jobs(new_time) for j in new_jobs: self.remaining_jobs.append(j) # 5. update current_time to be the new_time self.current_time = new_time def is_completely_done(self): ''' Are we completely done with everything, such that all job_receiver's jobs are all processed? ''' return self.job_receiver.all_jobs_received() and len(self.remaining_jobs) <= 0 def get_average_waiting_time_for_completed_jobs(self): ''' Get the average waiting time for all completed jobs. ''' return float(sum([j.waiting_time for j in self.completed_jobs])) / float(len(self.completed_jobs)) def has_remaining_jobs(self): ''' Does this CPU still have remaining jobs to run? ''' return len(self.remaining_jobs) > 0 def FCFS_scheduling(process_list): ''' Scheduling process_list on first come first serve basis. ''' cpu = Cpu(process_list) while not cpu.is_completely_done(): if not cpu.has_remaining_jobs(): cpu.wait_until_new_job_arrives() # always run the first job in the queue to completion (first come, first serve) cpu.switch_to_job_with_index(0) cpu.increment_current_time(cpu.get_current_running_job().remaining_time) return cpu.schedule, cpu.get_average_waiting_time_for_completed_jobs() # input: process_list, time_quantum (Positive Integer) # output_1: Schedule list contains pairs of (time_stamp, proccess_id) indicating the time switching to that proccess_id # output_2: Average Waiting Time def RR_scheduling(process_list, time_quantum): ''' Scheduling process_list on round robin policy with time_quantum. ''' cpu = Cpu(process_list) while not cpu.is_completely_done(): if cpu.get_current_running_job() is None: # cpu is idling, give it some job to do! if not cpu.has_remaining_jobs(): cpu.wait_until_new_job_arrives() cpu.switch_to_job_with_index(0) else: # run the current job within the quantum given (can be earlier if job can finish before the quantum) current_job_index = cpu.current_running_job_index time_spent_for_current_job = min(time_quantum, cpu.get_current_running_job().remaining_time) job_will_finish = (time_spent_for_current_job == cpu.get_current_running_job().remaining_time) cpu.increment_current_time(time_spent_for_current_job) # if there's still other jobs, switch to the next job if cpu.has_remaining_jobs(): next_job_index = (current_job_index + 1) % len(cpu.remaining_jobs) if job_will_finish: # finished job is removed on the spot, so the next job is the same spot next_job_index = (current_job_index) % len(cpu.remaining_jobs) cpu.switch_to_job_with_index(next_job_index) return cpu.schedule, cpu.get_average_waiting_time_for_completed_jobs() def SRTF_scheduling(process_list): ''' Scheduling process_list on SRTF, using process.burst_time to calculate the remaining time of the current process. ''' cpu = Cpu(process_list) while not cpu.is_completely_done(): if not cpu.has_remaining_jobs(): cpu.wait_until_new_job_arrives() cpu.switch_to_job_with_index(0) # find the smallest remaining time job and switch to it smallest_remaining_time_job = cpu.remaining_jobs[0] for j in cpu.remaining_jobs: if j.remaining_time < smallest_remaining_time_job.remaining_time: smallest_remaining_time_job = j cpu.switch_to_job_with_object(smallest_remaining_time_job) # determine how long needed to run it time_spent = smallest_remaining_time_job.remaining_time # if no new job arrives before job completion, then just run to job to completion. # Otherwise, we must only run till the next job arrives, in case the next job # preempts our current job (i.e. changes the candidate for the shortest remaining # time left) next_job_in_queue = cpu.job_receiver.peek_next_process() if next_job_in_queue is not None: duration_before_next_job_arrives = next_job_in_queue.arrival_time - cpu.current_time time_spent = min(time_spent, duration_before_next_job_arrives) # now actually run it cpu.increment_current_time(time_spent) return cpu.schedule, cpu.get_average_waiting_time_for_completed_jobs() def SJF_scheduling(process_list, alpha): ''' Scheduling SJF without using information from process.burst_time. ''' cpu = Cpu(process_list) # set up prediction table prediction = { } all_process_ids = [p.id for p in process_list] for i in all_process_ids: prediction[i] = 5 # hook up a prediction update function def update_prediction(completed_job): prediction[completed_job.id] = (alpha * completed_job.burst_time) + ((1 - alpha) * prediction[completed_job.id]) cpu.set_job_completed_event_callback(update_prediction) while not cpu.is_completely_done(): if not cpu.has_remaining_jobs(): cpu.wait_until_new_job_arrives() cpu.switch_to_job_with_index(0) # find the best job to run based on predictions best_job_to_run = cpu.remaining_jobs[0] for j in cpu.remaining_jobs: if prediction[j.id] < prediction[best_job_to_run.id]: best_job_to_run = j cpu.switch_to_job_with_object(best_job_to_run) # no preemption so just run to completion cpu.increment_current_time(best_job_to_run.remaining_time) return cpu.schedule, cpu.get_average_waiting_time_for_completed_jobs() def read_input(input_txt_path): ''' Read each process listed in the input.txt and returns a list of corresponding Process. ''' result = [] with open(input_txt_path, 'r') as f: for line in f: line_vals = [int(x) for x in line.split()] if len(line_vals) != 3: print('Invalid format! Expected 3 numbers in a line.') exit() result.append(Process(line_vals[0], line_vals[1], line_vals[2])) return result def write_output(output_txt_path, schedule, avg_waiting_time): ''' Write the results of a particular simulation. ''' with open(output_txt_path, 'w') as f: for item in schedule: f.write(str(item) + '\n') f.write('Average waiting time %.2f \n'%(avg_waiting_time)) def run_simulators(folder_path): ''' Read the list of processes and run each simulation. ''' input_txt_path = folder_path + '/input.txt' process_list = read_input(input_txt_path) print('printing input ----') for process in process_list: print(process) # note: each scheduler reloads the process_list, in case it is contaminated # by the previous scheduling algorithm's execution. print('simulating FCFS ----') process_list = read_input(input_txt_path) FCFS_schedule, FCFS_avg_waiting_time = FCFS_scheduling(process_list) write_output(folder_path + '/FCFS.txt', FCFS_schedule, FCFS_avg_waiting_time) print('simulating RR ----') process_list = read_input(input_txt_path) RR_schedule, RR_avg_waiting_time = RR_scheduling(process_list, time_quantum = 2) write_output(folder_path + '/RR.txt', RR_schedule, RR_avg_waiting_time) print('simulating SRTF ----') process_list = read_input(input_txt_path) SRTF_schedule, SRTF_avg_waiting_time = SRTF_scheduling(process_list) write_output(folder_path + '/SRTF.txt', SRTF_schedule, SRTF_avg_waiting_time) print ('simulating SJF ----') process_list = read_input(input_txt_path) SJF_schedule, SJF_avg_waiting_time = SJF_scheduling(process_list, alpha = 0.5) write_output(folder_path + '/SJF.txt', SJF_schedule, SJF_avg_waiting_time) # for task 2, to experiment with time_quantum and alpha # try all time quantum for q in range(1, 21): process_list = read_input(input_txt_path) q_schedule, q_avg_waiting_time = RR_scheduling(process_list, time_quantum = q) write_output(folder_path + ('/extra_RR_%02d.txt'%(q)), q_schedule, q_avg_waiting_time) # try all possible alpha for a in [x * 0.05 for x in range(0, 21)]: process_list = read_input(input_txt_path) a_schedule, a_avg_waiting_time = SJF_scheduling(process_list, alpha = a) write_output(folder_path + ('/extra_SJF_%.2f.txt'%(a)), a_schedule, a_avg_waiting_time) def main(argv): ''' Main entry point of the application. ''' process_name = argv[0] if len(argv) < 2: print('Please pass in the path of the folder containing input.txt.') print('Usage: python %s [path_to_folder]' % (process_name)) exit() folder_path = argv[1] run_simulators(folder_path) if __name__ == '__main__': main(sys.argv)
b3ab8b00135a652a46b05d51e423d9984db204de
lamborghini1993/LeetCode
/面试题/04.09-bst-sequences-lcci.py
1,470
3.53125
4
# -*- coding:utf-8 -*- ''' @Author: lamborghini1993 @Date: 2020-06-01 09:54:51 @Description: https://leetcode-cn.com/problems/bst-sequences-lcci/ ''' import copy from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def BSTSequences(self, root: TreeNode) -> List[List[int]]: if not root: return [[]] result = [] def dfs(cur: TreeNode, queue: List[int], path: List[int]): if cur.left: queue.append(cur.left) if cur.right: queue.append(cur.right) if not queue: result.append(path) return for i, nex in enumerate(queue): newq = queue[:i] + queue[i + 1:] dfs(nex, newq, path + [nex.val]) dfs(root, [], [root.val]) return result def build(lst: List[int]): root = TreeNode(lst[0]) N = len(lst) def dfs(node: TreeNode, i: int): if not node: return l = (i << 1) + 1 r = l + 1 if l < N: left = TreeNode(lst[l]) node.left = left dfs(left, l) if r < N: right = TreeNode(lst[r]) node.right = right dfs(right, r) dfs(root, 0) return root func = Solution().BSTSequences head = build([1, 2, 3, 4, 5, 6, 7]) print(func(head))
e48ed96f0838d67656402b553bfb32753ce8180b
Matheuspaixaocrisostenes/Python
/ex043.py
411
3.71875
4
peso = float(input('qual seu peso em (kg) ')) alt = float(input('qual sua altura em (M) ')) imc = peso / (alt ** 2) print('seu imc é de {:.1f}' .format(imc )) if imc < 18.5: print('abaixo do peso') elif imc >= 18.5 and imc < 25: print('peso ideal') elif imc >= 25 and imc < 30: print(' SOBREPESO') elif imc >= 30 and imc < 40: print('OBESSIDADE') elif imc >= 40: print('OBESSIDADE MORBIDA')
3ee13ce7b009191f168e0b2ba6937de002cac771
tooyoungtoosimplesometimesnaive/probable-octo-potato
/79_word_search.py
2,223
3.640625
4
# This got TLE class Solution: def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ self.row = len(board) self.col = len(board[0]) visited = [[False for _ in range(self.col)] for _ in range(self.row)] for i in range(self.row): for j in range(self.col): if self.find(board, visited, word, i, j, 0): return True return False def find(self, board, visited, word, i, j, current_index): if current_index == len(word): return True if i >= self.row or i<0 or j>=self.col or j<0 or visited[i][j] or board[i][j] != word[current_index]: return False visited[i][j] = True a = self.find(board, visited, word, i + 1, j, current_index + 1) b = self.find(board, visited, word, i - 1, j, current_index + 1) c = self.find(board, visited, word, i, j + 1, current_index + 1) d = self.find(board, visited, word, i, j - 1, current_index + 1) visited[i][j] = False return a or b or c or d # This is OK: class Solution: def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ self.row = len(board) self.col = len(board[0]) # visited = [[False for _ in range(self.col)] for _ in range(self.row)] for i in range(self.row): for j in range(self.col): if self.find(board, word, i, j, 0): return True return False def find(self, board, word, i, j, current_index): if current_index == len(word): return True if i >= self.row or i<0 or j>=self.col or j<0 or board[i][j] != word[current_index]: return False tmp = board[i][j] board[i][j] = '#' a = self.find(board, word, i + 1, j, current_index + 1) or self.find(board, word, i - 1, j, current_index + 1) \ or self.find(board, word, i, j + 1, current_index + 1) or self.find(board, word, i, j - 1, current_index + 1) board[i][j] = tmp return a
730add352a0929a4d439b4c7e1f2aad9830a716f
papalagichen/leet-code
/0338 - Counting Bits.py
917
3.625
4
from typing import List """ 0 => 0 0 1 => 1 1 2 => 10 1 3 => 11 2 4 => 100 1 5 => 101 2 6 => 110 2 7 => 111 3 8 => 1000 1 9 => 1001 2 10 => 1010 2 11 => 1011 3 12 => 1100 2 denominator [0, 1, 2, 4, 4, 8, 8, 8, 8] result [0, 1, 1, 2, 1, 2, 2, 3, 1] """ # Dynamic Programming. Time: O(n). Space: O(n) class Solution: def countBits(self, n: int) -> List[int]: results = [0] denominator = 1 for i in range(1, n + 1): if i % denominator == 0: results.append(1) denominator *= 2 else: results.append(1 + results[i % (denominator // 2)]) return results if __name__ == '__main__': import Test Test.test(Solution().countBits, [ (0, [0]), (1, [0, 1]), (2, [0, 1, 1]), (5, [0, 1, 1, 2, 1, 2]), (8, [0, 1, 1, 2, 1, 2, 2, 3, 1]), ])
9dbb54097634f031e78b99cf7c835dd7f000162c
zxwtry/OJ
/python/leetcode/P069_Sqrt_x.py
1,168
3.890625
4
#coding=utf-8 ''' url: leetcode.com/problems/sqrtx/ @author: zxwtry @email: zxwtry@qq.com @date: 2017年4月15日 @details: Solution: 56ms 55.71% @details: Solution: 59ms 45.65% ''' from math import sqrt class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ return int(sqrt(x)) class Solution2(object): def mySqrt(self, x): """ :type x: int :rtype: int """ n, xx = 0, x while xx != 0: xx, n = xx // 2, n+1 if n < 2: return x sqrt_max = 1 << (n // 2 + 1) sqrt_min = 1 << (n // 2 - 1) # print("%d %d" %(sqrt_max, sqrt_min)) sqrt_mid = 0 while sqrt_min < sqrt_max: sqrt_mid = (sqrt_max + sqrt_min+1) // 2 val = sqrt_mid * sqrt_mid if val < x: sqrt_min = sqrt_mid elif val == x: return sqrt_mid else: sqrt_max = sqrt_mid - 1 return sqrt_min if __name__ == "__main__": print(Solution2().mySqrt(1))
5b5f5ba6546938bc08530c523c525ff14a6c3011
emilioanh/python_study
/FullyDivided.py
862
4.375
4
""" Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2? Extras: If the number is a multiple of 4, print out a different message. Ask the user for two numbers: one number to check (call it num) and one number to divide by (check). If check divides evenly into num, tell that to the user. If not, print a different appropriate message. """ while True: try: check = int(input('Enter a number:')) num = int(input('enter the number you want to divide to:')) break except ValueError as e: print("Oops! That was no valid number. Try again...") if check%num==0: print(f'{check} is fully divided to {num}') else: print(f'{check} is not a multiple of {num}')
871c2811642608845f95e2311c3fc1fe913d273f
lenlehm/Classification-and-Regression
/Activation.py
3,456
3.5625
4
import numpy as np import sys class Activation : ''' class to make a modular approach for the activation functions along with their derivatives Implemented Activation Functions: - Softmax - ReLU - Leaky ReLU - ELU - Sigmoid - tanh - Identity ''' def __init__(self, function=None, alpha=None): self.derivative = None self.function = function if (function is not None) else 'sigmoid' self.alpha = alpha if (alpha is not None) else 0.01 self.name = 'sigmoid' self.function = self._parseFunctionString(self.function) def set(self, function=None, alpha=None): ''' constructor method to create the member variables and init them properly ''' self.alpha = alpha if (alpha is not None) else self.alpha if function is not None : self.function = function self.name = function self.function = self._parseFunctionString(self.function) def _parseFunctionString(self, string) : ''' check which activation function to use and call the mathematical function ''' self.name = string if string == 'sigmoid' : self.derivative = self._sigmoid_derivative return self._sigmoid elif string == 'tanh' : self.derivative = self._tanh_derivative return self._tanh elif string == 'relu' : self.derivative = self._relu_derivative return self._relu elif string == 'leakyrelu' or string == 'leaky_relu' : self.derivative = self._leakyrelu_derivative return self._leakyrelu elif string == 'identity' : self.derivative = self._identity_derivative return self._identity elif string == 'elu' : self.derivative = self._elu_derivative return self._elu elif string == 'softmax' : self.derivative = self._softmax_derivative return self._softmax else : raise ValueError("Unrecognized activation function <" + str(string) + ">.") ## --------------------- DOWN THERE IS THE MATHEMATICAL TURD OF EACH OF THE FUNCTIONS ---------------- def _sigmoid(self, x) : return 1.0 / (1.0 + np.exp(-x)) def _sigmoid_derivative(self, x) : return x * (1.0 - x) def _tanh(self, x) : return np.tanh(x) def _tanh_derivative(self, x) : return 1.0 - x**2 def _relu(self, x) : return np.maximum(0, x) def _relu_derivative(self, x) : return np.maximum(x, 0.0) def _leakyrelu(self, x) : return (x >= 0.0) * x + (x < 0.0) * (self.alpha * x) def _leakyrelu_derivative(self, x) : dx = np.ones_like(x) dx[x < 0] = 0.01 return dx def _identity(self, x) : return x def _identity_derivative(self, x) : return 1.0 def _elu(self, x) : neg = x < 0.0 x[neg] = (np.exp(x[neg]) - 1.0) return x def _elu_derivative(self, x) : neg = x < 0.0 x[neg] = np.exp(x[neg]) x[x >= 0.0] = 1.0 def _softmax(self, x) : exps = np.exp(x - np.max(x)) return exps / np.sum(exps, axis=0, keepdims=True) def _softmax_derivative(self, x) : return x def __call__(self, x) : return self.function(x)
c9ff9ec189048e06980c7ee0d47e6c52bec7c563
IonesioJunior/URI
/Beginner/1060.py
134
3.75
4
#coding: utf-8 count = 0 for i in range(6): if(float(raw_input()) >= 0): count = count + 1 print "%d valores positivos" % count
118bc90b9de477fb71bb628bd095c77abee17064
NathanF2001/Parte-2-CRUD-UFRPE
/Disciplina.py
2,148
3.53125
4
import sqlite3 from tkinter import * class Disciplina(object): def __init__(self,nome= '',codigo = ''): self.nome = nome self.codigo = codigo def add_nova_disciplina(self): self.conexão = sqlite3.connect("data/Disciplina.db") self.cursor = self.conexão.cursor() self.cursor.execute('''insert into Disciplina (nome,codigo) values(?,?)''',(self.nome,self.codigo)) self.conexão.commit() self.cursor.close() self.conexão.close() def read_disciplina(self): self.conexão = sqlite3.connect("data/Disciplina.db") self.cursor = self.conexão.cursor() self.cursor.execute("select * from Disciplina order by nome") dados = self.cursor.fetchall() self.cursor.close() self.conexão.close() return dados def update_disciplina(self,id_): self.conexão = sqlite3.connect("data/Disciplina.db") self.cursor = self.conexão.cursor() if self.nome != '': self.cursor.execute("""update Disciplina set nome = ? where id = ?""",(self.nome,id_)) if self.codigo != '': self.cursor.execute("""update Disciplina set codigo = ? where id = ?""",(self.codigo,id_)) self.conexão.commit() self.cursor.close() self.conexão.close() def delete_disciplina(self,id_): self.conexão = sqlite3.connect("data/Disciplina.db") self.cursor = self.conexão.cursor() self.cursor.execute("""delete from Disciplina where id = ?""",(id_,)) self.conexão.commit() self.cursor.close() self.conexão.close() def pesquisa_disciplina(self,dado): self.conexão = sqlite3.connect("data/Disciplina.db") self.cursor = self.conexão.cursor() self.cursor.execute("select codigo from Disciplina") dados = self.cursor.fetchall() self.cursor.close() self.conexão.close() dado = (dado,) if dado in dados : return True else: return False
22edc6306fd5dc14c8dc5a6bc79dde6f52c12bf2
sunjiebin/s12
/s12week29/代理模式.py
1,480
3.578125
4
#!/usr/bin/env python3 # Auther: sunjb # # 代理模式 # 应用特性:需要在通信双方中间需要一些特殊的中间操作时引用,多加一个中间控制层。 # 结构特性:建立一个中间类,创建一个对象,接收一个对象,然后把两者联通起来 ''' agent_class就是一个代理,我们要在原来的类send_class前面加点操作,而又不想改变send_class代码,那么就可以 这么写,比如我们在agent_class里面做了一个print操作,然后再执行send_class。 ''' class sender_base: def __init__(self): pass def send_something(self, something): pass class send_class(sender_base): def __init__(self, receiver): self.receiver = receiver def send_something(self, something): print("SEND " + something + ' TO ' + self.receiver.name) class agent_class(sender_base): def __init__(self, receiver): '''先将send_class实例化''' self.send_obj = send_class(receiver) def send_something(self, something): '''增加一个print操作,然后执行send_class实例''' print('agent_send_something') self.send_obj.send_something(something) class receive_class: def __init__(self, someone): self.name = someone if '__main__' == __name__: receiver = receive_class('Alex') agent = agent_class(receiver) agent.send_something('agentinfo') print(receiver.__class__) print(agent.__class__)
4dcf6fffa8ad3227a01a45cd16afb291f46d79ac
deep110/aoc-solutions
/2019/day01/solution.py
611
3.578125
4
from os import path with open(path.join(path.dirname(__file__), "input.txt")) as f: ms = f.readlines() ms = list(map(lambda x: int(x.strip()), ms)) def part1(): fuels_req = list(map(lambda x: int(x/3) - 2, ms)) return sum(fuels_req) def part2(): def calc_total_fr(mass: int): t = 0 while mass > 3: fr = int(mass/3) - 2 if fr > 0: t += fr mass = fr return t fuels_req = list(map(lambda x: calc_total_fr(x), ms)) return sum(fuels_req) print("Part1 solution: ", part1()) print("Part2 solution: ", part2())
f9248f41695d940201db252469abaf191af1b9fa
jjcrab/code-every-day
/day72_pythonpractices.py
785
4.0625
4
# print("hello " + "world") # print("hello " "world") # print("hello ""world") # print("hello, world", end=" ") # print(bool(None)) li = [1, 2, 4, 3] # li.remove(2) del li[1:3] # print(li) if 2 in li: # print(li) print(li.index(2)) # print(li.index(1)) # print(li.index(2)) # print("yay!" if 0 > 1 else "nay!") filled_dict = {"one": 1, "two": 2, "three": 3} # print(filled_dict.get("four")) # print(filled_dict["four"]) # our_iterable = filled_dict.keys() l = list(filled_dict.keys()) l = filled_dict.keys() # print(our_iterable) print(l) name = "Reiko" # print(f"She said her name is {name}.") # for animal in ["dog", "cat", "mouse"]: # You can use format() to interpolate formatted strings # print("{} is a mammal".format(animal)) # print(f"{animal} is a mammal.")
3971946734531c6de3333fccb98aaf2858cece4b
SatoshiJIshida/projects
/Python - Coding Challenges/arraychange.py
988
3.6875
4
""" You are given an array of integers. On each move you are allowed to increase exactly one of its element by one. Find the minimal number of moves required to obtain a strictly increasing sequence from the input. Example: For inputArray = [1, 1, 1], the output should be solution(inputArray) = 3. [execution time limit] 4 seconds (py3) [input] array.integer inputArray [output] integer The minimal number of moves needed to obtain a strictly increasing sequence from inputArray. It's guaranteed that for the given test cases the answer always fits signed 32-bit integer type. Tests passed: 20/20. """ def solution(inputArray): count = 0 for i, el in enumerate(inputArray): if i < len(inputArray)-1: prev = inputArray[i] cur = inputArray[i+1] if prev >= cur: temp = prev-cur+1 inputArray[i+1] += temp count += temp return count
8d56314fe4f7a7a9dd4804a3c5f6cd4641e363fe
ILiterallyCannot/script-programming
/script-programming/task28.py
1,633
3.96875
4
import sys def switch_case(arguement): switcher = { 0: "add", 1: "subtract", 2: "multiply", 3: "divide", 4: "quit" } print switcher.get(arguement, "Invalid request") def add(num1,num2): result=num1+float(num2) print "the total is %s" % result def subtract(num1,num2): result=num1-float(num2) print "the total is %s" % result def multiply(num1,num2): result= num1*float(num2) print "the total is %s" % result def divide(num1,num2): try: result = num1/float(num2) print "the total is %s" % result except ZeroDivisionError: print "You gonna break this computer if you try to divide by zero!" print "Try anyway? " txt = raw_input("y/n ") if txt == "y": while True: sys.stdout.write("9") sys.stdout.flush() else: sys.exit() def main(): while True: print "0) add\n1) sub\n2) multiply\n3) divide\n4) quit" print "Enter your choice" choice = int(raw_input("Choose an option: ")) num1 = int(raw_input("Enter number 1: ")) num2 = int(raw_input("Enter number 2: ")) if choice == 0: add(int(num1), int(num2)) elif choice ==1: subtract(int(num1), int(num2)) elif choice ==2: multiply(int(num1), int(num2)) elif choice ==3: divide(int(num1), int(num2)) elif choice==4: sys.exit() else: "Invalid option" main()
c67e87f95e08701d6f87fcf45933c082c122c82f
leozz37/url-scrapper
/scrapper/url_scrapper.py
2,079
3.6875
4
#!/usr/bin/env python3 # # This is a tool for getting image URLs from the internet # import errno import re import os import sys from urllib.request import urlopen from bs4 import BeautifulSoup, ResultSet class Scrapper: def create_url(self, keyword: str) -> str: """ Remove the spaces on the keyword and returns a Wikipedia URL :param: keyword: Keyword to be searched :return: Wikipedia URL with Keyword formatted :type: str """ formatted_keyword = keyword.replace(" ", "_") return "https://en.wikipedia.org/wiki/" + formatted_keyword def get_urls(self, search_url: str) -> ResultSet: """ Scrap the Wikipedia page and get the images URL :param: search_url: Wikipedia URL :return: set of images URL :type: ResultSet (bs) """ html = urlopen(search_url) bs = BeautifulSoup(html, 'html.parser') images_url = bs.find_all('img', {'src': re.compile('.jpg')}) return images_url def save_urls_to_file(self, images_url: ResultSet) -> bool: """ Save the images URL to a txt file :param: Set of images URL :return: True if succeed :type: bool """ # Creating directory and file if doesn't exists file_path = "../data/images_urls.txt" if not os.path.exists(os.path.dirname(file_path)): try: os.makedirs(os.path.dirname(file_path)) except OSError as exc: if exc.errno != errno.EEXIST: raise # Saving content to txt file with open(file_path, "w") as f: for image in images_url: f.write("https:" + image['src'] + '\r\n') return True if __name__ == '__main__': """ Main program entrypoint """ keyword = sys.argv[1] scrapper = Scrapper() url = scrapper.create_url(keyword) images_url = scrapper.get_urls(url) scrapper.save_urls_to_file(images_url) print(f'{len(images_url)} images found!')
70f13b7d3345760b8ec363e61617a942a541172c
jirujun/python_learn
/Week2/paydemo.py
1,186
3.71875
4
class pay(): def __init__(self,amount,discount): self.amount = amount self.discount = discount def total(self): print( '折扣为:'+ str(self.discount) + ' 折扣后金额为:' + str(self.amount * self.discount)) class vip(pay): def __init__(self,quantity,amount): self.quantity = quantity self.amount = amount self.discount = 1 if self.quantity >= 10 : self.discount = 0.85 if self.amount >= 200 : self.discount = 0.8 class novip(pay): def __init__(self,amount): self.amount = amount self.discount = 1 if self.amount >=200 : self.discount = 0.9 class Factory: def getpay(self,quantity,amount,isvip ): if isvip == 1 : return vip(quantity,amount) else: return novip(amount) if __name__ == '__main__': factory = Factory() isvip = int(input('请输入是否为VIP,1为是,0为否:')) quantity = int(input('请输入所购数量:')) amount = float(input('请输入所购总金额:')) paymoney = factory.getpay(quantity,amount,isvip) paymoney.total()
fdc405a83f1429f692b221a77c4a7a37b1c09571
gscriva/dlai-project
/score.py
713
4.03125
4
from typing import Callable, Optional def make_averager() -> Callable[[Optional[float]], float]: """ Returns a function that maintains a running average :returns: running average function """ count = 0 total = 0 def averager(new_value: Optional[float]) -> float: """ Running averager :param new_value: number to add to the running average, if None returns the current average :returns: the current average """ nonlocal count, total if new_value is None: return total / count if count else float("nan") count += 1 total += new_value return total / count return averager
75eee38576c134fd081d1a2f049124f6d6753195
cirosantilli/python-cheat
/string_cheat.py
12,197
3.8125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ## string ## str' There are 2 commonly used classes which are informaly called *strings* in python: *str* and *unicode* *basestring* is their common ancestor. """ import sys assert isinstance(str(), basestring) assert isinstance(unicode(), basestring) assert not isinstance(bytearray(), basestring) if '## string literals': if '## Single vs double quotes': # There is no semantic difference: assert 'abc' == 'abc' # Except for escaping quotes themselves: assert "'" == '\'' assert '"' == "\"" assert "\n" == '\n' # Advantages of single quote `'`: # - prints as less pixels so less noisy # - easier to type on a standard keyboard since no shift required # PEP 8 and Google Style say choose one and stick with it. # Only use the other to avoid backslash escaping the one. # Other styles promote a semantic differentiation: # - `'` for identifiers, e.g., map keys # - `"` for human readable messages: `print "Hello world!"` # But this differentiation harder to maintain. if '## multiline strings ## triple quotes': # Like in C, whitespace separated strings are glued together: assert 'ab' 'cd' == 'abcd' # This means that backslash continuation joins strings without newlines: assert \ 'ab' \ 'cd' == 'abcd' assert """a b""" == 'a\nb' assert '''a b''' == 'a\nb' # Spaces are kept: assert '''a b''' == 'a\n b' def f(): assert """a b""" == 'a\nb' f() # Backslash escapes are like in C. assert '\x61' == 'a' assert '\n' == '\x0A' if '## raw string literals ## r literals': # Raw literals lose all backslash escape magic. assert r'\n' == '\\n' assert r'\\' == '\\\\' # The exception is to escape the character that would terminate the string (`'` or `"`). # In that case, the backslash *remains* in the string: assert r'\"' == "\\\"" # A consequence is that it is impossible to write a raw string literal that ends in backslash. assert '\\' != r'' # Raw string literals are often used with regular expressions, # which often contain many literal backslashes. # Character access is like for a list: assert 'ab'[0] == 'a' assert 'ab'[1] == 'b' # Unlike lists, strings are immutable, to it is not possible to assign to an element, # or `TypeError` is raised. try: 'ab'[0] = 'a' except TypeError: pass else: assert False if '## Concatenate': # Used to be inefficient because strings are immutable, but CPython improved it: # http://stackoverflow.com/questions/4435169/good-way-to-append-to-a-string # If you are really concerned, use and array and then join at the end. assert 'ab' + 'cd' == 'abcd' # For string literals: assert 'ab' 'cd' == 'abcd' assert 'ab' * 3 == 'ababab' # `replace`: replaces at most once: assert 'aabbcc'.replace('b', '0') == 'aa00cc' assert 'aabbcc'.replace('bb', '0') == 'aa0cc' assert 'aabbcc'.replace('b', '0', 1) == 'aa0bcc' if '## string module': import string if '## constants': print 'string.whitespace = ' + string.whitespace.encode('string-escape') if '## join': assert '0'.join(['a', 'b', 'c']) == 'a0b0c' # Why not a method of list? # http://stackoverflow.com/questions/493819/python-join-why-is-it-string-joinlist-instead-of-list-joinstring if '## split': # Split string into array of strings: assert '0ab1ab2'.split('ab') == ['0', '1', '2'] assert '0abab2'.split('ab') == ['0', '', '2'] # If string not given, splits at `string.whitespace*` **regex**!: # Very confusing default that changes behaviour completely! # But kind of useful default. assert '0 1\t \n2'.split() == ['0', '1', '2'] if '## splitlines': # Split at `(\n\r?|\r)` regex, *and* exclude the last empty string that split # would generate if there was a trailing newline. assert '0\n1\r2\r\n3\n'.splitlines() == ['0', '1', '2', '3'] if '## strip ## rstrip ## lstrip': """ Strip chars either from either beginning or end, *not* middle! Characters to strip are given on a string. Default argument: `string.whitespace` r and l strip for one sided versions. """ assert 'cbaba0a1b2ccba'.strip('abc') == '0a1b2' assert '\t\n0 1 2\v \r'.strip() == '0 1 2' if '## chomp': """ chomp is a Perl function that takes one newline off the end. Therefore it is not equivalent to chomp! Best way to do it: http://stackoverflow.com/a/19531239/895245 """ if '## startswith': assert 'abc'.startswith('ab') == True assert 'abc'.startswith('bc') == False # Remove prefix: <http://stackoverflow.com/questions/599953/python-how-to-remove-the-left-part-of-a-string> # If sure that the prefix is there: prefix = 'ab' assert 'abcd'[len(prefix):] == 'cd' # Otherwise: prefix = 'ab' s = 'abcd' if s.startswith(prefix): assert s[len(prefix):] == 'cd' if '## contains substring': assert 'bc' in 'abcd' assert 'bc' not in 'abdc' # The empty string is contained in all others: assert '' in '' assert '' in 'a' # String to number: assert int('123') == 123 assert float('12.34e56') == 12.34e56 # Char to int: assert ord('a') == 97 # Encode: assert '\n'.encode('string-escape') == '\\n' # `string-escape` is similar to `repr`. if '## unicode ## encodings': """ Before reading this you should understand what is ASCII, Unicode, UTF8, UTF16. The difference between the `unicode` and `str` classes is that: - `str` is just an array of bytes. These could represent ASCII chars since those fit into 1 byte, but they could also represent UTF8 chars. If they represent UTF8 chars, which may have more than 1 byte per char, the str class has no way to know where each char begins and ends, so s[0] give gibberish. `str` is the output of an encode operation, or the input of a decode operation. - `unicode`: represents actual Unicode characters. Unicode strings do not have an explicit encoding, although Python probably uses one int per char containing the Unicode code of that character. `unicode` is the output of a decode operation, or the input of an encode operation. """ """ To be able to use utf8 directly in Python source. The second line of the file *must* be: -*- coding: utf-8 -*- Otherwise, you must use escape characters. This changes in Python 3 where utf-8 becomes the default encoding. """ if '## u backslash escapes ## unicode literals': """ Unicode literals are just like string literals, but they start with `u`. The string below has 2 characters. Characters are treated differently depending on if strings are str or unicode. """ u = u'\u4E2D\u6587' assert u[0] == u'\u4E2D' assert u[1] == u'\u6587' """ Each escape character represents exactly one Unicode character, however some escapes cannot represent all characters. The possile escapes are: - `\xAA` represents one character of up to one byte. This is not very useful with Unicode, since most of those characters have a printable and therefore more readable ASCII char to represent them. Characters with more than 1 byte cannot be represented with a `\xAA` escape. - `\uAAAA`: 2 bytes. This is the most useful escape, as the most common unicode code points are use either one or 2 bytes. - `\UAAAAAAAA`: 4 bytes It is very rare to have to use `\UAAAAAAAA` literals, since Unicode plane 0 which contains the most common characters fit into one byte. Also note that `\U0010FFFF` is the largest possible character: the first byte must always be 0, since that is as far as Unicode goes. Remember: `\` escapes are interpreted inside multiline comment strings. Therefore, if you write an invalid escape like `\\xYY`, your code will not run! """ assert u'\u4E2D\u6587' == u'中文' assert u'\U00010000' == u'𐀀' """ A is done to confirm that a byte is a known unicode character. For example `\UAAAAAAAA` does not currently represent any Unicode character, so you cannot use it. """ #u'\UAAAAAAAA' #Unicode \u escapes are only interpreted inside unicode string literals. s = '\u4E2D\u6587' assert s[0] == '\\' assert s[1] == 'u' assert s[2] == '4' """ ## encode ## decode Encode transforms an `unicode` string to a byte string `str`. Decode transforms a byte string `str` to an `unicode` string. """ assert u'中'.encode('utf-8') == '\xE4\xB8\xAD' assert u'中' == '\xE4\xB8\xAD'.decode('utf-8') # Most escapes in str literals strings are also interpreted inside unicode strings. assert u'\n'.encode('ASCII') == '\n' # When mixing encodings implicily, ASCII is assumed by default, # so things break only if there are non-ASCII chars. # Don't do any of the following: assert u'a' == 'a' assert u'\u20AC' != '\x20\xAC' try: str(u'\u20AC') except UnicodeEncodeError: #'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128) pass else: raise try: assert u'\u20AC'.decode('utf-8') except UnicodeEncodeError: #'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128) pass else: raise try: unicode('\x20\xAC') except UnicodeDecodeError: #'ascii' codec can't decode byte 0xac in position 1: ordinal not in range(128) pass else: raise """ ## Normalization Some unicode characters can be represented by multiple sequences. This is so for backwards compatibility with older encodings, and happens most often for accentuated versions of latin characters. unicode strings with different normalizations compare False. Normalization may be modified via `unicodedata`. """ assert u'\u00EAtre' != u'e\u0302tre' import unicodedata assert unicodedata.normalize('NFC', u'\u00eatre') == unicodedata.normalize('NFC', u'e\u0302tre') """ IO is typically done via arrays of bytes since that is how the system really sees it, and not via unicode chars. This includes operations like: - print - sys.stdout.write - file open + write There may be however some convenience wrappers that deal with encoding. For example, `codecs.open` opens a file in a encoding aware manner. """ """ ## Unicode and file IO First remember that `sys.stdout` is a file object, so terminal and file IO is much the same. Terminal output via `print` or `sys.stdout.write` always uses str byte strings. If given unicode, it first decodes via `sys.stdout.encoding` TODO how sys.stdout.encoding is determined TODO pipes affect `sys.stdout.encoding`? If print output goes to a pipe, `sys.stdout.encoding` is `None`, in which case `ASCII` conversion is attempted. If there are any non ASCII characters, this leads to an exception! Therefore, if it is ever possible that there could be unicode chars on the output string, encode it explicitly. """ print 'sys.stdout.encoding = ' + str(sys.stdout.encoding) # BAD: will raise an exception if output to a pipe! #print u'中文' # GOOD: print u'中文'.encode('utf-8') if '## lower and upper case': assert 'aBcD'.lower() == 'abcd' assert 'aBcD'.upper() == 'ABCD'
2b2fa3ec3db696ed596e609a498f750f29bb46d8
Vestenar/PythonProjects
/venv/02_Codesignal/02_The Core/056_htmlEndTagByStartTag.py
898
3.8125
4
def htmlEndTagByStartTag(startTag): print(startTag[1:-1]) a = "</" + startTag.split()[0][1:] if startTag.split()[0][-1] != '>': a += ">" return a ''' def htmlEndTagByStartTag(startTag): return "</" + startTag[1:startTag.find(" ")] + ">" # если пробела нет, то будет [1:-1] ''' print(htmlEndTagByStartTag("<i>")) ''' You are implementing your own HTML editor. To make it more comfortable for developers you would like to add an auto-completion feature to it. Given the starting HTML tag, find the appropriate end tag which your editor should propose. If you are not familiar with HTML, consult with this note. Example For startTag = "<button type='button' disabled>", the output should be htmlEndTagByStartTag(startTag) = "</button>"; For startTag = "<i>", the output should be htmlEndTagByStartTag(startTag) = "</i>". '''
adea06f198b83efc51f6cdd2eefc56e11871f9d9
Phipsee/RecommenderSystems
/02/task2_1.py
368
3.84375
4
import pandas as pd data = ['Toy Story', 'Jumanji', 'Grumpier Old Men'] # Standard Series series = pd.Series(data) print('First element: ', series[0]) print('First two elements: ', series[:2]) print('Last two elements: ', series[-2:]) # Series with custom indices series = pd.Series(data, index = ['a', 'b', 'c']) print('Element at position \'b\': ', series['b'])
47bd703f986220b15e7720d43b5f508a86e19ace
Brainkackwitz/chat_adventrue
/spielermenu.py
411
3.59375
4
import save import sys def menu(): c=0 a=1 while c < a: optionen = (['weiter', 'Speichern', 'exit']) for i, x in enumerate(optionen): print(f"{i+1}.", x) aktion = int(input('\nWähle deine Aktion ')) if aktion == 1: break if aktion == 2: save.save() break if aktion == 3: os._exit(1) menu()
dc6e644b856618ab25e8f287ba3ffefb425bcbf7
michmeng/Bioinformatics-Algorithms
/Locating Sequences/hamming_distance.py
277
3.796875
4
def hamming_dist(str1, str2): mismatch = 0 #should prob check if len(str1) == len(str2) for i in range(len(str1)): c1 = str1[i] c2 = str2[i] if c1 != c2: mismatch += 1 return mismatch #print (hamming_dist("",""))
5fd52d8abad5f7da03d59e1155d30553c6bf56fd
mnpitts/Python
/lstsq_eigs.py
6,804
3.546875
4
# lstsq_eigs.py """Volume 1: Least Squares and Computing Eigenvalues. <McKenna Pitts> <Section 2> <October 30> """ # (Optional) Import functions from your QR Decomposition lab. # import sys # sys.path.insert(1, "../QR_Decomposition") # from qr_decomposition import qr_gram_schmidt, qr_householder, hessenberg import numpy as np from matplotlib import pyplot as plt from scipy import linalg as la # Problem 1 def least_squares(A, b): """Calculate the least squares solutions to Ax = b by using the QR decomposition. Parameters: A ((m,n) ndarray): A matrix of rank n <= m. b ((m, ) ndarray): A vector of length m. Returns: x ((n, ) ndarray): The solution to the normal equations. """ Q,R = la.qr(A, mode = "economic") #Q, R decomposition y = np.dot(Q.T, b) #dot product of Q.T and b x = la.solve_triangular(R, y) #Solve triangular system return x # Problem 2 def line_fit(): """Find the least squares line that relates the year to the housing price index for the data in housing.npy. Plot both the data points and the least squares line. """ data = np.load("housing.npy") #load the data n = len(data) ones_col = np.ones((n,1)) x_col = data[:,0].reshape((n,1)) A = np.column_stack((x_col, ones_col)) #Create A b = data[:,1] #Create b x = least_squares(A,b) #find the least squares solution m = data[:,0] #plot the data points n = data[:,1] plt.plot(m, n, 'b*', label="Data Points") plt.plot(m, x[0]*m + x[1], 'g', label="Least Squares Fit") #plot the least squares fit plt.legend(loc="lower right") plt.show() # Problem 3 def polynomial_fit(): """Find the least squares polynomials of degree 3, 6, 9, and 12 that relate the year to the housing price index for the data in housing.npy. Plot both the data points and the least squares polynomials in individual subplots. """ data = np.load("housing.npy") #load the data A_three = np.vander(data[:,0],3) #create matrices for each degree A_six = np.vander(data[:,0],6) A_nine = np.vander(data[:,0],9) A_twelve = np.vander(data[:,0],12) b = data[:,1] x_three = la.lstsq(A_three, b)[0] #find the least squares solution for each degree x_six = la.lstsq(A_six, b)[0] x_nine = la.lstsq(A_nine, b)[0] x_twelve = la.lstsq(A_twelve, b)[0] f_three = np.poly1d(x_three) #Create a polynomial for each degree f_six = np.poly1d(x_six) #using the least squares solution f_nine = np.poly1d(x_nine) f_twelve = np.poly1d(x_twelve) m = data[:,0] #prepare data to plot n = data[:,1] x = np.linspace(0,16) three = plt.subplot(221) #plot polynomial of degree 3 three.plot(m, n, 'b*') three.plot(x, f_three(x), 'g') six = plt.subplot(222) #plot polynomial of degree 6 six.plot(m, n, 'b*') six.plot(x, f_six(x), 'g') nine = plt.subplot(223) #plot polynomial of degree 9 nine.plot(m, n, 'b*') nine.plot(x, f_nine(x), 'g') twelve = plt.subplot(224) #plot polynomial of degree 12 twelve.plot(m, n, 'b*', label="Data Points") twelve.plot(x, f_twelve(x), 'g', label="Least Squares Fit") plt.legend(loc="lower right") plt.show() def plot_ellipse(a, b, c, d, e): """Plot an ellipse of the form ax^2 + bx + cxy + dy + ey^2 = 1.""" theta = np.linspace(0, 2*np.pi, 200) cos_t, sin_t = np.cos(theta), np.sin(theta) A = a*(cos_t**2) + c*cos_t*sin_t + e*(sin_t**2) B = b*cos_t + d*sin_t r = (-B + np.sqrt(B**2 + 4*A)) / (2*A) plt.plot(r*cos_t, r*sin_t) plt.gca().set_aspect("equal", "datalim") # Problem 4 def ellipse_fit(): """Calculate the parameters for the ellipse that best fits the data in ellipse.npy. Plot the original data points and the ellipse together, using plot_ellipse() to plot the ellipse. """ x_col, y_col = np.load("ellipse.npy").T #load the data ones_col = np.ones_like(x_col) A = np.column_stack((x_col**2, x_col, x_col*y_col, y_col, y_col**2)) #Create A b = ones_col #create b a, b, c, d, e = la.lstsq(A, b)[0] #find least squares solution plt.plot(x_col, y_col, 'k*') #plot the data points plot_ellipse(a,b,c,d,e) #plot the ellipse plt.show() # Problem 5 def power_method(A, N=20, tol=1e-12): """Compute the dominant eigenvalue of A and a corresponding eigenvector via the power method. Parameters: A ((n,n) ndarray): A square matrix. N (int): The maximum number of iterations. tol (float): The stopping tolerance. Returns: (float): The dominant eigenvalue of A. ((n,) ndarray): An eigenvector corresponding to the dominant eigenvalue of A. """ m,n = A.shape #initialize m,n xn = np.random.random(n) #create a random vector of length n xn = xn/la.norm(xn) #normalize vector for k in range(1,N): xk = A.dot(xn) #create the next vector xk = xk/la.norm(xk) #normalize the vector if (la.norm(xk - xn) < tol): #check tolerance return xk.T.dot(A.dot(xk)), xk #return eigenvalue and corresponding eigenvector xn = xk return xn.T.dot(A.dot(xn)), xn #return eigenvalue and corresponding eigenvector # Problem 6 def qr_algorithm(A, N=50, tol=1e-12): """Compute the eigenvalues of A via the QR algorithm. Parameters: A ((n,n) ndarray): A square matrix. N (int): The number of iterations to run the QR algorithm. tol (float): The threshold value for determining if a diagonal S_i block is 1x1 or 2x2. Returns: ((n,) ndarray): The eigenvalues of A. """ m,n = A.shape #initialize m,n S = la.hessenberg(A) #Put A in upper Hessenberg form for k in range(N): Q,R = la.qr(S) #Get QR decomposition of A S = R.dot(Q) #Recombine R[k] and Q[k] into A[k+1] eigenvalues = [] #initialize empty list of eigenvalues i = 0 while i < n: if i == n-1 or abs(S[i+1][i] < tol): eigenvalues.append(S[i][i]) else: #use quadratic formula to get two eigenvalues b = -1*(S[i,i] + S[i+1,i+1]) c = (S[i,i] * S[i+1,i+1] - S[i,i+1] * S[i+1,i]) eigenvalues.append((-1*b + cmath.sqrt(b**2 - 4*c)) / 2) eigenvalues.append((-1*b - cmath.sqrt(b**2 - 4*c)) / 2) i += 1 i += 1 #move to the next S[i] return np.array(eigenvalues) #return array of eigenvalues
7291c4d10f6bc76963c76c636e8d680da899ba29
OsmanAliDurna/pythonExamples
/py_12th.py
897
3.921875
4
uni = "Istanbul Universitesi" stringLenght = len(uni) first10Uni = uni [:10] last10Uni = uni [-10:] reverseUni = uni[::-1] print("Length of uni\t\t: " , stringLenght) print("First 10 of uni\t\t: ", first10Uni) print("Last 10 of uni\t\t: ", last10Uni) print("Reverse of uni\t\t: ", reverseUni) swapNinUni = uni.replace("n","?") print("Original uni\t\t: ", uni) print("Swap n with ? in uni\t: ", swapNinUni) numberA = "987654" numberB = 6*numberA # string olduğu için "987654""987654""987654""987654""987654""987654" numberC = 6*numberA[0] # C 6 tane A nın ilk indexinden oluşmaktadır. 999999 print("\n\n") print("987654987654987654987654987654987654 nın 0-6-12-18-24-32. indexindeki rakamlar\t: ", numberB[::6]) # B nin 0. index ten başlayıp her 6. rakamını almaktadır. print("987654 ün 0. indexindeki rakamın 6 adet yanyana yazılmış hali\t\t\t: ", numberC)
df7b8d5b21b4337bff266adaf50e1de0eaa1a983
Aasthaengg/IBMdataset
/Python_codes/p03591/s087093878.py
141
3.828125
4
a=list(input()) if len(a)<=3: print("No") else: if a[0]=="Y" and a[1]=="A" and a[2]=="K" and a[3]=="I": print("Yes") else: print("No")
b27c1b9537ad4943d3b157ea3061934906b965d2
statco19/doit_pyalgo
/ch7/bf_match.py
495
3.640625
4
def bf_match(txt, pat) -> int: pt = 0 pp = 0 while pt != len(txt) and pp != len(pat): if txt[pt] == pat[pp]: pt += 1 pp += 1 else: pt = pt-pp + 1 pp = 0 return pt-pp if pp == len(pat) else -1 if __name__=="__main__": txt = "ABABCDEFGHA" pat = "ABC" print(bf_match(txt, pat)) assert(pat in txt) print(True) print(txt.find(pat)) print(txt.rfind(pat)) print(txt.index(pat)) print(txt.rindex(pat)) print(txt.startswith(pat)) print(txt.endswith(pat))
2db0cad36578bf13e07ba0b4ffe1ff5c32d8f830
LuisGerardoDC/challenge-prework-ds
/main.py
807
3.578125
4
import csv import pandas as pd def mostrarArchivoTerminal(): with open('INAH_detallado_2019.csv') as file: reader = csv.reader(file) for row in reader: print(row) def crearDataFrame(): print('Data en CSV-----------------------------------------------') dataINAH = pd.read_csv('INAH_detallado_2019.csv', engine='python') dataINAH = dataINAH.drop(['Siglas'],axis=1) print(dataINAH) return dataINAH def filtrarData(data,campo='Estado',valor='Aguascalientes'): print(f'\nData filtrada por {campo} [{valor}]-----------------------------------------------') filtro = data[campo] == valor return data[filtro] def totalesEstadoTemporalidad(data): if __name__ == '__main__': INAHDataFrame = crearDataFrame() print(filtrarData(INAHDataFrame))
c0dacb9352db6b0637806bd1b2b601136992d90c
jolene-loz/artificial-intelligence-game
/player.py
21,290
3.75
4
import random import time from self_driving_team.util import * from self_driving_team.minimax import * from self_driving_team.catapult import * # player 1: greedy player, makes the best move at the movement class GreedyPlayer: def __init__(self, colour): """ This method is called once at the beginning of the game to initialise your player. You should use this opportunity to set up your own internal representation of the game state, and any other information about the game state you would like to maintain for the duration of the game. The parameter colour will be a string representing the player your program will play as (White or Black). The value will be one of the strings "white" or "black" correspondingly. """ # initialising the board self.colour = colour self.board_dict = init_board() self.num_black = 12 self.num_white = 12 def action(self): """ This method is called at the beginning of each of your turns to request a choice of action from your program. Based on the current state of the game, your player should select and return an allowed action to play on this turn. The action must be represented based on the spec's instructions for representing actions. """ # get all moves for our colour moves = all_moves(self.board_dict,self.colour) # get the greediest move from the move move = greedy_move(self.board_dict, moves, self.colour, self.num_black, self.num_white) return move def update(self, colour, action): """ This method is called at the end of every turn (including your player’s turns) to inform your player about the most recent action. You should use this opportunity to maintain your internal representation of the game state and any other information about the game you are storing. The parameter colour will be a string representing the player whose turn it is (White or Black). The value will be one of the strings "white" or "black" correspondingly. The parameter action is a representation of the most recent action conforming to the spec's instructions for representing actions. You may assume that action will always correspond to an allowed action for the player colour (your method does not need to validate the action against the game rules). """ # update the board accordingly self.board_dict, self.num_black, self.num_white = make_move(self.board_dict, action, self.num_black, self.num_white) # player 2: random player, makes random move from all available moves class RandomPlayer: def __init__(self, colour): """ This method is called once at the beginning of the game to initialise your player. You should use this opportunity to set up your own internal representation of the game state, and any other information about the game state you would like to maintain for the duration of the game. The parameter colour will be a string representing the player your program will play as (White or Black). The value will be one of the strings "white" or "black" correspondingly. """ # initialising the board self.colour = colour self.board_dict = init_board() self.num_black = 12 self.num_white = 12 def action(self): """ This method is called at the beginning of each of your turns to request a choice of action from your program. Based on the current state of the game, your player should select and return an allowed action to play on this turn. The action must be represented based on the spec's instructions for representing actions. """ # get all moves for our colour moves = all_moves(self.board_dict, self.colour) # get a random move from those moves move = random.choice(moves) return move def update(self, colour, action): """ This method is called at the end of every turn (including your player’s turns) to inform your player about the most recent action. You should use this opportunity to maintain your internal representation of the game state and any other information about the game you are storing. The parameter colour will be a string representing the player whose turn it is (White or Black). The value will be one of the strings "white" or "black" correspondingly. The parameter action is a representation of the most recent action conforming to the spec's instructions for representing actions. You may assume that action will always correspond to an allowed action for the player colour (your method does not need to validate the action against the game rules). """ # update the board accordingly self.board_dict, self.num_black, self.num_white = make_move(self.board_dict, action, self.num_black, self.num_white) # player 3: alpha beta pruning minimax class AlphaBetaPlayer: def __init__(self, colour): """ This method is called once at the beginning of the game to initialise your player. You should use this opportunity to set up your own internal representation of the game state, and any other information about the game state you would like to maintain for the duration of the game. The parameter colour will be a string representing the player your program will play as (White or Black). The value will be one of the strings "white" or "black" correspondingly. """ # initialising the board self.colour = colour self.board_dict = init_board() self.num_black = 12 self.num_white = 12 def action(self): """ This method is called at the beginning of each of your turns to request a choice of action from your program. Based on the current state of the game, your player should select and return an allowed action to play on this turn. The action must be represented based on the spec's instructions for representing actions. """ # perform alpha beta minimax adversarial search max_depth = 3 alpha = -100000 # neg inf beta = 100000 # pos inf is_max_player = True val, move = minimax(self.board_dict, self.num_black, self.num_white, self.colour, max_depth, alpha, beta, is_max_player, self.colour) return move def update(self, colour, action): """ This method is called at the end of every turn (including your player’s turns) to inform your player about the most recent action. You should use this opportunity to maintain your internal representation of the game state and any other information about the game you are storing. The parameter colour will be a string representing the player whose turn it is (White or Black). The value will be one of the strings "white" or "black" correspondingly. The parameter action is a representation of the most recent action conforming to the spec's instructions for representing actions. You may assume that action will always correspond to an allowed action for the player colour (your method does not need to validate the action against the game rules). """ # update the board accordingly self.board_dict, self.num_black, self.num_white = make_move(self.board_dict, action, self.num_black, self.num_white) # player 4: alpha beta pruning minimax where 0 evals are recalculated to move in the right direction class AlphaBetaNonZeroPlayer: def __init__(self, colour): """ This method is called once at the beginning of the game to initialise your player. You should use this opportunity to set up your own internal representation of the game state, and any other information about the game state you would like to maintain for the duration of the game. The parameter colour will be a string representing the player your program will play as (White or Black). The value will be one of the strings "white" or "black" correspondingly. """ # initialising the board self.colour = colour self.board_dict = init_board() self.num_black = 12 self.num_white = 12 def action(self): """ This method is called at the beginning of each of your turns to request a choice of action from your program. Based on the current state of the game, your player should select and return an allowed action to play on this turn. The action must be represented based on the spec's instructions for representing actions. """ # perform alpha beta minimax adversarial search max_depth = 3 alpha = -100000 # neg inf beta = 100000 # pos inf is_max_player = True val, move = minimax_dist(self.board_dict, self.num_black, self.num_white, self.colour, max_depth, alpha, beta, is_max_player, self.colour) return move def update(self, colour, action): """ This method is called at the end of every turn (including your player’s turns) to inform your player about the most recent action. You should use this opportunity to maintain your internal representation of the game state and any other information about the game you are storing. The parameter colour will be a string representing the player whose turn it is (White or Black). The value will be one of the strings "white" or "black" correspondingly. The parameter action is a representation of the most recent action conforming to the spec's instructions for representing actions. You may assume that action will always correspond to an allowed action for the player colour (your method does not need to validate the action against the game rules). """ # update the board accordingly self.board_dict, self.num_black, self.num_white = make_move(self.board_dict, action, self.num_black, self.num_white) # player 5: minimax alpha beta pruning and zero reevaluation and time constraint class AlphaBetaTimeDist: def __init__(self, colour): """ This method is called once at the beginning of the game to initialise your player. You should use this opportunity to set up your own internal representation of the game state, and any other information about the game state you would like to maintain for the duration of the game. The parameter colour will be a string representing the player your program will play as (White or Black). The value will be one of the strings "white" or "black" correspondingly. """ # initialising the board self.colour = colour self.board_dict = init_board() self.num_black = 12 self.num_white = 12 def action(self): """ This method is called at the beginning of each of your turns to request a choice of action from your program. Based on the current state of the game, your player should select and return an allowed action to play on this turn. The action must be represented based on the spec's instructions for representing actions. """ # perform alpha beta minimax adversarial search max_depth = 10 alpha = -100000 # neg inf beta = 100000 # pos inf is_max_player = True start_time = time.perf_counter() val, move = minimax_time_dist(self.board_dict, self.num_black, self.num_white, self.colour, max_depth, alpha, beta, is_max_player, self.colour, start_time) return move def update(self, colour, action): """ This method is called at the end of every turn (including your player’s turns) to inform your player about the most recent action. You should use this opportunity to maintain your internal representation of the game state and any other information about the game you are storing. The parameter colour will be a string representing the player whose turn it is (White or Black). The value will be one of the strings "white" or "black" correspondingly. The parameter action is a representation of the most recent action conforming to the spec's instructions for representing actions. You may assume that action will always correspond to an allowed action for the player colour (your method does not need to validate the action against the game rules). """ # update the board accordingly self.board_dict, self.num_black, self.num_white = make_move(self.board_dict, action, self.num_black, self.num_white) # player 6: minimax alpha beta pruning and time constraint class AlphaBetaTime: def __init__(self, colour): """ This method is called once at the beginning of the game to initialise your player. You should use this opportunity to set up your own internal representation of the game state, and any other information about the game state you would like to maintain for the duration of the game. The parameter colour will be a string representing the player your program will play as (White or Black). The value will be one of the strings "white" or "black" correspondingly. """ # initialising the board self.colour = colour self.board_dict = init_board() self.num_black = 12 self.num_white = 12 def action(self): """ This method is called at the beginning of each of your turns to request a choice of action from your program. Based on the current state of the game, your player should select and return an allowed action to play on this turn. The action must be represented based on the spec's instructions for representing actions. """ # perform alpha beta minimax adversarial search max_depth = 10 alpha = -100000 # neg inf beta = 100000 # pos inf is_max_player = True start_time = time.perf_counter() val, move = minimax_time(self.board_dict, self.num_black, self.num_white, self.colour, max_depth, alpha, beta, is_max_player, self.colour, start_time) return move def update(self, colour, action): """ This method is called at the end of every turn (including your player’s turns) to inform your player about the most recent action. You should use this opportunity to maintain your internal representation of the game state and any other information about the game you are storing. The parameter colour will be a string representing the player whose turn it is (White or Black). The value will be one of the strings "white" or "black" correspondingly. The parameter action is a representation of the most recent action conforming to the spec's instructions for representing actions. You may assume that action will always correspond to an allowed action for the player colour (your method does not need to validate the action against the game rules). """ # update the board accordingly self.board_dict, self.num_black, self.num_white = make_move(self.board_dict, action, self.num_black, self.num_white) # player 7: Based on the Catapult trick discussed in our report class CatapultPlayer: def __init__(self, colour): """ This method is called once at the beginning of the game to initialise your player. You should use this opportunity to set up your own internal representation of the game state, and any other information about the game state you would like to maintain for the duration of the game. The parameter colour will be a string representing the player your program will play as (White or Black). The value will be one of the strings "white" or "black" correspondingly. """ # initialising the board self.colour = colour self.board_dict = init_board() self.num_black = 12 self.num_white = 12 def action(self): """ This method is called at the beginning of each of your turns to request a choice of action from your program. Based on the current state of the game, your player should select and return an allowed action to play on this turn. The action must be represented based on the spec's instructions for representing actions. """ # perform alpha beta minimax adversarial search max_depth = 3 alpha = -100000 # neg inf beta = 100000 # pos inf is_max_player = True val, move = minimax_catapult(self.board_dict, self.num_black, self.num_white, self.colour, max_depth, alpha, beta, is_max_player, self.colour) return move def update(self, colour, action): """ This method is called at the end of every turn (including your player’s turns) to inform your player about the most recent action. You should use this opportunity to maintain your internal representation of the game state and any other information about the game you are storing. The parameter colour will be a string representing the player whose turn it is (White or Black). The value will be one of the strings "white" or "black" correspondingly. The parameter action is a representation of the most recent action conforming to the spec's instructions for representing actions. You may assume that action will always correspond to an allowed action for the player colour (your method does not need to validate the action against the game rules). """ # update the board accordingly self.board_dict, self.num_black, self.num_white = make_move(self.board_dict, action, self.num_black, self.num_white) # player 7: Based on the Catapult trick discussed in our report and Zero reevaluation class CatapultNonZeroPlayer: def __init__(self, colour): """ This method is called once at the beginning of the game to initialise your player. You should use this opportunity to set up your own internal representation of the game state, and any other information about the game state you would like to maintain for the duration of the game. The parameter colour will be a string representing the player your program will play as (White or Black). The value will be one of the strings "white" or "black" correspondingly. """ # initialising the board self.colour = colour self.board_dict = init_board() self.num_black = 12 self.num_white = 12 def action(self): """ This method is called at the beginning of each of your turns to request a choice of action from your program. Based on the current state of the game, your player should select and return an allowed action to play on this turn. The action must be represented based on the spec's instructions for representing actions. """ # perform alpha beta minimax adversarial search max_depth = 3 alpha = -100000 # neg inf beta = 100000 # pos inf is_max_player = True val, move = minimax_catapult_dist(self.board_dict, self.num_black, self.num_white, self.colour, max_depth, alpha, beta, is_max_player, self.colour) return move def update(self, colour, action): """ This method is called at the end of every turn (including your player’s turns) to inform your player about the most recent action. You should use this opportunity to maintain your internal representation of the game state and any other information about the game you are storing. The parameter colour will be a string representing the player whose turn it is (White or Black). The value will be one of the strings "white" or "black" correspondingly. The parameter action is a representation of the most recent action conforming to the spec's instructions for representing actions. You may assume that action will always correspond to an allowed action for the player colour (your method does not need to validate the action against the game rules). """ # update the board accordingly self.board_dict, self.num_black, self.num_white = make_move(self.board_dict, action, self.num_black, self.num_white)
4f38153777275140df69aef72dbabacac1d3fd52
vishwakt/A-Problem-A-Day
/1189_maximum_number_of_balloons.py
420
3.578125
4
class Solution: def maxNumberOfBalloons(self, text: str) -> int: counter = {"b": 0, "a": 0, "l": 0, "o": 0, "n": 0} for char in text: if char in counter: counter[char] += 1 counter["l"] //= 2 counter["o"] //= 2 return min(counter.values()) if __name__ == "__main__": s = Solution() print(s.maxNumberOfBalloons(text = "loonbalxballpoon"))
c3cc4aaf02763de8840d71eb7617f91f8ff3227e
thijsishiernietgoedinaarts/prog
/p.9.2.py
241
3.796875
4
while True: word=input('gef een wordt van 4 tekens op') if len(word) > 4 or len(word) < 4: print(word,'heeft', len(word),'letters') if len(word) == 4: break print('inlezen van correce string:',word,'is geslaagd')
feb296e95950e6deea7967e9713851455ec70aa1
wenjie-p/my_repo
/src/leetcode/letterCombinationsOfPhoneNumber.py
676
3.609375
4
import itertools if __name__ == "__main__": digits = raw_input() kvmaps = {"2":"abc","3":"def","4":"ghi","5":"jkl","6":"mno","7":"pqrs","8":"tuv","9":"wxyz" } #for x in itertools.product(kvmaps[digits[i]] for i in range(len(digits))): #for x in itertools.product("abc","def"): # print x pools = [kvmaps[digits[i]] for i in range(len(digits))] #pools = ["abc","def"] ''' result = [[]] for pool in pools: result = [x + [y] for x in result for y in pool] for prod in result: print prod #for x in itertools.product(*pools): ''' for x in itertools.product(*pools): print x
e7ac874a590960ef7a4c5e94b09b83975fa7a7fe
lucilenikkels/EA3
/src/utils.py
1,130
3.609375
4
import numpy as np def comparator(solution1, solution2): ''' Comparator based on solutions rank and crowding distance ''' if solution1.rank < solution2.rank: return 1 if solution1.rank == solution2.rank and solution1.crowdingDistance > solution2.crowdingDistance: return 1 return -1 def calculateHypervolume(solutions): ''' Function for calculating hypervolume Input: list of Individuals assuming that these solutions do not dominate each other Output: single real value - the hypervolume formed by solutions with (1,1) as the reference point ''' result = 0.0 sorted_solutions_fitnesses = [np.copy(s.fitness) for s in solutions] bottom = 0 left = 0 #sort by first objective is descending order (from right to left) sorted_solutions_fitnesses = sorted(sorted_solutions_fitnesses, key = lambda x: x[0], reverse=True) for i, fitness in enumerate(sorted_solutions_fitnesses): current_hypervolume = (fitness[0] - left) * (fitness[1] - bottom) bottom = fitness[1] result += current_hypervolume return result
906b3579a729d7cf43dacad8879769ec5e4fa310
spensbot/Monkey
/strip.py
451
3.75
4
strip(reference) def strip(reference): #load files original = open(reference + ".txt",'r') stripped = open(reference + "_stripped.txt", 'w') text = original.read() #iterate over the file for char in text: #If the character is alphabetic, write it's lower case form to the stripped file. if char.isalpha(): stripped.write(char.lower()) #close files original.close() stripped.close()
9101362d99a06a39ba8e809e9cb096377f5a508b
LeopoldACC/Algorithm
/周赛/week182/5370UndergroundSystem.py
1,901
3.75
4
class UndergroundSystem: def __init__(self): self.time = {} self.station = {} def checkIn(self, id: int, stationName: str, t: int) -> None: self.time[id] = [stationName,t]#self.station.get(id,[stationName,t]) if stationName not in self.station: self.station[stationName] = {} def checkOut(self, id: int, stationName: str, t: int) -> None: time = t-self.time[id][1] start = self.time[id][0] self.station[start][stationName] = self.station[start].get(stationName,[0,0]) self.station[start][stationName][0]+=time self.station[start][stationName][1]+=1 def getAverageTime(self, startStation: str, endStation: str) -> float: return self.station[startStation][endStation][0]/self.station[startStation][endStation][1] undergroundSystem = UndergroundSystem() undergroundSystem.checkIn(45, "Leyton", 3) undergroundSystem.checkIn(32, "Paradise", 8) undergroundSystem.checkIn(27, "Leyton", 10) undergroundSystem.checkOut(45, "Waterloo", 15) undergroundSystem.checkOut(27, "Waterloo", 20) undergroundSystem.checkOut(32, "Cambridge", 22) print(undergroundSystem.getAverageTime("Paradise", "Cambridge")) # // 返回 14.0。从 "Paradise"(时刻 8)到 "Cambridge"(时刻 22)的行程只有一趟 print(undergroundSystem.getAverageTime("Leyton", "Waterloo")) # // 返回 11.0。总共有 2 躺从 "Leyton" 到 "Waterloo" 的行程,编号为 id=45 的乘客出发于 time=3 到达于 time=15,编号为 id=27 的乘客于 time=10 出发于 time=20 到达。所以平均时间为 ( (15-3) + (20-10) ) / 2 = 11.0 undergroundSystem.checkIn(10, "Leyton", 24) print(undergroundSystem.getAverageTime("Leyton", "Waterloo")) # // 返回 11.0 undergroundSystem.checkOut(10, "Waterloo", 38) print(undergroundSystem.getAverageTime("Leyton", "Waterloo")) # // 返回 12.0
4f1869efb11f0efac0b92afeb49361f1bb739f4f
HuilinLu/Python-for-Data-Science
/Using Databases with Python.py
39,704
4.03125
4
## Using Databases with Python ## Review Unicode, UTF-8, ASCII(American Standard Code for Information Interchange) ASCII ## Representing Simple Strings ## Each character is represented by a number between 0 and 256 stored in 8 bits of memory ## We refer to '8 bits of memory as a "byte" of memory - (ie. my desk drive contains 3 Terabytes of memory') ## The ord() function tells us the numeric value of a simple ASCII character print(ord('H')) ## 72 print(ord('e')) ## 101 print(ord('\n')) ## 10 ## Based on ASCII, US computer can not talk with Asia Computer, however, Unicode ## Using Unicode, computers can communicate, bc Unicode contains millions of characters ##Multi-Byte Characters ## To represent the wide range of characters computers must handle we represent characters with more than one byte ### UTF-16 -- Fixed Length - Two bytes ### UTF-32 -- Fixed Length - Four Bytes ### UFT-8 -- 1~4 Bytes #### Upwards compatible with ASCII #### Automatic detection between ASCII and UTF-8 #### UTF-8 is recommended practice for encoding data to be exchanged between systems ## In Python edition 2, there are two kinds of strings: str and unicode ## In Python 3, all strings are Unicode Python 2.7.10 x = '编程' ## regular string type(x) ## <type 'str'> x = u'编程' ## unicode string type(x) ## <type 'unicode'> Python 3.5.1 x = '编程' type(x) ## <class 'str'> x = u'编程' type(x) ## <class 'str'> Python 2.7.10 ## Byte String is the same with Regular String and they are different from Unicode String x = b'abc' type(x) ## <type 'str'> x = '编程' ## regular string type(x) ## <type 'str'> x = u'编程' ## unicode string type(x) ## <type 'unicode'> Python 3.5.1 ## Byte String is different from Regular String and Regular String is the same with Unicode String x = b'abc' type(x) ## <class 'bytes'> x = '编程' type(x) ## <class 'str'> x = u'编程' type(x) ## <class 'str'> ## Python 3 and Unicode ## In Python 3, all strings internally are UNICODE ## Working with string variables in Python programs and reading from files usually 'just works' ## When we talk to a network resource using sockets to talk to a database we have to encode(send) and decode(receive) data(usually to UTF-8) ## When we talk to an external resource like a network socket we send bytes, so we need to encode Python 3 strings into a given character encoding ## When We read data from an external resource, we must decode it based on the character set so it is properly represented in Python 3 as a string while True: ## The output of while loop is the METADATA data = mysock.recv(512) ## receive up to 512 characters, data is Bytes if (len(data) < 1): break ## ends the loop until go to the file final mystring = data.decode() ## decode means take the data outside work and interpret what it means internally for us print(mystring) ## mystring is Unicode, decode() converts bytes(UTF-8 or ASCII) to Unicode ## decode() is the opposite of encode, converts UTF-8 to unicode bytes.decode() str.encode() ## An HTTP Request in Python import socket mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mysock.connect(('data.pr4e.org', 80)) ## a tuple in the parentheses cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n'.encode() ## take the string into bytes ## Strings inside Python which is UNICODE, so we have to send them out in UTF-8 format ## encode() converts from unicode internally to UTF-8 mysock.send(cmd) while True: ## The output of while loop is the METADATA data = mysock.recv(512) ## receive up to 512 characters if (len(data) < 1): break ## ends the loop until go to the file final print(data.decode()) ## decode means take the data outside work and interpret what it means internally for us ## decode() is the opposite of encode, converts UTF-8 to unicode mysock.close() ## Objected Oriented Definition and Terminology ## Warning: ## This lecture is vey much about definitions and mechanics for objects ## This lecture is a lot more about 'how it works' and less about 'how you use it' ## You won't get the entire picture until this is all looked at in the context of a real problem ## So please suspend disbelief and learn technique for the next 40 or so slides inp = input('Euro Floor') usf = int(inp) + 1 print('US floor', usf) ## Objected Oriented ## A program is made up pf many cooperating objects ## Instead of being the 'whole program' - each object is a little 'island' within the program and cooperatively working with other objects ## A program is made up of one or more objects working together - objects make use of each other's capabilities ## Object ## An Object is a bit of self-contained Code and Data ## A key aspect of the Object apporach is to break the problem into smaller understandable parts (divide and conquer) ## Objects have boundaries that allow us to ignore un-needed detail ## We have been using objects all along: String Objects, Integer Objects, Dictionary Objects, List Objects ## Definitions of an Object ## 1. Class - a template(shape of object) -- eg: string ## 2. Method or Message - A defined capability of a class -- eg string.upper ## 3. Field or attribute - A bit of data in a class ## 4. Object or Instance - A particular instance of a class -- the word we give the real things-- number, ... x = 'abc' ## x is an object type(x) ## string is class, <class 'str'>, template dir(x) ## Methods .upper ## Our First Class and Object ## This is the template for making PartyAnimal objects, class is a reserved word class PartyAnimal: x = 0 ## Each PartyAnimal object has a bit of data def party(self): self.x = self.x + 1 print('So far', self.x) ## Each PartyAnimal object has a bit of code an = PartyAnimal() ## Construct a PartyAnimal object and store in an variable, 'an' is an object, it is like an = list() an.party() ## an.x = an.x + 1 an.party() an.party() ## It is like passing the 'an' to parameter PartyAnimal.party(an) ## Tell the 'an' project to run the party() code within it #============================================================================== # So far 1 # So far 2 # So far 3 #============================================================================== ## Playing with dir() and type() ## The dir() command lists capabilities ## Ignore the ones with underscores - These are used by Python itself ## The rest are real operations that the object can perform ## It is like type() - it tells use something *about* a variable print('Type', type(an)) print('Dir', dir(an)) #============================================================================== # Type <class '__main__.PartyAnimal'> # Dir ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'party', 'x'] #============================================================================== ## We can use dir() to find the 'capabilities' of our newly created class ## Object Life Cycle ## Objects are created, used and discarded ## We have special blocks of code (methods) that get called: ## 1. At the moment of creation (constructor) ## 2. At the moment of destruction (destructor) ## Constructors are used a lot: The primary purpose of the constructor is to set up some instance variables to have the proper initial values when the object is created ## Destructors are seldom used class PartyAnimal: x=0 def __init__(self): print('I am constructed') def party(self): self.x = self.x + 1 print('So far', self.x) def __del__(self): print('I am destructed', self.x) an = PartyAnimal() ## This is the moment of construction, so it will print 'I am constructed' 'I am destructed 0' an.party() ## So far 1 an.party() ## So far 2 an = 42 ## This is the destruction moment, it will print out 'I am destructed 2' print('an contains', an) ## an contains 42 ## The constructor and destructor are optional. The constructor is typically used to set up variables. The destructor is seldom used. ## Constructor: In object oriented programming, a constructor in a class is a special block of statements called when an object is created ## Many Instances ## We can create lots of objects - the class is the template for the object ## We can store each distinct object in its own variable ## We call this having multiple instances of the same class ## Each instance has its own copy of the instances variables class PartyAnimal: x = 0 name = " " def __init__(self, z): ## Notice, there are two '_' to become '__' self.name = z print(self.name, 'constructed') def party(self): self.x = self.x + 1 print(self.name, 'party count', self.x) s = PartyAnimal("Sally") ## so the z will be 'Sally' the name s.party() ## self.x = 1 j = PartyAnimal('Jim') j.party() ## j x=1, name='Jim' s.party() ## s x=2, name='Sally' ## We have two independent instances ## Defining the capabilities of Objects ## Object Inheritance ## 1. When we make a new class - we cna reuse an existing class and inherit all the capabilities of an existing class and then add our own little bit to make our new class ## 2. Another form of store nad reuse ## 3. Write once - reuse many times ## 4. The new class(child) has all the capabilities of the old class(parent) - and then some more ## Teminology: Inheritance ## 'Subclasses' are more specialized versions of a class, which inherit attributes and behaviors from their parent classes, and can introduce their own. class PartyAnimal: x = 0 name = "" def __init__(self, nam): self.name = nam print(self.name, "constructed") def party(self): self.x = self.x + 1 print(self.name, "party count", self.x) class FootballFan(PartyAnimal): points = 0 def touchdown(self): self.points = self.points + 7 self.party() print(self.name, "points", self.points, self.x) ## FootballFan is a class which extends PartyAnimal. It has all the capabilities of PartyAnimal and more. s = PartyAnimal("Sally") ## 'Sally constructed' s.party() #'Sally party count 1' j = FootballFan('Jim') ## 'Jim constructed' j.party() ## 'Jim party count 1' j.touchdown() ## "Jim party count 2" the number is 2 because party() is called in touchdown(). "Jim points 7 2" ## FootballFan has x, name, points instances variables, FootballFan has a constructor, party method and touchdown method ## Summary Definitions ## Class - a template; Attribute - A variable within a class(data); Method - A function within a class; Object - A particular instance of a class ## Constructor - Code that runs when an object is created; Inheritance - The ability to extend a class to make a new class ## Relational Databases ## Basic Structured Query Language: Database Introduction ## Relational databses model data by storing rows and columns in tables. The power of the relational database lines in its ability to efficiently retrieve data from those tables ## and in particular where there are multiple tables and the relationships between those tables involved in the query. ## Terminology ## Database - Contains many tables ## Relation (or table) - contains tuples and attributes ## Tuple (or row) - a set of fields that generally represents an "object" like a person or a music track ## Attribute (also column or field) - one of possibly many elements of data corresponding to the object represented by the row. ## SQL ## Structured Query Language is the language we use to issue commands to the database ## 1. Create a table 2. Retrieve some data 3. Insert data (Update Data) 4. Delete data ## Using Databases ## Two roles in Large Projects( Website tracking data has a databse): ## 1. Application Developer - Builds the logic for the application, the look and feel of the application - monitors the application for problems ## 2. Database Administrator - Monitors and adjusts the database as the program runs in production #### Often both people participate in the building of the 'Data model' ## Database Model: ## A database model or database schema is the structure or format of a database, described in a formal language supported by the database management system ## In other words, a 'database model' is the application of a data model when used in conjunction with a database management system. ## Operate some staff in SQLite Browser /* 1 */ CREATE TABLE Users( name VARCHAR(128), email VARCHAR(128)); insert into 'Users' (name, email) VALUES('Chuck', 'csev@umich.edu'); insert into 'Users' (name, email) VALUES('Colleen', 'vit@umich.edu'); insert into 'Users' (name, email) VALUES('Sally', 'sally@umich.edu'); ## SQL Insert ## The Insert statement inserts a row into a table INSERT INTO Users (name, email) VALUES ('Kristin', 'kf@umich.edu'); ## SQL Delete ## Deletes a row in a table based on a selection criteria DELETE FROM Users WHERE email='ted@umich.edu'; ## SQL: Update ## Allows the updating of a field with a where clause UPDATE Users SET name='Charles' WHERE email='csev@umich.edu'; ## Retrieving Records: SELECT ## The select statement retieves a group of records - you can either retrieve all the records or a subset of the records with a WHERE clause SELECT * FROM Users SELECT * FROM Users WHERE email='cesv@umich.edu'; ## Sorting with ORDER BY ## You can add an ORDER BY clause to SELECT statements to get the results sorted in ascending or descending order SELECT * FROM Users ORDER BY email SELECT * FROM Users ORDER BY name DESC ## Working Example: Counting Email in a Database: emaildb.py file import sqlite3 conn = sqlite3.connect('emaildb.sqlite') ## Create the file called 'emaildb' cur = conn.cursor() ## open the handle and also able to send SQL commands and get responses through that same cursor dir(cur) ## [ 'arraysize', 'close', 'connection', 'description', 'execute', 'executemany', 'executescript', 'fetchall', 'fetchmany', 'fetchone', 'lastrowid', 'row_factory', 'rowcount', 'setinputsizes', 'setoutputsize'] cur.execute(''' DROP TABLE IF EXISTS Counts''') ## drop the table unless it exists in emaildb file cur.execute(''' CREATE TABLE Counts (email TEXT, count INTEGER)''') fname = input('Enter file name: ') if (len(fname) < 1): fname = 'mbox-short.txt' fh = open(fname) for line in fh: if not line.startswith('From:'): continue line = line.strip() pieces = line.split() email = pieces[1] cur.execute('SELECT count FROM Counts WHERE email = ?', (email,)) ## '?" is a placeholder, make sure that we don't allow SQL injection ## (email,) is a one-thing tuple, "?" let the email to replace it ## The above step is not retrieving the data, is to make sure table name is right or if there is any syntax errors row = cur.fetchone() ## grab the first one and give it back to row ## the row will be a list, but only one thing, a list of None if row is None: cur.execute('''INSERT INTO Counts (email, count) Values (?, 1)''', (email,)) ## row is None, and then count will be initiate as 1 ## Then a record will be added in a table else: cur.execute('''UPDATE Counts SET count = count + 1 WHERE email= ?''', (email,)) ## row is not None and then the count in Count will be updated print((email, row)) conn.commit() ## force to write into the disk memory ## https://www.sqlite.org/lang_select.html sqlstr = 'SELECT email, count FROM Counts ORDER BY count DESC LIMIT 10' for row in cur.execute(sqlstr): print(str(row[0]), row[1]) cur.close() ## Exercise on the mbox document import sqlite3 conn = sqlite3.connect('domain.sqlite') ## Create the file called 'emaildb' cur = conn.cursor() ## open the handle and also able to send SQL commands and get responses through that same cursor dir(cur) ## [ 'arraysize', 'close', 'connection', 'description', 'execute', 'executemany', 'executescript', 'fetchall', 'fetchmany', 'fetchone', 'lastrowid', 'row_factory', 'rowcount', 'setinputsizes', 'setoutputsize'] cur.execute(''' DROP TABLE IF EXISTS Counts''') ## drop the table unless it exists in emaildb file cur.execute(''' CREATE TABLE Counts (org TEXT, count INTEGER)''') fname = input('Enter file name: ') if (len(fname) < 1): fname = 'mbox.txt' fh = open(fname) for line in fh: if not line.startswith('From:'): continue line = line.strip() pieces = line.split() email = pieces[1] email = email.split('@') org = email[1] cur.execute('SELECT count FROM Counts WHERE org = ?', (org,)) ## '?" is a placeholder, make sure that we don't allow SQL injection ## (email,) is a one-thing tuple, "?" let the email to replace it ## The above step is not retrieving the data, is to make sure table name is right or if there is any syntax errors row = cur.fetchone() ## grab the first one and give it back to row ## the row will be a list, but only one thing if row is None: cur.execute('''INSERT INTO Counts (org, count) Values (?, 1)''', (org,)) ## row is None, and then count will be initiate as 1 ## Then a record will be added in a table else: cur.execute('''UPDATE Counts SET count = count + 1 WHERE org= ?''', (org,)) ## row is not None and then the count in Count will be updated #print(row) conn.commit() ## force to write into the disk memory ## https://www.sqlite.org/lang_select.html sqlstr = 'SELECT org, count FROM Counts ORDER BY count DESC LIMIT 10' for row in cur.execute(sqlstr): print(str(row[0]), row[1]) cur.close() ## Worked Example: Twspider.py from urllib.request import urlopen import urllib.eror import twurl import json import sqlite3 import ssl TWITTER_URL = 'https://api.twitter.com/1.1/friends/list.json' conn = sqlite3.connect('spider.sqlite') cur = conn.cursor() cur.execute('CREATE TABLE IF NOT EXISTS Twitter (name TEXT, retrieved INTEGER, friends INTEGER)') ## Ignore SSL certificate errors cts = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE while True: acct = input('Enter a Twitter account, or quit: ') if (acct == 'quit'): break if (len(acct) < 1): cur.execute('SELECT name FROM Twitter WHERE retrieved = 0 LIMIT 1') ## read from the database on unretrieved Twitter person and then grab all that person's friends try: acct = cur.fetchone()[0] except: print('No unretrieved Twitter accounts found') continue url = twurl.augment(TWITTER_URL, {'screen_name':acct, 'count': '5'}) ## this has the hidden.py whihc has our secrets and tokens ## five recent friends only print('Retrieving', url) connection = urlopen(url, context=ctx) data = connection.read().decode() headers = dict(connection.getheaders()) print('Remaining', headers['x-rate-limit-remaing']) js = json.loads(data) ## it returns a list ## Debugging ## print json.dumps(js, indent = 4) cur.execute('UPDATE TABLE Twitter SET retrieved=1 WHERE name=?', (acct,)) countnew = 0 countold = 0 for u in js['users']: friend = u['screen_name'] print(frined) cur.execute('SELECT friends FROM Twitter WHERE name = ? LIMIT 1', (friend,)) try: count = cur.fetchone()[0] cur.execute('UPDATE Twitter SET friends = ? WHERE name = ?', (count+1, friend)) countold = countold + 1 except: cur.execute('INSERT INTO Twitter (name, retrieved, friends) VALUES (?, 0, 1)', (friend, )) countnew = countnew + 1 print('New accounts=', countnew, ' revisited=', countold) conn.commit() cur.close() ## Data Models and Relational SQL: Designing a Data Model ## Database Design ## 1. Database design is an art form of its own with particular skills and experience ## 2. Our goal is to avoid the really bad mistakes and design clean and easily understppd databases ## 3. Others may performance tune things later ## 4. Databse design starts with a picture... ## Building a Data Model ## 1. Drawing a picture of the data objects for our application and then figuring out how to represent the objects and their relationships. ## 2. Basic Rule: Don't put the same string data in twice - use a relationship instead. ## 3. When there is one thing in the 'real world' there should be one copy of that thing in the database. ## There are rules about do not put the same string in twice, what if that is the users exactly want to see? ## We need to write a very efficient data model to show this information to user ## For each 'piece of info': ## 1. Is the column an onject or an attribute of another object? ## 2. Once we define objects, we need to define the relationships between objects ## Building the data Model: Consider ## 1. What is the thing that is the most essential to this application? (eg. a thing that manages tracks ) ## 2. When confirm the thing is track: Consider which of these columns are themselves tables, and which of these things are just attributes of track #### The time, ratings are part of the track (attribute of track) #### So first table is Track: Title, Rating, Len, Count ## 3. Tracks belong to albums, albums belong to artists #### What if some fields is not an attribute and also not an object? Like genre #### Consider if you change genre in one row, the album/artist will change all the genre value if genre is attribute of album or artist. #### but the track will only change one row ## Create the tables ## The end point of the arrow can be the primary key which is a unique to each row in the table, ## The start point of the arrow canbe a foreign key in one table ## The logical key is the unique thing that we might use to look up this row from the outside world. Logical Keys might be used in WHERE clause. ## Creating a Database with Primary Key, Foreign Key, Logical Key, Attributes CREATE TABLE Track( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, title TEXT, album_id INTEGER, genre_id INTEGER, len INTEGER, rating INTEGER, count INTEGER); ## Inserting Relational Data INSERT INTO table(var) VALUES('values') INSERT INTO Album(title, artist_id) VALUES('Who Mde Who', 2); INSERT INTO Album(title, artist_id) VALUES('IV', 1); ## Model relationships and connection points rather than replicating data ## Reconstructing Data with JOIN ## Relational Power #### 1. By removing the replicated data and replacing it with references to a single copy of each bit of data we build a 'web' of information that the relational database can read through very quickly - even for every large amounts of data. #### 2. Often when you want some data it comes from a number of tables linked by these foreign keys. ## The JOIN Operation #### 1. The JOIN operation links across several tables as part of a select operation. #### 2. You must tell the JOIN how to use the keys that make the connection between the tables using an ON clause. ## For example: SELECT album.title, artist.name FROM album JOIN artist ON album.artist_id=artist.id; SELECT album.title, album.artist_id, artist.name FROM album JOIN artist ON album.artist_id=artist.id; SELECT track.title, genre.name FROM track JOIN genre ON track.genre_id=genre.id; ## Joining two tables without an ON clause gives all possible combinations of rows. ## Complex Inner Join SELECT track.title, artist.name, album.title, genre.name FROM track JOIN genre JOIN album JOIN artist ON track.genre_id=genre.id AND track.album_id=album.id AND album.artist_id=artist.id; ## We can reconstruct the replication, but we don't actually store the replication. ## Worked Example: Tracks.py ## Combined the SQL and Python import xml.etree.ElementTree as ET import sqlite3 conn = sqlite3.connect('trackdb.sqlite') cur = conn.cursor() ## like a file handle ## Make some fresh tables using executescript() cur.executescript(''' DROP TABLE IF EXISTS Artist; DROP TABLE IF EXISTS Album; DROP TABLE IF EXISTS Genre; DROP TABLE IF EXISTS Track; CREATE TABLE Artist( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT ); CREATE TABLE Genre ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT UNIQUE ); CREATE TABLE Album( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, artist_id INTEGER, title TEXT UNIQUE ); CREATE TABLE Track( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, title TEXT UNIQUE, album_id INTEGER, genre_id INTEGER, len INTEGER, rating INTEGER, count INTEGER ); ''') fname = input('Enter file name: ') if (len(fname)< 1): fname = 'Library.xml' ## Example # <key>Track ID</key><integer>369</integer> # <key>Name</key><string>Another One Bites The Dust</string> # <key>Artist</key><string>Queen</string> def lookup(d, key): found = False for child in d: if found: return child.text if child.tag == 'key' and child.text == key: found = True return None stuff = ET.parse(fname) all = stuff.findall('dict/dict/dict') ## find to the third level dictionary, find all the tracks(songs include the information) print('Dict count:', len(all)) for entry in all: if ( lookup(entry, 'Track ID') is None ) : continue name = lookup(entry, 'Name') genre = lookup(entry, 'Genre' ) artist = lookup(entry, 'Artist') album = lookup(entry, 'Album') count = lookup(entry, 'Play Count') rating = lookup(entry, 'Rating') length = lookup(entry, 'Total Time') if genre is None or name is None or artist is None or album is None: continue print(name, artist, genre, album, count, rating, length) ## IGNORE in SQL means if you insert the same thing twice, ignore once with violate the UNIQUE criteria cur.execute('''INSERT OR IGNORE INTO Artist(name) VALUES ( ? )''', (artist, )) cur.execute('SELECT id FROM Artist WHERE name= ?', (artist, )) ## Get the PRIMARY KEY for this particular INSERTED new row artist_id = cur.fetchone()[0] cur.execute('''INSERT OR IGNORE INTO Genre(name) VALUES ( ? )''', (genre, )) cur.execute('SELECT id FROM Genre WHERE name= ?', (genre, )) ## Get the PRIMARY KEY for this particular INSERTED new row genre_id = cur.fetchone()[0] cur.execute('''INSERT OR IGNORE INTO Album (title, artist_id) VALUES (?, ? )''', ( album, artist_id)) ## This artist_id is just retrieved from the previous execute statement cur.execute('SELECT id FROM Album WHERE title = ?', (album, )) album_id = cur.fetchone()[0] ## This is the foreign key for other table ## REPLACE in SQL means if the UNIQUE criteria is violated, then this turns into an update cur.execute('''INSERT OR REPLACE INTO Track (title, album_id, genre_id, len, rating, count) VALUES (?, ?, ?, ?, ?, ? )''', (name, album_id, genre_id, length, rating, count ) ) conn.commit() ## Many-to-Many Relationships #### 1. Sometimes we need to model a relationship that is many-to-many (for example: books -- authors) #### 2. We need to add a 'connection' table with two foreign keys. #### 3. There is usually no separate primary key. ## Examples of Coursear ## Start with a Fresh Database CREATE TABLE User ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT, email TEXT ) CREATE TABLE Course ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, title TEXT ) ## conjunction table / connector table ## The 'PRIMARY KEY(user_id, course_id) force that the combination of (user_id and course_id) must be unique in this table CREATE TABLE Member ( user_id INTEGER, course_id INTEGER, role INTEGER, PRIMARY KEY (user_id, course_id) ) ## Insert Users and Courses INSERT INTO User (name, email) VALUES ('Jane', 'jane@tsugi.org'); INSERT INTO User (name, email) VALUES ('Ed', 'ed@tsugi.org'); INSERT INTO User (name, email) VALUES ('Sue', 'sue@tsugi.org'); INSERT INTO Course (title) VALUES ('Python'); INSERT INTO Course (title) VALUES ('SQL'); INSERT INTO Course (title) VALUES ('PHP'); ## Insert Memberships INSERT INTO Member (user_id, course_id, role) VALUES (1, 1, 1); INSERT INTO Member (user_id, course_id, role) VALUES (2, 1, 0); INSERT INTO Member (user_id, course_id, role) VALUES (3, 1, 0); INSERT INTO Member (user_id, course_id, role) VALUES (1, 2, 0); INSERT INTO Member (user_id, course_id, role) VALUES (2, 2, 1); INSERT INTO Member (user_id, course_id, role) VALUES (2, 3, 1); INSERT INTO Member (user_id, course_id, role) VALUES (3, 3, 0); SELECT User.name, Member.role, Course.title FROM User JOIN Member JOIN Course ON Member.user_id = User.id AND member.course_id = Course.id ORDER BY Course.title, Member.role DESC, User.name; ## Worked Example: roster.py: Many to Many tables import json import sqlite3 conn = sqlite3.connect('rosterdb.sqlite') cur = conn.cursor() ## Do some Setup cur.executescript(''' DROP TABLE IF EXISTS User; DROP TABLE IF EXISTS Member; DROP TABLE IF EXISTS Course; CREATE TABLE User( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT UNIQUE ); CREATE TABLE Course ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, title TEXT UNIQUE ); CREATE TABLE Member ( user_id INTEGER, course_id INTEGER, role INTEGER, PRIMARY KEY (user_id, course_id) ); ''') fname = input('Enter file name:') if len(fname) < 1: fname='roster_data_sample.json'; # [ # [ "Charley", "si110", 1 ], # [ "Mea", "si110", 0], str_data = open(fname).read() json_data = json.loads(str_data) ## Parsing the JSON data and json_data will be an array of arrays for entry in json_data: ## entry itself is a row name = entry[0]; title = entry[1]; role = entry[2]; print((name, title)) cur.execute('''INSERT OR IGNORE INTO User (name) VALUES ( ? )''', (name, )) cur.execute('SELECT id FROM User WHERE name = ?', (name, )) user_id=cur.fetchone()[0] ## sub 0 means if there are more than one thing selected, just fetch the first one ## Ignore the older duplicated record and keep the latest one cur.execute('''INSERT OR IGNORE INTO Course (title) VALUES (?)''', (title, )) cur.execute('SELECT id FROM Course WHERE title = ?', (title, )) course_id = cur.fetchone()[0] cur.execute('''INSERT OR REPLACE INTO Member (user_id, course_id, role) VALUES (?, ?, ?)''', (user_id, course_id, role)) conn.commit() ## Code Sample Worked Example: Twfriends.py import urllib.request, urllib.parse, urllib.error import twurl import json import sqlite3 import ssl ## We also need to create a hidden.py file which contains th ekeys and tokens from Twitter TWITTER_URL = 'https://api.twitter.com/1.1/friends/list.json' conn = sqlite3.connect('friends.sqlite') cur = conn.cursor() cur.execute('''CREATE TABLE IF NOT EXISTS People (id INTEGER PRIMARY KEY, name TEXT UNQIUE, retrieved INTEGER)''') cur.execute('''CREATE TABLE IF NOT EXISTS Follows (from_id INTEGER, to_id INTEGER, UNIQUE(from_id, to_id))''') ## Ignore SSL Certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE while True: acct = input('Enter a Twitter account, or quit:') if (acct = 'quit'): break if (len(acct) < 1): cur.execute('SELECT id, name FROM People WHERE retrieved = 0 LIMIT 1') ## All the new accounts we put in are the ones for which we haven't retrieved. try: (id, acct) = cur.fetchone() except: print('No unretrieved Twitter accounts found') continue else: cur.execute('SELECT id FROM People WHERE name = ? LIMIT 1', (acct, )) ## Want to find out if the acct we entered is in the DB or not try: id = cur.fetchone()[0] except: cur.execute('''INSERT OR IGNORE INTO People (name, retrieved) VALUES (?, 0)''', (acct, )) conn.commit() if cur.rowcount != 1: print('Error inserting account:', acct) continue id = cur.lastrowid url = twurl.augment(TWITTER_URL, {'screen_name': acct, 'count': '100'}) print('Retrieving account', acct) try: connection = urllib.request.urlopen(url, context = ctx) except: print('Failed to Retrieve') break data = connection.read().decode() headers = dict(connection.getheaders()) print('Remaining', headers['x-rate-limit-remaining']) try: js = json.loads(data) except Exception as err: print('Unable to parse json', err) print(data) break if 'users' not in js: print('Incorrect JSON received') print(json.dumps(js, indent = 4)) continue cur.execute('UPDATE People SET retrieved = 1 WHERE name = ?', (acct, )) countnew = 0 countold = 0 for u in js['users']: friend = u['screen_name'] print(friend) cur.execute('SELECT id FROM People WHERE name = ? LIMIT 1', (friend, )) try: friend_id = cur.fetchone()[0] countold = countold + 1 except: cur.execute('''INSERT OR IGNORE INTO People (name, retrieved) VALUES (?, 0)''', (friend, )) conn.commit() if cur.rowcount != 1: print('Error inserting account:', friend) continue friend_id = cur.lastrowid countnew = countnew + 1 cur.execute('''INSERT OR IGNORE INTO Follows (from_id, to_id) VALUES (?, ?)''', (id, friend_id)) print('New accounts=', countnew, 'revisited=', countold) conn.commit() cur.close() ## Databases and Visualization ## Geocoding ## Multiple Steps on Data Analysis ## Many Data Mining Technologies #### 1. https://hadoop.apache.org/ #### 2. http://spark.apache.org/ #### 3. https://aws.amazon.com/redshift/ #### 4. http://community.pentaho.com/ ## GeoData #### Step 1. Makes a Google Map from user entered data #### Step 2. Uses the Google Geodata API #### Step 3. Caches data in a database to avoid rate limiting and allow restarting #### Step 4. Visualized in a browser using the Google Maps API ## Worked Example: Geodata ## the code is geocode.py which use the Google places API to look places up, where.date is a file with list of organizations people type in ## The where.data is read by geoload.py import urllib.request, urllib.parse, urllib.error import http import sqlite3 import json import time import ssl import sys api_key = False ## If you have a Google Places API key, enter it here ## api_key = 'AIzaSy___IDByT70' if api_key is False: serviceurl = "http://py4e-data.dr-chuck.net/geojson?" else: serviceurl = "https://maps.googleapis.com/maps/api/place/textsearch/json?" ## Additional detail for urllib ## http.client.HTTPConnection.debuglevel = 1 conn = sqlite3.connect('geodata.sqlite') cur = conn.cursor() cur.execute(''' CREATE TABLE IF NOT EXISTS Locations (address TEXT, geodata TEXT)''') ## Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE fh = open("where.data") count = 0 for line in fh: if count > 200: print('Retrieved 200 locations, restart to retrieve more') break address = line.strip() print(' ') cur.execute("SELECT geodata FROM Locations WHERE address= ?", (memoryview(address.encode()), )) try: data = cur.fetchone()[0] print('Found in Database', address) continue except: pass parms = dict() parms['query'] = address if api_key is not False: parms['key'] = api_key url = serviceurl + urllib.parse.urlencode(parms) print('Retrieving', url) uh = urllib.request.urlopen(url, context=ctx) data=uh.read().decode() print('Retrieved', len(data), 'characters', data[:20].replace('\n', ' ')) count = count + 1 try: js = json.loads(data) except: print(data) ## We print in case unicode causes an error continue if 'status' not in js or (js['status'] != 'OK' and js['status'] != 'ZERO_RESULTS'): print("====Failure To Retrieve ====") print(data) break cur.execute('''INSERT INTO Locations (address, geodata) VALUES (?, ?)''', (memoryview(address.encode()), memoryview(data.encode()))) conn.commit() if count % 10 == 0: print('Pause for a bit...') time.sleep(5) print("Run geodump.py to read the data from the database so you can visualize it on a map") ## Geodump data: use the data in database to make it visualize import sqlite3 import json import codecs conn = sqlite3.connect('geodata.sqlite') cur = conn.cursor() cur.execute('SELECT * FROM Locations') fhand = codecs.open('where.js', 'w', "utf-8") ## open the where.js with utf-8 fhand.write("myData = [\n") count = 0 for row in cur : data = str(row[1].decode()) ## use the geodata in the sql file try: js = json.loads(str(data)) except: continue if not('status' in js and js['status'] == 'OK') : continue lat = js["results"][0]["geometry"]["location"]["lat"] lng = js["results"][0]["geometry"]["location"]["lng"] if lat == 0 or lng == 0: continue where = js['results'][0]['formatted_address'] where = where.replace("'", "") try: print(where, lat, lng) count = count + 1 if count > 1: fhand.write(",\n") output = "["+str(lat)+","+str(lng)+", '"+where+"']" fhand.write(output) except: continue fhand.write("\n];\n") cur.close() fhand.close() print(count, "records written to where.js") print("Open where.html to view the data in a browser")
c37ffc29a82131dd5e0ebe9b4f6f2351ace3cb32
rafaelpellenz/Curso-de-Python-exercicios
/ex028.py
382
3.703125
4
import random import time print('*'*45) print('** Tente adivinhar o número entre 0 e 5!!! **') print('*'*45) computador = random.randint(0,5) jogador = int(input('\nDigite um número de 0 a 5: ')) print('PROCESSANDO...') time.sleep(3) if computador == jogador: print('Você acertou!!!') else: print('Você errou, o número era {}.'.format(computador))
f777474d3d7b89ea14c01f220f59642a6c4590e5
PropeReferio/practice-2
/bubble_sort.py
202
3.890625
4
def bubble_sort(arr): for i in range(len(arr) - 1): for j in range(len(arr) - i - 1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] return arr print(bubble_sort([4,7,1,3,90,25]))
017d2ea9ebb2ef25d12e6e5a380149789276fd51
dharam1/PythonTest
/Q3.py
747
4.09375
4
def BinarySearch(sorted_list,left,right,element): if(right >= left): mid = (left + right )//2 if(sorted_list[mid] == element): return sorted_list[mid] elif(sorted_list[mid] > element): return (BinarySearch(sorted_list,left,mid-1,element)) elif(sorted_list[mid] < element): return (BinarySearch(sorted_list,mid+1,right,element)) else: return "No Element" ip_list = list(map(int,input().split())) element = int(input()) sorted_list = sorted(ip_list) unsorted_list = ip_list answer = BinarySearch(sorted_list,0,len(sorted_list)-1,element) try: if(answer != "No Element"): print(unsorted_list.index(answer)) except: print("Element Not Found")
37a90a74828a56323c2dcc0e75dfcfce94c42e89
Sathyasree-Sundaravel/sathya
/Sort_the_given_words_in_ascending_order_based_on_its_length.py
182
3.96875
4
#Sort the given words in ascending order based on its length s=[] a=int(input()) b=input().split() for i in b: s.append(i) s.sort() s.sort(key=len) for i in s: print (i,end=" ")
61e05ddce9bc09f0f81f3442a1ca80b544608ad8
jmwoloso/Python_3
/Lesson 2 - Converting Data Into Structured Objects/project/attempt_2/test_coconuts.py
2,166
4.25
4
#!/usr/bin/python # # Test Suite For coconuts.py # test_coconuts.py # # Created by: Jason M Wolosonovich # 6/04/2015 # # Lesson 2 - Project Attempt 2 """ test_coconuts.py: Test suite for coconuts.py @author: Jason M. Wolosonovich """ import unittest from coconuts import South_Asian, Middle_Eastern, American, Inventory class TestCoconuts(unittest.TestCase): def test_weight(self): """ Tests that different coconut types each have a different weight """ # create a coconut of each type self.nuts = [variety() for variety in [Middle_Eastern, South_Asian, American]] # check that weights are as expected self.weights = [2.5, 3.0, 3.5] for i in range(0,3): self.assertEqual(self.nuts[i].weight, self.weights[i], "The weight is wrong") def test_total_weight(self): """ Tests that the sum of a specified number of coconuts of each type returned matches the expected total """ varieties = [variety() for variety in [Middle_Eastern, South_Asian, South_Asian, American, American, American]] self.inventory = Inventory() for variety in varieties: self.inventory.add_coconut(variety) self.assertEqual(self.inventory.total_weight(), 'Total weight: 19.0', "Your total weight is wrong") def test_string_attribute_errors(self): """ Tests that a string passed as a coconut to the Inventory class throws an AttributeError """ self.inventory = Inventory() with self.assertRaises(AttributeError): self.inventory.add_coconut('south asian') if __name__=="__main__": unittest.main()
d410f6194d7cc7be681b8d8a6f2f04806a36daa1
rahmahkn/TravellingSalesmanProblem
/src/processing/element/Path.py
802
3.78125
4
class Path(): def __init__(self, coordinateList, indexList): self.coordinates = coordinateList # list of Coordinates that make the path self.index = indexList # list of Index that correspond to coordinateList # Function to count distance of a path from first to last vertex def countDistance(self): dist = 0 for i in range (len(self.index)-1): dist += self.coordinates[self.index[i]].eucDistance(self.coordinates[self.index[i+1]]) return dist # Function to get path in string def pathToString(self): result = '' for i in range (len(self.index)): result += self.coordinates[self.index[i]].name if (i != len(self.index)-1): result += ("->") return result
d1dca23c414d69b4382d87148964df032fcbe083
yuntaochn/DsaProject
/sort/sort.py
667
3.796875
4
""" 排序算法实现 """ """ 插入排序 直接插入 折半插入排序 希尔排序 """ def insert_sort(li): for i in range(2, len(li)): if li[i] < li[i-1]: li[0] = li[i] # 复制为哨兵 li[i] = li[i-1] j = i-1 while li[0] < li[j]: li[j+1] = li[j] j = j-1 li[j+1] = li[0] return li def b_insert_sort(li): print(li) return li def shell_sort(li, dk): # dk为步长因 return li if __name__ == '__main__': test_li = [0, 3, 12, 22, 33, 55, 43, 32, 21, 5, 1, 6, 4, 9] li_res = insert_sort(test_li) print(li_res)
159967f4e0ef641d1e8f579e0273530bf25b39f5
kwccoin/MLAlgorithm
/cracking_coding_interview/DataStructures/array_left_rotation.py
281
3.609375
4
# Sample input # 5 4 # 1 2 3 4 5 # Sample Output # 5 1 2 3 4 def array_left_rotation(a,n,k): return (a[k:] + a[0:k]) def array_right_rotation(a,n,k): return (a[k-1:] + a[0:k-1]) a =[1, 2, 3, 4, 5] k = 4 n = 5 print ' '.join(map(str,array_left_rotation(a,n,k)))
41158b60af462f88a5c6f56e2f1c4f063ba29293
karakose77/complete-python-masterclass-exercises
/mk004-reaction_game.py
1,474
3.984375
4
def reaction_game(): """ A game measuring the players reaction time in seconds. """ import time import random print("The epoch on this system starts at " + time.strftime("%c", time.gmtime(0))) print("The current timezone is " + f"{time.tzname[0]} with an offset of {time.timezone}") if time.daylight != 0: print("\tDaylight Saving Time is effect for this location.") print("\tThe DST timezone is " + time.tzname[1]) print("Local time is " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) print("UTC time is " + time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())) print(time.time()) print("Year:", time.localtime()[0]) input("Press enter to start.") time.sleep(random.randint(1, 3)) start_time_t = time.time() start_time_p = time.perf_counter() start_time_m = time.monotonic() start_time_pt = time.process_time() input("Press enter to stop.") stop_time_t = time.time() stop_time_p = time.perf_counter() stop_time_m = time.monotonic() stop_time_pt = time.process_time() print(f"Your reaction time was {stop_time_t - start_time_t} seconds.") print(f"Your reaction perf time was {stop_time_p - start_time_p} seconds.") # Best function for reaction game. print("Your reaction monotonic time was " + f"{stop_time_m - start_time_m} seconds.") print("Your reaction process time is " + f"{stop_time_pt - start_time_pt} seconds.") reaction_game()
5aa50711fd20b8e85eae1d461da04c5bb93ff286
Nipun2016/Core-Python-Training
/Exercises/Yogendra/OOP/p5.py
727
3.734375
4
class Student: def __init__(self,nm,rno): self.nm=nm self.rno=rno def get_details(self): return self.nm,self.rno def sort(lst): lst.sort() return(lst) if __name__=="__main__": lst=[] ch='y' while ch=='y': name=input("enter student name: ") roll_no=input("enter student roll_no: ") #lst.append((name,roll_no)) stud=Student(name,roll_no) lst.append((stud.get_details())) #lst.append((stud)) #lst.append((stud.name,stud.roll_no)) #stud.get_details(lst) ch=input("do u wish to continue: enter y for continue") print(lst) print(sort(lst))
fc1316889c4c4c18ad4d3ddc8cee5bf50a16808f
zguy85/python
/example.py
309
3.875
4
import time print("Welcome") time.sleep(2) print("What is your name?") name = input() if name != "": print("Hello, " + name) print("It is nice to meet you.") else: print("I'm sorry. I did not catch your name.") print("Thank you for trying out this sample code.") print("Check my page later for more.")
225c36d7ac11aedbb8f2e8df673358151815b796
qiyundai/is_even
/is_even.py
211
4.09375
4
def mod(a, b): return a - a // b * b def is_even(num): if mod(num, 2) == 0: print("it's even!") else: print("No it ain't") youtype = input("Enter a number: ") is_even(int(youtype))
24b52a65ee3df62d92fb76d17a1507103306b75f
samoel07/desafios-python
/DESAFIO 36.py
552
3.609375
4
pessoas = ['samoel', 'carlos', 'joao'] for pessoas in pessoas: print(pessoas.title() + ', voces vao ao jogo?') print(pessoas.title() + ': talvez nao, o jogo nao vai ser muito bom.\n') print(pessoas.title() + ':mais tarde darei a respostas.') #cm o \n fica desorganizado. pessoas = ['samoel', 'carlos', 'joao'] for pessoas in pessoas: print(pessoas.title() + ', voces vao ao jogo?') print(pessoas.title() + ': talvez nao, o jogo nao vai ser muito bom.') print(pessoas.title() + ':mais tarde darei a respostas.') #sem o \n fica normal.
1e6219f1866d7a8f10b6bd2317d0153d5465153b
shivam221098/max-min
/max & min.py
756
3.6875
4
array = [1, 2, 3, 4, 10, 100, 8, 4, 2, 0] temp_array = list(set(array)) mx_array = [] index = 0 for j in range(4): # 4 because i want 4 maximums from array mx = 0 for i in range(len(temp_array)): # finding maximum elements if temp_array[i] >= mx: mx = temp_array[i] index = i mx_array.append(temp_array.pop(index)) print(mx_array) # similarly for minimum elements temp_array = list(set(array)) mn_array = [] index = 0 for j in range(4): # 4 because i want 4 minimums from array mn = 10000000000 for i in range(len(temp_array)): # finding minimum elements if temp_array[i] <= mn: mn = temp_array[i] index = i mn_array.append(temp_array.pop(index)) print(mn_array)
8361b32facb2165a07c5c49951b90cf98132bcb0
luckkyzhou/leetcode
/1_3.py
323
3.5625
4
# -*- coding: utf-8 -*- def twoSum(nums:list,target:int): hashmap = {} for index,num in enumerate(nums): hashmap[num] = index for i,num in enumerate(nums): j = hashmap.get(target - num) if j != None: return [i,j] if __name__ == '__main__': print(twoSum([2,7,11,15],9))
654972cc3203296f4e2dc77ceec660c9e3605061
githubjyotiranjan/pytraining
/data/all-pratic/VivekKumar_DCC/python_2/while.py
117
3.8125
4
count=int(input('enter the count=')) vals = 1; while(vals <= count): a = '*' * vals vals = vals+1 print(a)
35ed9b0cbedce779b6e9f8f239337a5014410015
gabriellaec/desoft-analise-exercicios
/backup/user_079/ch23_2019_09_04_13_37_51_120993.py
193
3.6875
4
def verifica_idade(x): y = float(input('idade: ') if y<19 : print('Não está liberado') elif 21<y>17 : print('Liberado BRASIL') elif y<20: print('Liberado EUA e BRASIL') return y
6966f616449a932210bbb706c89fb133081a8a5a
samuelmgalan/pythonchallenge
/15.py
416
3.890625
4
#!/usr/bin/env python3 # http://www.pythonchallenge.com/pc/return/uzi.html import datetime import calendar years = [x for x in range(1582, 1997)] for i in range(len(years)): if datetime.datetime(years[i], 1, 1).weekday() == 3 and calendar.isleap(years[i]): # leap years since the begining of the Gregorian Calendar print(str(years[i])) # 1756 # todo: buy flowers for tomorrow <- 27/01/1986 Mozart's birthday
1687db784c79e4b7dcd95d5dc5fad1a081b2495f
durandal42/projects
/spelltower/tower.py
3,476
3.609375
4
class Cell: value = '.' min_length = 0 def __init__(self, value, min_length=0): self.value = value self.min_length = min_length def __str__(self): return value class Tower: cells = {} width = 10 def __init__(self, width=None, lines=None): self.cells = {} self.width = width if not lines: return for line in lines: self.append(line) def append(self, line): print 'adding tower row:',line for x,y in sorted(self.cells.keys()): self.cells[x-1,y] = self.at(x,y) del self.cells[x,y] y = 0 for c in line.rstrip(): if c.isdigit(): y -= 1 self.cells[13,y].min_length = int(c) elif c != ' ': self.cells[13,y] = Cell(c.upper()) y += 1 def occupied(self, x, y): return (x,y) in self.cells def at(self, x, y): if self.occupied(x,y): return self.cells[x,y] else: return None def copy(self): result = Tower() result.cells = self.cells.copy() result.width = self.width return result def __str__(self): return self.show() def show(self, play=None): touched = play and play.touched() or set() destroyed = self.find_destroyed(touched) result = '+' + ' - '*self.width + '+\n' for x in range(14): result += '|' for y in range(self.width): value = ' ' frame = ' %s ' if self.occupied(x,y): cell = self.at(x,y) value = cell.value if touched and (x,y) in touched: frame = '[%s]' elif destroyed and (x,y) in destroyed: frame = '>%s<' result += frame % value result += '|\n' result += '+' + ' - '*self.width + '+' return result def export(self): result = '' for x in range(14): line = '' for y in range(self.width): if self.occupied(x,y): cell = self.at(x,y) line += cell.value if cell.min_length > 0: line += str(cell.min_length) else: line += ' ' if line == ' '*self.width: continue result += line result += '\n' return result def update(self, play): for x,y in sorted(self.find_destroyed(play.touched())): self.destroy(x,y) def find_destroyed(self, touched): destroyed = touched.copy() for x,y in touched: for dx,dy in [(-1,0), (1,0), (0,-1), (0,1)]: if (self.occupied(x+dx, y+dy) and (len(touched) >= 5 or self.at(x+dx, y+dy).value == '.')): destroyed.add((x+dx,y+dy)) for x,y in touched: if self.at(x,y).value in ['Z', 'Q', 'J', 'X']: for y2 in range(self.width): destroyed.add((x,y2)) return destroyed def destroy(self, x,y): while x >= 0: if self.occupied(x,y): del self.cells[x,y] if self.occupied(x-1,y): self.cells[x,y] = self.at(x-1,y) x -= 1
4ab553a705789fec9821aaa44266c99bf1947054
aSTRonuun/LIP-Codes
/02-Analisar-lexemas/Analise Lexica/exercicio03-ponto-flutante.py
127
3.578125
4
import re code = input() pattern = r'(\d+\.)|(\.\d+)' for s in code.split(): if re.findall(pattern, s): print(s)
ecaed602d70c778ad160ea231fd0d28c4fb178e8
janeon/automatedLabHelper
/testFiles/imageEdit/imageEdit7.py
8,949
3.78125
4
import picture2 import math def editOptions(Origpic) : done = 0 pic1, h, w = picCopy(Origpic) try: while done == 0 : print "There are many editing options, please choose one of the following:" print "1 for Flip Horizontally" print "2 for Mirror Horizontally" print "3 for Scroll Horizontally" print "4 for Make Negative" print "5 for Make Grayscale" print "6 for Cycle Color Channels" print "7 for Zoom" print "8 for Posterize" print "9 for Change Brightness" print "10 for Increase Contrast" print "11 for Blur" print "12 Rotate 180 Degrees" print "13 for dots" print "14 for Fade" inpu = eval(raw_input("Editing option number: " )) if inpu == 1 : flip(pic1, h, w) if inpu == 2 : mirror(pic1, h, w) if inpu == 3 : scroll(pic1, h, w) if inpu == 4 : negative(pic1, h, w) if inpu == 5 : grayscale(pic1, h, w) if inpu == 6 : cycle(pic1, h, w) if inpu == 7 : zoom(pic1, h, w) if inpu == 8 : poster(pic1, h, w) if inpu == 9 : bright(pic1, h, w) if inpu == 10 : contrast(pic1, h, w) if inpu == 11: blur(pic1, h, w) if inpu == 12: rotate(pic1, h, w) if inpu == 13 : dots(pic1, h, w) if inpu == 14 : cool(pic1, h, w) ans = raw_input("Would you like to conintue editing this picture? (yes or no) : " ) answ = ans.lstrip() answr = answ.lower() if str(answr[0]) == "y": done = 0 else: done = done +10 print "Hope you have enjoyed yourself!" except IndexError : print "" print "Oops. I don't think you answered the question correctly." except SyntaxError : print "" print "Oops. Make sure you are entering a number." except NameError: print "" print "Oops. Make sure you are entering a number." def cool(pic1, h, w): pic11, h, w = picCopy(pic1) for x in range(w-1): for y in range(h-1): r, g, b = pic11.getPixelColor(x, y) r, g, b = staybetween(r, g, b) pic1.setPixelColor(x, y, r+(x//10)*8, g +(x//30)*8, b + (x//30)*8) for y in range(h-1): for x in range(w-1): r, g, b = pic11.getPixelColor(x, y) r, g, b = staybetween(r, g, b) pic1.setPixelColor(x, y, r+(y//10)*8, g +(y//30)*8, b + (y//30)*8) pic1.display() def rotate(pic1, h, w): rocopy, h, w = picCopy(pic1) for x in range(w-1): for y in range(h-1): r, g, b = rocopy.getPixelColor(x, y) pic1.setPixelColor(x, h-y-1, r, g, b) pic1.display() def blur(pic1, h, w): blurcopy, h, w = picCopy(pic1) for y in range(1, h-2): for x in range(1, w-2): r, g, b = blurcopy.getPixelColor(x-1, y-1) a, c, d = blurcopy.getPixelColor(x, y-1) e, f, g = blurcopy.getPixelColor(x+1, y-1) i, j, k =blurcopy.getPixelColor(x-1, y) l, m, n =blurcopy.getPixelColor(x-1, y+1) o, p, q =blurcopy.getPixelColor(x+1, y) s, t, u =blurcopy.getPixelColor(x, y+1) v, wo, z =blurcopy.getPixelColor(x+1, y+1) red = (r+a+e+i+l+o+s+v)//8 green = (g+c+f+j+m+p+t+wo)//8 blue = (b+d+g+k+n+q+u+z)//8 pic1.setPixelColor(x, y, red, green, blue) pic1.display() def contrast(pic1, h, w): for y in range(h-1): for x in range(w-1): r, g, b = pic1.getPixelColor(x, y) r = r+(r-128)*2 g = g+(g-128)*2 b = b+(b-128)*2 r, g, b = staybetween(r, g, b) pic1.setPixelColor(x, y, r, g, b) pic1.display() def bright(pic1, h, w): change = eval(raw_input("How much would you like to change the brightness(positive or negative integer)?: " )) for y in range(h-1): for x in range(w-1): r, g, b = pic1.getPixelColor(x, y) r = r+change g = g+change b = b+change r, g, b = staybetween(r, g, b) pic1.setPixelColor(x, y, r, g, b) pic1.display() def staybetween(r, g, b): if r>255 : r = 255 if g >255: g = 255 if b >255 : b = 255 if r<0: r =0 if g <0: g = 0 if b <0: b = 0 else: r = r g = g b = b return r, g, b def poster(pic1, h, w): for y in range(h-1): for x in range(w-1): r, g, b = pic1.getPixelColor(x,y) if (r%32) >= 16 : r = r + (r%32) if r%32 < 16: r = r -(r%32) if g%32 >= 16 : g = g + (g%32) if g%32 < 16 : g = g-(g%32) if b%32 >= 16 : b= b + (b%32) if b%32 < 16: b = b - (b%32) pic1.setPixelColor(x, y, r, g, b) pic1. display() def zoom(pic1, h, w): zoomcopy, h, w = picCopy(pic1) for y in range(h-1): for x in range(w-1): r, g, b = zoomcopy.getPixelColor((w//4 + x//2), (h//4 + y//2)) pic1.setPixelColor(x, y, r, g, b) pic1.display() def dots(pic1, h, w): dotspic, h, w = picCopy(pic1) for i in range(h-1): for j in range(w-1): pic1.setPixelColor(j, i, 205, 197, 191) for y in range(0, h-1, 2): for x in range(0, w-1, 2): r, g, b = dotspic.getPixelColor(x, y) pic1.setPixelColor(x, y, r, g, b) pic1.display() def cycle(pic1, h, w): for y in range(h-1): for x in range(w-1): r, g, b = pic1.getPixelColor(x, y ) pic1.setPixelColor(x,y, b, r, g) pic1.display() def grayscale(pic1, h, w) : for y in range(h-1): for x in range(w-1) : r, g, b = pic1.getPixelColor(x, y) color = ((r+b+g)/3) pic1.setPixelColor(x, y, color, color, color) pic1.display() def negative(pic1, h, w) : for y in range(h-1) : for x in range(w-1) : r, g, b = pic1.getPixelColor(x, y) pic1.setPixelColor(x, y, 255-r, 255-g, 255-b) pic1.display() def scroll(pic1, h, w) : distance = eval(raw_input("By how many pixels would you like to shift your image?: ")) scrollcopy, h, w = picCopy(pic1) for y in range(h-1): for x in range(w-1): if x > distance: r, g, b = scrollcopy.getPixelColor(x, y) pic1.setPixelColor(x-distance, y, r, g, b) else: r, g, b = scrollcopy.getPixelColor(x, y) pic1.setPixelColor(w-x-1, y, r, g, b) pic1.display() def flip(pic1, h, w) : flipcopy, h, w = picCopy(pic1) for y in range(h-1): for x in range(w/2): r, g, b = pic1.getPixelColor(w-1-x, y) pic1.setPixelColor(x, y, r, g, b) for y in range(h-1) : for x in range(w/2): r, g, b = flipcopy.getPixelColor(x, y) pic1.setPixelColor(w-1-x, y, r, g, b) pic1.display() def mirror(pic1, h, w) : for y in range(h-1): for x in range(w-1): r, g, b = pic1.getPixelColor(x, y) pic1.setPixelColor(w-1-x, y, r, g, b) pic1.display() def picCopy(Origpic): h = Origpic.getHeight() w = Origpic.getWidth() pitcha = picture2.Picture(w, h) for y in range(0, h-1): for x in range(0, w-1): r, g, b = Origpic.getPixelColor(x, y) pitcha.setPixelColor(x, y, r, g, b) return pitcha, h, w def Origpic() : try: print "Welcome to my picture editing program!" filename = raw_input("Please enter the filename for the image you would like to edit (.bmp): " ) Origpic = picture2.Picture(filename) Origpic.display() print() print "This is the image you have selected." editOptions(Origpic) except IOError : print "I'm sorry we couldn't find that file" Origpic()
8c7e406abdc232154c59168d84e65a76472ec9d4
SerhijZhenzhera/zhzhs_python
/03 lesson/home_work_3d_fixed_Serhij_Zhenzhera.py
1,328
4.125
4
''' Задание 1. Получить от пользователя его номер телефона, проверить подходит ли номер под форматы +380_________ (прочерки - любая цифра) 0_________ (например 0931233232) 0__ ___ __ __ (пробелы именно пробелы и телефон например 095 321 12 21) Если номер введен верно - похвалите человека. Если нет - поругайте ''' while True: number_tel = input('Введите номер телефона: ') number_tel = ''.join(number_tel.split()) if number_tel[:1] != '0': print('Начните номер с нуля') continue elif len(number_tel) > 10: print('Номер должен состоять из 10 цифр') continue elif len(number_tel) < 10: print('Вы пропустили несколько цифр') continue else: number_tel = number_tel[1:10] if number_tel.isnumeric(): print('Спасибо! Вы ввели номер: +380', number_tel[:2], number_tel[2:5], number_tel[5:7], number_tel[7:9]) else: print('Вводите только цифры, пожалуйста')
9f240c000890cff3fc16f7a402015d125ce72ceb
bd52622020/appSpaceAden
/Task4_Python.py
873
4.09375
4
# task 7 # 1) write a python function that accepts a string and calculates the number of upper and case and lower case letters # def string_test(s): # d={"UPPER_CASE":0, "LOWER_CASE":0} # for c in s: # if c.isupper(): # d["UPPER_CASE"]+=1 # elif c.islower(): # d["LOWER_CASE"]+=1 # else: # pass # print ("Original String : ", s) # print ("No. of Upper case characters : ", d["UPPER_CASE"]) # print ("No. of Lower case Characters : ", d["LOWER_CASE"]) # string_test('I Love SoftwaRe') # 2) write a python function that prints out the first n rows of a pascals triangle # def pascal_triangle(n): # trow = [1] # y = [0] # for x in range(max(n,0)): # print(trow) # trow=[l+r for l,r in zip(trow+y, y+trow)] # return n>=1 # pascal_triangle(10)
5e4010fb969a1702d8309518b783f4bdf8d29444
choijaehoon1/backjoon
/greedy/test04_02.py
587
3.6875
4
# 최소값을 만들려면 -를 기준으로 괄호를 치면 된다. arr = input().split('-') answer = [] for i in arr: inner_arr = i.split('+') # +가 없든 있든 그냥 괄호를 기준으로 잘라서 num = 0 # 리스트에 우선 다 넣음 for j in inner_arr: num += int(j) # 괄호 덩어리안에 거 더한 후 answer.append(num) # 더해줌 # print(answer) result = answer[0] # 맨 앞에 숫자는 더 해주고 for i in range(1,len(answer)):# 나머지는 다 빼줌 result -= answer[i] print(result)
8f19345c8bb8ee640a2b9084179459d5027a4edb
hongweihsu/NATO-alphabet-project
/main.py
417
4.21875
4
import pandas # TODO 1. Create a dictionary in this format: data = pandas.read_csv("nato_phonetic_alphabet.csv") df = pandas.DataFrame(data) data_dict = {v.letter: v.code for (k, v) in df.iterrows()} print(data_dict) # TODO 2. Create a list of the phonetic code words from a word that the user inputs. word = input("Enter a word: ").upper() output_list = [data_dict[letter] for letter in word] print(output_list)
04a71a25ec3382e3ecee16bdd308ab77866f25de
SnShine/Data_Encryption_Standard-Freelance
/new_main.py
14,543
3.75
4
import sys, time #to know which python version is installed pythonVersion = sys.version_info[0] class base(object): def __init__(self): #set the size of the block to encrypt/decrypt the data self.block_size = 8 def getKey(self): """returns key used to encrypt/decrypt""" return self.__key def setKey(self, key): """will set the key used for encrypting/decrypting""" self.__key = key def padData(self, data): #length of string to be added to data to make its length a multiple of 8 pad_len = 8 - (len(data) % self.block_size) #add characters if python version is 2 if pythonVersion < 3: data += pad_len * chr(pad_len) #add bytes of data if python version using is 3 else: data += bytes([pad_len] * pad_len) return data def unpadData(self, data): #used for unpadding the data if not data: return data #use the function ord to return unicode integer while using python version 2 if pythonVersion< 3: pad_len = ord(data[-1]) #python 3 automatically converts it into integer else: pad_len = data[-1] #then remove the extra data we attached at the end of the string data = data[:-pad_len] return data class des(base): #initial permutation(IP) ip = [57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7, 56, 48, 40, 32, 24, 16, 8, 0, 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6 ] #final permutation(FP) fp = [ 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25, 32, 0, 40, 8, 48, 16, 56, 24 ] #expansion function table(E) expansion_table = [ 31, 0, 1, 2, 3, 4, 3, 4, 5, 6, 7, 8, 7, 8, 9, 10, 11, 12, 11, 12, 13, 14, 15, 16, 15, 16, 17, 18, 19, 20, 19, 20, 21, 22, 23, 24, 23, 24, 25, 26, 27, 28, 27, 28, 29, 30, 31, 0 ] #32-bit permutation function P used on the output of the S-boxes p = [ 15, 6, 19, 20, 28, 11, 27, 16, 0, 14, 22, 25, 4, 17, 30, 9, 1, 7, 23, 13, 31, 26, 2, 8, 18, 12, 29, 5, 21, 10, 3, 24 ] #PC1 for des pc1 = [56, 48, 40, 32, 24, 16, 8, 0, 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 60, 52, 44, 36, 28, 20, 12, 4, 27, 19, 11, 3 ] #PC2 for des pc2 = [ 13, 16, 10, 23, 0, 4, 2, 27, 14, 5, 20, 9, 22, 18, 11, 3, 25, 7, 15, 6, 26, 19, 12, 1, 40, 51, 30, 36, 46, 54, 29, 39, 50, 44, 32, 47, 43, 48, 38, 55, 33, 52, 45, 41, 49, 35, 28, 31 ] #S-boxes sbox = [ #Sbox1 [14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13], #Sbox2 [15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9], #Sbox3 [10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12], #Sbox4 [7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14], #Sbox5 [2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3], #Sbox6 [12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13], #Sbox7 [4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12], #Sbox8 [13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11], ] #left-rotations in key-schedule left_rotations = [ 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 ] #type of crypting ENCRYPT= 0x00 DECRYPT= 0x01 #initialisation def __init__(self, key): base.__init__(self) self.key_size = 8 #left and right parts of string self.L = [] self.R = [] #16 sub-keys of 48 bits each self.Kn = [[0]* 48]* 16 self.final = [] self.setKey(key) def setKey(self, key): """will set the key used for encrypting/decrypting""" base.setKey(self, key) self.create_sub_keys() def String_to_BitList(self, data): """turn the string data, into a list of bits""" if pythonVersion < 3: #turn the strings into integers. python3 uses a bytes #class, which already has this behaviour. data= [ord(c) for c in data] l= len(data) * 8 result= [0] * l pos= 0 for ch in data: i = 7 while i>= 0: if ch& (1<< i)!= 0: result[pos]= 1 else: result[pos]= 0 pos+= 1 i-= 1 return result def BitList_to_String(self, data): """turn the list of bits into a string""" result = [] pos = 0 c = 0 while pos < len(data): c+= data[pos]<< (7- (pos% 8)) if (pos% 8)== 7: result.append(c) c= 0 pos+= 1 if pythonVersion< 3: return ''.join([ chr(c) for c in result ]) else: return bytes(result) def permutate(self, table, block): """Permutate this block with the specified table""" return list(map(lambda x: block[x], table)) def create_sub_keys(self): """create 16 subkeys of 48 bits of length from given key of length of 56 bits""" key = self.permutate(des.pc1, self.String_to_BitList(self.getKey())) i = 0 #split the key into left and right sections, each of 28 bits of length self.L= key[:28] self.R= key[28:] print("\nPrinting all 16 sub-keys used in 16 stages...") while i< 16: j= 0 #perform left shifts. left most bit while j< des.left_rotations[i]: self.L.append(self.L[0]) del self.L[0] self.R.append(self.R[0]) del self.R[0] j+= 1 #create one of the 16 subkeys through pc2 permutation self.Kn[i]= self.permutate(des.pc2, self.L + self.R) print "\tSub-Key "+str(i)+" :", ''.join(self.BitList_to_String(self.Kn[i])) i+= 1 #important part of encryption algorithm def des_crypt(self, block, crypt_type): """ Takes a block of data (8 bytes in ths case) as input Runs bit-manipulation on block of data following DES algorithm (16 stages). """ #permutating with initial permutation block block = self.permutate(des.ip, block) #dividing into left and right blockes self.L = block[:32] self.R = block[32:] #encryption starts from Kn[1] through to Kn[16] if crypt_type== des.ENCRYPT: iteration= 0 iteration_change= 1 #decryption starts from Kn[16] down to Kn[1] else: iteration= 15 iteration_change= -1 i= 0 print("\tPrinting value of current block in all of 16 stages...") while i< 16: #get a copy of R[i-1] which will later become L[i] #this is why this method is called as criss-cross method tempR= self.R[:] #permutate R[i-1] with expansion table self.R= self.permutate(des.expansion_table, self.R) #exclusive or R[i-1] with K[i], create B[1] to B[8] whilst here self.R= list(map(lambda x, y: x ^ y, self.R, self.Kn[iteration])) B= [self.R[:6], self.R[6:12], self.R[12:18], self.R[18:24], self.R[24:30], self.R[30:36], self.R[36:42], self.R[42:]] #permutate B[1] to B[8] using the S-Boxes j= 0 Bn= [0]* 32 pos= 0 while j< 8: #work out the offsets m= (B[j][0]<< 1)+ B[j][5] n= (B[j][1]<< 3)+ (B[j][2]<< 2) + (B[j][3]<< 1) + B[j][4] #find the permutation value v= des.sbox[j][(m<< 4)+ n] #turn value into bits, add it to result: Bn Bn[pos]= (v& 8)>> 3 Bn[pos+ 1]= (v& 4)>> 2 Bn[pos+ 2]= (v& 2)>> 1 Bn[pos+ 3]= v& 1 pos += 4 j += 1 #permutate the concatination of B[1] to B[8] (Bn) self.R = self.permutate(des.p, Bn) #XOR with L[i-1] self.R = list(map(lambda x, y: x ^ y, self.R, self.L)) #new L[i] is R[i-1] self.L = tempR i+= 1 iteration+= iteration_change print "\tStage "+str(i)+" :", ''.join(self.BitList_to_String(self.permutate(des.fp, self.R+ self.L))) # Final permutation of R[16] and L[16] self.final= self.permutate(des.fp, self.R + self.L) #print("final", ''.join(self.BitList_to_String(self.final))) return self.final #data to be encrypted/decrypted def crypt(self, data, crypt_type): """ Crypt the data in blocks, running it through des_crypt() If the input data has more bytes than 8, we will divide it into blocks with 8 bytes of data. Then we will run des_crypt function on every block of data to encryp/ decrypt the data. """ #Error, check the data if not data: return '' if len(data)% self.block_size!= 0: #decryption works only on data blocks of 8 bytes of length. if crypt_type== des.DECRYPT: raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n.") if not self.getPadding(): raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n. Try setting the optional padding character") else: data+= (self.block_size - (len(data) % self.block_size)) * self.getPadding() #split the data into blocks, crypting each one seperately i = 0 dict = {} result = [] while i < len(data): block = self.String_to_BitList(data[i:i+8]) print("\nCurrent block: "+str(i/8)) processed_block = self.des_crypt(block, crypt_type) print "\tProcessed block "+str(i/8)+": ", ''.join(self.BitList_to_String(processed_block)) #append the resulting crypted block to our list result.append(self.BitList_to_String(processed_block)) i += 8 #return the full crypted string if pythonVersion < 3: return ''.join(result) else: return bytes.fromhex('').join(result) def encrypt(self, data): """ """ data = self.padData(data) return self.crypt(data, des.ENCRYPT) def decrypt(self, data): """ """ data = self.crypt(data, des.DECRYPT) return self.unpadData(data) if __name__== "__main__": def detectUnicode(data): if pythonVersion < 3: if isinstance(data, unicode): raise ValueError("Only works with bytes, not Unicode strings!") else: if isinstance(data, str): # Only accept ascii unicode values. try: return data.encode('ascii') except UnicodeEncodeError: pass raise ValueError("Only works with encoded strings, not with Unicode strings!") return data if len(sys.argv)!= 3: print("Error occured! See below how to use.\nUsage: python main.py <message to encrypt in quotes> <key to use in quotes>") sys.exit() out_file= open("out.txt", "w") #sys.srgv[1] is data #sys.argv[2] is key data= sys.argv[1] data= detectUnicode(data) key= sys.argv[2] if len(key) != 8: print("Invalid key size. The length of key should be 8 bytes") sys.exit() key= detectUnicode(key) k= des(sys.argv[2]) #encrypting the data and saving to enc_data enc_data= k.encrypt(data) print("\nEncrypted data...") print(enc_data) out_file.write(enc_data) print("\n") out_file.write("\n") #decrypting the encrypted data dec_data= k.decrypt(enc_data) print("\nDecrypted data...") print(dec_data) out_file.write(dec_data) print("\n") out_file.write("\n") out_file.close()
b1293a2504e71d61d93b45e0590473311ad776bd
leiverandres/Compiler
/check.py
20,707
3.671875
4
# check.py # -*- coding: utf-8 -*- ''' Proyecto 3 : Chequeo del Programa ================================= En este proyecto es necesario realizar comprobaciones semánticas en su programa. Hay algunos aspectos diferentes para hacer esto. En primer lugar, tendrá que definir una tabla de símbolos que haga un seguimiento de declaraciones de identificadores previamente declarados. Se consultará la tabla de símbolos siempre que el compilador necesite buscar información sobre variables y declaración de constantes. A continuación, tendrá que definir los objetos que representen los diferentes tipos de datos incorporados y registrar información acerca de sus capacidades. Revise el archivo types.py. Por último, tendrá que escribir código que camine por el AST y haga cumplir un conjunto de reglas semánticas. Aquí está una lista completa de todo los que deberá comprobar: 1. Nombres y símbolos: Todos los identificadores deben ser definidos antes de ser usados. Esto incluye variables, constantes y nombres de tipo. Por ejemplo, esta clase de código genera un error: a = 3; // Error. 'a' no está definido. var a int; Nota: los nombres de tipo como "int", "float" y "string" son nombres incorporados que deben ser definidos al comienzo de un programa (función). 2. Tipos de constantes A todos los símbolos constantes se le debe asignar un tipo como "int", "float" o "string". Por ejemplo: const a = 42; // Tipo "int" const b = 4.2; // Tipo "float" const c = "forty"; // Tipo "string" Para hacer esta asignación, revise el tipo de Python del valor constante y adjunte el nombre de tipo apropiado. 3. Chequeo de tipo operación binaria. Operaciones binarias solamente operan sobre operandos del mismo tipo y produce un resultado del mismo tipo. De lo contrario, se tiene un error de tipo. Por ejemplo: var a int = 2; var b float = 3.14; var c int = a + 3; // OK var d int = a + b; // Error. int + float var e int = b + 4.5; // Error. int = float 4. Chequeo de tipo operador unario. Operadores unarios retornan un resultado que es del mismo tipo del operando. 5. Operadores soportados Estos son los operadores soportados por cada tipo: int: binario { +, -, *, /}, unario { +, -} float: binario { +, -, *, /}, unario { +, -} string: binario { + }, unario { } Los intentos de usar operadores no soportados debería dar lugar a un error. Por ejemplo: var string a = "Hello" + "World"; // OK var string b = "Hello" * "World"; // Error (op * no soportado) 6. Asignación. Los lados izquierdo y derecho de una operación de asignación deben ser declarados del mismo tipo. Los valores sólo se pueden asignar a las declaraciones de variables, no a constantes. Para recorrer el AST, use la clase NodeVisitor definida en pasAST.py. Un caparazón de código se proporciona a continuación. ''' import sys, re, string from errors import error from pasAST import * import paslex import pasAST #=============================================================================== # Types declaration #=============================================================================== class MpasType(object): ''' Clase que representa un tipo en el lemguaje mpascal. Los tipos son declarados como instancias singleton de este tipo. ''' def __init__(self, name, bin_ops=set(), un_ops=set()): ''' Deber� ser implementada por usted y averiguar que almacenar ''' self.name = name self.bin_ops = bin_ops self.un_ops = un_ops int_type = MpasType("int", set(('+', '-', '*', '/', '<=', '<', '==', '!=', '>', '>=')), set(('+', '-')) ) float_type = MpasType("float", set(('+', '-', '*', '/', '<=', '<', '==', '!=', '>', '>=')), set(('+', '-')) ) string_type = MpasType("string", set(('+',)), set(), ) boolean_type = MpasType("bool", set(('and', 'or', '==', '!=')), set(('not',)) ) #=============================================================================== # Types declaration #=============================================================================== class SymbolTable(object): ''' Clase que representa una tabla de símbolos. Debe proporcionar funcionabilidad para agregar y buscar nodos asociados con identificadores. ''' class SymbolDefinedError(Exception): ''' Exception disparada cuando el codigo trara de agregar un simbol a la tabla de simbolos, y este ya esta definido ''' error(None, "") pass class SymbolConflictError(Exception): ''' ''' pass def __init__(self, parent=None): ''' Crea una tabla de simbolos vacia con la tabla padre dada ''' self.symtab = {} self.parent = parent if self.parent != None: self.parent.children.append(self) self.children = [] def add(self, a, v): ''' Agrega un simbol con el valor dado a la tabla de simbolos func foo(x:int, y:int) x:float; ''' if self.symtab.has_key(a): if type(self.symtab[a]) != type(v): raise SymbolTable.SymbolConflictError() else: raise SymbolTable.SymbolDefinedError() self.symtab[a] = v def lookup(self, a): if self.symtab.has_key(a): return self.symtab[a] else: if self.parent != None: return self.parent.lookup(a) else: return None #just for function tables def update_datatype(self, a, value): if self.symtab.has_key(a): self.symtab[a]['datatype'] = value else: if self.parent != None: self.parent.update_datatype(a, value) class CheckProgramVisitor(NodeVisitor): ''' Clase de Revisión de programa. Esta clase usa el patrón visitor como está descrito en pasAST.py. Es necesario definir métodos de la forma visit_NodeName() para cada tipo de nodo del AST que se desee procesar ''' def __init__(self): ''' Inicializa la tabla de simbolos ''' self.global_symtab = SymbolTable() self.local_symtab = None self.current_function = None self.has_return = False self.in_while = False # Agrega nombre de tipos incorporados ((int, float, string) a la tabla de simbolos self.symtab_add('int', int_type) self.symtab_add('float', float_type) self.symtab_add('string', string_type) self.symtab_add('bool', boolean_type) def symtab_add(self, name, values): if self.local_symtab: self.local_symtab.add(name, values) else: self.global_symtab.add(name, values) def symtab_lookup(self, name): result = None if self.local_symtab: result = self.local_symtab.lookup(name) else: result = self.global_symtab.lookup(name) return result def update_datatype(self, name, new_value): if self.local_symtab: self.local_symtab.update_datatype(name, new_value) else: self.global_symtab.update_datatype(name, new_value) def push_symtab(self, node): self.local_symtab = SymbolTable(self.local_symtab) node.symtab = self.local_symtab def pop_symbol(self): self.local_symtab = self.local_symtab.parent def find_fun_type(self, function): queue = [] for item in function.statements.statements: queue.append(item) while queue: cur = queue.pop(0) if isinstance(cur, pasAST.Return): self.visit(cur.value) return cur.value.datatype for i in xrange(0, len(cur._fields)): att = getattr(cur, cur._fields[i]) if isinstance(att, pasAST.AST): queue.append(att) def visit_Program(self, node): self.local_symtab = self.global_symtab # 1. Visita todas las funciones # 2. Registra la tabla de simbolos asociada self.visit(node.funList) if not self.symtab_lookup('main'): error(0, "main function missing") def visit_Function(self, node): # Asegurarse que tenga return self.has_return = False if self.symtab_lookup(node.id): error(node.lineno, "Function %s already defined" % node.id) else: v = { 'datatype': None, 'lineno' : node.lineno, 'cant_argms' : len(node.arglist.arguments), 'type_argms' : [], 'fun_instance' : node } self.symtab_add(node.id, v) self.push_symtab(node) self.current_function = node if self.current_function.id == 'main': if not isinstance(node.arglist.arguments[0], pasAST.Empty): error(node.lineno, "Function 'main' should not have arguments") else: self.local_symtab.parent.symtab[node.id]['cant_argms'] = 0 else: node.type_argms = self.visit(node.arglist) self.local_symtab.parent.symtab[node.id]['type_argms'] = node.type_argms self.visit(node.localslist) self.visit(node.statements) if not self.has_return: error(node.lineno, "Return was not found. Function must have return.") node.symtab = self.local_symtab.symtab self.pop_symbol() self.local_symtab.symtab[node.id]['table'] = node.symtab def visit_ArgList(self, node): type_argms = [] for arg in node.arguments: self.visit(arg) type_argms.append(arg.datatype) return type_argms def visit_LocalsList(self, node): for local in node.locals: if isinstance(local, Function): old_function = self.current_function self.visit(local) self.current_function = old_function self.has_return = False # to avoid conflic between global and local function return else: self.visit(local) def visit_Statements(self, node): for stm in node.statements: self.visit(stm) def visit_VarDeclaration(self,node): # 1. Revise que el nombre de la variable no se ha definido if self.symtab_lookup(node.id): self.visit(node.type) node.datatype = node.type.datatype error(node.lineno, "Variable '%s' already defined" % node.id) # 2. Agrege la entrada a la tabla de símbolos else: current = self.local_symtab.symtab self.symtab_add(node.id, {'datatype': None}) self.visit(node.type) if isinstance(node.type, Type): #simple type current[node.id]['varClass'] = 'simple_var' else: # Vector current[node.id]['varClass'] = 'vector' current[node.id]['size'] = node.type.size node.datatype = node.type.datatype current[node.id]['datatype'] = node.datatype current[node.id]['lineno'] = node.lineno # simple type def visit_Type(self, node): node.datatype = self.global_symtab.symtab[node.name] # vector type def visit_Vector(self, node): self.visit(node.type) node.datatype = node.type.datatype def visit_WhileStatement(self, node): self.in_while = True self.visit(node.condition) if not node.condition.datatype == boolean_type: error(node.lineno, "Wrong Type for While condition") else: self.visit(node.body) self.in_while = False def visit_UnaryOp(self, node): # 1. Asegúrese que la operación es compatible con el tipo # 2. Ajuste el tipo resultante al mismo del operando self.visit(node.right) if not node.op in node.right.datatype.un_ops: error(node.lineno, "Operación no soportada con este tipo") node.datatype = node.right.datatype def visit_RelationalOp(self, node): self.visit(node.left) self.visit(node.right) if not node.left.datatype == node.right.datatype: error(node.lineno, "Operandos de relación no son del mismo tipo") elif not node.op in node.left.datatype.bin_ops: error(node.lineno, "Operación no soportada con este tipo") elif not node.op in node.right.datatype.bin_ops: error(node.lineno, "Operación no soportada con este tipo") node.datatype = self.symtab_lookup('bool') def visit_BinaryOp(self, node): # 1. Asegúrese que los operandos left y right tienen el mismo tipo # 2. Asegúrese que la operación está soportada # 3. Asigne el tipo resultante self.visit(node.left) self.visit(node.right) if not node.left.datatype == node.right.datatype: error(node.lineno, "Operandos de operacionn no son del mismo tipo") elif not node.op in node.left.datatype.bin_ops: error(node.lineno, "Operación no soportada con este tipo") elif not node.op in node.right.datatype.bin_ops: error(node.lineno, "Operación no soportada con este tipo") node.datatype = node.left.datatype def visit_IfStatement(self, node): self.visit(node.condition) if not node.condition.datatype == boolean_type: error(node.lineno, "Tipo incorrecto para condición if") else: self.visit(node.then_b) if node.else_b: self.visit(node.else_b) def visit_AssignmentStatement(self,node): # 1. Asegúrese que la localización de la asignación está definida self.visit(node.location) sym = self.symtab_lookup(node.location.id) if not sym: error(node.lineno, "Asignado a un symbol desconocido") # 2. Revise que los tipos coincidan. else: self.visit(node.value) if node.location.datatype == node.value.datatype: node.datatype = sym['datatype'] else: error(node.lineno, "expression cannot be assigned to a %s variable" \ % (sym['datatype'].name)) def visit_LocationId(self, node): # 1. Revisar que la localización es una variable válida # 2. Asigne el tipo de la localización al nodo var_values = self.symtab_lookup(node.id) if not var_values: node.datatype = None error(node.lineno, "variable '%s' is not defined" % node.id) else: node.datatype = var_values['datatype'] def visit_LocationVectorAsign(self, node): # 1. Revisar que la localización cargada es válida. # 2. Asignar el tipo apropiado # 3. index debe ser entero var_values = self.symtab_lookup(node.id) if not var_values: error(node.lineno, "Assigment invalid, variable '%s' is not defined" % node.id) else: if var_values['varClass'] == 'vector': node.datatype = var_values['datatype'] self.visit(node.index) if isinstance(node.index, Literal) and node.index.datatype == int_type: if not (node.index.value >= 0 and node.index.value < var_values['size']): error(node.lineno, "Vector index out of range") else: error(node.lineno, "Index of vector '%s' must be INTEGER" % node.id) else: error(node.lineno, "Variable is not defined as a vector.") def visit_LocationVector(self, node): # 1. Revisar que la localización cargada es válida. # 2. Asignar el tipo apropiado var_values = self.symtab_lookup(node.id) if not var_values: error(node.lineno, "Access invalid, variable '%s' is not defined" % node.id) else: self.visit(node.index) node.datatype = var_values['datatype'] if not node.index.datatype == int_type: error(node.lineno, "Access invalid, index of vector must be INTEGER") def visit_Literal(self,node): # Adjunte un tipo apropiado a la constante if isinstance(node.value, bool): node.datatype = self.symtab_lookup("bool") elif isinstance(node.value, int): node.datatype = self.symtab_lookup("int") elif isinstance(node.value, float): node.datatype = self.symtab_lookup("float") elif isinstance(node.value, basestring): node.datatype = self.symtab_lookup("string") def visit_Print(self, node): pass def visit_Write(self, node): self.visit(node.expr) def visit_Read(self, node): self.visit(node.location) def visit_FunCall(self, node): # 1.Revisar que la funcion exista # 2.Comparar cantidad de paramentros y sus tipos # por ahora #si no tiene tipo aun, es por que esta definida despues o es un llamado recursivo #entonces buscamos el tipo en los statements de la instancia sym = self.symtab_lookup(node.id) if not sym: error(node.lineno, "Function '%s' is not defined" % node.id) else: if sym['datatype'] == None: datatype = self.find_fun_type(sym['fun_instance']) self.update_datatype(node.id, datatype) sym = self.symtab_lookup(node.id) #update if not node.id == 'main': node.datatype = sym['datatype'] if sym['cant_argms'] == len(node.params.expressions): type_params = self.visit(node.params) type_argms = sym['type_argms'] for i in xrange(0, sym['cant_argms']): if not type_argms[i] == type_params[i]: error(node.lineno, "Arguments must have same type") break else: if sym['type_argms'][0] == None: error(node.lineno, "Function '%s' takes no arguments %d given" \ % (node.id, len(node.params.expressions))) else: error(node.lineno, "Function '%s' takes exactly %d arguments %d given" \ % (node.id, sym['cant_argms'], len(node.params.expressions))) else: error(node.lineno, "You cannot call main function") def visit_ExprList(self, node): type_params = [] for expr in node.expressions: self.visit(expr) type_params.append(expr.datatype) return type_params def visit_Casting(self, node): node.datatype = self.symtab_lookup(node.type) self.visit(node.expr) def visit_Break(self, node): if not self.in_while: error(node.lineno, "Break statement is not inside a While loop") def visit_Return(self, node): if not isinstance(node.value, pasAST.Empty): self.visit(node.value) cur_fun = self.current_function if self.has_return: # verificar el tipo de todos los return sym = self.symtab_lookup(cur_fun.id) if not node.value.datatype == sym['datatype']: error(node.lineno, "Conflic with function type and return expressions type") else: self.has_return = True self.local_symtab.parent.symtab[cur_fun.id]['datatype'] = node.value.datatype else: self.has_return = True error(node.lineno, "Return can not be empty") def visit_Empty(self, node): node.datatype = None def check_program(ast_root): ''' Comprueba el programa suministrado (en forma de un AST) ''' checker = CheckProgramVisitor() checker.visit(ast_root) def main(): import pasparser import sys from errors import subscribe_errors lexer = paslex.make_lexer() parser = pasparser.make_parser() with subscribe_errors(lambda msg: sys.stdout.write(msg+"\n")): program = parser.parse(open(sys.argv[1]).read()) check_program(program) if __name__ == '__main__': main() ''' * Que hacer con funciones que todavia no tienen return, y visito un llamado recursivo a esa funcion '''
615c1ec463f0f1f303be655b9fa72a7255dc4641
gsudarshan1990/Training_Projects
/Classes/class_example32.py
809
4.375
4
""" This is an example of the class and elaborating how to create the objects """ class Name: """This class provides the name with firstname and lastname""" def __init__(self, firstname, lastname): """This is used to initialize the values""" self.firstname = firstname self.lastname = lastname class Student: """This class describes the name of the student""" def __init__(self, studentname, enrolled): """This is used to initialize the Student class""" self.studentname = studentname self.GPA = 0.0 self.creditHours = 0 self.enrolled = enrolled self.classes = [] newStudent = Student(Name('sonu','Garim'),True ) name1 = Name('shashank', 'Graim') newStudent2 = Student(name1,True) newStudent3 = Student("Sonu Garim",True)
f2fb940f55a145472294ecf40018d257e71c29f6
pratikpc/Pracs-Sem4-CRCE
/OSTL/question7.py
209
3.75
4
def convertToOctal(n): print(oct(n)) def convertToBinary(n): if n > 1: convertToBinary(n//2) print(n % 2, end = '') dec = int(input('Enter a number')) convertToOctal(dec)
06a2e76f4519a1c23dd87f3e50a5708c3daf7ec3
slowrunner/Carl
/Examples/GoogleCloud/GoogleCloudVision/file_vision_label.py
1,173
3.53125
4
#!/usr/bin/env python3 """ # filename: file_vision_label.py # usage: - raspistill -o image.jpg - ./file_vision_label.py -i image.jpg read an the passed image filename convert to GoogleCloudVision image create a request send to google cloud print labels found in the image Example run: ./file_vision_label.py -i wheel.jpg Labels: Tire Automotive tire Yellow Wheel Rim Auto part Automotive wheel system Synthetic rubber Tire care """ from google.cloud import vision import argparse client = vision.ImageAnnotatorClient() def main(): """Run a label request on a single image""" ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to image file") args = vars(ap.parse_args()) filename = args['image'] with open(filename, 'rb') as image_file: content = image_file.read() image = vision.types.Image(content=content) response = client.logo_detection(image=image) response = client.label_detection(image=image) labels = response.label_annotations print('Labels:') for label in labels: print(label.description) if __name__ == '__main__': main()