text
stringlengths
37
1.41M
import math import numpy as np """Given a binary number it returns its integer decimal form""" def convertEntero(number): counter = 0 NumberPreDec = [] for numero in number[::-1]: NumberPreDec.append((2**counter) * int(numero)) counter = counter+1 return (np.sum(NumberPreDec)) """Given a decimal binary dumber it returns its decimal form""" def convertDecimal(number): counter = -1 NumberPostDec = [] for numero in number: NumberPostDec.append((2**counter) * int(numero)) counter = counter-1 return round((np.sum(NumberPostDec)), 2) """This function parses a integer number from decimal to binary""" def getBinaryIntPart(num): finalString = "" while num != 1 and num != 0: finalString = finalString + str(num % 2) num = math.trunc(num / 2) return str(finalString + str(num))[::-1] """This function parses a decimal number from decimal to binary""" def getBinaryDecimalPart(num, integerLenght, base): finalString = "" while num != 1 and num != 0: mult = num * 2 finalString = finalString + str("1" if mult >= 1 else "0") num = mult if mult < 1 else mult - 1 mantise = 23 if base == 32 else 52 return finalString[0:mantise - integerLenght] if len(finalString) >= mantise else finalString.ljust(mantise - integerLenght, "0") """Given a number it returns its equivalent to hex form""" def getLetterFromNum(num): num = int(num) if num <= 9: return str(num) elif num == 10: return "A" elif num == 11: return "B" elif num == 12: return "C" elif num == 13: return "D" elif num == 14: return "E" elif num == 15: return "F" else: return str(num) """Given an integer number it returns the equivalent to the hex form""" def getHexIntPart(num): finalString = "" while num != 1 and num != 0: finalString = finalString + getLetterFromNum(str(num % 16)) num = math.trunc(num / 16) return str(num) + str(finalString)[::-1] if num == 1 else str(finalString)[::-1] """Given a decimal number it returns the equivalente to the hex form""" def getHexDecimalPart(num): finalString = "" while num != 1 and num != 0: mult = num * 16 roundedNumber = round(math.modf(abs(mult))[1]) finalString = finalString + getLetterFromNum(roundedNumber) num = mult if mult < 1 else mult - roundedNumber return finalString """Given a hex number it returns it equivalent to the decimal form""" def getNumFromLetter(num): if num == "A": return "10" elif num == "B": return "11" elif num == "C": return "12" elif num == "D": return "13" elif num == "E": return "14" elif num == "F": return "15" else: return str(num) """Gets the exponent of a IEEE hex number""" def getExponentialNumberHex(number): arrayNumber = [] counter = 0 exponentialBin = number[1:3] for numero in exponentialBin[::-1]: arrayNumber.append((16**counter) * int(getNumFromLetter(numero))) counter = counter+1 return (np.sum(arrayNumber)) """Calculates the mantise of a IEEE hex number""" def calculateMantisaHex(number, exponentialNumber): mantisa = number[3:11] newMantisa = mantisa[:exponentialNumber] + \ "," + mantisa[exponentialNumber:] return newMantisa.split(",")
class searchNode(object): def __init__(self, gameState, previousNode=None,heuristic=0): if(previousNode is None): self.previousStates=list() self.currentCost=0 self.currentDepth=0 self.currentState=gameState self.currentHeuristicValue=heuristic else: self.previousStates=list(previousNode.previousStates) self.previousStates.append(previousNode) self.currentCost=previousNode.currentCost+gameState[2] self.currentDepth=previousNode.currentDepth+1 self.currentState=gameState self.currentHeuristicValue=heuristic def ToDirection(self, directionString): n = Directions.NORTH e = Directions.EAST s = Directions.SOUTH w = Directions.WEST if (directionString=='North'): return n elif(directionString=='East'): return e elif(directionString=='South'): return s elif(directionString=='West'): return w def GetDirections(self): directions=list() for x in self.previousStates: if x.currentState[1] != "START": directions.append(x.currentState[1]) directions.append(self.currentState[1]) return directions def AStarCost(self): return self.currentCost+self.currentHeuristicValue
# should_continue = True # if should_continue: # print("Hello") # # known_people = ["John", "Pioter", "Mary"] # person = input("Enter the person you know: ") # # if person in known_people: # print(f"Super, kurwa! Znasz {person}") # else: # print("You don't know shit") def who_do_you_know(): people = input("Enter the names of people you know, separated by commas: ") people_list = people.split(", ") return people_list def ask_user(): user_name = input('Give a goddamn\' name: ') if user_name in who_do_you_know(): print(f'You know {user_name}.') else: print(f'You don\'t know {user_name}.') ask_user()
class Store: def __init__(self, name): # You'll need 'name' as an argument to this method. # Then, initialise 'self.name' to be the argument, and 'self.items' to be an empty list. self.name = name self.items = [] def add_item(self, name, price): # Create a dictionary with keys name and price, and append that to self.items. new_item = {"name": name, "price": price} self.items.append(new_item) def stock_price(self): # Add together all item prices in self.items and return the total. total = 0 for item in self.items: total += item['price'] return total sklepJanusza = Store("JanuszSklep") sklepJanusza.add_item("wódka", 10) sklepJanusza.add_item("kiełbasa", 15) sklepJanusza.add_item("ogórki", 15) print(sklepJanusza.stock_price())
import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline dataset=pd.read_csv("Students_Score.csv") dataset.head() dataset.describe() dataset.plot(x='Hours',y='Scores',style="*") plt.title('Student mark prediction') plt.xlabel('Hours') plt.ylabel('Percentage marks') plt.show() X=dataset.iloc[:, :-1].values Y=dataset.iloc[:,1].values from sklearn.model_selection import train_test_split X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2,random_state=0) from sklearn.linear_model import LinearRegression regressor=LinearRegression() regressor.fit(X_train,Y_train) print(regressor.intercept_) print(regressor.coef_) y_pred=regressor.predict(X_test) df=pd.DataFrame({'Actual':Y_test,'Predicted':y_pred}) df
#!python import math def linear_search(array, item): """return the first index of item in array or None if item is not found""" # implement linear_search_iterative and linear_search_recursive below, then # change this to call your implementation to verify it passes all tests return linear_search_recursive(array, item) # return linear_search_recursive(array, item) def linear_search_iterative(array, item): # loop over all array values until item is found for index, value in enumerate(array): if item == value: return index # found return None # not found def linear_search_recursive(array, item, index=0): # TODO: implement linear search recursively here if index >= len(array): return None elif array[index] == item: return index else: return linear_search_recursive(array, item, index+1) def binary_search(array, item): """return the index of item in sorted array or None if item is not found""" # implement binary_search_iterative and binary_search_recursive below, then # change this to call your implementation to verify it passes all tests return binary_search_recursive(array, item) # return binary_search_recursive(array, item) def binary_search_iterative(array, item): # TODO: implement binary search iteratively here curr_index = len(array)/2 last_index = 0 curr_value = array[curr_index] while curr_value != item: new_index = int(math.ceil(abs(curr_index - last_index) / 2.0)) if curr_value < item: new_index = curr_index + new_index else: new_index = curr_index - new_index if curr_index <= 0 or curr_index >= len(array) - 1 or new_index == last_index: return None last_index = curr_index curr_index = new_index curr_value = array[curr_index] return curr_index def binary_search_recursive(array, item, left=None, right=None): # TODO: implement binary search recursively here if left is None: left = 0 if right is None: right = len(array) print("Right: ", right, "Left: ", left) incrementor = (right - left) / 2 index = left + incrementor if index < 0 or index > len(array) - 1 or index - 1 == right or index + 1 == left: return None if array[index] == item: print("index", index) return index elif array[index] > item: return binary_search_recursive(array, item, left, index - 1) elif array[index] < item: return binary_search_recursive(array, item, index + 1, right)
#Math Phys HW5 problem 3 import numpy as np import scipy as sp from matplotlib import pyplot as pp #Runge-Kutta 4 numerical integration # y - Function value at start (vector) # h - step size # dFunc - derivatives of y's (physics of the problem) # dFunc(x, y) - Returns derivatives of y's at x's def RK4(y, h, dFunc): yout = np.array(np.zeros(len(y))) h2 = h/2.0 h6 = h/6.0 #First step dy = dFunc(y) yt = y + h2*dy #Second step dyt = dFunc(yt) yt = y + h2*dyt #Third step dym = dFunc(yt) yt = y + h*dym dym = dym + dyt #Fourth step dyt = dFunc(yt) yout = y + h6*(dy+dyt+2.0*dym) return yout #Lorenz problem #y - y values (vector of {x,y,z}) # #Returns derivative values (dx, dy, dz) def lorenzLaw(y): sigma = 10 b = 8./3. r = 30 dy = np.array(np.zeros(len(y))) dy[0] = -sigma*y[0] + sigma*y[1] dy[1] = r*y[0] - y[1] - y[0]*y[2] dy[2] = -b*y[2] + y[0]*y[1] return dy #Main function, numerical integration of Lorenz system y = np.array(np.zeros(3)) y[0] = 5 y[1] = 6 y[2] = 10 dt = 0.01 tmax = 100.0 nsteps = int(tmax/dt) t = np.linspace(0,tmax, nsteps) #Positions p = np.matrix([np.zeros(nsteps), np.zeros(nsteps), np.zeros(nsteps)]) x1 = np.array(np.zeros(nsteps)) x2 = np.array(np.zeros(nsteps)) x3 = np.array(np.zeros(nsteps)) for jj in range(nsteps): x1[jj] = y[0] x2[jj] = y[1] x3[jj] = y[2] y = RK4(y,dt,lorenzLaw) pp.figure(1) pp.hold(True) pp.plot(t, x1, 'b', label='x') pp.plot(t, x2, 'r', label='y') pp.plot(t, x3, 'g', label='z') pp.xlabel('Time (sec)') pp.ylabel('Value') pp.title('XYZ evolution for Lorenz system') pp.legend() pp.figure(2) pp.plot(x1, x3) pp.xlabel('X') pp.ylabel('Z') pp.title('X-Z cut of Lorenz attractor') pp.show()
import pygame import random class Base_ranger(pygame.sprite.Sprite): """ It a base class of the ranger enemy """ def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.rect = pygame.Rect(50, 50, 75, 75) self.rect.bottom = y self.rect.centerx = x self.bullet = Laser(self.rect.centerx, self.rect.bottom, self, None) self.lastMove = 'down' def damage(self, pl): if self.rect.colliderect(pl) or self.bullet.colliderect(pl): pl.health -= 3 class Laser(pygame.sprite.Sprite): """ Class describing of behavior of the bullet which used to shooting by the Player """ def __init__(self, x, y, enemy, storage): """ Initializing the bullet """ pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((10, 100)) self.image.fill((0, 255, 0)) self.rect = self.image.get_rect() self.rect.bottom = y self.rect.centerx = x self.speedy = -30 self.__var__ = enemy.lastMove self.enemy_ammo = storage def update(self): """ Updating bullet's position every turn and control bullet out-of-screen""" if self.__var__ == 'right': self.rect.x -= self.speedy elif self.__var__ == 'left': self.rect.x += self.speedy elif self.__var__ == 'up': self.rect.y += self.speedy elif self.__var__ == 'down': self.rect.y -= self.speedy if self.rect.x > WIDTH or self.rect.x < 0 or self.rect.y > HEIGHT or self.rect.y < 0: self.enemy_ammo.remove(self)
from heapq import heappush, heappop class Solution: def minDistance(self, word1, word2): """ :type word1: str :type word2: str :rtype: int """ heap = [(0, word1, word2)] visited = set() while heap: d, w1, w2 = heappop(heap) if (w1, w2) in visited: continue visited.add((w1, w2)) if w1 == w2: return d if w1 and w2 and w1[0] == w2[0]: heappush(heap, (d, w1[1:], w2[1:])) else: if w1: heappush(heap, (d+1, w1[1:], w2)) #delete if w1 and w2: heappush(heap, (d+1, w1[1:], w2[1:])) #replace if w2: heappush(heap, (d+1, w1, w2[1:])) #add if __name__ == "__main__": word1 = "horse" word2 = "ros" print(Solution().minDistance(word1, word2))
class Solution: def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ return (3*sum(set(nums)) - sum(nums))//2 if __name__ == "__main__": nums = [2,2,3,2] print(Solution().singleNumber(nums))
class Solution: def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ k = 0 for i, num in enumerate(nums): if num != val: if i != k: nums[k] = num k += 1 else: #i == k k += 1 return k if __name__ == "__main__": nums = [3, 2, 2, 3] val = 2 print(Solution().removeElement(nums, val))
class Solution: def isUnivalTree(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True if (root.left and root.val != root.left.val) or (root.right and root.val != root.right.val): return False return self.isUnivalTree(root.left) and self.isUnivalTree(root.right)
class Solution: def sumNumbers(self, root): """ :type root: TreeNode :rtype: int """ result = 0 if not root: return result path = [(0, root)] while path: pre, node = path.pop() if node: if not node.left and not node.right : result += pre*10 + node.val path += [(pre*10 + node.val, node.right), (pre*10 + node.val, node.left)] return result # class Solution: # def _sumNumbers(self, root, value): # if root: # self._sumNumbers(root.left, value*10+root.val) # self._sumNumbers(root.right, value*10+root.val) # if not root.left and not root.right: # self.result += value*10 + root.val # def sumNumbers(self, root): # """ # :type root: TreeNode # :rtype: int # """ # self.result = 0 # self._sumNumbers(root, 0) # return self.result
class Solution: def gameOfLife(self, board): """ :type board: List[List[int]] :rtype: void Do not return anything, modify board in-place instead. """ r, c = len(board), len(board[0]) neighbors = [(0, 1), (0, -1), (1, 0), (-1, 0), (-1, -1), (1, 1), (-1, 1), (1, -1)] for i in range(r): for j in range(c): lives = 0 for m, n in neighbors: if 0 <= i + m < r and 0 <= j + n < c: lives += board[i+m][j+n] & 1 if board[i][j] and 2 <= lives < 4: board[i][j] = 3 if not board[i][j] and lives == 3: board[i][j] = 2 for i in range(r): for j in range(c): board[i][j] >>= 1 if __name__ == "__main__": board = [[1,1],[1,0]] Solution().gameOfLife(board) print(board)
class Solution: def longestPalindrome(self, s): """ :type s: str :rtype: str """ if len(s) < 2 or s == s[::-1]: return s start, maxlength = 0, 1 for i in range(len(s)): odd = s[i-maxlength-1:i+1] even = s[i-maxlength:i+1] if i-maxlength-1 >= 0 and odd == odd[::-1]: start = i-maxlength-1 maxlength += 2 elif i-maxlength >= 0 and even == even[::-1]: start = i-maxlength maxlength += 1 return s[start:start+maxlength] if __name__ == "__main__": s = "babad" print(Solution().longestPalindrome(s))
class Solution: def deleteNode(self, root, key): """ :type root: TreeNode :type key: int :rtype: TreeNode """ if not root: return None if key < root.val: root.left = self.deleteNode(root.left, key) return root elif key > root.val: root.right = self.deleteNode(root.right, key) return root else: if not root.left: return root.right if not root.right: return root.left minNode = root.right while minNode.left: minNode = minNode.left root.val = minNode.val root.right = self.deleteNode(root.right, minNode.val) return root
class Solution: def numUniqueEmails(self, emails): """ :type emails: List[str] :rtype: int """ raw_emails = set() for email in emails: sp_at = email.split('@') pre = sp_at[0].split('+') raw_emails.add(pre[0].replace('.', '') + sp_at[1]) return len(raw_emails) if __name__ == "__main__": emails = ["[email protected]","[email protected]","[email protected]"] print(Solution().numUniqueEmails(emails))
class Solution: def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix: return False r, c = len(matrix), len(matrix[0]) left, right = 0, r*c while left < right: mid = (left+right)//2 m, n = mid//c, mid%c if matrix[m][n] == target: return True elif matrix[m][n] < target: left = mid + 1 else: right = mid return False if __name__ == "__main__": matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 13 print(Solution().searchMatrix(matrix, target))
class Solution: def subsetsWithDup(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() result = list() self._subsetsWithDup(nums, 0, list(), result) return result def _subsetsWithDup(self, nums, index, path, result): result.append(path.copy()) for i in range(index, len(nums)): if index < i and nums[i] == nums[i - 1]:# add continue self._subsetsWithDup(nums, i + 1, path + [nums[i]], result) if __name__ == '__main__': nums = [1, 2, 2] print(Solution().subsetsWithDup(nums))
class Solution: def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ l = 0 r = len(numbers) - 1 while l < r: if numbers[l] + numbers[r] == target: return [l + 1, r + 1] elif numbers[l] + numbers[r] < target: l += 1 else: r -= 1 return [] if __name__ == "__main__": arr = [2, 7, 11, 15] target = 9 print(Solution().twoSum(arr, target))
# -*- coding: utf-8 -*- '''Misclaneous string programs for coding exercise''' import time import numpy as np #Performing reverse a string name=list('Tanay') rname=[] for l in range(len(name)): rname.append(name[len(name)-l-1]) print 'The reverse of string',''.join(name),'is',''.join(rname ) #Check uniqueness of a string def isunq(name): uchk={} lname=list(name) for l in range(len(lname)): if (lname[l] in uchk.keys()): return False else: uchk[lname[l]]=True return True def isunq2(name): if(len(name))!=len(set(name)): return False return True isunq("Tanay") #Remove duplicates from a string def delunq(name): uchk={} lname=list(name) for l in range(len(lname)): if (lname[l] in uchk.keys()): lname[l]='' else: uchk[lname[l]]=True print 'Deduplicated string is:',''.join(lname) delunq("Tanay") #1.4:Write a method to decide if two strings are anagrams or not. def anagram(str1,str2): lstr1=list(str1);lstr2=list(str2) lstr1.sort();lstr2.sort() for i in range(len(lstr1)): if(lstr1[i]!=lstr2[i]): return False return True '''1.7 Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0. ;''' def mnary(): x = np.array([[1, 0, 3], [4, 5, 6]], np.int32); i=0;j=0 for i in range(len(x[:,j])): for j in range(len(x[i,:])): if(x[i,j]==0): x[i,:]=0;x[:,j]=0 return x return x mnary() '''1.8 Assume you have a method isSubstring which checks if one word is a substring of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring (i.e., “waterbottle” is a rotation of “erbottlewat”).''' #ls.insert(0,ls.pop()) def issubstring(s1,s2): if s1.find(s2)==-1: return False return True def isrotate(s1,s2): ls1=list(s1);ls2=list(s2) for i in range(len(ls2)): ls2.insert(0,ls2.pop()) if((ls2[0]==ls1[0])&(ls2[len(ls2)-1]==ls1[len(ls1)-1])): if(issubstring(''.join(ls1),''.join(ls2))): return True return False #Computation test=['Tanay', 'Arnab', 'Sumir', 'Samir', 'Debasree', 'Rina', 'Tanmoy', 'Kalyani','Peter','Moly', 'Dev','Eugene','Sarah','Kate','Aiden'] t=time.time(); for i in range(len(test)): isunq(test[i]); print 'Computation time for isunique:',time.time()-t t=time.time(); for i in range(len(test)): isunq2(test[i]); print 'Computation time for isunique2:',time.time()-t
# grading function def grading (avg): if avg >= 90: grade = "A" elif avg >= 80: grade = "B" elif avg >= 70: grade = "C" elif avg >= 60: grade = "D" else: grade ="F" return grade def search(): sid = input("Student ID: ") printer(sid) def add(): newID = input("Student ID: ") if (newID in students.keys()): print("ALREADY EXIST") else: name = input("Name: ") mid = int(input("Midterm Score: ")) final = int(input("Final Score: ")) students[newID] = {"Name" : name, "Midterm": mid, "Final" : final} add_avgrade() print("Student added") def searchGrade(): targetGrade = input("Grade to search: ") gradeset = "ABCDF" if targetGrade in gradeset: for sid in students: if students[sid]["Grade"] == targetGrade: printer(sid) def remove(): sid = input("Student ID: ") if sid not in students: print("NO SUCH PERSON.") else: del students[sid] print("Student removed") def quit(): yORn = input("Save data?[yes/no]") if yORn == "yes": fname = input("File name: ") f_write = open(fname, "r") f_write.write(printer(students)) def printer(sid): # print(colslins) print(sid, end="\t") for values in students[sid].values(): print(values, end="\t") print() """while (True): command = input("Please input your command: ") if command == "show": show() elif command == "search": search() elif command == "changescore": changeScore() elif command == "add": add() elif command == "searchgrade": searchGrade() elif command == "remove": remove() elif command == "quit": quit() elif command == "q": break""" def changeScore(): sid = input("Student ID: ") if sid in range(5): print("NO SUCH PERSON.") else: mORf = input("Mid/Final? ") if mORf != "mid" and mORf != "final": return newScore = int(input("Input new score: ")) if newScore > 100 or newScore < 0: print("score not exist");return printer(sid) if mORf == "mid": students[sid]["Midterm"] = newScore elif mORf == "final": students[sid]["Final"] = newScore add_avgrade() print("Score Changed") printer(sid) def add_avgrade(): for sid in students: students[sid]["Average"] = (students[sid]["Midterm"] + students[sid]["Final"])/2 students[sid]["Grade"] = grading(students[sid]["Average"]) def show(): columns = "Student\t\tName\t\tMidterm\tFinal\tAverage\tGrade" lines = "-------------------------------------------------------------" print(columns+"\n"+lines) for key, value in sorted(students.items(), key=lambda item: item[1]["Average"], reverse=True): print(key, end="\t") printer(key) import sys f = open(sys.argv[1], "r") students = {} for s in f.readlines(): s2 = s.rstrip().split() students[s2[0]] = {"Name" : " ".join(s2[1:3]), "Midterm": int(s2[3]), "Final" : int(s2[4])} add_avgrade() show() #sort() #printers()
#coding:utf8 class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ #return [n for i,n in enumerate(nums) if i>=1 and n!=nums[i-1] or i==0] # if not A: # return 0 # # newTail = 0 # # for i in range(1, len(A)): # if A[i] != A[newTail]: # newTail += 1 # A[newTail] = A[i] # print A # # return newTail + 1 nums[0:len(set(nums))] = list(set(nums)) print nums return len(set(nums)) s = Solution() print s.removeDuplicates([1,1,2,2,2,4])
class Values(object): dict_ = {1:'dd',2:'gg'} def as_dict(self): return {'4':'ddd'} dict_ = {1:'dd',2:'gg'} va = Values() def test(**kw): print kw test(**va.as_dict()) _D = 1 def print_d(val): print val class DD(object): def dd(self): print_d(_D) d = DD() d.dd()
#coding:utf8 def read_lines(): with open('desc.txt', 'r') as f: #f.seek(0,2) #for i in range(15): #print f.readline() while True: lines = f.readline() if not lines: yield 0 #continue yield lines #print r.next() #print r.next() def read_file_by_line(): r = read_lines() while True: put = raw_input('>>>') if put == 'close': print 'closing... ok' break else: content = r.next() print type(content) if content: print content else: break #print 'nothing' read_file_by_line()
#coding:utf8 def checkio(pawns): pawns_indexes = set() for p in pawns: row = int(p[1]) - 1 col = ord(p[0]) - 97 pawns_indexes.add((row, col)) print pawns_indexes count = 0 for row, col in pawns_indexes: is_safe = ((row - 1, col - 1) in pawns_indexes) or ((row - 1, col + 1) in pawns_indexes) if is_safe: count += 1 return count print checkio({"b4", "d4", "f4", "c3", "e3", "g5", "d2"}) print checkio({"b4", "c4", "d4", "e4", "f4", "g4", "e5"})
#coding:utf8 import datetime def checkio(year): result = [i for i in range(1,13) if datetime.datetime(year,i,13).weekday()==4] return len(result) if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert checkio(2015) == 3, "First - 2015" assert checkio(1986) == 1, "Second - 1986"
#coding:utf8 import copy class Solution(object): def gameOfLife(self, board): """ :type board: List[List[int]] :rtype: void Do not return anything, modify board in-place instead. """ result = copy.deepcopy(board) def check(board,num,x,y): count = 0 temp = [(-1,-1),(+1,+1),(-1,+1),(+1,-1),(0,+1),(0,-1),(+1,0),(-1,0)] for i,j in temp: if x+i>=0 and y+j>=0: try: count+=board[x+i][y+j] except: pass if num==1: if count==2 or count==3: return 1 else: return 0 else: if count==3: return 1 else: return 0 for i,nums in enumerate(board): for j,num in enumerate(nums): result[i][j]=check(board,num,i,j) return result s = Solution() print s.gameOfLife([[1]])
#coding:utf8 class Solution(object): def search_word_util(self, board, row, col, word): if len(word) == 0: return True if row < 0 or row >= len(board) or col < 0 or col >= len(board[0]) or board[row][col] != word[0]: return False board[row][col] = " " print board if self.search_word_util(board, row-1, col, word[1:]): return True if self.search_word_util(board, row+1, col, word[1:]): return True if self.search_word_util(board, row, col-1, word[1:]): return True if self.search_word_util(board, row, col+1, word[1:]): return True board[row][col] = word[0] print board return False def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ m,n = len(board),len(board[0]) def find(result,x,y,word,check): # if x==0 and y==3: # print 'this is',result # print result if result==word: return True if 0<=x<=m-1 and 0<=y<=n-1 and board[x][y]==word[len(result)] \ and (x,y) not in check: check.append((x,y)) result+=board[x][y] print result,check,'//',(x,y) f = [(1,0),(-1,0),(0,-1),(0,+1)] for i,s in f: print x+i,y+s find(result,x+i,y+s,word,check) #问题出在check上 # else: # return 'exit' for i in range(m): for y in range(n): # try: find('',i,y,word,[]) # except:return True #f = find('',i,y,word,[]) f = self.search_word_util(board,i,y,word) return f return False s = Solution() # print s.exist([ # ['A','B','C','E'], # ['S','F','C','S'], # ['A','D','E','E'] # ],"ABCCED") # # print s.exist([ # ['A','B','C','E'], # ['S','F','C','S'], # ['A','D','E','E'] # ],"ABG") print s.exist( [["A","B","C","E"], ["B","F","E","S"], ["A","D","E","E"] ],"ABCESEEEF") ''' A [(0, 0)] // (0, 0) 1 0 AB [(0, 0), (1, 0)] // (1, 0) 2 0 0 0 1 -1 1 1 -1 0 0 -1 0 1 AB [(0, 0), (1, 0), (0, 1)] // (0, 1) 1 1 -1 1 0 0 0 2 ABC [(0, 0), (1, 0), (0, 1), (0, 2)] // (0, 2) 1 2 ABCE [(0, 0), (1, 0), (0, 1), (0, 2), (1, 2)] // (1, 2) 2 2 0 2 1 1 1 3 ABCES [(0, 0), (1, 0), (0, 1), (0, 2), (1, 2), (1, 3)] // (1, 3) 2 3 ABCESE [(0, 0), (1, 0), (0, 1), (0, 2), (1, 2), (1, 3), (2, 3)] // (2, 3) 3 3 1 3 2 2 ABCESEE [(0, 0), (1, 0), (0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (2, 2)] // (2, 2) 3 2 1 2 2 1 2 3 2 4 0 3 ABCESE [(0, 0), (1, 0), (0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (2, 2), (0, 3)] // (0, 3) 1 3 -1 3 0 2 0 4 1 2 1 4 -1 2 0 1 0 3 None '''
#!/usr/bin/env python3 import sys def hanoi(start, temp, end, height): if height>0: #Move the top height-1 disks to the temp stack step1 = hanoi(start, end, temp, height-1) #Move the bottom disk to the end step2 = start+' '+end+'\n' #Move the height-1 disks from temp to the end step3 = hanoi(temp, start, end, height-1) return step1+step2+step3 else: #Base case (height=0): return no text return ''; #argv[0] is always the program name if len(sys.argv)==2: #Python starts indexing at 0 height = int(sys.argv[1]) if height<=8: print(hanoi('1','2','3',height))
#!/usr/bin/env python # -*- coding: utf-8 -*- # File : OOP05.py # Author: roohom # Date : 2018/10/18 0018 # 继承 # class Super: def method(self): print("In Super.method") class Sub(Super): def method(self): print("Starting Sub.method") Super.method(self) print("Ending Sub.method") s = Super() s.method() x = Sub() x.method() print("=" * 30) # 类接口技术 ''' Super: 定义一个method函数以及在子类中期待一个动作的delegate Inheritor: 没有提供任何新的变量名,因此会获得Super中定义的一切内容 Replacer : 用自己的method覆盖Super的method Extender : 覆盖并回调默认method,从而定制Super的method Provider : 实现Super的delegate方法预期的action方法 ''' class Super: def method(self): print("In Super.method") def delegate(self): self.action() class Inheritor(Super): pass class Replacer(Super): def method(self): print("In Replacer.method") class Extender(Super): def method(self): print("Starting Extender.method") Super.method(self) print("Ending Extender.method") class Provider(Super): def action(self): print("In Provider.action") if __name__ == '__main__': for i in (Inheritor, Replacer, Extender): print("\n" + i.__name__ + "......") i().method() print("\nProvider...") l = Provider() l.delegate() print("---------------")
import csv import matplotlib.pyplot as plt from scipy import stats # Get values from example dataset with open('example_data.csv', 'r') as file: read = csv.DictReader(file) x = [] y = [] for row in read: if row['Country'] == 'Indonesia': x.append(int(row['Year'])) y.append(float(row['Life expectancy '])) # Get key values for linear regression slope, intercept, r, p, std_err = stats.linregress(x, y) # Print the coefficient of correlation between values print('r =', r) # Function to determine where on the y-axis the corresponding x value will be placed def func(x): return slope * x + intercept # Run each value of x through the function model = list(map(func, x)) # Draw scatter plot plt.scatter(x, y) # Draw the line of linear regression plt.plot(x, model) # Save plot as image plt.savefig('linear_regression.png')
import random import time import heapq def heapify(a, i, size, k=2): childs = [k*i+j for j in xrange(1, k+1) if k*i+j < size] largest = i for j in childs: if a[j] > a[largest]: largest = j if largest > i: a[i], a[largest] = a[largest], a[i] heapify(a, largest, size, k) def buildHeap(a, k=2): size = len(a) for i in xrange( len(a) / k, -1, -1): heapify(a, i, size, k) return a def insert(a,value, k=2): a.append(value) i = len(a) - 1 parent = (i-1) / k while i > 0 and a[parent] < a[i]: a[parent], a[i] = a[i], a[parent] i = parent parent = (i-1) / k def maxElem(a,k=2): if not len(a): print "Heap is empty" maxElem , a[0] = a[0], a[-1] a.pop(0) heapify(a, 0, len(a), k) return maxElem def pythonHeapSort(iterable): h = [] for value in iterable: heapq.heappush(h, value) return [heapq.heappop(h) for i in xrange(len(h))] def pythonHeapBuild(a): pythonheap = [] for i in a: heapq.heappush(pythonheap, i) return pythonheap def SelectSort(a): size = len(a) for i in xrange(size-1): elem = i for j in xrange(i+1, size): if a[j] < a[elem]: elem = j if elem != i: a[elem], a[i] = a[i], a[elem] return a def heapSort(a): buildHeap(a) for i in xrange(len(a)-1, 0, -1): a[i], a[0] = a[0], a[i] heapify(a, 0, i) return a a= range(10**3) random.shuffle(a) #a = [3,2,4,5,6,7,8,9] t = time.clock() buildHeap(a[:]) print "My heap build :" , time.clock() - t ,"sec" t = time.clock() pythonHeapBuild(a[:]) print "Python heap build:" , time.clock() - t , "sec" t=time.clock() buildHeap(a[:],10) print "My 10 heap build:" , time.clock()-t, "sec" t= time.clock() SelectSort(a[:]) print "Select Sort : ", time.clock()-t, "sec" t= time.clock() heapSort(a[:]) print "heapSort: " , time.clock()-t, "sec"
# Project Euler #3 - Largest Prime Factor # The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143 ? theNumber = 13195 # Sets end point of finding primes primeList = [] # Initializes empty list of prime numbers primeFactors = [] # Initializes empty list of prime factors for theNumber for primeCan in range (2, theNumber): # Looping through "prime candidates" between 2 and end isPrime = True # Initialize prime to be True until shown not to be for i in range(2, primeCan): # Loops through 2 to primeCan to see if divisible. If not, PRIME if primeCan % i == 0: isPrime = False if isPrime: primeList.append(primeCan) # Adds prime to the list for i in range(0,len(primeList)): # Looping to determine if element in primeList is a factor in theNumber if theNumber % primeList[i] == 0: primeFactors.append(primeList[i]) print(primeList) print(primeFactors)
# Medelvärde, fullständigt program def medelv (a, b): return (a+b)/2 # Här startar exekveringen x = float(input('Det första talet? ')) y = float(input('Det andra talet? ')) mv = medelv(x, y) print(f'Medelvärde: {mv:.2f}')
import math a = float(input('Första sidan? ')) b = float(input('Andra sidan? ')) c = math.sqrt(a**2 + b**2) print(f'Hypotenusans längd: {c:.2f}')
t1 = input('Den första texten: ') t2 = input('Den andra texten: ') t1 = t1.replace(' ', '').lower() t2 = t2.replace(' ', '').lower() anagram = True for t in t1: n1 = 0 for e in t1: if e == t: n1 += 1 n2 = 0 for e in t2: if e == t: n2 += 1 if n1 != n2: anagram = False break if anagram: print('Anagram') else: print('Inte anagram')
största = 0 minsta = 1.e300 # ett stort tal while True: tal = float(input('> ')) if tal < 0: break if tal > största: största = tal if tal < minsta: minsta = tal print(f'Största talet: {största}') print(f'Minsta talet: {minsta}')
l = input('Skriv en lista: ').split() t = tuple(input('Skriv en tupel: ').split()) if l == t: print('Ska aldrig hända') l2 = list(t) if l == l2: print('Lika') else: print('Olika')
print('Skriv in flaggornas färger. Avsluta med en tom rad') flaggor = [] while True: s = input('> ') if s == '': break ordlist = s.split() # en lista med orden färger = set(ordlist) # en mängd med orden flaggor.append(färger) alla = set() gemensamma = flaggor[0] for f in flaggor: alla = alla | f gemensamma = gemensamma & f print('Alla färger:', alla) print('Gemensam färg:', gemensamma)
# Beräkning av summan 1+2+3+ .. +n n = int(input('n? ')) summa = 0 k = 1 while k <= n: summa = summa + k # öka summan med k k = k + 1 # öka k med 1 print('Summan blir', summa)
class Hus: def __init__(self, l, b): self.längd = l self.bredd = b def kvadratiskt(self): return self.längd == self.bredd def yta(self): return self.längd * self.bredd class Flervåningshus(Hus): def __init__(self, l, b, v): super().__init__(l, b) self.antal = v # antalet våningar def höghus(self): return self.antal >= 10 def yta(self): return self.längd * self.bredd * self.antal class Skola(Flervåningshus): def __init__(self, l, b, v, n): super().__init__(l, b, v) self.antal_klassrum = n def klassrum_per_vån(self): return self.antal_klassrum / self.antal def yta(self): return self.antal_klassrum * 50 l = [Hus(50, 30), Skola(50, 30, 3, 10)] for e in l: print(e.yta())
def isPrime(n): if n>=2: for i in range(2,n,1): if n%i==0: return False else: return False return True dic = { } limit = int(input("Enter the limit : ")) for i in range(2,limit+1): if isPrime(i): dic[i]="prime" else: dic[i]="non prime" print(dic) length = len(dic) for i in range(length): if dic[i+2]=="non prime": del dic[i+2] print(dic)
# Shruthi & Grace, Make Me Tic-Tac-Toe! # if you need to use random numbers.... # import random # randomNumber = random.randint(1, 10) # To print text on the screen: print("text goes here") # To take in user input call: userInput = raw_input("Your prompt goes here?") # If you need to convert a string, to an int call something like... # myString = str(myInteger) # myInteger = int(myString) # Python language reference: https://www.w3schools.com/python/default.asp def printBlankBoard(): print("1 2 3") print("4 5 6") print("7 8 9") import random # def printCom(): print(" TIC TAC TOE ") print("THECODERSCHOOL, FLOWER MOUND TEXAS") print(" ") print("The Game Board is Numbered:") print(" ") printBlankBoard() print(" ") print(" ") print(" ") randomNumber = random.randint(1, 9) ComChoice = "The Computer Chooses " + str(randomNumber) print(ComChoice)
str=input("enter any string") str1=" " for i in range(1,len(str)+1): str1+=str[-i] print(str1)
a=input("enter any string") b=input("enter any string") '''if (a==b): print("equal") else: print("not")''' c=set(a.split(' ')) d=set(b.split(' ')) if(c==d): print("equal") else: print("not")
fact=1 n=int(input("enter num")) for i in range(1,n+1): fact=fact*i print(fact)
l=[] num=int(input("how many no u want to enter")) for i in range(num): n=int(input("enter num")) l.append(n) print(l) length=len(l) n1=int(input("enter the element to found")) for i in range(length): if(n1==l[i]): print("element is found at loc",i) break else: print("element is not found at loc")
num=int(input("enter num")) for i in range(num): for j in range((num-i)-1): print(end=" ") for j in range(0,i): print("*",end=" ") print()
n=int(input("enter the number of terms")) x=int(input("enter the value of x")) sum=1 for i in range(1,n+1): sum=sum+((x**i)/i) print("sum of series is",sum)
employee={"name":"hello world","age":29,"salary":2500} c=0 for i in range(employee): if(i>='a' or i<='z'): c=c+1 print(c)
lst=[1,3,2,1,21,1,1] length=len(lst) n=int(input("enter num")) c=0 for i in range(0,length): if n==lst[i]: c+=1 if c==0: print(n,"not found") else: print(n,"has frequency",c)
list=[] num=int(input("how many no u want to enter")) for i in range(num): n1=input("enter num") list.append(n1) print(list) max=smax=list[0] for i in range(len(list)): if(list[i]>max): #smax=max max=list[i] smax=max elif(list[i]>smax): smax=list[i] print(smax)
def solve_maze_p1(fname): return solve_maze(fname, make_incrementor()) def solve_maze_p2(fname): return solve_maze(fname, make_gt3_check()) def make_incrementor(): return lambda x: x + 1 def make_gt3_check(): return lambda x: x + 1 if x < 3 else x - 1 def solve_maze(fname, xform): maze = parse_maze_file(fname) reg = 0 njumps = 0 while reg < len(maze): tmp = reg reg += maze[reg] if reg < 0: reg = 0 maze[tmp] = xform(maze[tmp]) njumps += 1 return [njumps, maze] def parse_maze_file(fname): f = open(fname, 'r') maze = [int(line) for line in f] f.close() return maze
# 문제 8 def solution(sentence): str = '' for c in sentence: # 해당 문장을 문자 하나씩 c 대입 if c != '.' and c != ' ': # 문자가 , 이거나 공백이 아니면 str += c # str 에 문자 저장 size = len(str) # 합쳐진 문자 길이 구하기 for i in range(size//2): # //: 몫 문자길이//2 if str[i] != str[size-1 -i]: # 첫문자 와 마지막 문자가 다를 경우 return False # 팰린드롬 x return True sentence1 = "never odd or even" ret1 = solution(sentence1) print("solution1 함수 결과", ret1) sentence2 = "palindrome" ret2 = solution(sentence2) print("solution2 함수 결과", ret2)
#문제 31번 예상 : 문자끼리는 더할 수 없고 연결된다. a = "3" b = "4" print(a + b) # 문제 32번 print("Hi" * 3) # 문제 33번 print("-" * 80) # 문제 34번 t1 = 'python' t2 = 'java' print((t1 + t2) * 4) # 문제 35번 name1 = "김민수" age1 = 10 name2 = "이철희" age2 = 13 print("이름 : %s 나이 : %d " % (name1, age1)) print("이름 : %s 나이 : %d " % (name2, age2)) # 문제 36번 format() 함수 : () 안에 들어갈 데이터를 format 함수 안에 넣기 print("이름 : {} 나이 : {}", format(name1, age1)) print("이름 : {} 나이 : {}", format(name2, age2)) # 문제 37번 f-string print( f"이름 : {name1} 나이 : {age1}") print( f"이름 : {name1} 나이 : {age1}") # 문제 38번 상장주식수 = "5,969,782,550" 상장주식수1 = 상장주식수.replace(",", "") print(상장주식수1) #문제 39번 분기 = "2020/03(E) (IFRS연결)" print(분기[0:7]) #문제 40번 공백제거 strip() 함수 사용시 앞뒤에 공백 제거 함수 data = " 삼성전자 " 공백제거 = data.strip() print(공백제거)
# coding: utf-8 # In[ ]: # Set the passcode the user needs to enter as their name to activate program. passcode = "a" messages = [] # Need to find a way for this not to reset the list each time the code is run. #Get the user to enter a passcode, check if its compatible, if not kick user. login = input("Welcome to Message Mate \n Please enter your name :). ") while True: if passcode != login: print("Sorry this program is down for maintence. \n We expect all upgrades to be done within 48 hours. \n Please check back then.") break else: name = input("Now that we know you can be trusted what name would you like to go by?") #If user passes the test welcome them back, and find out if they wish to receive or leave a message if passcode == login: print("Welcome back Commander",name.title() +"!") # Get user input for action and make sure that its either receive, or leave. while True: action = input("Do you wish to leave a message, or receive a message?") if action.lower() == "receive": print("I understand, lets see if anyone cares enough about you to have left a message") break if action.lower() == "leave": print("Excellent, I am sure someone will be very happy to hear from you",name + "!") break else: print("Sorry but we only deal in certainties, please enter either 'receive' or 'leave':D!") #Allow user to leave a message, save message in a list, hash message, display hash to be used as a key. if action.lower() == "leave": message = input("So what exactly is so important that you couldn't say it anywhere else? : ") messages.append(message) location = messages.index(message) message = "" lock = hash(messages[location]) print(key) print(messages[location]) print(location) break # This is the part of the code to check your messages # Check the hash against the hashes of the items in the list, if its the same display the message, and change the messages if action.lower() == "receive": key = input("What key were you given?") for item in messages: if hash(item) == key: print(item) item = "Sorry we can't find what your looking for" break else: print("Sorry that code doesn't exist, it may have been used already :(. \n Try torturing the information out of your friend!)") break
import gameBoard import gameLogic def run_loop(): """The main run loop""" print "Welcome to ticTacToe" pc = choose_color() board = gameBoard.Board() game_logic = gameLogic.GameLogic(); board.display() cc = pc while not game_logic.solved(board) and not game_logic.deadlock(board): if cc == pc: move = choose_move(board, cc) board.makeMove(move, cc) else: game_logic.computerMove(board, cc) board.display() cc = board.oppositeColor(cc) if game_logic.solved(board): print "We have a winner!" else: print "We have a deadlock!" return def choose_move(board, cc): """Choose the next move for the current color""" move = raw_input("Please Choose a move as [r,c]> ") while not board.validate(move, cc): move = raw_input("Please Choose a move as [r,c]> ") return move def choose_color(): """Choose the player color""" color = raw_input("Please Choose a Color (B or W)> ") while color != "B" and color != "W": color = raw_input("Please Choose a Color (B or W)> ") return color[0] run_loop()
from art import logo2 print(logo2) bids = {} bidding_finished = False while not bidding_finished: name = input("What is your name? ") price = input("What is your bid? $") bids[name] = price should_continue = input("Are there any other bidders? Type 'yes' or 'no'. ") if should_continue == "no": bidding_finished = True winner = max(bids, key=bids.get) bid_max = bids[winner] print(f"The winner is {winner} with a bid of ${bid_max}.") elif should_continue == "yes": continue
def sum_below_1000(): sum_3 = sum(x for x in range(0,1000,3)) sum_5 = sum(x for x in range(0,1000,5)) sum_15 = sum(x for x in range(0,1000,15)) return sum_3 + sum_5 - sum_15
class Tree: def __init__(self, val ): self.data = val self.left = None self.right = None def maxsum(root): if root is None: return 0 l = maxsum(root.left) r = maxsum(root.right) max_single = max(max(l,r) + root.data, root.data) max_top = max(max_single, l+r+ root.data) maxsum.res = max(maxsum.res, max_top) return max_single ''' 5 1 4 a3 a6 ''' a5 = Tree(5) a1 = Tree(1) a4 = Tree(4) a3 = Tree(3) a6 = Tree(6) a5.left = a1 a5.right = a4 a4.left = a3 a4.right = a6 maxsum.res = float('-inf') print (maxsum (a5))
def climbStairs (n: int) -> int: def _helper (n): if n in d: return d[n] return _helper (n - 1) + _helper (n - 2) from collections import defaultdict d = defaultdict(int) d[0] = 0 d[1] = 1 d[2] = 2 d[3] = 3 for i in range(n+1): d[i] = _helper(i) return d[n] print (climbStairs (44))
def heightChecker(heights): if not heights: return None count = 0 temp_array = heights[:] temp_array.sort() for i in range(len(heights)): if heights[i] != temp_array[i]: count += 1 return count heights = [1, 1, 4, 2, 1, 3] # [1,1,1,2,3,4] print(heightChecker(heights))
''' Input: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse" Output: [ ["mobile","moneypot","monitor"], ["mobile","moneypot","monitor"], ["mouse","mousepad"], ["mouse","mousepad"], ["mouse","mousepad"] ] Explanation: products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"] After typing m and mo all products match and we show user ["mobile","moneypot","monitor"] After typing mou, mous and mouse the system suggests ["mouse","mousepad"] ''' from collections import defaultdict import random class Trie: def __init__(self): self.word = defaultdict() self.phase = False self.suggestion = set() self.count = random.randint(0,10) class Classy: def __init__(self): self.head = Trie() def insert(self, phases): if not phases: return 0 for each in phases: temp_dic = self.head for ch in each: if ch not in temp_dic.word: temp_dic.word[ch] = Trie() temp_dic.suggestion.add((each, temp_dic.count)) temp_dic = temp_dic.word[ch] temp_dic.word['phase'] = True def searchWord(self, phases, word): if not phases or not word: return 0 self.insert(phases) temp_dic = self.head for each in word: if each in temp_dic.word: suggest = list(temp_dic.suggestion) suggest.sort() if len(suggest) > 3: print(suggest[:3]) else: print(suggest) temp_dic = temp_dic.word[each] else: print([]) obj = Classy() products = ["mobile","mouse","moneypot","monitor","mousepad"] searchWord = "mouse" obj.searchWord(products,searchWord)
def _checkPalindrome(st): for i in range(len(st)//2): if st[i] != st[len(st)-i-1]: return False return True def longestPalindrome(st): final_count = 0 final_word = "" ''' babad ''' visited = set() if _checkPalindrome(st): return len(st),st else: for i in range(len(st)-1): for j in range(i+1,len(st)): temp = st[i:j] if temp not in visited: if _checkPalindrome(temp): if len(temp)>final_count: final_count = len(temp) final_word = temp visited.add(temp) return final_count,final_word def longestPalindrome1(st): ''' :param st: :return: b a b a d b 1 0 3 0 0 a 1 0 3 0 b 1 0 0 a 1 0 d 1 b a d a b b 1 0 0 5 a 1 0 3 0 d 1 0 a 1 0 b 1 ''' final_count = 0 final_word = "" l = len(st) mat = [[0 for i in range(l)] for j in range(l)] for i in range(l): mat[i][i] = 1 for i in range(l-1): if st[i] == st[i+1]: mat[i][i+1]= 2 for i in range(2,l-1): for j in range(l-i+1): if st[j] == st[i+j] and mat[i+1][j-1]: mat[j][i+j] = mat[i+1][j-1] + 2 if mat[j][i+j] > final_count: final_count = mat[j][i+j] final_word = st[i:i+final_count] return final_count,final_word print (longestPalindrome1 ('babad'))
def sum3(num): l = len(num) for i in range(l-2): for j in range(i+1, l-1): for k in range(j+1,l): if
def _helper2(sortedList, num, position): count = 1 while ((position-count) > 0 and sortedList[position-count] == num) or ((position+count) < len(sortedList)-1 and sortedList[position+count] == num): if ((position-count) > 0 and sortedList[position-count] == num) and ((position+count) < len(sortedList)-1 and sortedList[position+count] == num): count += 2 elif ((position-count) > 0 and sortedList[position-count] == num) or ((position+count) < len(sortedList)-1 and sortedList[position+count] == num): count += 1 else: return count return count def _helper(sortedList, num, start, end): if sortedList[start] == num: return _helper2(sortedList, num, start) elif sortedList[end] == num: return _helper2(sortedList, num, end) else: mid = (start+end)//2 if sortedList[mid] >= num: return _helper(sortedList, num, start, mid-1) else: return _helper(sortedList, num, mid+1, end) def countOccurence(sortedList, num): if not sortedList or not num: return 0 return _helper(sortedList, num, 0, len(sortedList)-1) arr = [4, 4, 8, 8, 8, 15, 16, 23, 23, 42] target = 8 print(countOccurence(arr, target))
class Node: def __init__(self, data): self.data = data self.left = None self.right = None class MergeTree: def __init__(self): self.finalPaths = [] def allPath(self, node, path): if node is None: return path.append(node.data) if node is not None and (node.left is None and node.right is None): self.finalPaths.append(path[:]) self.allPath(node.left, path) self.allPath(node.right, path) path.pop() def printAll(self, node): if not node: return self.printAll(node.left) print(node.data) self.printAll(node.right) a1 = Node('1') a2 = Node('2') a3 = Node('3') a4 = Node('4') a5 = Node('5') b1 = Node('6') b2 = Node('7') b3 = Node('8') b4 = Node('9') b5 = Node('10') a1.left = a2 a1.right = a3 a2.left = a4 a3.right = a5 a2.right = b2 a5.left = b3 a5.right = b1 a4.left = b4 a4.right = b5 obj = MergeTree() obj.allPath(node=a1, path=[]) print(obj.printAll(a1)) print(obj.finalPaths)
from LeetcodeRandom import unittest from LeetcodeRandom.unittest import PhoneBook class PhoneBookTest(unittest.TestCase): def test_lookup_by_name(self): phonebook = PhoneBook () phonebook.add("bob", "12345") number = phonebook.lookup("bob") self.assertEqual("12345", number)
def trappingRainWater(steps): ''' :param steps: Input: [0,1,0,2,1,0,1,3,2,1,2,1] :return: 6 ''' l = 0 r = len(steps) - 1 left_max , right_max = 0,0 result = 0 while l<r: if steps[l]<steps[r]: if left_max < steps[l]: left_max = steps[l] else: result += (left_max - steps[l]) l+=1 else: if right_max < steps[r]: right_max = steps[r] else: result += (right_max - steps[r]) r -= 1 return result steps = [0,1,0,2,1,0,1,3,2,1,2,1] print (trappingRainWater (steps))
def sum3(nums): l = len(nums) s= [] if l>2: for i in range(l): for j in range(i+1,l): for k in range(j+1,l): if nums[i]+nums[j]+nums[k] == 0: temp = [nums[i],nums[j],nums[k]] temp.sort() if temp not in s: s.append(temp) temp = set(s) return s def threesum(nums): l = [] for i in range(0, len(nums)-1): ls = [] for j in range(i+1, len(nums)): temp = nums[i] + nums[j] if -temp in ls: temp_ls = [nums[i],nums[j],-temp] temp_ls.sort() if temp_ls not in l: l.append(temp_ls) else: ls.append(nums[j]) return l def threesum2(nums): dic = {} def twosum(nums): for i in range(0,len(nums)-1): for j in range(i+1, len(nums)): temp = nums[i]+nums[j] if temp not in dic: if nums[i]< nums[j]: dic[nums[i] + nums[j]] = [[nums[i],nums[j]]] else: dic[nums[i] + nums[j]] = [[nums[j], nums[i]]] else: temp_l =[] temp_l = dic[nums[i]+nums[j]] temp_l.append([nums[i],nums[j]]) dic[nums[i]+nums[j]] = temp_l twosum(nums) l = [] for i in range(0, len(nums)): if -nums[i] in dic: le = len(dic[-nums[i]]) while le >=1: val0, val1 = dic[-nums[i]][le] if i != val0 and i != val1: temp = -nums[i] temp1 = [] if nums[val0] <= nums[val1] and nums[val0] <= -temp: if nums[val1] <= -temp: temp1.append([val0,val1,-temp]) elif nums[val1] <= nums[val0] and nums[val1] <= -temp: if nums[val0] <= -temp: temp1.append([val1,val0,-temp]) else: if nums[val1]< nums[val0]: temp1.append([-temp,val1,val0]) else: temp1.append([-temp,val0,val1]) if len(temp1)>2 and temp1 not in l: l.append(temp1) le-=1 # def threeSum (self, nums: List[int]) -> List[List[int]]: # l = len (nums) # nums.sort () # ls = [] # # for i in range (l): # s = i + 1 # lst = l - 1 # while s < lst: # temp = nums[i] + nums[s] + nums[lst] # if temp == 0: # ls.append (nums[i] + nums[s] + nums[lst]) # s += 1 # lst -= 1 # # elif temp < 0: # s += 1 # else: # lst -= 1 # return ls #l=sum3([-1, 0, 1, 2, -1, -4]) print(threesum2([-1,0,1,2,-1,-4]))
class Trie(): def __init__(self, ls): for each in ls: self.each = each self.next = None class Tree: def __init__(self): self.firstNode = None def insert(self, ls): node = Trie(ls) if self.firstNode is None:
class Anagram: def __init__ (self): self.ans = [] self.temp_ans = [] def _permutation (self, word, index): ''' @param: str - take a word and find all its permutation and check if exist in self.wordList @return: list ''' if len (word)-1 == index: temp_word = str(''.join(word)) if temp_word in self.wordList: self.temp_ans.append (temp_word[:]) self.wordList[self.wordList.index (temp_word)] = '-1' for i in range (index, len (word)): word[i], word[index] = word[index], word[i] self._permutation (word, index + 1) word[i], word[index] = word[index], word[i] def checkAnagram (self, wordList): ''' @param wordList []: List - wordlist contains the word and we need to find if anagram each word exist in the list @return [[]]: list - list of list of each anagram that are same @exception: if the list is empty or wrong input logic - take each word and find all its permutation and see it exist in the list and it exist remove add the common word and make that -1 in the list. ''' self.wordList = wordList for each in wordList: if each != '-1': self.temp_ans = [] self._permutation (list (each), 0) self.ans.append(self.temp_ans[:]) return self.ans ''' ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ''' wordlist = ["eat", "tea", "tan", "ate", "nat", "bat"] wort_temp = wordlist wort_temp.sort(key= lambda i:i in i[:]) obj = Anagram() print (obj.checkAnagram (wordlist))
class Node: def __init__(self, data): self.data = data self.left = None self.right = None class MergeTree: def merge(self, a, b): if not a and not b: return None elif not a and b: return b elif not b and a: return a else: a.data += b.data a.left = self.merge(a.left, b.left) a.right = self.merge(a.right, b.right) return a def printAll(self, node): if not node: return self.printAll(node.left) print(node.data) self.printAll(node.right) a1 = Node(1) a2 = Node(2) a3 = Node(3) a4 = Node(4) a5 = Node(5) b1 = Node(6) b2 = Node(7) b3 = Node(8) b4 = Node(9) b5 = Node(10) a1.left = a2 a1.right = a3 a2.left = a4 a3.right = a5 b1.left = b2 b1.right = b3 b2.right = b4 b3.left = b5 obj = MergeTree() obj.printAll(obj.merge(a1, b1))
from threading import Thread from threading import current_thread class subThread(Thread): def __init__(self): Thread.__init__(self,name='subclassThread',args = (2,3)) def run(self): print('{} is the running thread'.format(current_thread().getName())) obj1 = subThread() obj1.start() obj1.run() obj2 = subThread() obj2.run()
''' Given a string "atdoer" and a dictionary {"to", "toe", "top"}, what is the maximum length word that can be formed using the letters in the string ,and that word must be present in dictionary as well. For eg, in this case, answer will be "toe" ''' def checkMaximum(dict, inputString):
''' You work on a team whose job is to understand the most sought after toys for the holiday season. A teammate of yours has built a webcrawler that extracts a list of quotes about toys from different articles. You need to take these quotes and identify which toys are mentioned most frequently. Write an algorithm that identifies the top N toys out of a list of quotes and list of toys. Your algorithm should output the top N toys mentioned most frequently in the quotes. Input: The input to the function/method consists of five arguments: numToys, an integer representing the number of toys topToys, an integer representing the number of top toys your algorithm needs to return; toys, a list of strings representing the toys, numQuotes, an integer representing the number of quotes about toys; quotes, a list of strings that consists of space-sperated words representing articles about toys Output: Return a list of strings of the most popular N toys in order of most to least frequently mentioned Note: The comparison of strings is case-insensitive. If the value of topToys is more than the number of toys, return the names of only the toys mentioned in the quotes. If toys are mentioned an equal number of times in quotes, sort alphabetically. Example 1: Input: numToys = 6 topToys = 2 toys = ["elmo", "elsa", "legos", "drone", "tablet", "warcraft"] numQuotes = 6 quotes = [ "Elmo is the hottest of the season! Elmo will be on every kid's wishlist!", "The new Elmo dolls are super high quality", "Expect the Elsa dolls to be very popular this year, Elsa!", "Elsa and Elmo are the toys I'll be buying for my kids, Elsa is good", "For parents of older kids, look into buying them a drone", "Warcraft is slowly rising in popularity ahead of the holiday season" ]; Output: ["elmo", "elsa"] ''' def solution(quotes, numToys,topToys, toys): from collections import defaultdict from heapq import heapify,heappush,nlargest import re working_dic = defaultdict(int) for line in quotes: temp = re.sub(r'''[,!.;'"]+'''," ",line).lower().split() for word in temp: if str(word) in toys: working_dic[word]+=1 import operator sorted_d = sorted (working_dic.items (), key=operator.itemgetter (1)) working_list = [] heapify(working_list) for k,v in working_dic.items(): heappush(working_list,(v,k)) print('{} {}'.format(k,v)) t = nlargest(topToys,working_list) final_list = [] for each in t: final_list.append(each[1]) return final_list numToys = 6 topToys = 2 toys = ["elmo", "elsa", "legos", "drone", "tablet", "warcraft"] numQuotes = 6 quotes = [ "Elmo is the hottest of the season! Elmo will be on every kid's wishlist!", "The new Elmo dolls are super high quality", "Expect the Elsa dolls to be very popular this year, Elsa!", "Elsa and Elmo are the toys I'll be buying for my kids, Elsa is good", "For parents of older kids, look into buying them a drone", "Warcraft is slowly rising in popularity ahead of the holiday season" ] print (solution (quotes, numToys, topToys, toys))
#! /usr/bin/env python # -*- coding: utf-8 -*- # Ejercicion No 5 def sum(lista): suma = 0 for i in lista: suma += i return suma def multip(lista): multiplicacion = 1 for i in lista: multiplicacion *= i return multiplicacion n=int(input("cantidad numeros:")) lista=[] for i in range(0,n): lista.append(int(input("ingrese numero "+str(i+1)+" de la lista: "))) print "La Suma de los elementos es: " + str(sum(lista)) print "La Multiplicación de los elementos es: " + str(multip(lista))
#!/usr/bin/env python # -*- coding: utf-8 -* # funcion max a = int(input("Digite primer numero: ")) b = int(input("Digite segundo numero: ")) if a>b: print ("el numero mayor es:", a) else: print ("el numero menor es:", b) if a == b: print "los numeros son iguales"
a= int(input("enter thye number")) i=2 while i<a: if a%i == 0: print("Not prime") break i= i+1 else: print("prime")
myList=[1,-2,3,-4,5,-6,7,-8,9,-10] a=int(input('Enter an index to check the number in the list...')) try: if myList[a]<0: print('Number at this index is negative.') else: print('Number at this index is positive.') except: print('Please enter a valid index number.')
thislist=[] n=int(input("Enter the number of elements you want to input.")) i=0 print("Enter the elements...") while i < n: a=(input()) thislist.append(a) i+=1 print("List is...",thislist) a=input("Enter the element you want to append at the end of this list.") thislist.append(a) print("List after adding the element...",thislist)
n=int(input("Enter the nuber of elements you want to enter in the list.")) thisList=[] i=0 while i<n: a=input() thisList.append(a) i+=1 print("List...",thisList) a=input("Enter the element which you want to remove.") thisList.remove(a) print("List after removing the element...",thisList)
a=int(input("Enter value of a: ")) b=int(input("Enter value of b: ")) print("Before swaping, a=",a,"and b=",b) c=a a=b b=c #another way to swap is :- a=a+b -> b=a-b -> a=a-b print("After swaping, a=",a,"and b=",b)
n=input('Enter a number...') try: n=int(n) except: print('Please enter a valid input.') else: if n<0: print('Please enter a positive number.') else: i=2 flag=1 for i in range(2,n//2): if n%i==0: flag=0 break else: i+=1 if flag==1: print(n,'is a prime number.') else: print(n,'is not a prime number.')
f1=open('sample1.txt','a') a=input('Enter the text you want to add to the file...') f1.write(a+'\n') f1.close() print('File updated...')
a=int(input("How far would you like to travel in miles?")) if a<3: print("I suggest Bicycle to your destination.") elif a in range(3,300): print("I suggest Motor-Cycle to your destination.") else: print("I suggest Super-Car to your destination.")
a=13 print(a," is of type: ", type(a)) a=13.03 print(a," is of type: ", type(a)) a=True print(a," is of type: ", type(a)) a='Saini' print(a," is of type: ", type(a))
#Writing to a file writeMe = 'Example text' #variable saveFile = open('exampleWrite.txt','w')#open = built in function #the 'w' means write to file saveFile.write(writeMe) saveFile.close()
# coding:utf-8 class Stack(object): # 栈的顺序结构 def __init__(self): # 初始化 self.__list = list() def is_empty(self): # 判断是否为空栈 return len(self.__list) <= 0 def push(self, data): # 入栈 self.__list.append(data) def pop(self): # 出栈 if self.is_empty(): return "stack is empty" else: return self.__list.pop() def get_top(self): # 获取栈顶数据元素 if self.is_empty(): return "stack is empty" else: return self.__list[-1] def clear(self): # 清空栈 self.__list.clear() if __name__ == '__main__': stack = Stack() stack.push(1) stack.push(2) stack.push(3) print(stack.pop()) print(stack.pop()) print(stack.pop()) print(stack.is_empty()) print(stack.pop())
''' The nth fibonacci number can be computed more efficiently by not using recursion, but instead by building up the answer from the bottom. Create an iterative version of the fibonacci function, fib_iterative, that takes one argument, n, and returns the nth fibonacci number. Allocate a list of length n. Initialize fib[0] = 1 and fib[1] = 1. Then fill in each entry in your list in ascending order with: mylist[i] = mylist[i-1] + mylist[i-2] Now measure the running time of fib_iterative for each of the fibonacci numbers between 1 and 40. How does it computer to the recursive version? Submit both your function and a plot of its running time. ''' def fib_iterative(n): fiblist = [1,1] for i in range(2, n): fiblist.append(fiblist[i - 1] + fiblist[i - 2]) return fiblist print(fib_iterative(7))
""" Aluno: Cicero Josean O objetivo da MLP é a partir de uma base de dados de filmes que são produzidos, gerar a classificação se um filme tem um bom score ou não (bom é >= 7, e ruim < 7) """ import pandas as pd # Importing the dataset dataset =pd.read_csv('dados - filmes.csv') dataset.head() X = dataset.iloc[:,[1,2,3,4,6,8,9,10]].values y = dataset.iloc[:,-1].values newy = [] #vetor que vai classificar o score como bom ou ruim for i in y: if i<7: newy.append(0) #score ruim else: newy.append(1) #score bom # Separação da base de dados entre Treino e Teste from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, newy, test_size = 0.25, random_state = 0) #Normalizando os dados de entrada from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # MultiLayerPerceptronClassifier from sklearn.neural_network import MLPClassifier redeNeural_01 = MLPClassifier(verbose=True) #cria um objeto redeNeural_01.score #mostra os parâmetros usados no treinamento redeNeural_01.fit(X_train,y_train) #fazer o treinamento # Fazendo a previsão dos Resultados y_pred_01 = redeNeural_01.predict(X_test) # Matriz de Confusão from sklearn.metrics import confusion_matrix cm_01 = confusion_matrix(y_test, y_pred_01) #Parâmetros Modificados redeNeural_02 = MLPClassifier(verbose=True,max_iter=1000000,tol=0.000001,activation='logistic') redeNeural_02.score #mostra os parâmetros usados no treinamento redeNeural_02.fit(X_train,y_train) #fazer o treinamento # Fazendo a previsão dos Resultados y_pred_02 = redeNeural_02.predict(X_test) # Matriz de Confusão cm_02 = confusion_matrix(y_test, y_pred_02) #Comparando os dois Resultados print("Matriz de Confusão Inicial: \n",cm_01) score_confusao_01 = (cm_01[0,0]+cm_01[1,1])/(cm_01[0,0]+cm_01[0,1]+cm_01[1,0]+cm_01[1,1])*100 print("Score = ",round(score_confusao_01,2),"%") print("Matriz de Confusão Modificada: \n",cm_02) score_confusao_02 = (cm_02[0,0]+cm_02[1,1])/(cm_02[0,0]+cm_02[0,1]+cm_02[1,0]+cm_02[1,1])*100 print("Score = ",round(score_confusao_02,2),"%")
"""Check if string has balanced parens.""" from typing import List def main(): s = '[]' s2 = '{}' s3 = '([])' s4 = '[(])' print(BalanceParen(s)) print(BalanceParen(s2)) print(BalanceParen(s3)) print(BalanceParen(s4)) print(BalanceParen('')) print(BalanceParen('[')) def BalanceParen(s: str) -> bool: if len(s) < 2: return False leftChars = ['(','[','{'] rightChars = [')',']','}'] stack = [] for e in s: if e in leftChars: stack.append(e) if e in rightChars: if len(stack) == 0: return False else: last = stack.pop() if leftChars.index(last) == rightChars.index(e): return True else: return False if __name__ == '__main__': main()
"""Array Sequence Practice """ __author__ = 'Xavier Collantes' import copy import random def main(): print('Anagram Check, Solution 1: %s' % AnagramCheck('clint eastwood', 'old west action')) print('Anagram Check, Solution 2: %s' % AnagramCheck2('clint eastwood', 'old west action')) print('Array Pairs, Solution 1: %s' % ArrayPair([1, 3, 2, 2], 4)) find_list = [1,2,3,4,5,6,7,7,7,8,9] shuffle = copy.deepcopy(find_list) random.shuffle(shuffle) shuffle = shuffle[1:] print('FinderBest: %s' % FinderBest(find_list, shuffle)) print(find_list) print(shuffle) print('Sentence reversal: %s' % SentReverse('There is no try only do or do not. ')) def Finder(list, shuffled_list): """Find the missing element in shuffled_list. Time complexity is O(n^2). Given two lists, the second a shuffled version of first, return the element missing in shuffled_list. list: Ordered list of non-negative numbers. shuffled_list: Randomized version of list with one element missing. Returns: The missing element not in shuffled_list but present in list. """ if len(list) == len(shuffled_list) - 1: return 'Error' for e in list: if e not in shuffled_list: return e def FinderBest(list, list_shuffle): """Same as Finder but more efficient time complexity O(n). We iterate through each list once. """ if len(list) == len(list_shuffle) - 1: return 'Error' count = {} for e in list_shuffle: print('e ', e, count) if e in count: count[e] += 1 else: count[e] = 1 for s in list: print('s ', s, count) if s in count: count[s] -= 1 else: return s if count[s] == 0: count.pop(s) def SentReverse(sentence): """Reverse the words in a sentence. sentence: String in forward order. Returns: String sentence with reverse order words. """ sentence = sentence.strip() sentence = sentence.split(' ') length = len(sentence) out = '' for word in sentence: out = word + ' ' + out print(out) return out def ArrayPair(arr, sum): """Find the pairs in given array that sum up to the given sum. """ eval = [] for col in arr: for row in arr: if ((col + row) == sum) and ([col, row] not in eval) : eval.append([col, row]) return eval def AnagramCheck(x, y): ''' Anagram Check: Check to see if both inputs are anagrams of each other. Solution 1: Sort strings then compare since both should have the same number of letters. ''' x = x.replace(' ', '').lower() y = y.replace(' ', '').lower() return sorted(x) == sorted(y) def AnagramCheck2(x, y): '''Solution 2: Verify two inputs are anagrams. ''' x = x.replace(' ', '').lower() y = y.replace(' ', '').lower() if len(x) is not len(y): return False countDict = {} for a in x: # Loop first word if a in countDict: countDict[a] = countDict[a] + 1 else: countDict[a] = 1 print(countDict) for b in y: if b in countDict: countDict[b] = countDict[b] - 1 else: return False if countDict[b] == 0: countDict.pop(b) if len(countDict) == 0: return True #print(countDict) #print(len(countDict)) if __name__=='__main__': main()
"""Binary Search Trees Practice. """ __author__ = 'Xavier Collantes' class BSTNode: def __init__(self, key, data=None): self.key = key self.data = data self.left = None self.right = None def GetRight(self): return self.right def GetLeft(self): return self.left def SetRight(self, data): self.data = data def SetLeft(self, data): self.data = data def GetKey(self): return self.key def GetData(self): return self.data
"""Queue behavior with two stacks.""" from typing import List import unittest class Queue2Stacks: def __init__(self): self._stack1 = [] self._stack2 = [] self.size = 0 def enqueue(self, element: int): self._stack1.append(element) self.size += 1 def dequeue(self) -> int: for e in range(self.size - 1): last = self._stack1.pop() print(last) self._stack2.append(last) result = self._stack1.pop() self.size -= 1 print(f'RESULT: {result}') for i in range(self.size): self._stack1.append(self._stack2.pop()) return result class Queue2StacksTest(unittest.TestCase): def testRun(self): q = Queue2Stacks() q.enqueue(0) q.enqueue(1) q.enqueue(2) q.enqueue(3) q.enqueue(4) self.assertEqual(q.dequeue(), 0) self.assertEqual(q.dequeue(), 1) self.assertEqual(q.dequeue(), 2) self.assertEqual(q.dequeue(), 3) if __name__=='__main__': unittest.main()
import random import time def selection_sort(alist): comparisons = 0 for i in range(len(alist)-1, 0, -1): positionOfMax = 0 for location in range(1, i+1): comparisons += 1 if alist[location] > alist[positionOfMax]: positionOfMax = location temp = alist[i] alist[i] = alist[positionOfMax] alist[positionOfMax] = temp return comparisons def insertion_sort(alist): comparisons = 0 for i in range(1, len(alist)): value = alist[i] j = i - 1 while j >= 0: comparisons += 1 if value < alist[j]: alist[j + 1] = alist[j] alist[j] = value j = j - 1 else: break return comparisons def main(): # Give the random number generator a seed, so the same sequence of # random numbers is generated at each run random.seed(1234) # Generate 5000 random numbers from 0 to 999,999 randoms = random.sample(range(1000000), 32000) start_time = time.time() comps = insertion_sort(randoms) stop_time = time.time() print(comps, stop_time - start_time) if __name__ == '__main__': main()
''' 利用parse模块模拟post请求 分析百度词典 分析步骤: 1. 打开F12 2. 尝试输入单词girl·返现没敲一个字母后都有请求 3. 请求地址是 https://fanyi.baidu.com/sug 4. 利用network-All-Hearders·查看·发现FormData的值是 kw:girl 5. 检查返回内容格式·发现返回的是json格式内容==>需要用到json包 ''' import requests from urllib import parse # 负责处理json格式的模块 import json ''' 大致流程是: 1. 利用data结构内容·然后urlopen打开 2. 返回一个json格式的结果 3. 结果应该是girl的释义 ''' baseurl = 'https://fanyi.baidu.com/sug' # 存放用来模拟form的数据一定是dict格式 data = { # girl是翻译输入的英文内容·应该是由客户输入·此处使用硬编码 "kw":"girl" } # 我们需要构造一个请求头·请求头部应该至少包含传入的数据的长度 # request要求传入的请求头是一个dict格式 headers = { # 因为使用post·至少应该包含content-length字段 "Content-Length":str(len(data)) } # 有了headers·data·url·就可以尝试发出请求了 rsp = requests.post(baseurl,data=data,headers=headers) print(rsp.text) print(rsp.json()) #for item in json_data["data"]: # print(item["k"],"--",item["v"])
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ###for循环### #sum = 0 #for x in range(101): # sum += x #print(sum) ###while循环### #sum = 0 #n = 99 #while n > 0: # sum += n # n -= 2 #print(sum) ###print list### #L = ['Bart', 'Lisa', 'Adam'] #for name in L: # print(name) ###break### n = 1 while n <= 100: # if n > 20: # break n += 1 if n % 2 == 0: continue print(n) print('END')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def fact(n): if n == 1: return 1 return n * fact(n - 1) def move(n, a, b, c): if n == 1: print('move', a, '-->', c) else: move(n-1, a, c, b) move(1, a, b, c) move(n-1, b, a, c) move(4, 'A', 'B', 'C')