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)) """Give...
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 ...
# 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 =...
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 wi...
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') ...
#!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_recur...
#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 RK...
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 s...
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 (...
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...
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 ...
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.l...
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)] ...
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-maxlengt...
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 ...
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...
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: ...
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):...
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] ...
# -*- 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 uniquenes...
# 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:...
#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 # ...
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(...
#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, co...
#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" a...
#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 ...
#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] = " " prin...
#!/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 ...
#!/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): ...
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.app...
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 = l...
# 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 ...
# 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: ...
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 flaggo...
# 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.ant...
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" pr...
# 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 cal...
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 ...
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 =...
# 문제 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 ...
#문제 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)) # 문제 3...
# 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("Welcom...
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): ...
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": ...
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+ r...
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...
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(height...
''' 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","...
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:...
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)-...
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 ...
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] ...
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() ...
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: ...
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 el...
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.r...
''' 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 ...
#! /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:")) ...
#!/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 addi...
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: ...
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.__l...
''' 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...
""" 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,...
"""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) -> b...
"""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...
"""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, dat...
"""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(...
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 ...
''' 利用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. 返回一个js...
#!/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: # ...
#!/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')