Dataset Viewer
Auto-converted to Parquet
text
stringlengths
37
1.41M
# coding:utf-8 ''' 礼物的最大价值 ''' def maxValue(matrix, i, j, value): row = len(matrix) col = len(matrix[0]) while i < row-1 and j < col-1: if matrix[i + 1][j] >= matrix[i][j + 1]: value += matrix[i + 1][j] i += 1 else: value += matrix[i][j + 1] j += 1 while i == row-1 and j < col-1: value += matrix[i][j + 1] j += 1 while i < row-1 and j == col: value += matrix[i + 1][j] i += 1 # value = maxValue(matrix, i, j, value) return value if __name__ == '__main__': matrix = [[1, 10, 3, 8], [12, 2, 9, 6], [5, 7, 4, 11], [3, 7, 16, 5]] value = 0 value += matrix[0][0] i, j = 0, 0 print maxValue(matrix, i, j, value)
# coding:utf-8 # The factorial of number def factorial(number): try: if number == 1: return 1 elif number >= 1: return number * factorial(number - 1) except Exception, e: print 'Please input a natural number:', e number = -233 print factorial(number)
# coding:utf-8 ''' 栈的建立 ''' class Stack(object): def __init__(self): self.stack = [] def is_empty(self): return self.stack == [] def push(self, val): self.stack.append(val) def pop(self): if self.stack: return self.stack.pop() def peek(self): if self.stack: return self.stack[len(self.stack) - 1] def size(self): return len(self.stack) if __name__ == '__main__': s = Stack() s.push(3) s.push(4) s.push(7) print(s.pop()) print(s.peek()) print(s.size())
# coding:utf-8 ''' 2.9 斐波那契数列 (1)递归,从后向前,产生重复元素 (2)动态规划:从前向后 ''' def Fib(n): if n < 0: return None fib = [0, 1] if n <= 1: return fib[n] for i in range(2, n+1): fib.append(fib[i-2]+fib[i-1]) return fib if __name__ == '__main__': n = 10 print Fib(n)
# coding:utf-8 # Reverse a list by recursive def Reverse_list(string_list): if len(string_list) == 1: return string_list[0] else: return string_list[-1] + Reverse_list(string_list[:-1]) string_list = '1738323839289382938923892' print Reverse_list(string_list)
# coding:utf-8 ''' 二叉树中和为某一值的路径 输入一个二叉树和一个整数,打印二叉树中节点值得和为输入整数的所有路径, 从根节点开始往下一直到叶节点所经过的节点形成一条路径 ''' class BinaryTreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): # 树:递归算法 def PathSum(self, pRoot, N): if pRoot is None: return [] if pRoot.left is None and pRoot.right is None: if pRoot.val == N: return [[pRoot.val]] # 不同的分支要放到不同的list中 # print type([pRoot.val]) else: return [] # 由于list不能加bool类型,因此使用[]来表示 a = self.PathSum(pRoot.left, N - pRoot.val) + self.PathSum(pRoot.right, N - pRoot.val) # print type(a) return [[pRoot.val] + i for i in a] if __name__ == '__main__': pNode1 = BinaryTreeNode(10) pNode2 = BinaryTreeNode(5) pNode3 = BinaryTreeNode(12) pNode4 = BinaryTreeNode(4) pNode5 = BinaryTreeNode(7) pNode1.left = pNode2 pNode1.right = pNode3 pNode2.left = pNode4 pNode2.right = pNode5 s = Solution() print s.PathSum(pNode1, 22)
# coding:utf-8 from Deques import deque # Palindrome Checker:回文检查程序,字符串关于中间对称 def checker_palindrome(ch_string): d = deque() for c in ch_string: d.add_front(c) while d.size() > 1: if d.remove_front() != d.remove_rear(): return False return True return False ch_string = 'rr' print checker_palindrome(ch_string)
# codinng:utf-8 class ListNode: def __init__(self, x): self.val = x self.next = None # def getval(self): # return self.val # # def getnext(self): # return self.next # # def setval(self, newval): # self.val = newval # # def setnext(self, newnext): # self.next = newnext class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ s1 = str() s2 = str() while l1: s1 = str(l1.val) + s1 l1 = l1.next while l2: s2 = str(l2.val) + s2 l2 = l2.next s1 = int(s1) s2 = int(s2) sum = s1 + s2 sum = str(sum) sum = sum[::-1] ret = ListNode(sum[0]) cur1 = ret for i in range(1,len(sum)): cur1.next = ListNode(sum[i]) cur1 = cur1.next return ret l1 = [2, 4, 3] l2 = [5, 6, 4] s = Solution() print s.addTwoNumbers(l1, l2)
# coding:utf-8 import turtle my_win = turtle.Screen() # The Tutorial of Turtle # 1、Turtle motion print turtle.position() turtle.forward(25) # 沿x轴正方向移动25 turtle.fd() print turtle.position() turtle.forward(-75) # 沿x轴负方向移动75 print turtle.position() print '--------------------------' print turtle.position() # turtle.pos turtle.backward(25) # 沿x轴负方向移动25 turtle.bk(), turtle.back() print turtle.position() turtle.back(100) print turtle.position() print turtle.pos() print '--------------------------' print turtle.heading() turtle.right(90) # 度数,左加右减 turtle.rt() print turtle.heading() # 270度 turtle.left(100) # turtle.lf() print turtle.heading() # 10度 print '---------------------------' print turtle.pos() turtle.setpos(0, 0) print turtle.pos() turtle.setpos((20, 100)) print turtle.pos() turtle.setx(100) print turtle.pos() turtle.sety(0) print turtle.pos() print '---------------------------' turtle.setheading(90) # 设置角度 print turtle.heading() print turtle.position() turtle.home() # 恢复到初始状态 print turtle.heading() print turtle.position() print '---------------------------' turtle.circle(100) # 半径为50 print turtle.pos() turtle.circle(50, 360) # 半径120,角度180 print turtle.pos() print '---------------------------' turtle.home() turtle.dot(20, 'blue') # 画一个点,点半径20,颜色为blue turtle.color('blue') # 线条颜色为blue print turtle.stamp() for i in range(8): turtle.stamp() turtle.fd(30) turtle.clearstamps(2) for i in range(5): turtle.fd(50) turtle.lt(72) for i in range(10): turtle.undo() # 回退,返回到之前的操作 turtle.speed(6) turtle.circle(40) print '--------------------------------------' print '--------------------------------------' # 2、Tell Turtle's state turtle.home() print turtle.position() turtle.goto(10, 10) # 直接去某一点 print turtle.position() print turtle.towards(0, 0) # (10,10)到(0,0)的角度为225度 turtle.goto(0, 0) print turtle.towards(10,10) # (0,0)到(10,10)的角度为45度 print '-------------------------------------' turtle.home() turtle.left(50) turtle.forward(100) print turtle.pos() print turtle.xcor() print turtle.ycor() # my_win.exitonclick()
# coding:utf-8 ''' 2.21连续加法 判断一个数是否可以使用连续数之和来表示 ''' # 计算序列之和 def seqsum(first, last): sum = 0 for i in range(first, last + 1): sum += i return sum # 打印找到的序列 def showseq(first, last): s = [] for i in range(first, last + 1): s.append(i) return s def SequenceAdd(n): if n <= 2: print None L = n / 2 + 2 first = 1 second = 2 while first < second and (second <= L): sum = seqsum(first, second) if sum == n: print showseq(first, second) first += 1 second += 1 elif sum < n: second += 1 else: first += 1 print None if __name__ == '__main__': for i in range(1001): print str(i)+':' SequenceAdd(i) print '---------------'
# coding:utf-8 # quick sort def quickSort(num_list): quickSortHelper(num_list, 0, len(num_list) - 1) def quickSortHelper(num_list, first, last): if first < last: split_point = partition(num_list, first, last) quickSortHelper(num_list, first, split_point - 1) quickSortHelper(num_list, split_point + 1, last) def partition(num_list, first, last): pivot_value = num_list[first] left_mark = first + 1 right_mark = last done = False while not done: while left_mark <= right_mark and num_list[left_mark] <= pivot_value: left_mark += 1 while right_mark >= left_mark and num_list[right_mark] >= pivot_value: right_mark -= 1 if right_mark < left_mark: done = True else: temp = num_list[left_mark] num_list[left_mark] = num_list[right_mark] num_list[right_mark] = temp temp = num_list[first] num_list[first] = num_list[right_mark] num_list[right_mark] = temp return right_mark if __name__ == '__main__': num_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] print quickSort(num_list)
# coding:utf-8 ''' 快速排序:一半一半排序,递归排序 ''' def partion(nums, left, right): key = nums[left] while left < right: while left < right and (nums[right] >= key): right -= 1 nums[left] = nums[right] print nums while left < right and (nums[left] <= key): left += 1 nums[right] = nums[left] nums[left] = key print nums print '-------------' print left, right # 相等的情况下,不能继续了 print '-------------' return left def quicksort(nums, left, right): if left < right: p = partion(nums, left, right) quicksort(nums, left, p - 1) quicksort(nums, p + 1, right) return nums if __name__ == '__main__': nums = [6, 8, 1, 4, 3, 9, 5, 4, 11, 2, 2, 15, 6] print quicksort(nums, 0, len(nums)-1)
# coding:utf-8 ''' 将两个栈的操作写到main中,效果会差一些 优化方案:直接定义两个不同的栈,将栈之间的操作写入到队列类的创建中,main函数中只进行队列数据的进入和输出 ''' class MyQueue(object): def __init__(self): self.stack = [] def push(self, val): self.stack.append(val) def pop(self): if self.stack: return self.stack.pop() if __name__ == '__main__': p = MyQueue() q = MyQueue() p.push(2) p.push(3) q.push(p.pop()) q.push(p.pop()) print q.pop() print q.pop()
#Funkcijas atgriež 10% no a un 20% no skaitlā b def procenti(a,b): return a/10, b/5 print(procenti(100,100)) #1. Uzraksti funkciju var_pagulet, kas atgriež True, ja ir brīvdiena un False, ja ir darbdiena. (Dienas no 1-7) def var_pagulet(diena): if diena <=5: def monkey_trouble(a_smile, b_smile): if monkey_trouble: return True elif monkey_trouble: return True else: monkey_trouble('True, False') return True def sum_double(a, b): if a is b: return 2 * (a + b) else: return a+b #4. uzdevums def modulis(n): if n>21: starpiba=n-21 else: starpiba=21-n if starpiba>21: return starpiba*2 return starpiba print(modulis(3)) #5. uzdevums def papagaila_problema(runaja, laiks): if runaja == True and laiks < 7 == True or laiks > 20 == True: return(True) def papagaila_problema(runa, laiks): if(runa and (laiks<7 or laiks>20)): print("True") else: print("False")
#salīdzināšana print(2 == 2) print(2 == "2") print(2 * 2 != 5) a = 50 b = 4 c = 4 print(a > b, b > c, c < a) print(a != b, b < c, c < a) #loģiskie operatori - and/or/not print(True and True) a = 5 b = 10 c = 15 print(a > 5 and b > 20) print(a >= 5 and b >= 10) print(a >= 5 or b > 20) print(not a > 7) print(a >= 5 and b < 12 and c > 4 and a > c) print(a < b and b < c) print(a < b < c)
#!/usr/bin/env python import csv import re """ This code deals with loading data from two files and saving changes when done. This code can accept database operation for find and insert Examples of command Find order EmployeeID=5, ShipCountry=Brazil Insert customer ("ALFKI","Alfreds Futterkiste","Maria Anders","Sales Representative","Obere Str.57","Berlin","null","12209","Germany","030-0074321","030-0076545") When inserting a new line. Make sure to use null when wanting to leave a plaec blank """ # csv reader 's indice is integer while cvs DictReader uses indice of the firstrow str userInput = raw_input('please enter your instruction') userInput2 = re.split('\"|,|\(|\)| ', userInput) userInput2 = [item for item in filter(lambda x:x != '', userInput2)] userInput3 = re.split('\"|,|\(|\)', userInput) userInput3 = [item for item in filter(lambda x:x != '', userInput3)] if userInput2[0]=='Find': if userInput2[1] == 'order': with open('orders.csv') as csvfile: readCSV = csv.DictReader(csvfile, delimiter=',') findOrNot = False for row in readCSV: isthis = True index = 2 #Find order OrderID=10248, CustomerID=VINET while(index < len(userInput2)): indexparse = re.split('=', userInput2[index]) isthis = isthis and (row[indexparse[0]] == indexparse[1]) index=index+1 if (isthis): print(row) findOrNot=True if(findOrNot==False): print"Sorry, we don't have this query" if(userInput2[1]=='customer'): with open('customers.csv') as csvfile: readCSV = csv.DictReader(csvfile, delimiter=',') findOrNot = False for row in readCSV: isthis = True index = 2 while(index < len(userInput2)): indexparse = re.split('=', userInput2[index]) isthis = isthis and (row[indexparse[0]] == indexparse[1]) index=index+1 if (isthis): print(row) findOrNot=True if(findOrNot==False): print"Sorry, we don't have this query" # When inserting things into file. Null is needed for the field which tends to left as blank if userInput2[0]=='Insert': if userInput2[1]=='order': userInput3=userInput3[1:len(userInput3)] with open('orders.csv', 'a') as csvfile: writeCSV = csv.writer(csvfile, delimiter=",") writeCSV.writerow(userInput3) if userInput2[1]=='customer': userInput3=userInput3[1:len(userInput3)] with open('customers.csv', 'a') as csvfile: writeCSV = csv.writer(csvfile, delimiter=",") writeCSV.writerow(userInput3) # Insert customer ("ALFKI","Alfreds Futterkiste","Maria Anders","Sales Representative","Obere Str.57","Berlin","","12209","Germany","030-0074321","030-0076545")
import csv import urllib import os.path drugs = open("data/data.csv", "r") reader = csv.reader(drugs) highschool = {} college = {} def constructDicts(): #row[129] = year, row[66] = state #row[51] = percentage for high school-aged people #row[52] = percentage for college-aged people for row in reader: state = row[66] if ( state in highschool.keys() ): #to avoid overwriting data highschool[state].append(row[129]) #add year highschool[state].append(row[57]) #add rate college[state].append(row[129]) college[state].append(row[58]) else: highschool[state] = [row[129],row[57]] college[state] = [row[129],row[58]] #print highschool #print college constructDicts() def getHPercentages(year): results = {} for state in highschool.keys(): years = highschool.get(state) l = len(years) x = 0 while ( x < l ): if ( years[x] == year ): results[state] = years[x+1] x = l else: x += 2 return results def getCPercentages(year): results = {} for state in college.keys(): years = college.get(state) l = len(years) x = 0 while ( x < l ): if ( years[x] == year ): results[state] = years[x+1] x = l else: x += 2 return results
def greedy_solver_1(items, capacity): # a trivial greedy algorithm for filling the knapsack # it takes items in-order until the knapsack is full value = 0 weight = 0 taken = [0]*len(items) for item in items: if weight + item.weight <= capacity: taken[item.index] = 1 value += item.value weight += item.weight return value, taken def greedy_solver_2(items, capacity): # a trivial greedy algorithm for filling the knapsack # it takes items in-order of most valuable until the knapsack is full sorted_items = sorted(items, key=lambda x: x.value, reverse=True) value = 0 weight = 0 taken = [0]*len(items) for item in sorted_items: if weight + item.weight <= capacity: taken[item.index] = 1 value += item.value weight += item.weight return value, taken def greedy_solver_3(items, capacity): # a trivial greedy algorithm for filling the knapsack # it takes items in-order of smallest until the knapsack is full sorted_items = sorted(items, key=lambda x: x.weight) value = 0 weight = 0 taken = [0]*len(items) for item in sorted_items: if weight + item.weight <= capacity: taken[item.index] = 1 value += item.value weight += item.weight return value, taken def greedy_solver_4(items, capacity): # a trivial greedy algorithm for filling the knapsack # it takes items in-order of value_density until the knapsack is full sorted_items = sorted(items, key=lambda x: x.value_density, reverse=True) value = 0 weight = 0 taken = [0]*len(items) for item in sorted_items: if weight + item.weight <= capacity: taken[item.index] = 1 value += item.value weight += item.weight return value, taken
i=0 str =input("enter a string :\n") while i<len(str): print(str[i],end='') i=i+2
""" 10. Create a class called First and two classes called Second and Third which inherit from First. Create class called Fourth which inherits from Second and Third. Create a common method called method1 in all the classes and provide the Method Resolution Order. """ import math class First: def method1(self): print"this class is first" class Second(First): def method1(self): print"this class is second" First.method1(self) class Third(First): def method1(self): print"this class is third" First.method1(self) class Fourth(Second,Third): def method1(self): print"this class is fourth" Second.method1(self) Third.method1(self) obj = Fourth() obj.method1()
""" 5.Write a code to implement a child class called mathnew and parent classes as sqroot, addition,subtraction, multiplication and division. Use the super() function to inherit the parent methods. """ import math class Mymath(object): def sqroot(self,a): c=math.sqrt(a) print "square-root of number is =",c def addition(self,a,b): c=a+b print "addion of two number is =",c def subtraction(self,a,b): c=a-b print "subtraction of two number is =",c def multiplication(self,a,b): c=a*b print "multiplication of two number is =",c def division(self,a,b): c=a/b print "division of two number is =",c class My(Mymath): def __init__(self,a,b): self.a=a self.b=b super(My, self).sqroot(a) super(My, self).addition(a,b) super(My, self).subtraction(a,b) super(My, self).multiplication(a,b) super(My, self).division(a,b) a=input("enter the first number\n") a1=int(a) b=input("enter the second number\n") b1=int(b) obj = My(a1,b1)
import urllib.request, json, csv import datetime as datetime import openpyxl # Import the data from the CoinMarketCap public API with urllib.request.urlopen("https://api.coinmarketcap.com/v1/ticker/?convert=GBP") as url: data = json.loads(url.read().decode()) # Print a list of all coins and their GBP values for x in range(0, len(data)):# Increment x from 0, to the length of data (our list) print("The current coin is: " + str(data[x]['id']) + " the current GBP rate is : " + str(data[x]['price_gbp'])) # Pull current date, and format it as year/month/day hour:minutes and save it as a variable date = datetime.datetime.today().strftime('%Y-%m-%d %H:%M') # Create a file to save the outputs filename = 'output.csv' f = open(filename,'a') # Write the data to the csv file each time the programme runs for x in range(0, len(data)):# Increment x from 0, to the length of data (our list) f.write("\n" + (data[x]['last_updated']) + "," + (data[x]['id']) + "," + (data[x]['price_gbp']) + "," + (data[x]['price_btc']) + "," + (date)) f.close()
# TODO: Script definition import socket from time import time def get_socket(): """Gives the UDP socket for use. We don't create the socket in 'send_udp' because if we do that, every time we send a package we need to create a socket.""" print('Creating UDP Socket...') try: return socket.socket(socket.AF_INET, socket.SOCK_DGRAM) except socket.error: raise Exception('Cannot create UDP Socket for sending the data. Please ensure that you are root and try again.') def send_udp(my_socket, d_ip, d_port, data): """Sends the UDP Package. Takes the socket as first argument. Second argument is Destination IP and the third is Destination Port. Lastly, Raw Data is the final argument.""" print('Sending UDP Packet...') try: my_socket.sendto(data, (d_ip, d_port)) print('UDP Packet sent.') return True except socket.error: print('Error while sending UDP Packet') return False def receive_udp(my_socket, s_port): """Receives UDP Package from source. If it does not receive a packet until default timeout it returns False. Takes socket as first argument and Source Port as second argument.""" print('Receiving UDP Packet') try: packet = my_socket.recvfrom(1000) print('UDP Packet received.') except socket.timeout: print('Receive timed out.') return False return packet
# IMPORTS # DATA data = [] with open("Data - Day05.txt") as file: for line in file: data.append(int(line)) part2_data = data.copy() # GOAL 1 """ An urgent interrupt arrives from the CPU: it's trapped in a maze of jump instructions, and it would like assistance from any programs with spare cycles to help find the exit. The message includes a list of the offsets for each jump. Jumps are relative: -1 moves to the previous instruction, and 2 skips the next one. Start at the first instruction in the list. The goal is to follow the jumps until one leads outside the list. In addition, these instructions are a little strange; after each jump, the offset of that instruction increases by 1. So, if you come across an offset of 3, you would move three instructions forward, but change it to a 4 for the next time it is encountered. """ # ANSWER 1 def part_1(data): final = len(data) count = 0 idx = 0 while idx < final: val = data[idx] data[idx] += 1 idx = idx + val count += 1 print(f"Answer 5a: {count}") part_1(data) # GOAL 2 """ Now, the jumps are even stranger: after each jump, if the offset was three or more, instead decrease it by 1. Otherwise, increase it by 1 as before. How many steps does it now take to reach the exit? """ # ANSWER 2 def part_2(data): final = len(data) count = 0 idx = 0 while idx < final: val = data[idx] if val >= 3: data[idx] -= 1 else: data[idx] += 1 idx = idx + val count += 1 print(f"Answer 5b: {count}") part_2(part2_data)
# coding = utf-8 """ ============== Deck Class ============== """ from Card import Card from Const import CARD_FORMAT import random class Deck: __cards = list() __number = __cards def __init__(self): for suit in ['H', 'D', 'C', 'S']: for number in range(1, 13+1, 1): __card = Card(suit, number) self.__cards.append(__card) def shuffle(self): random.shuffle(self.__cards) def pop(self): card = self.__cards.pop() return card
# A clustering data structure implementing k-means. # (c) 2018 from random import randint __all__ = [ "KMeans", "fdist", "fmean" ] def fdist(a,b): """A distance function for float values.""" return abs(a-b) def fmean(s): """A Mean function for float values.""" assert(s) return sum(s)/len(s) class KMeans(object): """An implementation of k-means clustering. Typical use: data = [ randint(0,1000000) for _ in range(1000) ] cl = KMeans(data, k = 10) for rep in cl.means(): print("Cluster {}:".format(rep)) for value in cl.cluster(rep): print(" {}".format(value)) """ __slots__ = [ "_means", "_k", "_clusters", "_distf", "_meanf", "_data" ] def __init__(self, data, k = 5, distf = None, meanf = None): """Load a cluster data into k clusters. The distf and meanf functions, if not specified, default to distance and mean computations on floating point values.""" self._distf = fdist if distf is None else distf self._meanf = fmean if meanf is None else meanf self._k = k self._data = list(data) # values we compute self._clusters = [] self._cluster() def _pickMeans(self): """Select some initial means. Here, we pick k random values from the original dataset. We try to avoid repeats.""" n = len(self._data) locations = [] means = [] for _ in range(self._k): loc = randint(0,n-1) while loc in locations: loc = randint(0,n-1) locations.append(loc) means.append(self._data[loc]) self._means = means def _findClosest(self,value): """Find the cluster number that has a representative that is closest to value.""" mindex = 0 minDist = self._distf(value,self._means[0]) for ind in range(1,self._k): d = self._distf(value,self._means[ind]) if d < minDist: mindex = ind minDist = d return mindex def _classify(self): """For each data value, place it in a cluster which best represents it; all data in a cluster are closest to their representative.""" self._clusters = [ [] for _ in range(self._k) ] for value in self._data: repIndex = self._findClosest(value) self._clusters[repIndex].append(value) def _adjustMeans(self): """Compute means based on the current clustering.""" self._means = [] for i in range(self._k): self._means.append(self._meanf(self._clusters[i])) def _cluster(self): """Iteratively find representative values, classify data and iterate.""" self._pickMeans() self._classify() for _ in range(10): self._adjustMeans() self._classify() def means(self): return self._means.copy() def classify(self, value): repIndex = self._findClosest(value) return self._means[repIndex] def cluster(self,rep): if rep not in self._means: rep = self.classify(rep) return self._clusters[self._means.index(rep)] if __name__ == "__main__": data = [ randint(0,1000000) for _ in range(1000) ] cl = KMeans(data, k = 10) for rep in cl.means(): print("Cluster {}:".format(rep)) for value in cl.cluster(rep): print(" {}".format(value)) # rep = cl.classify(value)
import errno import os import os.path import shutil import platform class Utils: """ This class stores some useful functions """ @staticmethod def delete_if_exist(file_path): """ This function deletes a file if it exists. :param file_path: The file we want to delete. :return: nothing. """ import os if os.path.exists(file_path): os.remove(file_path) @staticmethod def create_file_if_not_exist(in_file_path, out_file_path): """ This funtion writes the content of an input file into an output file. :param in_file_path: The input file path. :param out_file_path: The output file path. :return: nothing. """ file_exists = os.path.isfile(out_file_path) if not file_exists: with open(in_file_path, "r"), \ open(out_file_path, "w"): shutil.copyfile(in_file_path, out_file_path) @staticmethod def create_folder_if_not_exist(folder_path): """ This function create a folder if doesn't exist. :param folder_path: The name of the folder we want to create. :return: nothing. """ if not os.path.exists(os.path.dirname(folder_path)): try: os.makedirs(os.path.dirname(folder_path)) except OSError as exc: if exc.errno != errno.EEXIST: raise @staticmethod def is_linux(): """ THis function test if we are using linux. :return: True if we are using linux. """ return platform.system() == 'Linux' @staticmethod def is_windows(): """ THis function test if we are using windows. :return: True if we are using windows. """ return platform.system() == 'Windows' @staticmethod def is_mac(): """ THis function test if we are using mac. :return: True if we are using mac. """ return platform.system() == 'Darwin' @staticmethod def reverse_path_if_windows(path): return path.replace('\\', '/') if Utils.is_windows() else path
#!/usr/bin/env python import sys def find_steps(n): if n < 1: return 0 steps = 0 while True: print n, if n == 1: return steps elif n%2 == 0: n //= 2 steps += 1 else: n = 3*n + 1 steps += 1 def find_steps_rec(n, steps=0): print n, if n == 1: return steps if n%2 == 0: return find_steps_rec(n//2, steps + 1) else: return find_steps_rec(3*n+1, steps + 1) def find_steps_rec2(n): steps = 0 print n, if n == 1: return steps if n%2 == 0: return steps + find_steps_rec2(n//2) else: return steps + find_steps_rec2(3*n+1) steps = find_steps(int(sys.argv[1])) print "steps=",steps steps = find_steps_rec(int(sys.argv[1])) print "steps=",steps steps = find_steps_rec2(int(sys.argv[1])) print "steps=",steps
#!/usr/bin/env python def count_vowels(word): is_vowel = lambda x: x in 'aeiou' vowels = dict([(i,0) for i in 'aeiou']) for letter in word: if is_vowel(letter): vowels[letter] += 1 print vowels,sum(vowels.values()) count_vowels('aeiou') count_vowels('wassup') count_vowels('hello') count_vowels('ttrrsdsd')
def bubble_sort(alist): for _ in range(len(alist)-1,0,-1): for i in range(_): if alist[i] > alist[i+1]: alist[i+1],alist[i] = alist[i],alist[i+1] return alist alist = [10,2,3,11,23,0,1,4] print(bubble_sort(alist))
class HashTable: def __init__(self): self.size = 11 self.slots = [None]*self.size self.data = [None]*self.size def hashfunction(self, key, size): return key%size def put(self, key, data): hashvalue = self.hashfunction(key, len(self.slots)) if self.data[hashvalue] == None: self.slots[hashvalue] == key self.data[hashvalue] == data else: if self.slots[hashvalue] == key: self.data[hashvalue] == data else: nextslot = self.rehash(hashvalue, len(self.slots)) while self.slots[nextslot] != None and self.slots[nextslots] != key: nextslot = self.rehash(hashvalue, len(self.slots)) if self.data[nextslot] == None: self.slots[nextslot] == key self.data[nextslot] == data else: if self.slots[nextslot] == key: self.data[nextslot] == data
from node import node import random class LinkedList(object): def __init__(self, root_node: node = None): if type(root_node) != node and root_node != None: raise TypeError("Root node must be node or None class") self.root_node = root_node if self.root_node: self.size = 1 else: self.size = 0 def get_size(self): return self.size def find(self, node_data_to_find: int): if type(node_data_to_find) != int: raise TypeError("Node data to find must be int") current_node = self.root_node while current_node is not None: if current_node.get_data() == node_data_to_find: return current_node elif current_node.get_next() == None: return False else: current_node = current_node.get_next() def add(self, node_data_to_add: int): if type(node_data_to_add) != int: raise TypeError("Node data to add must be int") new_node = node (node_data=node_data_to_add, next_node=self.root_node) self.root_node = new_node self.size += 1 def remove(self, node_data_to_remove: int): if type(node_data_to_remove) != int: raise TypeError("Node data to remove must be int") current_node = self.root_node previous_node = None while current_node is not None: if current_node.get_data() == node_data_to_remove: if previous_node is not None: previous_node.set_next(current_node.get_next()) else: self.root_node = current_node.get_next() self.size -= 1 return True else: previous_node = current_node current_node = current_node.get_next() return False def validate_size(self): count = 0 current_node = self.root_node while current_node is not None: count += 1 current_node = current_node.get_next() return count def main(): myList = LinkedList() added_numbers = [] i = random.randint(2,30) while i > 0: random_int = random.randint(1,100) myList.add(random_int) added_numbers.append(random_int) i -= 1 print (f"Node values: {added_numbers}") print(f"List Size: {myList.get_size()}") print(f"Validated List Size: {myList.validate_size()}") print(f"Removing value {added_numbers[1]} from List : {myList.remove(added_numbers[1])}") print(f"New List Size: {myList.get_size()}") print(f"New Validated List Size: {myList.validate_size()}") find_value = random.choice(added_numbers) print(f"Finding value: {find_value}: {myList.find(find_value)}") main()
# SelectionSort implementation in Python. # # Time Complexity of a Solution: # Best: O(n^2) # Average: O(n^2) # Worst: O(n^2) import sys import random script, number = sys.argv def SelectionSort(aList): for i in range(len(aList)): minimum = i for j in range(i + 1, len(aList)): if (aList[minimum] > aList[j]): minimum = j aList[minimum], aList[i] = aList[i], aList[minimum] print(aList) def main(): num = int(number) try: array = random.sample(xrange(100), num) except ValueError: print('Sample size exceeded population size.') print(array) SelectionSort(array) main()
num = 100; def getFactorial(num): if(num == 1): return 1 else: return num * getFactorial(num - 1) total = 0 for n in list(str(getFactorial(num))): total += int(n); print(total);
#1) Import the random function and generate both a random number between 0 and 1 as well as a random number between 1 and 10. import random randon_number = random.random() random_number_2 = random.randint(1, 10) print(randon_number) print(random_number_2) #2) Use the datetime library together with the random number to generate a random, unique value. import datetime random_unique = str(randon_number) + str(datetime.datetime.now()) print(random_unique)
#What will the value of z be? x = input("Enter the value for x: ") #Lets say you entered 1 as your response when you ran this program y = input("Enter the value for y: ") #Lets say you entered 2 as your response when you ran this program z = x + y print("z = ", z)
#-- Clean merge sort # Recursive def merge(t, i, j, k, aux): # merge t[i:k] in aux[i:k] supposing t[i:j] and t[j:k] are sorted a, b = i, j # iterators for s in range(i, k): if a == j or (b < k and t[b] < t[a]): aux[s] = t[b] b += 1 else: aux[s] = t[a] a += 1 def merge_sort(t): aux = [None] * len(t) def merge_rec(i, k): # merge sort t from i to k if k > i + 1: j = i + (k - i) // 2 merge_rec(i, j) merge_rec(j, k) merge(t, i, j, k, aux) t[i:k] = aux[i:k] merge_rec(0, len(t)) # Iterative, O(1) in space but worse time complexity # merge subarrays of size s^k for every k so that s**k < n def merge_sort_ite(t): s = 1 while s <= len(t): for i in range(0, len(t), s * 2): left, right = i, min(len(t), i + 2 * s) mid = i + s # merge t[i:i + 2 * s] p, q = left, mid while p < mid and q < right: if t[p] > t[q]: tmp = t[q] t[p + 1: q + 1] = t[p:q] # /!\ O(n) t[p] = tmp mid += 1 q += 1 p += 1 s *= 2 return t tab = [172, 4784, 4, 623, 8, 2, 63, 9479, 42, 98] merge_sort_ite(tab) print(tab)
#-- Print or count all the subsets of a set def subsets(A): # O(2^n * n) res = [[]] for item in A: n = len(res) for i in range(n): res.append(res[i] + [item]) # O(n) return res A = [1, 2, 3] subs = subsets(A) print(subs) print(len(subs), " = ", 2**len(A)) def recSubsets(A, subset, i): if i < len(A): subset[i] = A[i] recSubsets(A, subset, i + 1) # With our item subset[i] = None recSubsets(A, subset, i + 1) # Without else: printSet(subset) def printSet(a_set): print("{ ", end='') for item in a_set: if item != None: print(item, end=' ') print("}") A = [1, 2, 3] recSubsets(A, [None] * len(A), 0)
"""" list = [1, 3, 5, 7, 8, 9] for x in list: sentence = "list contains " + str(x) print(sentence) """ ''' import range: for i in range(11) print(6) ''' def chibuzor(*args): # for multiple number of argument we introduce *args to our function number_list = args result_list = [] for number in number_list: string = str(number) replaced = string.replace("234", "0") result_list.append(replaced) variable = chibuzor("234894656478364", "234567588593354673", "23483544667383", "234844536478498") #OOP allows us to represent real life objects as software objects attributes of the objects attributes and characteristics, behaviours and methods
""" x = ["chibuzor", "chigozie", "chinyere", "kelechi", "ifeanyi"] response = "" while response != "end": response = input("enter item: ") if response in x: print("certainly") else: x.append(response) print(x) """ """ x = [1, 2, 4, 5, 7, 8] for item in x: sentence = "list contains " + str(item) print(sentence) """ """ name = input("enter a name: ") state = input("enter state: ") current_location = input("enter current location: ") user_sentence = "my name is {}, i come from {}, and am currently based in {}".format( name, state, current_location) print(user_sentence) """
import time class Neighborhood(): def __init__(self): self.r = -1 self.c = -1 def FindRowNeighbors(self): return [(self.r, i) for i in range(1, 10)] def FindColNeighbors(self): return [(i, self.c) for i in range(1, 10)] def FindBlockNeighbors(self): if self.r <= 3: ir = [1, 2, 3] elif self.r >= 7: ir = [7, 8, 9] else: ir = [4, 5, 6] if self.c <= 3: ic = [1, 2, 3] elif self.c >= 7: ic = [7, 8, 9] else: ic = [4, 5, 6] bnbs = list() for iir in ir: for iic in ic: bnbs.append((iir, iic)) return bnbs def FindNeighbors(self): # 回傳一個包含所有鄰居的list nbs = list() nbs += self.FindRowNeighbors() nbs += self.FindColNeighbors() nbs += self.FindBlockNeighbors() return(nbs) class Sudoku(Neighborhood): def __init__(self, inp): super().__init__() self.inp = inp self.start_time = time.time() def Print(self): # 印出目前的數獨 time.sleep(0.0000001) for pos, n in self.inp.items(): print(n, end=' ') if pos[1] == 9: print() print() def Solve(self): # 印出數獨 self.Print() # 找出第一個0的位置 for pos, n in self.inp.items(): if n == 0: self.r, self.c = pos break # 找不到數字是0的位置,代表數獨完成了 if self.r == -1 and self.c == -1: print("完成了") print("花了{:.2}秒".format(time.time()-self.start_time)) exit() # 終止程式(剛好可以離開遞迴) # 判斷可以輸入哪幾個數字 nbs = self.FindNeighbors() candidates = [i for i in range(1, 10)] for pos in nbs: if self.inp[pos] == 0 or self.inp[pos] not in candidates: continue candidates.remove(self.inp[pos]) try_pos_of_r, try_pos_of_c = self.r, self.c # 為了保存數獨目前位置的座標,而用兩個變數儲存 self.r, self.c = -1, -1 # 如果沒有可以輸入的數字 -> 離開solve函式 if not candidates: return # 進入新的solve函式 for cand in candidates: self.inp[(try_pos_of_r, try_pos_of_c)] = cand self.Solve() # 所有候選人數字都試過,代表無解 -> 離開solve函式 self.inp[(try_pos_of_r, try_pos_of_c)] = 0 # 把目前位置的數字還原 return
""" n = "" while n != 50: n = int(input("Digite aqui um numero inteiro: ")) if n > 50: print(" Esse número é muito alto. Tente novamente: ") """ """ # 1 - Crie uma lista com 20 números quaisquer (certifique-se de que alguns números são repetidos). Ordene a lista em ordem numérica com o método 'sort()' e exiba-a na tela. # 2 - Exiba a quantidade de elementos que a lista possui. # 3 - Varra todos os números da lista utilizando o for e exiba na tela apenas os números repetidos. Certifique-se de que cada número repetido apareça apenas uma vez. lista = [1, 2, 4, 5, 6, 3, 7, 2, 7, 7, 4, 3, 8, 82, 97, 97, 75, 3, 86, 2] # lista.sort() lista1 = len(lista) print("Existem {} números nessa lista. ".format(lista1)) lista_vazia = [] for numero in lista: # print(numero) # resp = lista.count(numero) # print("O número {} esta presente {} na lista.".format(numero,resp)) if lista_vazia.count(numero) == 0: lista_vazia.append(numero) resp = lista.count(numero) if resp >= 2: print(numero) # print("O número {} esta presente {} vezes nessa lista.".format(numero,resp)) 4 - Declare uma nova lista e insira 20 números (de 1 a 30) de forma aleatória utilizando a biblioteca random, com o método random.randint(inicio, limite). Ordene a lista em ordem numérica com o método 'sort()' e exiba-a na tela. Consulte a documentação da biblioteca em caso de dúvidas. lista3 = [] from random import randint for numeros in range(20): lista3.append(randint(1, 30)) lista3.sort() print(lista3) 5 - Pegue o código de varredura da lista com o for declarado no item 3 e coloque-o em uma função chamada 'detectar_numeros_repetidos(lista)' que recebe um argumento referente a lista de números e retorna apenas os números repetidos. Execute a função para a lista de números criada no item 1 e exiba-a na tela. def detectar_numeros_repetidos(lista4): lista_vazia2 = [] for numero in lista4: #print(lista4) resp = lista4.count(numero) if resp >= 2: lista_vazia2.append(numero) print(lista_vazia2) lista4 = [1, 2, 4, 5, 6, 3, 7, 2, 7, 7, 4, 3, 8, 82, 97, 97, 75, 3, 86, 2] lista4.sort() print(lista4) lista4 = detectar_numeros_repetidos(lista4) 6 - Execute a função declarada no item 5 para a lista de números criada no item 4. from random import randint def detectar_numeros_repetidos(lista4): lista_vazia2 = [] lista5 = [] for numeros in range(20): lista5.append(randint(1, 30)) lista5.sort() print(lista5) for numero in lista5: #print(lista4) resp = lista5.count(numero) if resp >= 2: lista_vazia2.append(numero) print(lista_vazia2) lista4 = [1, 2, 4, 5, 6, 3, 7, 2, 7, 7, 4, 3, 8, 82, 97, 97, 75, 3, 86, 2] lista4.sort() print(lista4) lista4 = detectar_numeros_repetidos(lista4) 7 - Crie uma função que receba uma lista de números e exiba na tela a quantidade de vezes que o número aparece repetido. Exiba a mensagem apenas para números repetidos e uma só vez por número. Dica: utilize o método 'lista.count(elemento)'. def numeros_repetidos(lista5): lista_vazia3 = [] for numeros in lista5: resp = lista5.count(numeros) print(resp) if resp >= 2: lista_vazia3.append(resp) print("O número {} esta presente {} vezes na lista.".format(numeros,resp)) lista5 = [1, 2, 3, 3, 4, 5, 5, 5] lista5 = numeros_repetidos(lista5) 8 - Crie uma função que receba uma lista de números e retorne um dicionário para cada número, onde a chave do dicionário é o número em questão e o valor do dicionário é a quantidade de vezes que o número se repete. Utilize o método 'lista.count(elemento)'. Se o item não se repetir, exiba a mensagem "O número X não se repete.", caso contrário, exiba a mensagem "O número X se repete Y vezes.". 9 - Faça a mesma coisa que no item 9, porém, em vez de utilizar o método 'count()', faça a checagem para saber se o item em questão está no dicionário utilizando a checagem do método 'dicionário.get(chave)'. Caso a checagem seja negativa (o dicionário ainda não possui o numero) adicione-o no dicionário utilizando 'dicionario[numero] = 1'. Caso a checagem seja positiva, atribua um valor adicional à posição do dicionário utilizando: 'dicionario[numero] = dicionario[numero] + 1'. 10 - Crie uma função que insere 20 números aleatórios (de 1 a 30) em uma lista certificando de que NENHUM número é repetido. Ordene a lista em ordem numérica com o método 'sort()' e exiba-a na tela. """ from random import randint def numeros_sem_repetir(): lista6 = [] while len(lista6) < 20: numero = randint(1,30) resp = lista6.count(numero) if resp == 0: lista6.append(numero) # print(lista6) return lista6 lista_aleatoria = numeros_sem_repetir() lista_aleatoria.sort() print(lista_aleatoria)
""" pessoas = { "SP": 447, "RJ": 323, "MG": 121 } print(pessoas) print(pessoas["SP"]) print(pessoas.get("MG")) refeicoes = { "cafe": 5, "bolo": 10 } print(refeicoes) for indice in refeicoes: print(indice) preco = refeicoes[indice] print(preco) print() def pegarrefeicoes(indices): refeicao = refeicoes.get(indices) print(indices) print(refeicao) if refeicao == None: print("A refeição não existe") else: print("Refeição: {}".format(refeicao)) return refeicao custo1 = pegarrefeicoes("bolo") custo2 = pegarrefeicoes("cafe") conta = 0 conta = conta + custo1 conta = conta + custo2 print(conta) print() #del refeicoes["bolo"] print(refeicoes) """ precos = { "banana":4, "maca":2, "laranja":1.5, "pera":3 } # print(precos) # print(precos["pera"]) estoques = { "banana":6, "maca":0, "laranja":32, "pera":15 } # print(estoques) mantimentos = ["banana", "laranja", "maca"] def computar_compra(mantimento): total = 0 total2 = 0 print("A sua compra foi realizada com suceeso") #print(mantimento) for fruta in mantimento: preco = precos[fruta] #print(preco) estoque = estoques[fruta] if estoque > 0: # print(estoque) print("Você comprou a fruta: {} e pagou R${:.2f} por ela.". format(fruta, preco)) # print("\tPreço: {}".format(preco)) # print("\tEstoques: {}".format(estoque)) #total += preco * estoque # print(total) #print() total2 += preco estoques[fruta] = estoques[fruta] - 1 print("O valor total pago foi de: R${:.2f}".format(total2)) return total computar_compra(mantimentos) print(estoques) mantimentos2 = [] frutas_disponiveis = list(precos.keys()) print("Frutas disponiveis: \n".format("\n ". join(frutas_disponiveis))) print("Digite 'comprar' para realizar a compra") while True: comprar_frutas = input("Qual fruta você gostaria de comprar? ") if comprar_frutas == "comprar": computar_compra(mantimentos) break else: mantimentos2.append(comprar_frutas)
import requests import json import wikipedia class WikiApi: """ Class for setting up API. Contains methods for loading suggestions. """ url = 'http://en.wikipedia.org/w/api.php' headers = { 'Content-Type': 'application/json' } def process_request(self, search_data): """ Queries the wikipedia opensearch API and retreives the links along with matching article names :param search_term: search term for which suggestions has to be retreived :return results: nested list of title, summary for the retreived suggestions """ params = { 'action': 'opensearch', 'search': search_data, 'limit' : 20, 'format': 'json' } response = requests.get(url=self.url, headers=self.headers, params=params) suggestions = json.loads(response.text) results = [] try: for title, summary in zip(suggestions[1], suggestions[2]): results.append([title, summary]) except KeyError: results = [] return results def get_article(self, article_name): """ Fetches the article from the wikipedia :param article_name: Article for which data has to be retreived :return: page object containing the retreived data """ try: page = wikipedia.page(article_name) return page except wikipedia.exceptions.WikipediaException: print("Please provide an article name") return None x = WikiApi() x.process_request('')
# coding: utf-8 # In[1]: import numpy as np import pandas as pd # In[2]: totals = pd.read_csv('totals.csv').set_index(keys=['name']) # In[3]: counts = pd.read_csv('counts.csv').set_index(keys=['name']) # In[4]: #print(totals) # In[5]: #print(counts) # In[6]: print("City with lowest total precipitation:") # In[7]: total_row = totals.sum(axis=1) # In[8]: print(total_row.idxmin()) # In[9]: print("Average precipitation in each month:") # In[10]: total_column = totals.sum(axis=0) # In[11]: #print(total_column) # In[12]: count_column = counts.sum(axis=0) # In[13]: print(total_column / count_column) # In[14]: print('Average precipitation in each city:') # In[15]: count_row = counts.sum(axis=1) # In[16]: print(total_row/count_row)
#!/usr/bin/env python # -*- coding: utf-8 -*- def main(): game=[["#","#","#"], ["#","#","#"], ["#","#","#"]] A=1 B=2 C=3 turn="X" continuous=0 while continuous < 9: c=0 print " A B C" for row in game: c+=1 print str(c)+'|'.join(row) print "It's "+turn+"'s turn." print "Select a coordinate Ex. A,2" a2, a1=input(">"); a2=a2-1; a1=a1-1 if game[a1][a2] == "X" or game[a1][a2] == "O": print "Position is already taken!" continue else: continuous+=1 game[a1][a2]=turn isit=gameover(game,turn) if isit == "break": c=0 for row in game: c+=1 print str(c)+'|'.join(row) print turn+" got three in a row!" break if turn=="X": turn="O" else: turn="X" if continuous == 9: print "It's a draw!" break return 0 def gameover(game,Var): if game [0][0] == Var and game[0][0] == game[1][0] and game[1][0] == game[2][0]: return "break" elif game [0][1] == Var and game[0][1] == game[1][1] and game[1][1] == game[2][1]: return "break" elif game [0][2] == Var and game[0][2] == game[1][2] and game[1][2] == game[2][2]: return "break" elif game [0][0] == Var and game[0][0] == game[0][1] and game[0][1] == game[0][2]: return "break" elif game [1][0] == Var and game[1][0] == game[1][1] and game[1][1] == game[1][2]: return "break" elif game [2][0] == Var and game[2][0] == game[2][1] and game[2][1] == game[2][2]: return "break" elif game [0][0] == Var and game[0][0] == game[1][1] and game[1][1] == game[2][2]: return "break" elif game [0][2] == Var and game[0][2] == game[1][1] and game[1][1] == game[2][0]: return "break" else: return 0 if __name__=='__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*- from motor import Elmotor,Bensinmotor import cPickle as pickle def main(): #Create Electric Engine Motor3=Elmotor() #Create Fuel Engine Motor1=Bensinmotor() #Start/stop the Engine for Motor1 reply=raw_input("Start/Stop engine: ") Motor1.changestate(reply) #Run Fuel Engine driving test? reply=raw_input("Run test? (y/n) ") if reply.lower() == "y": #Create additional Fuel Engine and set fuel to 1 liter Motor2=Bensinmotor() Motor2.fuel=1 #Test Motor1 with set values for time and length print "Motor1 starts driving..." Motor1.driving(60,9000) #Same with Motor2, but Motor2 is off, so it'll "fail". print "Motor2 starts driving..." Motor2.driving(20,1000) else: #If you didn't say you wanted to do the test print "Assuming you meant no..." #Input for how long, and how far, you wanna drive time=input("For how long do you intend to drive? (In minutes): ") length=input("How far do you intend to drive? (In meters): ") Motor1.driving(time,length) #Stuff to charge the Electric Engine Motor3.charge=46 energy=str(Motor3.charge) reply=input("Current charge at "+energy+"% Insert how much charge? ") Motor3.recharge(reply) #Save the values we got. f=open("6-2.data", "w") pickle.dump(Motor1, f) pickle.dump(Motor2, f) pickle.dump(Motor3, f) return 0 if __name__=='__main__': main()
''' This script takes a multicast IP address and finds the multicast mac address. Takes multicast IP, converts to binary string, then takes the hex value of every 4 chars in that string to find the mac ''' print "There's no error checking, please be careful and enter IP addresses correctly" first25 = '0000000100000000010111100' #First 25 bits of multicast mac address first = [] #stores the first octet of multicast range, e.g 224,225, 226, etc... used to provide collision addresses second = 0 #second octet, will +/- 128 used to provide collision addresses ipinput = raw_input("Please enter your IP address: ") IP = ipinput.split('.') firstoctet = IP[0] IP = [int(i) for i in IP[1:]] for i in range(224,240): first.append(i) first.remove(int(firstoctet)) if IP[0] <= 128: second = IP[0] + 128 else: second = IP[0] - 128 mcast = '' macaddr = '' #print IP for i in IP: octet = bin(i)[2:] while (len(octet) < 8): octet = '0' + octet mcast += octet mcast = mcast[1:] #mcast is 24 bit number but mac address conversion only takes last 23 bits. first25 += mcast mac = [first25[i:i+4] for i in range(0, len(first25), 4)] for i in mac: macaddr += hex(int(i, 2))[2:] print 'Here is your MAC address: ', macaddr print 'Here are the multicast addresses with the same mac address' for i in first: print str(i) + '.' + str(second) + '.' + str(IP[1]) + '.' + str(IP[2]) print str(i) + '.' + str(IP[0]) + '.' + str(IP[1]) + '.' + str(IP[2])
n=int(input()) for i in range(n): print('*'*(n-i)) # 참고코드 # n=int(input())+1 # while n:=n-1: # print("*"*n) # :=연산자를 통해 값 사용과 갱신을 한줄에 작성
# Splits lines into a left and right set. class LeftRightSplitter: SAFETY_MARGIN = 0.025 def __init__(self, width, logger): self.width = width self.logger = logger def run(self, lines): left_lines = [] right_lines = [] rejected_lines = [] # Sometimes a line does extend past the middle; we'll filter # those out. In fact, we don't want any lines, too close to # the middle, even if they don't cross it. min_x = (self.width / 2) - (self.width * self.SAFETY_MARGIN) max_x = (self.width / 2) + (self.width * self.SAFETY_MARGIN) for line in lines: if line[0] < min_x and (line[2] < min_x): left_lines.append(line) elif (line[0] > max_x) and (line[2] > max_x): right_lines.append(line) else: rejected_lines.append(line) if (len(left_lines) == 0): raise Exception("Why no lines on left side?") if (len(right_lines) == 0): raise Exception("Why no lines on right side?") self.logger.log_lines("LeftRightSplitter/left", left_lines) self.logger.log_lines("LeftRightSplitter/right", right_lines) self.logger.log_lines("LeftRightSplitter/rejected", rejected_lines) return (left_lines, right_lines)
#6.S08 FINAL PROJECT #Leaderboard.py #GET returns the current leaderboard, formatted by teensey, also can delete and clear the current leaderboard import _mysql import cgi exec(open("/var/www/html/student_code/LIBS/s08libs.py").read()) #HTML formatting print( "Content-type:text/html\r\n\r\n") print('<html>') #Set up the server connection cnx = _mysql.connect(user='cnord_jennycxu', passwd='Pg8rdAyj',db='cnord_jennycxu') method_type = get_method_type() form = get_params() #Display leaderboard if method_type == "GET": # Now pull data from database and compute on it shouldDelete = False if 'shouldDelete' in form.keys(): shouldDelete = form.getvalue("shouldDelete")[0] == "T" if(shouldDelete): query = ("DELETE FROM response_db") try: cnx.query(query) cnx.commit() except: # Rollback in case there is any error cnx.rollback() #display the leaderboard by ordering all players query = ("SELECT * FROM response_db ORDER BY currentScore") #should return senders with 5 highest scores (bug: there will be duplicates from the same game...) cnx.query(query) result = cnx.store_result() rows = result.fetch_row(maxrows=0,how=0) #what does this do? print(rows) else: #print leaderboard so that teensey can pull information to display query = ("SELECT * FROM response_db ORDER BY currentScore DESC") #should return senders with 5 highest scores (bug: there will be duplicates from the same game...) cnx.query(query) result = cnx.store_result() rows = result.fetch_row(maxrows=0,how=0) alph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" #If on teensey, display the players and the winners if(form.getvalue('deviceType') == 'teensy' or form.getvalue('deviceType') == 'teensey'): print('LEADERBOARD\n') playersCount = 0 winnerScore = 0 currentWinner = '' for i in range(len(rows)): if rows[i][8] != None: playersCount = playersCount + 1 print(str(playersCount) + "." + rows[i][4].decode("utf-8") + " : " + str(rows[i][8]) + "\n") if(int(rows[i][8]) >= winnerScore): winnerScore = int(rows[i][8]) currentWinner = rows[i][4].decode("utf-8") else : playersCount = playersCount + 1 print(str(playersCount) + "." + rows[i][4].decode("utf-8") + " : 0\n") print("<b>Current winner is <w>"+currentWinner+"</w> with a score of <s>"+str(winnerScore)+"</s>") else: #If on web, display the players and the winners with more headers and formatting print('<head>') print('<title>Posts Trivia Responses to Database</title>') print('</head>') print('<body>') #print leaderboard stuff now print('<h1>LEADERBOARD</h1>') print('<h2>Your current leaders are:</h2>') playersCount = 0 for i in range(len(rows)): print("<p>") if rows[i][8] != None: playersCount = playersCount + 1 print("%i. <%s>%s</%s>: %s" %(playersCount, alph[i], rows[i][4].decode("utf-8"), alph[i], rows[i][8])) else : playersCount = playersCount + 1 print("%i. <%s>%s</%s>: 0" %(playersCount, alph[i], rows[i][4].decode("utf-8"), alph[i])) print("</p>") print("<h3>Total players: " + str(playersCount) + "</h3>") print('</body>') #this has to be included! print('</html>')
from syllable3 import * from repo import make_syllable import json def syllabify(word): syllable = generate(word.rstrip()) if syllable: syllables = [] encoding = [] for syll in syllable: for s in syll: syllables.append(make_syllable(s)) encoding.append(s) return (syllables, encoding) if __name__ == '__main__': if len(sys.argv) > 1: words = sys.argv[1:] for word in words: (syllables, encoding) = syllabify(word) print(json.dumps(encoding, default=lambda o: o.__dict__)) else: print('Please input a word, or list of words (space-separated) as argument variables') print('e.g. python3 syllable3.py linguist linguistics')
# 8.1) A child can take 1,2 or 3 hops in a staircase of n steps. Given n, how many possible ways the child can # up the stairs? cache = {} def steps(n): if n < 0: return 0 if n == 1: return n if not cache.get(n, False): cache[n] = steps(n - 3) + steps(n - 2) + steps(n -1) return cache[n] # test code print(steps(37))
# given a sorted array, find the range of a given number. class Solution: # @param A : tuple of integers # @param B : integer # @return a list of integers def searchRange(self, A, B): a_len = len(A) if a_len < 1: return [-1, -1] elif a_len == 1 and A[0] == B: return [0, 0] elif a_len == 1 and A[0] != B: return [-1, -1] if self.find(A, B, 0, a_len-1) > -1: low = self.find_lower(A, B, 0, a_len-1) high = self.find_higher(A, B, 0, a_len-1) return [low, high-1] return [-1, -1] def find_lower(self, arr, key, low, high): if low > high: return low mid = low + ((high - low) >> 1) mid_val = arr[mid] if mid_val >= key: return self.find_lower(arr, key, low, mid - 1) else: return self.find_lower(arr, key, mid + 1, high) def find_higher(self, arr, key, low, high): if low > high: return low mid = low + ((high - low) >> 1) mid_val = arr[mid] if mid_val > key: return self.find_higher(arr, key, low, mid - 1) else: return self.find_higher(arr, key, mid + 1, high) def find(self, arr, key, low, high): if low > high: return -1 mid = low + ((high - low) >> 1) mid_val = arr[mid] if mid_val == key: return mid if mid_val < key: return self.find(arr, key, mid+1, high) else: return self.find(arr, key, low, mid-1) # testing code A = [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 ] sol = Solution() print(sol.searchRange(A, 10))
# 8.8) write a program that writes the permutations of a word with duplicates def permutations(word): if len(word) == 1: return word word_list = list(word) result = [] done = [] for i in range(len(word)): temp = word_list.pop(i) if temp in done: word_list.insert(i, temp) continue temp_perm = permutations(''.join(word_list)) result += [temp + x for x in temp_perm] word_list.insert(i, temp) done.append(temp) return result # test code worxd = 'aaaaaaaaaaaa' final = permutations(worxd) print(final)
# Write code to remove duplicates from SinglyLikedList import SinglyLikedList # solution with hash table def delete_duplicates_hash(l1): current_node = l1.head previous_node = None frequencies = {} while current_node is not None: if frequencies.get(current_node.element, 0) > 0: delete_node(current_node, previous_node) else: frequencies[current_node.element] = 1 + frequencies.get(current_node.element, 0) previous_node = current_node current_node = current_node.next # solution with two pointers def delete_duplicates_runner(l1): current_node = l1.head runner = l1.head.next.next previous_node = None while current_node is not None: while runner is not None: if current_node.element == runner.element: delete_node(current_node, previous_node) previous_node = runner runner = runner.next current_node = current_node.next # list solution def delete_duplicates_list(l1): current_node = l1.head previous_node = None node_buffer = [] while current_node is not None: if current_node.element in node_buffer: delete_node(current_node, previous_node) else: node_buffer.append(current_node.element) previous_node = current_node current_node = current_node.next def delete_node(node, previous): previous.next = node.next # create list the_list = SinglyLikedList() the_list.add_element(2) the_list.add_element(5) the_list.add_element(3) the_list.add_element(5) the_list.add_element(1) delete_duplicates_list(the_list) the_list.print_all()
from random import randint def quick_sort(arr, left, right): if left >= right: return pivot_index = partition(arr, left, right) # partition the array. quick_sort(arr, left, pivot_index - 1) # sort left side quick_sort(arr, pivot_index, right) # sort right side def partition(arr, left, right): index = randint(left, right) # random index for partition pivot = arr[index] while left <= right: while arr[left] < pivot: # find elements to left that are > that pivot left += 1 while arr[right] > pivot: # find elements to right that are < that pivot right -= 1 if left <= right: # swap numbers temp = arr[left] arr[left] = arr[right] arr[right] = temp left += 1 right -= 1 return left # return the partition point # test code array = [10, 5, 4, 1, 2, 3, 25] quick_sort(array, 0, len(array) - 1) print(array)
# Given a list of non negative integers, arrange them such that they form the largest number. class Solution: # @param A : tuple of integers # @return a strings def largestNumber(self, arr): arr = list(arr) a_len = len(arr) if a_len < 1: return '' if a_len == 1: return str(arr[0]) result = self.the_sort(arr) str_result = [str(x) for x in result[::-1]] joined_res = ''.join(str_result).lstrip('0') return joined_res if joined_res != '' else '0' def the_sort(self, arr): a_len = len(arr) if a_len < 2: return arr mid = a_len // 2 left_half = self.the_sort(arr[0:mid]) right_half = self.the_sort(arr[mid:]) result = self.merge(left_half, right_half) return result def merge(self, left, right): helper = left + right left_pointer = 0 right_pointer = 0 current = 0 while left_pointer < len(left) and right_pointer < len(right): str_l = str(left[left_pointer]) str_r = str(right[right_pointer]) num_l = int(str_l + str_r) num_r = int(str_r + str_l) if num_l < num_r: helper[current] = left[left_pointer] left_pointer += 1 else: helper[current] = right[right_pointer] right_pointer += 1 current += 1 while left_pointer < len(left): helper[current] = left[left_pointer] current += 1 left_pointer += 1 return helper
class Array(object): def sum(self, size, array_string): numbers = [int(number) for number in array_string.split(' ')] if size != len(numbers): raise Exception('array size is not matched') return sum(numbers)
#================================================== #==> Title: invert-binary-tree #==> Author: Zhang zhen #==> Email: hustmatnoble.gmail.com #==> GitHub: https://github.com/MatNoble #==> Date: 1/19/2021 #================================================== """ https://leetcode-cn.com/problems/invert-binary-tree/ """ class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def invertTree(self, root): if root == None: return None root.left, root.right = root.right, root.left self.invertTree(root.left) self.invertTree(root.right) return root mat = Solution() mat.iverTree(root)
#================================================== #==> Title: 769. 最多能完成排序的块 #==> Author: Zhang zhen #==> Email: hustmatnoble.gmail.com #==> GitHub: https://github.com/MatNoble #==> Date: 2/6/2021 #================================================== """ https://leetcode-cn.com/problems/max-chunks-to-make-sorted/ """ from typing import List class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: k = 0 max_ = arr[0] for idx, val in enumerate(arr): max_ = max(max_, val) if max_ <= idx: k += 1 return k mat = Solution() arr = [4,3,2,1,0] arr = [1,0,2,3,4] mat.maxChunksToSorted(arr)
#================================================== #==> Title: 154. 寻找旋转排序数组中的最小值 II #==> Author: Zhang zhen #==> Email: hustmatnoble.gmail.com #==> GitHub: https://github.com/MatNoble #==> Date: 1/31/2021 #================================================== """ https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array-ii/ """ from typing import List class Solution: def findMin(self, nums: List[int]) -> int: left, right = 0, len(nums)-1 while left < right: mid = left + (right - left) // 2 while left < mid and nums[left] == nums[mid]: left += 1 if nums[left] < nums[right]: return nums[left] if nums[left] <= nums[mid]: left = mid+1 else: right = mid return nums[left] mat = Solution() nums = [2, 0, 2, 2] nums = [1, 2, 3] nums = [1] nums = [2, 0, 2, 2, 2, 2, 2] mat.findMin(nums)
#================================================== #==> Title: Stack #==> Author: Zhang zhen #==> Email: hustmatnoble.gmail.com #==> GitHub: https://github.com/MatNoble #==> Date: 1/15/2021 #================================================== """ Next Greater Element in: [2,1,2,4,3] out: [4,2,4,-1,-1] """ def nextGreaterElement(nums): n = len(nums) res = [-1] * n stack = [] for i in range(n-1, -1, -1): while len(stack) != 0 and nums[i] >= nums[stack[-1]]: stack.pop() if len(stack) != 0: res[i] = nums[stack[-1]] stack.append(i) return res """ 循环数组 in: [2,1,2,4,3] out: [4,2,4,-1,4] """ def nextGreaterElementCircle(nums): n = len(nums) res = [-1] * n stack = [] for i in range(2*n-1, -1, -1): while len(stack) != 0 and nums[i % n] >= nums[stack[-1]]: stack.pop() if len(stack) != 0: res[i % n] = nums[stack[-1]] stack.append(i % n) return res nums = [2,1,2,4,3] # Next Greater Element print(nextGreaterElement(nums)) # 循环数组 print(nextGreaterElementCircle(nums))
#================================================== #==> Title: single-element-in-a-sorted-array #==> Author: Zhang zhen #==> Email: hustmatnoble.gmail.com #==> GitHub: https://github.com/MatNoble #==> Date: 1/11/2021 #================================================== """ https://leetcode-cn.com/problems/single-element-in-a-sorted-array/ """ class Solution: def singleNonDuplicate(self, nums): if len(nums) == 1: return nums[0] i, j = 0, len(nums) - 1 while i < j: k = ((j - i)/2) % 2 mid = i + (j-i) // 2 atemp, temp, tempa = nums[mid-1], nums[mid], nums[mid+1] if temp != atemp and temp != tempa: return temp elif temp == tempa: if k == 0: i = mid + 2 elif k == 1: j = mid - 1 elif temp == atemp: if k == 0: j = mid - 2 elif k == 1: i = mid + 1 return nums[i] nums = [1,1,2,3,3,4,4,8,8] # nums = [3,3,7,7,10,11,11] # nums = [3] # nums = [1,2,2] # nums = [1,1,2] mat = Solution() mat.singleNonDuplicate(nums)
#================================================== #==> Title: first-unique-character-in-a-string #==> Author: Zhang zhen #==> Email: hustmatnoble.gmail.com #==> GitHub: https://github.com/MatNoble #==> Date: 1/20/2021 #================================================== """ https://leetcode-cn.com/problems/first-unique-character-in-a-string/ """ import collections class Solution: def firstUniqChar(self, s): # hashMap = {} # for c in s: hashMap[c] = hashMap.get(c,0) + 1 hashMap = collections.Counter(s) for i, c in enumerate(s): if hashMap[c] == 1: return i return -1 s = "loveleetcode" # s = "z" # s = "" # s = "cc" # s = "aadadaad" mat = Solution() mat.firstUniqChar(s)
import sys sys.path.append('./Data Structures and Algorithms') from LinkedLists import * def printLinkedList(head): if head == None: return printLinkedList(head.next) print(head.val) def reverse(head): pre, cur = None, head while cur != None: next = cur.next cur.next, pre = pre, cur cur = next return pre def isPalindrome(head): slow, fast = head, head while fast != None and fast.next != None: slow = slow.next fast = fast.next.next if fast != None: slow = slow.next left, right = head, reverse(slow) while right != None: if left.val != right.val: return False left, right = left.next, right.next return True mat = LinkedList() # for i in range(5): # mat.append(i) # mat.display() mat.head = ListNode(3) e1 = ListNode(3) e2 = ListNode(3) e3 = ListNode(4) mat.head.next = e1 # e1.next = e2 # e2.next = None current_node = mat.head while current_node != None: print(current_node.val) current_node = current_node.next isPalindrome(mat.head)
#================================================== #==> Title: peak-index-in-a-mountain-array #==> Author: Zhang zhen #==> Email: hustmatnoble.gmail.com #==> GitHub: https://github.com/MatNoble #==> Date: 1/10/2021 #================================================== """ https://leetcode-cn.com/problems/peak-index-in-a-mountain-array/ """ class Solution: def peakIndexInMountainArray(self, arr): i, j = 0, len(arr) - 1 while i < j: mid = i + (j-i+1) // 2 if arr[mid] > arr[mid-1]: i = mid else: j = mid - 1 return j arr = [0, 2, 4, 7, 13, 5, 2, 0] mat = Solution() index = mat.peakIndexInMountainArray(arr) print(arr[index]) if arr[index] == max(arr): print(True) else: print(False)
#================================================== #==> Title: shortest-distance-to-a-character #==> Author: Zhang zhen #==> Email: hustmatnoble.gmail.com #==> GitHub: https://github.com/MatNoble #==> Date: 1/27/2021 #================================================== """ https://leetcode-cn.com/problems/shortest-distance-to-a-character/ """ from typing import List class Solution: def shortestToChar(self, S: str, C: str) -> List[int]: n = len(S) res = [n]*n # first loop i = 0 while S[i] != C[0]: i += 1 while i < n: res[i] = 0 if S[i] == C[0] else res[i-1]+1 i += 1 # second loop i -= 2 while i > -1: if res[i+1]+1 < res[i]: res[i] = res[i+1]+1 i -= 1 return res mat = Solution() S = "loveleetcode" C = 'e' # S = "aaba" # C = "b" mat.shortestToChar(S, C)
#================================================== #==> Title: 59. 螺旋矩阵 II #==> Author: Zhang zhen #==> Email: hustmatnoble.gmail.com #==> GitHub: https://github.com/MatNoble #==> Date: 2/1/2021 #================================================== """ https://leetcode-cn.com/problems/spiral-matrix-ii/ """ from typing import List class Solution: def generateMatrix(self, n: int) -> List[List[int]]: i = j = 0 k = c = 1 res = [[0]*n for i in range(n)] while k < n*n: while j < n-c: res[i][j] = k k += 1 j += 1 while i < n-c: res[i][j] = k k += 1 i += 1 while j > c-1: res[i][j] = k k += 1 j -= 1 while i > c-1: res[i][j] = k k += 1 i -= 1 i += 1 j += 1 c += 1 if k == n*n: res[i][i] = k return res mat = Solution() n = 7 # n = 1 mat.generateMatrix(n)
def order_inputs(x1, y1, x2, y2): if x1 > x2: x1, x2 = swap_inputs(x1,x2) if y1 > y2: y1, y2 = swap_inputs(y1,y2) return x1, y1, x2, y2 def swap_inputs(a,b): return b, a def is_input_valid(layout, x1, y1, x2, y2): width = len(layout) height = len(layout[0]) if width > 0 else 0 if x1 < 1 or x1 > width or x2 < 1 or x2 > width: return False if y1 < 1 or y1 > height or y2 < 1 or y2 > height: return False return True
def isprime(n): nn = n - 1 for i in xrange(2, nn): if n % i == 0: return False return True def primes(n): count = 0 for i in xrange(2, n): if isprime(i): count = count + 1 return count N = 10 * 10000 print(primes(N))
import re import collections # 获取词表、计数 with open('/Users/zhangwanyu/data.txt') as f: data = f.readlines() model = collections.defaultdict(int) vocab = set() for line in data: line = re.findall("[a-z]+",line.lower()) for word in line: model[word] += 1 vocab.add(word) print(len(model)) # 29154 print(len(vocab)) # 29154 alphabet = "abcdefghijklmnopqrstuvwxyz" def filter(words): new_words = set() for word in words: if word in vocab: new_words.add(word) return new_words # 增删改1个字符 def edist_1(word): n = len(word) # 删除 n种情况 word1 = [word[0:i] + word[i+1:] for i in range(n)] # 增加 n*len(alphabet)种情况 word2 = [word[0:i] + c + word[i+1:] for i in range(n) for c in alphabet] # 相邻交换 n-1种情况 word3 = [word[0:i] + word[i+1] + word[i] + word[i+2:] for i in range(n-1)] # 替换 word4 = [word[0:i] + c + word[i+1:] for i in range(n) for c in alphabet] words = set(word1+word2+word3+word4) return filter(words) def edist_2(word): words = set() for w in edist_1(word): word_2 = edist_1(word) words.add(word_2) return words def correct(word): if word not in vocab: candidates = edist_1(word) or edist_2(word) print(candidates) return max(candidates,key=lambda w:model[w]) else: return word res = correct('mske') print('正确答案是:',res)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #. Дано предложение. Найти наибольшее количество идущих подряд пробелов. if __name__ == '__main__': st = input('Введите предложение') mx = [0] c = 0 for i in range(len(st)): if st[i] == ' ': mx[c] += 1 elif st[i] != ' ' and st[i-1] == ' ': c += 1 mx.append(0) print(max(mx))
from .functions import _DEPRECATION_ERROR_FUNCTION_KWARGS from . import Units from .data.data import Data def relative_vorticity( u, v, wrap=None, one_sided_at_boundary=False, radius=6371229.0, cyclic=None ): """Calculate the relative vorticity using centred finite differences. The relative vorticity of wind defined on a Cartesian domain (such as a plane projection) is defined as ζcartesian = δv/δx − δu/δy where x and y are points on along the 'X' and 'Y' Cartesian dimensions respectively; and u and v denote the 'X' and 'Y' components of the horizontal winds. If the wind field field is defined on a spherical latitude-longitude domain then a correction factor is included: ζspherical = δv/δx − δu/δy + (u/a)tan(ϕ) where u and v denote the longitudinal and latitudinal components of the horizontal wind field; a is the radius of the Earth; and ϕ is the latitude at each point. The relative vorticity is calculated using centred finite differences (see the *one_sided_at_boundary* parameter). The grid may be global or limited area. If missing values are present then missing values will be returned at points where the centred finite difference could not be calculated. The boundary conditions may be cyclic in longitude. The non-cyclic boundaries may either be filled with missing values or calculated with off-centre finite differences. Reference: H.B. Bluestein, Synoptic-Dynamic Meteorology in Midlatitudes, 1992, Oxford Univ. Press p113-114 :Parameters: u: `Field` A field containing the x-wind. Must be on the same grid as the y-wind. v: `Field` A field containing the y-wind. Must be on the same grid as the x-wind. radius: optional The radius of the sphere when the winds are on a spherical polar coordinate domain. May be any numeric scalar object that can be converted to a `Data` object (which includes numpy array and `Data` objects). By default *radius* has a value of 6371229.0 metres, representing the Earth's radius. If units are not specified then units of metres are assumed. *Parameter example:* Five equivalent ways to set a radius of 6371200 metres: ``radius=6371200``, ``radius=numpy.array(6371200)``, ``radius=cf.Data(6371200)``, ``radius=cf.Data(6371200, 'm')``, ``radius=cf.Data(6371.2, 'km')``. wrap: `bool`, optional Whether the longitude is cyclic or not. By default this is autodetected. one_sided_at_boundary: `bool`, optional If True then if the field is not cyclic off-centre finite differences are calculated at the boundaries, otherwise missing values are used at the boundaries. :Returns: `Field` The relative vorticity calculated with centred finite differences. """ if cyclic: _DEPRECATION_ERROR_FUNCTION_KWARGS( "relative_vorticity", {"cyclic": cyclic}, "Use the 'wrap' keyword instead", ) # pragma: no cover # Get the standard names of u and v u_std_name = u.get_property("standard_name", None) v_std_name = v.get_property("standard_name", None) # Copy u and v u = u.copy() v = v.copy() # Get the X and Y coordinates (u_x_key, u_y_key), (u_x, u_y) = u._regrid_get_cartesian_coords( "u", ("X", "Y") ) (v_x_key, v_y_key), (v_x, v_y) = v._regrid_get_cartesian_coords( "v", ("X", "Y") ) if not u_x.equals(v_x) or not u_y.equals(v_y): raise ValueError("u and v must be on the same grid.") # Check for lat/long is_latlong = (u_x.Units.islongitude and u_y.Units.islatitude) or ( u_x.units == "degrees" and u_y.units == "degrees" ) # Check for cyclicity if wrap is None: if is_latlong: wrap = u.iscyclic(u_x_key) else: wrap = False # --- End: if # Find the relative vorticity if is_latlong: # Save the units of the X and Y coordinates x_units = u_x.Units y_units = u_y.Units # Change the units of the lat/longs to radians u_x.Units = Units("radians") u_y.Units = Units("radians") v_x.Units = Units("radians") v_y.Units = Units("radians") # Find cos and tan of latitude cos_lat = u_y.cos() tan_lat = u_y.tan() # Reshape for broadcasting u_shape = [1] * u.ndim u_y_index = u.get_data_axes().index(u_y_key) u_shape[u_y_index] = u_y.size v_shape = [1] * v.ndim v_y_index = v.get_data_axes().index(v_y_key) v_shape[v_y_index] = v_y.size # Calculate the correction term corr = u.copy() corr *= tan_lat.array.reshape(u_shape) # Calculate the derivatives v.derivative( v_x_key, wrap=wrap, one_sided_at_boundary=one_sided_at_boundary, inplace=True, ) v.data /= cos_lat.array.reshape(v_shape) u.derivative( u_y_key, one_sided_at_boundary=one_sided_at_boundary, inplace=True ) radius = Data.asdata(radius).squeeze() radius.dtype = float if radius.size != 1: raise ValueError("Multiple radii: radius={!r}".format(radius)) if not radius.Units: radius.override_units(Units("metres"), inplace=True) elif not radius.Units.equivalent(Units("metres")): raise ValueError( "Invalid units for radius: {!r}".format(radius.Units) ) # Calculate the relative vorticity. Do v-(u-corr) rather than # v-u+corr to be nice with coordinate reference corner cases. rv = v - (u - corr) rv.data /= radius # Convert the units of latitude and longitude to canonical units rv.dim("X").Units = x_units rv.dim("Y").Units = y_units else: v.derivative( v_x_key, one_sided_at_boundary=one_sided_at_boundary, inplace=True ) u.derivative( u_y_key, one_sided_at_boundary=one_sided_at_boundary, inplace=True ) rv = v - u # Convert the units of relative vorticity to canonical units rv.Units = Units("s-1") # Set the standard name if appropriate and delete the long_name if (u_std_name == "eastward_wind" and v_std_name == "northward_wind") or ( u_std_name == "x_wind" and v_std_name == "y_wind" ): rv.standard_name = "atmosphere_relative_vorticity" else: rv.del_property("standard_name", None) rv.del_property("long_name", None) return rv def histogram(*digitized): """Return the distribution of a set of variables in the form of an N-dimensional histogram. The number of dimensions of the histogram is equal to the number of field constructs provided by the *digitized* argument. Each such field construct defines a sequence of bins and provides indices to the bins that each value of one of the variables belongs. There is no upper limit to the number of dimensions of the histogram. The output histogram bins are defined by the exterior product of the one-dimensional bins of each digitized field construct. For example, if only one digitized field construct is provided then the histogram bins simply comprise its one-dimensional bins; if there are two digitized field constructs then the histogram bins comprise the two-dimensional matrix formed by all possible combinations of the two sets of one-dimensional bins; etc. An output value for an histogram bin is formed by counting the number cells for which the digitized field constructs, taken together, index that bin. Note that it may be the case that not all output bins are indexed by the digitized field constructs, and for these bins missing data is returned. The returned field construct will have a domain axis construct for each dimension of the histogram, with a corresponding dimension coordinate construct that defines the bin boundaries. .. versionadded:: 3.0.2 .. seealso:: `cf.Field.bin`, `cf.Field.collapse`, `cf.Field.digitize`, `cf.Field.percentile`, `cf.Field.where` :Parameters: digitized: one or more `Field` One or more field constructs that contain digitized data with corresponding metadata, as would be output by `cf.Field.digitize`. Each field construct contains indices to the one-dimensional bins to which each value of an original field construct belongs; and there must be ``bin_count`` and ``bin_bounds`` properties as defined by the `cf.Field.digitize` method (and any of the extra properties defined by that method are also recommended). The bins defined by the ``bin_count`` and ``bin_bounds`` properties are used to create a dimension coordinate construct for the output field construct. Each digitized field construct must be transformable so that its data is broadcastable to any other digitized field contruct's data. This is done by using the metadata constructs of the to create a mapping of physically compatible dimensions between the fields, and then manipulating the dimensions of the digitized field construct's data to ensure that broadcasting can occur. :Returns: `Field` The field construct containing the histogram. **Examples:** Create a one-dimensional histogram based on 10 equally-sized bins that exactly span the data range: >>> f = cf.example_field(0) >>> print(f) Field: specific_humidity (ncvar%q) ---------------------------------- Data : specific_humidity(latitude(5), longitude(8)) 1 Cell methods : area: mean Dimension coords: latitude(5) = [-75.0, ..., 75.0] degrees_north : longitude(8) = [22.5, ..., 337.5] degrees_east : time(1) = [2019-01-01 00:00:00] >>> print(f.array) [[0.007 0.034 0.003 0.014 0.018 0.037 0.024 0.029] [0.023 0.036 0.045 0.062 0.046 0.073 0.006 0.066] [0.11 0.131 0.124 0.146 0.087 0.103 0.057 0.011] [0.029 0.059 0.039 0.07 0.058 0.072 0.009 0.017] [0.006 0.036 0.019 0.035 0.018 0.037 0.034 0.013]] >>> indices, bins = f.digitize(10, return_bins=True) >>> print(indices) Field: long_name=Bin index to which each 'specific_humidity' value belongs (ncvar%q) ------------------------------------------------------------------------------------ Data : long_name=Bin index to which each 'specific_humidity' value belongs(latitude(5), longitude(8)) Cell methods : area: mean Dimension coords: latitude(5) = [-75.0, ..., 75.0] degrees_north : longitude(8) = [22.5, ..., 337.5] degrees_east : time(1) = [2019-01-01 00:00:00] >>> print(bins.array) [[0.003 0.0173] [0.0173 0.0316] [0.0316 0.0459] [0.0459 0.0602] [0.0602 0.0745] [0.0745 0.0888] [0.0888 0.1031] [0.1031 0.1174] [0.1174 0.1317] [0.1317 0.146 ]] >>> h = cf.histogram(indices) >>> rint(h) Field: number_of_observations ----------------------------- Data : number_of_observations(specific_humidity(10)) 1 Cell methods : latitude: longitude: point Dimension coords: specific_humidity(10) = [0.01015, ..., 0.13885] 1 >>> print(h.array) [9 7 9 4 5 1 1 1 2 1] >>> print(h.coordinate('specific_humidity').bounds.array) [[0.003 0.0173] [0.0173 0.0316] [0.0316 0.0459] [0.0459 0.0602] [0.0602 0.0745] [0.0745 0.0888] [0.0888 0.1031] [0.1031 0.1174] [0.1174 0.1317] [0.1317 0.146 ]] Create a two-dimensional histogram based on specific humidity and temperature bins. The temperature bins in this example are derived from a dummy temperature field construct with the same shape as the specific humidity field construct already in use: >>> g = f.copy() >>> g.standard_name = 'air_temperature' >>> import numpy >>> g[...] = numpy.random.normal(loc=290, scale=10, size=40).reshape(5, 8) >>> g.override_units('K', inplace=True) >>> print(g) Field: air_temperature (ncvar%q) -------------------------------- Data : air_temperature(latitude(5), longitude(8)) K Cell methods : area: mean Dimension coords: latitude(5) = [-75.0, ..., 75.0] degrees_north : longitude(8) = [22.5, ..., 337.5] degrees_east : time(1) = [2019-01-01 00:00:00] >>> indices_t = g.digitize(5) >>> h = cf.histogram(indices, indices_t) >>> print(h) Field: number_of_observations ----------------------------- Data : number_of_observations(air_temperature(5), specific_humidity(10)) 1 Cell methods : latitude: longitude: point Dimension coords: air_temperature(5) = [281.1054839143287, ..., 313.9741786365939] K : specific_humidity(10) = [0.01015, ..., 0.13885] 1 >>> print(h.array) [[2 1 5 3 2 -- -- -- -- --] [1 1 2 -- 1 -- 1 1 -- --] [4 4 2 1 1 1 -- -- 1 1] [1 1 -- -- 1 -- -- -- 1 --] [1 -- -- -- -- -- -- -- -- --]] >>> h.sum() <CF Data(): 40 1> """ if not digitized: raise ValueError( "Must provide at least one 'digitized' field construct" ) f = digitized[0].copy() f.clear_properties() return f.bin("sample_size", digitized=digitized)
'''There is a function mu(k,N) := the probability that k random numbers from 1...N have a connected graph. strategy: given N and k pick k random numbers from 1...N and determine if the graph is connected. the graph on subset of the naturals, S, has edge between a,b if they are not coprime. ''' from itertools import izip # gabe's from number_theory import coprime def reverse_enumerate(sequence): """Enumerate over a sequence in reverse order while retaining proper indexes""" return izip(reversed(xrange(len(sequence))), reversed(sequence)) def is_connected(S): '''pick random vertex, do depth-first search on graph. if find all vertices, stop return true. if finishes without finding all vertices stop return false.''' S = set(S) vertex = S.pop() return depth_first(vertex, S, [vertex]) def is_edge(a,b): return not coprime(*sorted(a,b)) def depth_first(vertex, the_rest, connected_component): """given a vertex, its known connected component, determine if the_rest is connected to it""" for b in tuple(the_rest): if b in the_rest and is_edge(vertex,b): connected_component.append(b) the_rest.remove(b) depth_first(b, the_rest, connected_component) if the_rest: return False else: return True def test(): S = [14, 18, 20, 26, 3] assert is_connected(S) S = [14, 18, 20, 26, 3,142,13] assert is_connected(S) S = [14, 18, 20, 26, 3, 7] assert is_connected(S) S = [14, 18, 20, 26, 3, 7,31] assert not is_connected(S) S = [2*3,3*5,5*7,7*11,11*13,13*15,15*17,29*2,2*41,2*17*19*37] assert is_connected(S) assert is_connected(S+[17]) assert not is_connected(S+[43]) assert is_connected([7]) import random D = [5*3*17, 2*3, 13*11, 2*17*19*37, 7*11, 7*5, 5*19, 41*2, 29*2, 3*5, 13*7] for p in xrange(10**3): random.shuffle(D) assert is_connected(D) if __name__=="__main__": test()
s = "Global variable" def func(): #return 1 #global s #s=50 #print(s) mylocal = 10 print(locals()) print(globals()['s']) func() print(s) def hello(name="Rafina"): return "hello "+name print(hello()) mynewgreet = hello print(mynewgreet()) def hello1(name="Rafina"): print("THE HELLO() FUNCTION HAS BEEN RUN!") def greet(): return "THIS STRING IS INSIDE GREET()" def welcome(): return "THIS STRING IS INSIDE WELCOME!" if name == "Rafina": return greet else: return welcome #print(greet()) #print(welcome()) #print("End of hello()") x = hello1() print(x()) def hello2(): return "Hi Rafina" def other(func): print("hello") print(func()) other(hello2) def new_decorator(func): def wrap_func(): print("CODE HERE BEFORE EXECUTING FUNC") func() print("FINC() HAS BEEN CALLED") return wrap_func @new_decorator def func_needs_decorator(): print("THIS FUNCTION IS IN NEED OF A DECORATOR") #func_needs_decorator = new_decorator(func_needs_decorator) func_needs_decorator()
""" This practice shows how class attribute is created and its namespace is different from instance attribute more details are here: https://www.toptal.com/python/python-class-attributes-an-overly-thorough-guide """ class Test_Class(object): class_attribute = 1 def __init__(self, instance_attribute): self.instance_attribute = instance_attribute def method_1(self): return 1 if __name__ == "__main__": instance_1 = Test_Class(2) print('instance 1 has a class attribute of {}'.format(instance_1.class_attribute)) print('instance 1 has an instance attribute of {}'.format(instance_1.instance_attribute)) instance_2 = Test_Class(3) print('instance 2 has a class attribute of {}'.format(instance_2.class_attribute)) print('instance 2 has an instance attribute of {}'.format(instance_2.instance_attribute)) print('class_attribute' in instance_1.__dict__) # False because it's a class attribute print('class_attribute' in Test_Class.__dict__) # True because it's a class attribute print("So far, so good!") # expected results: # instance 1 has a class attribute of 1 # instance 1 has an instance attribute of 2 # instance 2 has a class attribute of 1 # instance 2 has an instance attribute of 3 # False # True # So far, so good!
print("Hello estranho!") name = input("Qaul o seu nome ? ") print("Praazer, " + name)
import random l=["s","p","si"] print(l) #print(l[1]) #print(l[0]) #print(l[4]) #print(l[5]) #for i in range(0,6): #print(i) #l[1]=10 #print(l) #print(l[1]) #print(len(l)) '''if "hi" in l: print("Yes") else: print("No")''' '''y = input("Enter your choice: ") print("Hii ",y)''' c = random.choice(l) u = input("Enter your choice: ") if u == c: print("It's a tie") if c == 's' and u == 'si': print("C is the winner") if c == 's' and u == 'p': print("U is the winner") if c == 'si' and u == 'p': print("C is the winner") if c == 'si' and u == 's': print("U is the winner") if c == 'p' and u == 'si': print("U is the winner") if c == 'p' and u == 's': print("C is the winner") print(c)
class Family: # class attribute visits = 0 # instance attribute def __init__(self, name, house_name): self.family_name = name self.house_name = house_name self.members = [] # instance method def add_member(self, x): self.members.append(x) # instance method def remove_member(self, x): self.members.remove(x) def get_family_name(self): return self.family_name def get_family_hash(self,): return (len(self.family_name) + 342432324) % 233 class Person(Family): """ Person inherits Family Class """ def __init__(self, person_name, person_age, family_name, house_name): super().__init__(family_name, house_name) self.person_name = person_name self.person_age = person_age @property def wealth(self): return 100 if self.person_age > 30 else 60 # Polymorphism def get_family_name(self): return self.person_name.split(' ')[-1] print("Person is subClass of Family: {}".format(issubclass(Person, Family))) person = Person('R Jha', 24, 'Jha', 'Jha_House') print("person is instance of Person: {}".format(isinstance(person, Person))) # Creating variable on the fly person.nationality = 'Indian' # deleting the attribute # del person.nationality print(dir(person))
import pprint class invalidAgeError(Exception): pass f=open("empdata.txt") employees=[] for line in f.readlines(): line=line.rstrip() emp={} emp['Id']=line.split(":")[0] emp['Name']=line.split(":")[1] emp['Age']=line.split(":")[2] emp['Salary']=line.split(":")[3] try: if(int(emp['Age'])<18): msg="entry",emp['Id'],"Skipped due to Inappropriate age" raise invalidAgeError(msg) else: employees.append(emp) except invalidAgeError as e: print e pp=pprint.PrettyPrinter(indent=4) pp.pprint (employees)
class Counter: __count = 0 def getCounter(self): self.__count += 1 print self.__count print "-----------------------------------------------------------" counter = Counter() counter.getCounter() counter.getCounter() # print counter.__count - ERROR print counter._Counter__count print "-----------------------------------------------------------"
str1 = raw_input("Enter the string : ") rev = str1[::-1] if str1==rev: print "%s is Palindrome" %str1 else: print "%s is not Palindrome" %str1
class SayHello: def __init__(self,arg): print "Inside Constructor = ",self self.greeting = "Hello " +arg +", How are you ?" def displayGreeting(self): return self.greeting def convertUpper(self): return self.greeting.upper() print "-----------------------------------------------------------------" # Object Instantiation hello1 = SayHello("Saddam") print "Object 1 = ",hello1 print "Greeting From Class Instance Memmber: ",hello1.greeting print "Greeting From Class Method: ",hello1.displayGreeting() print "Greeting From Class Method: ",hello1.convertUpper() print "-----------------------------------------------------------------" hello2 = SayHello("Jhutan") print "Object 2 = ",hello2 print "Greeting From Class Instance Memmber: ",hello2.greeting print "Greeting From Class Method: ",hello2.displayGreeting() print "Greeting From Class Method: ",hello2.convertUpper() print "-----------------------------------------------------------------"
unsortedList = ['Aaaa', 'bb', 'cccccccc', 'zzzzzzzzzzzz'] print "Unsorted List : " ,unsortedList sortedList = sorted(unsortedList,key=len) print "Sorted List : " ,sortedList
lst = range(50) print "Numbers Divisible by 4 : ",filter(lambda i:i%4==0, lst) def evenCheck(x): return x%2==0 print "Even Numbers \t\t: ",filter(evenCheck, lst) words = ["abc","xyz","NIL","AMN"] #print [i for i in words if i.isupper()] print "Only Uppercase Words : ",filter(lambda i:i.isupper(),words)
listOne = [123,'abc',4.56] print listOne print "-----------------------------------------------------------" tupleOne = (123,'abc',4.56) print tupleOne print "-----------------------------------------------------------" print listOne[2] listTwo = ['inner','first',listOne,56] print listTwo print "-----------------------------------------------------------" tupleTwo = 'a',4,'b' print type(tupleTwo) print type(listTwo) print "-----------------------------------------------------------" print listTwo[1:3] print listTwo[2][1] print "-----------------------------------------------------------" listTwo.append('ram') print listTwo print "-----------------------------------------------------------" print tupleTwo[1] print "-----------------------------------------------------------" print tupleTwo.index('b') print "-----------------------------------------------------------" print listTwo.pop() print listTwo print "-----------------------------------------------------------" listTwo.remove('first') print listTwo print "-----------------------------------------------------------" listTwo.insert(1,'third') print listTwo * 3 print "-----------------------------------------------------------" listTwo.reverse() print listTwo print "-----------------------------------------------------------" listTwo.sort() print listTwo print "-----------------------------------------------------------" listTwo.append(56) print listTwo.count(56) print "-----------------------------------------------------------" listOne.remove(123) print listTwo print "-----------------------------------------------------------" print 'third' in listTwo print "-----------------------------------------------------------" print dir(listTwo) print "-----------------------------------------------------------" print dir(tupleTwo) print "-----------------------------------------------------------" listThree = [11,55,22,4,223,434,12,43] print listThree print sorted(listThree) print "-----------------------------------------------------------" listFour = listThree print id(listThree) print id(listFour) print "-----------------------------------------------------------" import copy listFive = copy.deepcopy(listThree) print id(listFive) print listFive print "-----------------------------------------------------------" listThree.append(66) print listThree print listFive print "-----------------------------------------------------------" print "-----------------------------------------------------------"
"""def long_words(n,str1): longWordsList=[] words = str1.split(' ') for i in words: if len(i) > n: longWordsList.append(i) return longWordsList print(long_words(3,"The quick brown fox jumps over the lazy dog")) """ longWords = lambda : [i for i in raw_input("Enter the String ").split(' ') if len(i) >3 ] print longWords()
class BookingSystem(object): ''' This is the class for booking system logic ''' def __init__(self, row_count, seat_count): self._seats = {} # array of array containing seat data 0 - free, 1 - occupied self.row_count = row_count self.seat_count = seat_count for row in range(0,row_count): self._seats[row] = {} for seat in range(0, seat_count): self._seats[row][seat] = 0 def book_specific_seat(self, row, seat): ''' Book specific seat :param row: :param seat: :return: True if successfully booked False if already occupied ''' try: x = self._seats[row][seat] except KeyError as x: raise ValueError("value is out of range") if x==0: self._seats[row][seat] = 1 return True else: return False def book_best(self, n_seats): ''' Book n best seats :param n_seats: :return: list of tuples [(row, seat),] ''' bookinglist = [] for row in range(0,self.row_count): for seat in range(0, self.seat_count): if self._seats[row][seat] == 0: self._seats[row][seat] = 1 bookinglist.append((row, seat)) if len(bookinglist) == n_seats: break if len(bookinglist) == n_seats: break if len(bookinglist) < n_seats: for row,seat in bookinglist: self._seats[row][seat] = 0 return "error" return bookinglist @staticmethod def something_static(): return 123 @classmethod def something_for_the_class(cls): return cls
import sys from time import time def bubble_sort(lista): ordenado = False while not ordenado: ordenado = True for i in range(len(lista)-1): if lista[i] > lista[i+1]: lista[i], lista[i+1] = lista[i+1], lista[i] ordenado = False def merge_sort(array, begin=0, end=None): if end == None: end = len(array) if (end-begin) > 1: middle = (begin+end) // 2 merge_sort(array, begin, middle) merge_sort(array, middle, end) merge(array, begin, middle, end) def merge(array, begin, middle, end): left = array[begin:middle] right = array[middle:end] l, r = 0, 0 for i in range(begin, end): if l >= len(left): array[i] = right[r] r += 1 elif r >= len(right): array[i] = left[l] l += 1 elif left[l] < right[r]: array[i] = left[l] l += 1 else: array[i] = right[r] r += 1 def minimo(lista, index): tamanho = len(lista) index_minimo = index for j in range(index, tamanho): if lista[index_minimo] > lista[j]: index_minimo = j return index_minimo def selection_sort(lista): tamanho = len(lista) for i in range(tamanho - 1): index_minimo = minimo(lista, i) if lista[i] > lista[index_minimo]: lista[i], lista[index_minimo] = lista[index_minimo], lista[i] def insertion_sort(lista): tamanho = len(lista) for i in range(1, tamanho): pivot = i anterior = i - 1 while anterior >= 0 and lista[pivot] < lista[anterior]: lista[pivot], lista[anterior] = lista[anterior], lista[pivot] anterior -= 1 pivot -= 1 def quick_sort(lista, inicio=0, fim=None): if fim is None: fim = len(lista) - 1 if inicio < fim: p = partition(lista, inicio, fim) quick_sort(lista, inicio, p - 1) quick_sort(lista, p + 1, fim) def partition(lista, inicio, fim): pivot = lista[fim] i = inicio for c in range(inicio, fim): if lista[c] <= pivot: lista[c], lista[i] = lista[i], lista[c] i += 1 lista[i], lista[fim] = lista[fim], lista[i] return i if __name__ == "__main__": # Para executar um algoritmo específico use o terminal: # python3 algoritmos_de_ordenacao.py <nome_do_algoritmo> <lista> # EXEMPLO: # python3 algoritmos_de_ordenacao.py bubble 2 5 8 9 4 1 args = sys.argv try: entrada_flag = args[1] entrada_lista = args[2:] lambda_converter = lambda n: int(n) lista = list(map(lambda_converter, entrada_lista)) if entrada_flag == "quick": inicio = time() quick_sort(lista) final = time() print(lista) print(f"O algoritmo executou em {(final-inicio)*(10**9)} ns") elif entrada_flag == "bubble": inicio = time() bubble_sort(lista) final = time() print(lista) print(f"O algoritmo executou em {(final-inicio)*(10**9)} ns") elif entrada_flag == "merge": inicio = time() merge_sort(lista) final = time() print(lista) print(f"O algoritmo executou em {(final-inicio)*(10**9)} ns") elif entrada_flag == "insertion": inicio = time() insertion_sort(lista) final = time() print(lista) print(f"O algoritmo executou em {(final-inicio)*(10**9)} ns") elif entrada_flag == "selection": inicio = time() selection_sort(lista) final = time() print(lista) print(f"O algoritmo executou em {(final-inicio)*(10**9)} ns") else: print("Algoritmo indicado não encontrado...") except: print("Algo deu errado... verifique os argumentos")
#This is an example using a csv file for inputs. #This example was created for use as a demo at the FIA NRMT 2018. from PyEVALIDator import fetchTable import csv from EVALIDatorVars import * def main(): #read inputs for fetchTable from inputFile.csv #fetchTable(st, yr, nm, dn, pg, r, c, of, ot, lat, lon, rad) #----------[0, 1, 2 3, 4, 5, 6, 7, 8, 9, 10, 11] inFile = open('inputFile.csv') rdr = csv.reader(inFile) ev = EVALIDatorVars() firstLine = True n = 1 print("Let's get some data!") #read the rows of the input csv #skip the first row as headers for row in rdr: if firstLine == True: firstLine = False else: #assign and cast each input variable from csv print('Reading line '+str(n)) st = ev.stateDict[row[0]] yr = str(row[1]) nm = str(row[2]) dn = str(row[3]) pg = str(row[4]) r = str(row[5]) c = str(row[6]) of = str(row[7]) ot = str(row[8]) lat = int(row[9]) lon = int(row[10]) rad = int(row[11]) #go fetch! fetchTable(st,yr,nm,dn,pg,r,c,of,ot,lat,lon,rad) n+=1 inFile.close() print('DONE!') if __name__ == '__main__': main()
import tkinter # Calculator main window details m_window = tkinter.Tk() m_window.title('Calculator') m_window.geometry('300x300+800+350') # Results entry box results = tkinter.Entry(m_window, justify='center', borderwidth=4, relief='sunken') results.grid(row=0, column=0, sticky='nsew', ipady=4) # Button frame b_frame = tkinter.Frame(m_window, borderwidth=4, relief='groove') b_frame.grid(row=2, column=0, sticky='nsew') # Button list b_list = [[('C', 1), ('CE', 1)], [('7', 1), ('8', 1), ('9', 1), ('+', 1)], [('4', 1), ('5', 1), ('6', 1), ('-', 1)], [('1', 1), ('2', 1), ('3', 1), ('*', 1)], [('0', 1), ('=', 1), ('/', 1)]] # Initializing the row for the buttons b_row = 0 # Loop that creates the buttons on the calculator for button_row in b_list: b_column = 0 # Initializes the columns in the b_frame for button in button_row: tkinter.Button(b_frame, text=button[0]).grid(row=b_row, column=b_column, columnspan=button[1], sticky=tkinter.E + tkinter.W) b_column += button[1] # Adds the columns using the list key b_row += 1 # Adds the button rows # To resize the calculator window m_window.update() m_window.minsize(b_frame.winfo_width(), results.winfo_height() + b_frame.winfo_height()) m_window.maxsize(b_frame.winfo_width() + 10, results.winfo_height() + 10 + b_frame.winfo_height()) # Add function def add(x, y): add_total = x + y return add_total # Subtract function def subtract(x, y): subtract_total = x - y return subtract_total # Multiply function def multiply(x, y): multiply_total = x * y return multiply_total # Divide function def divide(x, y): divide_total = x // y return divide_total m_window.mainloop()
# Esta funcion verifica que cada digito # de nuestro numero se encuentre dentro # de la base a converitr def checkNumber(number, dictionary): for digit in number: if digit not in dictionary: return False return True
#!/usr/bin/python3 import sys from my_priority_queue import PriorityQueue from math import inf from time import time def get_graph(n, edges): graph = [[] for _ in range(n)] for edge in edges: graph[int(edge[0])].append((int(edge[1]), float(edge[2]))) return graph def dijskstra_path(graph, start): data = [[inf, None] for _ in range(len(graph))] data[start][0] = 0 data[start][1] = start queue = PriorityQueue() for i in range(len(graph)): queue.insert(i, data[i][0]) while queue.length > 0: u = queue.pop() for edge in graph[u]: if data[edge[0]][0] > data[u][0] + edge[1]: data[edge[0]][0] = data[u][0] + edge[1] data[edge[0]][1] = u queue.priority(edge[0], data[edge[0]][0]) return data def recreate_paths(graph, data, start): paths = [[] for _ in range(len(graph))] for i in range(len(graph)): done = False v = i if i == start: continue paths[i].append(i) while not done: paths[i].append(data[v][1]) v = data[v][1] if v == start: done = True paths[i].reverse() paths[i].pop(0) return paths def calculate_cost(graph, paths, start): for path in paths: if path == []: print('-> -, 0', file=sys.stderr) else: prev = start for v in path: i = 0 while graph[prev][i][0] != v: i += 1 print('-> {}, {};'.format(v, graph[prev][i][1]), end=' ', file=sys.stderr) prev = v print(file=sys.stderr) def main(): args = sys.stdin.readlines() args = [arg.split() for arg in args] n = int(args[0][0]) m = int(args[1][0]) start = int(args[-1][0]) if len(args) != m+3: print('Podano nieprawidłowe dane') else: s = time() graph = get_graph(n, args[2:-1]) data = dijskstra_path(graph, start) for i in range(len(data)): print(i, data[i][0]) p = recreate_paths(graph, data, start) calculate_cost(graph, p, start) print('Czas działania programu: {} ms'.format((time()-s)*1000), file=sys.stderr) if __name__ == '__main__': main()
#!/usr/bin/python import sys swap_counter = 0 comp_counter = 0 arr_len = 0 def select(array, k): medians = [] n = len(array) for i in range(0, n-n%5, 5): print("Sortowanie fragmentu tablicy {}".format(array[i:i+5]), file=sys.stderr) insertion(array,i,i+4) medians.append(array[i+2]) mod = n%5 if mod > 0: print("Sortowanie fragmentu tablicy {}".format(array[n-mod:n]), file=sys.stderr) insertion(array, n-mod, n-1) medians.append(array[n-mod+(mod+1)//2-1]) m = len(medians) if m <= 5: print("Sortowanie tablicy median {}".format(medians), file=sys.stderr) insertion(medians, 0, m-1) pivot = medians[(m+1)//2-1] else: pivot = select(medians, len(medians)//2) j = partition(array, 0, len(array)-1, pivot) if k < j+1: return select(array[:j], k) elif k > j+1: return select(array[j+1:], k-j-1) else: global swap_counter, comp_counter print("Calkowita liczba porowan: {}\nCalkowita liczba przestawien: {}".format(comp_counter, swap_counter), file=sys.stderr) swap_counter = 0 comp_counter = 0 return pivot def insertion(array, p, r): global swap_counter, comp_counter for i in range(p+1, r+1): key = array[i] j = i-1 while j>=p and array[j] > key: comp_counter += 1 print("\tporownanie {} i {}".format(array[j], key), file=sys.stderr) print("\tprzestawienie {} i {}".format(array[j], array[j+1]), file=sys.stderr) array[j+1] = array[j] swap_counter += 1 j -= 1 comp_counter += 1 print("\tporownanie {} i {}".format(array[j], key), file=sys.stderr) array[j+1] = key def partition(array, p, r, pivot): if p == r: return 0 global swap_counter, comp_counter print("Partycja pod-tablicy {} wedlug pivota {}".format(array, pivot), file=sys.stderr) index = array.index(pivot) array[p], array[index] = array[index], array[p] print("\tzamiana {} i {}".format(array[index], array[p]), file=sys.stderr) swap_counter += 1 i = p j = r+1 while True: j -= 1 while array[j]>pivot: print("\tporownanie {} i {}".format(array[j], pivot), file=sys.stderr) comp_counter += 1 j -= 1 print("\tporownanie {} i {}".format(array[j], pivot), file=sys.stderr) comp_counter += 1 i += 1 while array[i]<pivot: print("\tporownanie {} i {}".format(array[i], pivot), file=sys.stderr) comp_counter += 1 i += 1 print("\tporownanie {} i {}".format(array[i], pivot), file=sys.stderr) comp_counter += 1 if i<j: array[i], array[j] = array[j], array[i] print("\tzamiana {} i {}".format(array[i], array[j]), file=sys.stderr) swap_counter += 1 else: array[i-1], array[p] = array[p], array[i-1] print("\tzamiana {} i {}".format(array[i-1], array[p]), file=sys.stderr) swap_counter += 1 return j def select_stat(array, k, filename): global swap_counter, comp_counter, arr_len if comp_counter == 0: arr_len = len(array) medians = [] n = len(array) for i in range(0, n-n%5, 5): insertion_stat(array,i,i+4) medians.append(array[i+2]) mod = n%5 if mod > 0: insertion_stat(array, n-mod, n-1) medians.append(array[n-mod+(mod+1)//2-1]) m = len(medians) if m <= 5: insertion_stat(medians, 0, m-1) pivot = medians[(m+1)//2-1] else: pivot = select_stat(medians, len(medians)//2, filename) j = partition_stat(array, 0, len(array)-1, pivot) if k < j+1: out = select_stat(array[:j], k, filename) elif k > j+1: out = select_stat(array[j+1:], k-j-1, filename) else: out = pivot if len(array) == arr_len: with open(filename, "a") as f: f.write("{};{}\n".format(len(array), comp_counter)) swap_counter = 0 comp_counter = 0 arr_len = 0 return out def insertion_stat(array, p, r): global swap_counter, comp_counter for i in range(p+1, r+1): key = array[i] j = i-1 while j>=p and array[j] > key: comp_counter += 1 array[j+1] = array[j] swap_counter += 1 j -= 1 comp_counter += 1 array[j+1] = key def partition_stat(array, p, r, pivot): if p == r: return 0 global swap_counter, comp_counter index = array.index(pivot) array[p], array[index] = array[index], array[p] i = p j = r+1 while True: j -= 1 while array[j]>pivot: comp_counter += 1 j -= 1 comp_counter += 1 i += 1 while array[i]<pivot: comp_counter += 1 i += 1 comp_counter += 1 if i<j: array[i], array[j] = array[j], array[i] swap_counter += 1 else: array[i-1], array[p] = array[p], array[i-1] return j
#!/usr/bin/env python # coding: utf-8 # In[1]: ''' Building a Stock Price Predictor Using Python https://www.section.io/engineering-education/stock-price-prediction-using-python/ ''' # In[2]: ''' What is a RNN? When you read this text, you understand each word based on previous words in your brain. You wouldn’t start thinking from scratch, rather your thoughts are cumulative. Recurrent Neural Networks implement the same concept using machines; they have loops and allow information to persist where traditional neural networks can’t. Let’s use a few illustrations to demonstrate how a RNN works. ''' # In[3]: ''' What is LSTM? Long short-term memory (LSTM) is an artificial recurrent neural network (RNN) architecture that you can use in the deep learning field. In LSTM, you can process an entire sequence of data. For example, handwriting generation, question answering or speech recognition, and much more. Unlike the traditional feed-forward neural network, that passes the values sequentially through each layer of the network, LSTM has a feedback connection that helps it remember preceding information, making it the perfect model for our needs to do time series analysis. ''' # In[4]: ''' Choosing data In this tutorial, I will use a TESLA stock dataset from Yahoo finance, that contains stock data for ten years. You can download it for free from here. I’m also going to use Google Colab because it’s a powerful tool, but you are free to use whatever you are comfortable with. ''' # In[5]: import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential, load_model from keras.layers import LSTM, Dense, Dropout # In[6]: ''' We are going to use numpy for scientific operations, pandas to modify our dataset, matplotlib to visualize the results, sklearn to scale our data, and keras to work as a wrapper on low-level libraries like TensorFlow or Theano high-level neural networks library. ''' # In[7]: ''' Let’s build our app! First of all, if you take a look at the dataset, you need to know that the “open” column represents the opening price for the stock at that “date” column, and the “close” column is the closing price on that day. The “High” column represents the highest price reached that day, and the “Low” column represents the lowest price. ''' # In[8]: #we need to make a data frame: df = pd.read_csv('TSLA.csv') # In[9]: df.shape # In[10]: #To make it as simple as possible we will just use one variable which is the “open” price. df = df['Open'].values #1列のデータに変換する。行数は変換前のデータ数から計算される。 #https://qiita.com/yosshi4486/items/deb49d5a433a2c8a8ed4 df = df.reshape(-1, 1) # In[11]: df.shape # In[12]: ''' The reshape allows you to add dimensions or change the number of elements in each dimension. We are using reshape(-1, 1) because we have just one dimension in our array, so numby will create the same number of our rows and add one more axis: 1 to be the second dimension. ''' # In[13]: #intは整数値に変換する #https://www.javadrive.jp/python/function/index3.html dataset_train = np.array(df[:int(df.shape[0]*0.8)]) dataset_test = np.array(df[int(df.shape[0]*0.8):]) print(dataset_train.shape) print(dataset_test.shape) # In[14]: ''' We will use the MinMaxScaler to scale our data between zero and one. In simpler words, the scaling is converting the numerical data represented in a wide range into a smaller one. ''' # In[15]: scaler = MinMaxScaler(feature_range=(0,1)) dataset_train = scaler.fit_transform(dataset_train) dataset_train[:5] # In[16]: dataset_test = scaler.transform(dataset_test) dataset_test[:5] # In[17]: #Next, we will create the function that will help us to create the datasets: def create_dataset(df): x = [] y = [] for i in range(50, df.shape[0]): x.append(df[i-50:i, 0]) y.append(df[i, 0]) x = np.array(x) y = np.array(y) return x,y # In[18]: ''' For the features (x), we will always append the last 50 prices, and for the label (y), we will append the next price. Then we will use numpy to convert it into an array. Now we are going to create our training and testing data by calling our function for each one: ''' # In[19]: x_train, y_train = create_dataset(dataset_train) x_test, y_test = create_dataset(dataset_test) # In[20]: ''' Next, we need to reshape our data to make it a 3D array in order to use it in LSTM Layer. ''' # In[ ]: # In[21]: model = Sequential() model.add(LSTM(units=96, return_sequences=True, input_shape=(x_train.shape[1], 1))) model.add(Dropout(0.2)) model.add(LSTM(units=96,return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM(units=96,return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM(units=96)) model.add(Dropout(0.2)) model.add(Dense(units=1)) # In[22]: ''' First, we initialized our model as a sequential one with 96 units in the output’s dimensionality. We used return_sequences=True to make the LSTM layer with three-dimensional input and input_shape to shape our dataset. Making the dropout fraction 0.2 drops 20% of the layers. Finally, we added a dense layer with a value of 1 because we want to output one value. After that, we want to reshape our feature for the LSTM layer, because it is sequential_3 which is expecting 3 dimensions, not 2: ''' # In[23]: x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1)) x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1)) # In[24]: model.compile(loss='mean_squared_error', optimizer='adam') # In[25]: ''' We used loss='mean_squared_error' because it is a regression problem, and the adam optimizer to update network weights iteratively based on training data. We are ready! Let’s save our model and start the training: ''' # In[26]: model.fit(x_train, y_train, epochs=25, batch_size=32) model.save('stock_prediction.h5') # In[27]: ''' Every epoch refers to one cycle through the full training dataset, and batch size refers to the number of training examples utilized in one iteration. ''' # In[28]: model = load_model('stock_prediction.h5') # In[29]: ''' Results visualization The last step is to visualize our data. If you are new to data visualization please consider going through our Getting Started with Data Visualization using Pandas tutorial first. ''' # In[30]: predictions = model.predict(x_test) predictions = scaler.inverse_transform(predictions) y_test_scaled = scaler.inverse_transform(y_test.reshape(-1, 1)) fig, ax = plt.subplots(figsize=(16,8)) ax.set_facecolor('#000041') ax.plot(y_test_scaled, color='red', label='Original price') plt.plot(predictions, color='cyan', label='Predicted price') plt.legend() # In[ ]:
add1 = int(input ()) add2 = int(input()) amal = input("vared konid amalgar\n") if amal == "+": print (add1 + add2) elif amal == "-": print (add1 - add2) elif amal == "*": print (add1 * add2) else : print ("nashenas hast")
n=int(input("enter anumber")) dict= {} i=1 while i<=n: dict[i]=i*i i=i+1 print(dict)
list1=['one','two','three','four','five'] list2=[1,2,3,4,5,] data=dict(zip(list1,list2)) print(data)
student_data={'a':'raam','b':'raaj','c':'raani','d':'class','g':'raam','h':'class'} dict={} for key,value in student_data.items(): if value not in dict.values(): dict[key]=value print(dict)
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
127