text
stringlengths
37
1.41M
from turtle import Turtle WIDTH = 5 HEIGHT = 1 MOVE_DISTANCE = 20 class Paddle(Turtle): def __init__(self, initial_x, initial_y): super().__init__() self.x_pos = initial_x self.y_pos = initial_y self.color("white") self.shape("square") self.turtlesize(stretch_wid=W...
#!/usr/bin/env python3 # encoding: utf-8 # Splits a word into multiple parts def split_word(word): split_indexes = list(range(0, len(word))) for i in split_indexes: first_part = word[:i] second_part = word[i:] yield (first_part, second_part)
""" ============== Plotting bars ============== Here's a small example showcasing how to plot bars on a circular strip. """ import numpy as np from circhic._base import CircHiCFigure ############################################################################### # First, simulate some data lengths = np.array([3500]) ...
""" Utilizando lambdas Conhecidas por expressões lambdas ou simplesmente lambdas funções anonimas """ nome_completo = lambda nome, sobrenome: nome.strip().title() + " " + sobrenome.strip().title() print(nome_completo(" ANGELINA ", " JOLIE"))
import random import time import os Jogadores = [] Classes = [] salvados = [""] Atribuido = {} def cadastraJogadores(): jogador = "" numJog=0 while True: numJog = int(input("--Diga quantos jogadores terá: ")) if numJog < 5: print("Numero de jogadores menor que 5, insuficiente, ...
from tkinter import * import os root=Tk() # root.title('tk using label') #根窗口的标题 root.geometry('600x600') #根窗口的大小 'text: Label显示的文本' 'font: Label显示的字体' 'relief:控件的样式' 'padx:x方向上,Label内文字与Label边缘的距离' 'pady:y方向上,Label内文字与Label边缘的距离' x = Label(root, text='a beautiful girl', font=('Arial',12), ...
import numpy as np def gradient_descent(x,y): m_curr = b_curr = 0 n = len(x) learning = 0.07 iterations = 100 for i in range(iterations): y_pred = (m_curr * x + b_curr) cost = (1/n) * sum([val**2 for val in (y - y_pred)]) md = -(2/n) * sum(x * (y - y_...
import threading from queue import Queue import statistics import sys def calcul(fonction, data_ready): print("Starting thread:", threading.current_thread().name) data_ready.wait() data = queue.get() print(fonction.__name__ + " : " + str(fonction(data))) print("Ending thread:", threadin...
import math def pascal(rows): for rownum in range (rows): newValue=1 PrintingList = [newValue] for iteration in range (rownum): newValue = newValue * ( rownum-iteration ) * 1 / ( iteration + 1 ) PrintingList.append(int(newValue)) print(PrintingList) rows = input('Enter the number of rows \n') rows = i...
import numpy as np import pandas as pd import visuals as vs import matplotlib.pyplot as pl pd.set_option('display.width', 800) data = pd.read_csv('../resources/customers.csv') SHOW_VISUALS = False print ''' /* * ************************************** * ********** DATA EXPLORATION ********** * ***************...
########################################### # Suppress matplotlib user warnings # Necessary for newer version of matplotlib import warnings warnings.filterwarnings("ignore", category = UserWarning, module = "matplotlib") # # Display inline matplotlib plots with IPython #from IPython import get_ipython #get_ipython().ru...
""" Skills function assessment. Please read the instructions first. Your solutions should go below this docstring. """ ############################################################################### # PART ONE: Write your own function declarations. # NOTE: We haven't given you function signatures or docstrings for...
n = int(input()) if n%2 != 0: print("Weird") elif n < 6: print("Not Weird") elif n < 21: print("Weird") else: print("Not Weird")
n = int(input()) total = "" i = 1 while i < (n+1): total = total + str(i) i += 1 print (total)
import numpy as np import matplotlib.pyplot as plt import pandas as pd import math def sigmoid(x): # changing if x goes less than e^-16 if( x < math.exp(-16)): x = math.exp(-16) y = 1 / (1 + math.exp(-x)) return y def cross_entropy(y, r): z = 1-y if(z < math...
# python3 # this program takes list as input and returns new list without duplicates user_list = list(input("enter list with some duplicates: ")) def remove_duplicates1(user_list): user_list.sort() i = len(user_list) - 1 while i > 0: if user_list[i] == user_list[i - 1]: user_list.pop(i...
# python3 # this is example of list comprehensions # for (set of values to iterate): # if (conditional filtering): # output_expression() # TO # [output_expression() for(set of values to iterate) if(conditional filtering)] import random list = random.sample(range(100), 10) # it generates random list wi...
import numpy as np import mysklearn.mypytable as mypytable import operator import copy import random def mean(x): """Computes the mean of a list of values """ return sum(x)/len(x) def compute_slope_intercept(x, y): """ """ mean_x = mean(x) mean_y = mean(y) m = sum([(x[i] - mean_x)...
def linkage(T): """ This function converts a tree from our current format to a linkage matrix Z and leaf node list V. """ condensations = sorted([v for v in T if len(v)==2]) increasing = condensations[0][0]<T[condensations[0]][0] inner_nodes = sorted(list(set(T.values())), key=lambda e: e[0]...
x = 1 if x == 1 : print("x is ", x) while x != 10: print(x) x += 1 print("Done!") # https://www.learnpython.org/en/Variables_and_Types one = 1 two = 2 three = one + two print( "one + two = ", three ) hello = "hello" world = "world" print( hello + " " + world) a,b = 3,4 print(a,b) print("Strin...
def test(x): even = lambda z: True if z == k else odd(z+-1) odd = lambda z: False if z == k else even(z+-1) k = 0 return even(x) print test(4)
x = 5 y = 2 l = [1,2,3] b = x or y z = not b q = not (not l) and not x or not y z = q or z and not l print z print q print (not []) or (not [])
def foldl_p(f, init, lst, idx, length): return init if idx == length else foldl_p(f, f(init, lst[idx]), lst, idx+1, length) def foldl(f, init, lst, l): return foldl_p(f, init, lst, 0, l) def my_sum(lst, length): return foldl(lambda x, y: x + y, 0, lst, length) def mul(x, y): return 0 if x == 0 or y ...
x = 5 y = 0 z = [1,2,3,4,5,6,7,8,9] print (z if y else False) if x else True
import csv ####### EXAMPLES ######## ''' This is a file of examples of how to open the csv file of data and get things out of it. Please add to this when you find interesting things. Please add anything you find as a function, as below, so people can use it in their code. Act like you are building an API.''' ### Nick...
#!/usr/bin/env python3 ''' template_sample.py Jeff Ondich 6 November 2020 Using templates in Flask. ''' import sys import argparse import flask import json app = flask.Flask(__name__) @app.route('/') def home(): return flask.render_template('index.html') @app.route('/hello/<name>') def hello(nam...
#!/usr/bin/env python3 ''' api-test.py Jeff Ondich, 11 April 2016 Updated 7 October 2020 An example for CS 257 Software Design. How to retrieve results from an HTTP-based API, parse the results (JSON in this case), and manage the potential errors. ''' import sys import argparse import json imp...
# Uses python3 import sys # https://www.youtube.com/watch?v=Vj5IOD7A6f8 # the exact algorthim is at 27:03 total_count = 0 def merge(left_array,right_array): i, j, inversion_counter = 0,0,0 final = [] while i < len(left_array) and j < len(right_array): if left_array[i] <= right_array[j]: ...
# Uses python3 import sys #https://www.coursera.org/learn/algorithmic-toolbox/discussions/weeks/4/threads/IP3NQ-lEEeWFuw7QEATDpw """ get_majority(A[1...n]): if n == 1: return A[1] {If there is only one element, it is the majority element} mid = n/2 a = get_majority(A[1..mid]) b = get_majority(A[mid+...
# Uses python3 import sys bag_size = 10 items = 3 import numpy as np # define a matrix of 11 columns, 3 items # fill in the first row # weight, value pair # code in the lecture notes items_list = [(4, 16), (6, 30), (3, 14), (2, 9)] n_items = len(items_list) n_cols = 10 matrix = np.zeros((n_items + 1, n_cols + 1)) fo...
""" Day 22, part 1, a card shuffler https://adventofcode.com/2019/day/22 """ from typing import List def new_stack(deck: List[int]) -> List[int]: return [num for num in reversed(deck)] def cut(deck: List[int], n: int) -> List[int]: return deck[n:] + deck[:n] deck = [num for num in range(10)] assert new_st...
#!/usr/bin/env python3 string = "This is a string" print(string.count("a")) #we can use .count to count things like how many s's. integer = 4 print (integer.real)
""" 6.8 문제 : 시계 맞추기 - 난이도 : 중 """ # 2021/02/16 15:34 ~ 16:12 # 내가 생각했던 방법이 큰 그림에서는 비슷함. # 하나의 스위치는 최대 3번까지 누를 수 있고 4번 누르면 처음 상태로 돌아가는 것을 생각해야함. INF = int(1e9) switch = [ [0, 1, 2], [3, 7, 9, 11], [4, 10, 14, 15], [0, 4, 5, 6, 7], [6, 7, 8, 10, 12], [0, 2, 14, 15], [3, 14, 15], [4, 5,...
""" 8.11 예제 : 타일링 방법의 수 세기 - 난이도 : 하 - 부분 문제의 수는 O(n)이고 각각의 값을 계산하는데 O(1)의 시간이 들기 때문에 - 시간 복잡도 : O(n) """ # 부분 문제 정의하기 # tiling(n) = 2 * n 크기의 사각형을 2*1 크기의 타일로 덮는 방법을 의미 # 위 함수가 한 번 호출될 때 할 수 있는 선택은 세로 타일 하나를 쓰냐, 가로 타일 두 개를 쓰냐로 나뉜다. # 점화식 tiling(n) = tiling(n - 1) + tiling(n - 2) # n = 100이면 64bit 정수형 표현 범위도 훌쩍 넘어가기...
""" 6.5 문제 : 게임판 덮기 - 난이도 : 하 """ # 2021/02/16 13:55 ~ 14:59 # 가능한 블럭의 모양을 배열을 통해 구현 """ def checkComplete(temp): for i in range(h): for j in range(w): if temp[i][j] == '.': return False return True def turnBlock(center, wing1, wing2): pass def putBlock(temp, r, c): ...
# For loop # Initialize three list numbers = [10, 20, 30, 40] vehicles = ['cars', 'bikes', 'buses', 'trucks'] age = [40, 'fifty', 60, 'seventy'] # List can have numbers and strings # Execute for loop using the numbers in numbers list for count in numbers: print 'This is number: %d' % count # %d indicates the lis...
def poweroftwo(num): num = int(num) result = 2 ** num result = int(result) print("The result is", result) return result def main(): num1 = input("Give a number:") poweroftwo(num1) if __name__ == '__main__': main()
def openfile(): fname=input("Give the file name: ") try: sourcefile = open(fname, 'r') content = sourcefile.read() sourcefile.close() return content except IOError: return False def conversion(fcontent): try: fcontent=int(fcontent) re...
# Functions # Defining a function def student_scores(English, German, Spanish, French): print 'My score in English is %d:' % English print 'My score in German is %d:' % German print 'My score in Spanish is %d:' % Spanish print 'My score in French is %d:' % French # Scores given to function directly print 'Scor...
import random def win(): print("You WIN!") result = 1 return result def lose(): print("You LOSE!") result = 3 return result def choiceDisplay(user, AI): print("You chose:", user) print("Computer chose:", AI) def play(user): """ Takes user choice. Select A...
lists=[] def addition(name): lists.append(name) return lists def remove(number): del lists[number] return lists count = 0 while True: select = int(input("""Would you like to (1)Add or (2)Remove items or (3)Quit?:""")) if select == 1: add = input("What w...
text = input("Give a file name:") readfile = open(text,"w") print("Write something:") readtext = readfile.write(input()) readfile.close() readfile = open(text,"r") content = readfile.readlines() for i in content: print("Wrote", i,"to the file", text) readfile.close()
# coding=utf8 __author__ = 'smilezjw' def longestPalindrome(s): if len(s) == 1: return s p = s[0] # 遍历中心点,以中心点向两侧取出回文字符串 for i in range(1, len(s)): # 如果长度是奇数回文字符串,如‘abcba' m = palindrome(s, i, i) # 如果长度是偶数回文字符串,如‘abba’ n = palindrome(s, i-1, i) mlen = l...
# coding=utf8 __author__ = 'smilezjw' class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 深度优先搜索,耗时46ms def preorderTraversal(self, root): Solution.res = [] self.preOder(root) return Solution.res de...
# coding=utf8 __author__ = 'smilezjw' class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeTwoLists(self, l1, l2): curr = ListNode(0) # 头结点 dummy = curr while l1 and l2: # 主要循环条件 if l1.val <= l2.val: ...
# coding=utf8 __author__ = 'smilezjw' class ListNode: def __init__(self, x): self.val = x self.next = None def removeNthFromEnd(head, n): if not head or n == 0: return None dummy = ListNode(0) dummy.next = head p1, p2 = dummy, dummy # 双指针 for i in xrange(n): # p1先移...
# coding=utf8 __author__ = 'smilezjw' class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class BSTIterator: def __init__(self, root): # 初始化栈用于依次入栈下一个最小的元素 self.stack = [] self.pushLeft(root) # @return a boolean, whether we hav...
# coding=utf8 class Solution(object): def detectCapitalUse(self, word): # if len(word) < 2: # return True # return word.upper() == word or word[1:].lower() == word[1:] return word.isupper() or word.islower() or word.istitle() if __name__ == '__main__': solution = Solution(...
# coding=utf8 # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def constructMaximumBinaryTree(self, nums): """ :type nums: List[int] :rtype: TreeNode ...
# coding=utf8 __author__ = 'smilezjw' class Solution: def combine(self, n, k): Solution.res = [] Solution.count = 0 self.dfs(n, k, 1, []) return Solution.res def dfs(self, n, k, start, valueList): # 求组合的问题,这里用DFS来解决 if Solution.count == k: # count记录value...
# coding=utf8 __author__ = 'smilezjw' def isPalindrome(x): if x < 0: return False elif 0 <= x < 10: return True else: flag = True num = x length = 0 while x >= 10: x = x / 10 length += 1 ll = length while length > 0: ...
# coding=utf8 __author__ = 'smilezjw' class Solution: # 一开始想到这种方法,不能处理负数啊 def hammingWeight(self, n): count = 0 while n > 0: count += n & 1 # n和1做位与操作,计算最低位的1的个数, 还可以n%2也是取得最低位1的个数 n >>= 1 # n向右移一位相当于n /= 2 return count # 这种方法需要循环n的二进制位数次 def ...
# coding=utf8 __author__ = 'smilezjw' class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def binaryTreePaths(self, root): res = [] self.dfs(root, '', res) return res def dfs(self, root,...
# coding=utf8 __author__ = 'smilezjw' class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def merge(self, head1, head2): # 对两个链表进行归并排序 if head1 is None: return head2 if head2 is None: return head1 dummy = ListN...
# coding=utf8 __author__ = 'smilezjw' class Solution: def sqrt(self, x): # Implement int sqrt(int x) i = 0 j = x / 2 + 1 # 二分查找的终点为x / 2 + 1, 因为(x / 2 + 1) ^ 2 > x while i <= j: mid = (i + j) / 2 if mid ** 2 == x: return mid elif mid...
# coding=utf8 class Solution(object): def isToeplitzMatrix(self, matrix): """ :type matrix: List[List[int]] :rtype: bool """ row = len(matrix) column = len(matrix[0]) for i in range(row-1): for j in range(column-1): num = matrix[i]...
# coding=utf8 class TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None class Solution(object): def trimBST(self, root, L, R): """ :type root: TreeNode :type L: int :type R: int :rtype: TreeNode ""...
# coding=utf8 __author__ = 'smilezjw' class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseBetween(self, head, m, n): dummy = ListNode(0) dummy.next = head prev = dummy curr = head for i in xrange(1, m): # pr...
# coding=utf8 __author__ = 'smilezjw' class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeElements(self, head, val): dummy = ListNode(0) dummy.next = head p = dummy while p and p.next: if p.next.val == val...
#!/usr/bin/env python # coding=utf-8 def get_Mutil_CnFirstLetter(str): index = 0; strReturnCn = "" print "len(str)=%s" % len(str) while index < (len(str) - 1): # print "strReturnCn=%s" % strReturnCn # print get_cn_first_letter(str[index:index+2],"GBK") # print str[index:index...
#!/usr/bin/env python3 import sys def gcd(a, b): if a == 0: return (b, 0, 1) else: g, x, y = gcd(b%a, a) return (g, y-(b//a)*x, x) def inv(b, n): g, x, _ = gcd(b, n) if g == 1: return x%n else: return None if len(sys.argv) != 3: print(f"Usage: {sys.argv...
from math import log def addition(a, b): return a + b def subtraction(a, b): return a - b def multiplication(a, b): return a * b def division(a, b, division_type=""): if division_type == "float": return a / b elif division_type == "remainder": return a % b else: retu...
''' Selection Sort ''' import random def SelectionSort(array): for step in range(len(array)): min = step for i in range(min+1,len(array)): if array[i] < array[min]: min = i array[step],array[min] = array[min],array[step] if __name__ == "__main__": d = rando...
min_num = 1 mid = 0 max_num = 100 while True : #print('Max', max_num, 'Min', min_num) mid = (min_num + max_num) // 2 print('%d입니까?'%mid) user = input('높으면 H, 낮으면 L, 맞으면 C를 입력하세요.') if user == 'H' or user == 'h' : min_num = mid max_num = max_num elif user == 'L' or user == 'l' ...
def firstVerse(count, bottleTense): firstVerse = "%s %s of beer on the wall, %s %s of beer." % (count, bottleTense, count, bottleTense) print(firstVerse) def secondVerse(count, bottleTense): secondVerse = "Take one down and pass it around, %s %s of beer on the wall!\n" % (count, bottleTense) print(seco...
from functools import reduce l = [8, 10, 1, -8, 4, -9, 10, -5, -10, 5] l1 = [1, 2, 3] def x(num): if num > 0: return num def double_num(num): return num * 2 ml = map(x, l) m2 = map(double_num, l1) f1 = filter(x, l) # print(list(f1)) # print(list(ml)) # map(函数,可迭代对象):返回可迭代对象的每一个元素传入这个函数后的返回值, # ma...
# 解析xml文件 from xml.etree.ElementTree import parse f = open('../tmp/test.xml', 'r') et = parse(f) print(et) root = et.getroot() print(root) print(root.tag) print(root.attrib) # python3中使用elementtree.iter()来代替getiterator,使用list()来代替getChildren() # print(list(et.iter())) # for child in et.iter(): # print(child.tag) #...
# 如何让字段有序 # tips:使用collection中的OrderedDict # 存进去的时候顺序是什么样,再OrderedDict中的顺序就是什么样 from collections import OrderedDict import time import random d = OrderedDict() people = ["Tom","Bob","Jerry","ketty","Tiffy","Hanna","Sun"] start = time.time() for i in range(7): p = people.pop(random.randint(0,6-i)) time.sleep(ran...
# 根据字典中的值的大小对字典的项进行排序 stu = {'tom': 80, 'jerry': 90, 'kelly': 64, 'kimmy': 45} # 使用sotred() # sorted()里面传入的是可迭代对象,而字典的可迭代对象是字典的key # 方法1:利用zip把字典转成每一对转成元组 # r = zip(stu.values(),stu.keys()) # r = sorted(r, reverse=False) # print(r) # 方法2:sorted()的key参数 r = sorted(stu.items(), key=lambda x:x[1],reverse=False) print(r)
#Dylan Grafius 1/16/2018 #CSC131-004 #Purpose: The purpose of this program is to convert binary into its base 10 value. a = int(input('Enter leftmost digit:')) num1=a*(2**0) b = int(input('Enter the next digit:')) num2=b*(2**1) c = int(input('Enter the next digit:')) num3=c*(2**2) d = int(input('Enter the next di...
########################################### #Dylan Grafius 1/31/2018 #CSC 131-005 #Problem 1: The purpose of this program is to evaluate the length of the 3 sides of a triangle that the user will enter and state whether it is an equilateral or not. print('Problem 1: Using if statements') side1 = int(input('Ente...
# Modify the previous program such that only the users Alice and Bob are greeted with their names. def greeting_alice_and_bob(): user = input("Enter your name: ") name = ["Alice", "Bob"] if user == name[0] or name == name[1]: print(f"Hello {user}!") greeting_alice_and_bob()
#User function Template for python3 class Solution: #Function to return the count of number of elements in union of two arrays. def doUnion(self,a,n,b,m): a=list(set(a)) b=list(set(b)) n=len(a) m=len(b) ans=len(a)+len(b) count=0 if(n<=m): ...
#!/bin/python3 import math import os import random import re import sys # https://www.hackerrank.com/challenges/grading/problem # # Complete the 'gradingStudents' function below. # # The function is expected to return an INTEGER_ARRAY. # The function accepts INTEGER_ARRAY grades as parameter. # def gradingStudents(...
while True: entrada = raw_input(“> “) if entrada == “adios”: break else: print entrada
class Calculator: def __init__(self, name, make, model): self.name = name self.make = make self.model = model def get_calculator_details(self): details = (self.name, self.make, self.model) return details def addition(self, x, y): print("inside addition self...
class Calculator: def __init__(self, name, make, model, x,y): self.name = name self.make = make self.model = model self.x = x self.y = y def get_calculator_details(self): details = (self.name, self.make, self.model) return details def get_addition(s...
from math import ceil import heapq class Heap: def __init__(self, arr=None): self.heap = [] self.heap_size = 0 if arr is not None: self.heapify(arr) self.heap = arr self.heap_size = len(arr) def heapify(self, arr): """ Convert a given...
#!/usr/bin/python3 import sys def mapper_1(): """ First Job - Mapper This mapper selects three columns from the input: video_id, category, country Return key: video_id value: category + country """ header = True for line in sys.stdin: # Clean and split input l...
def sorted(A): if len(A)==1: return 0 return A[0]<=A[1] and sorted(A[1:]) A=[127,72,42,25,727] print(sorted(A))
# given an algorithms for finding maximum element in tree . # class newNode: # def __init__(self,data): # self.data = data # self.left=self.right = None # def findmax(root): # if (root == None): base case for resursion.. # return float('-inf') # res = root.dat...
def Min(arr,n): res = arr[0] for i in range(1,n): res= min(res,arr[i]) return res def Max(arr,n): res=arr[0] for i in range(1,n): res = max(res,arr[i]) return res arr =[15, 16, 10, 9, 6, 7, 17] n=len(arr) MIN=Min(arr,n) MAX=Max(arr,n) print(MIN) print(MAX) Range=MAX-MIN...
#More advanced calculator. num1 = float(input("Enter first number:")) op = input("Enter operator: ") num2 = float(input("Enter second number: ")) #If condition statements to check the operator the user would like to use. if op == "+": print(num1 + num2) elif op == "-": print(num1 - num2) elif op == "*": pr...
# 线程之间数据安全的容器队列 import queue # 不是内置的错误类型,而是queue模块中的错误 from queue import Empty # fifo 先进先出的队列 # q = queue.Queue(4) # q.get() # q.put(1) # q.put(2) # q.put(3) # q.put(4) # print('4 done') # q.put_nowait(5) # q.put('5 done') # try: # q.get_nowait() # except queue.Empty: # pass # # print('队列为空') # last in firs...
''' 和python解释器相关的操作 ''' # 获取命令行方式运行的脚本后面的参数 import sys # 脚本名 # print('脚本名',sys.argv[0]) # # 第一个参数 # print('第一个参数',sys.argv[1]) # # 第二个参数 # print('第二个参数',sys.argv[2]) # 类型字符串 # print(type(sys.argv[1])) # arg1 = int(sys.argv[1]) # arg2 = int(sys.argv[2]) # print(arg1 +arg2) # 解释器寻找模块的路径 # sys.path # 已经加载的模块 # prin...
''' 自定义模块 ''' # 使用__all__控制被导入的成员 __all__ = ['age','age2'] age = 10 def f1(): print('hell') age2 = 20 age3 = 30 # 调试函数,在开发阶段,对本模块的功能进行测试 def main(): print(age) f1() # 可以快速生成 if __name__ == '__main__': main()
# # 作业:用函数完成登录注册功能以及购物车的功能 # # 1.启动程序,用户可以选择四个选项:登录,注册,购物,退出 # # 2.用户注册,用户名不能重复,注册成功之后,用户名密码记录到文件中,密码的长度不能超过14个字符 # # # # 3.用户登录,用户名密码从文件中读取,进行三次验证,验证不成功则退出整个程序 # # 4.用户登录成功之后才能选择购物车功能进行购物,购物功能 # # 购物要求: # # 1.将购物车封装到一个函数中 # # 2.在上周的基础上,可以实现充值的扩展,以及其他相关扩展 # # 3.用户选择退出购物车时,将以购物的商品记录到一个文件中,将未付钱的但加入购物车的商品记...
# 用一行代码构建一个比较复杂有规律的列表 # l1 = [] # for i in range(1,11): # l1.append(i) # print(l1) # 列表推导式 # l1 = [i for i in range(1,11)] # print(l1) # 列表推导式分为两类 # 循环模式 # 1.将10以内所有整数的平方写入列表。 # l1 = [i**2 for i in range(1,11)] # print(l1) # # 2.100以内所有的偶数写入列表. # l2 = [i for i in range(2,101,2)] # print(l2) # # 3.python1期到pytho...
''' web框架 根据不同的url返回不同的内容 1.先拿到用户访问的url是什么 2.返回不同的url ''' import socket sk = socket.socket() sk.bind(('127.0.0.1',8088)) sk.listen() while 1: conn,addr = sk.accept() data = conn.recv(9000) # 用户发送的请求消息 print(data) # 从请求的消息中拿到请求的url是什么? data_str = str(data,encoding='utf8') # 按照\...
# 函数 # def func(): # print(111) # print(222) # return 3 # ret = func() # print(ret) # 生成器 # def func(): # print(111) # print(222) # yield 3 # yield 4 # # ret = func() # # print(ret) # print(next(ret)) # print(next(ret)) # 一个next对应一个yield # return 和 yield # return:函数中只存在一个return结束函数,并且给函...
# 猫 # 吃 # 喝 # 睡 # 爬树 # 狗 # 吃 # 喝 # 睡 # 看家 # class Cat: # def __init__(self,name): # self.name = name # # def eat(self): # print('%s is eating'%(self.name)) # # def drink(self): # print('%s is drinking'%(self.name)) # # def sleep(self): # ...
# 基础数据类型的复习 # 整型,布尔值,字符串,字典,元组,集合 # 1.字符串 不可变数据类型 # 方法 # 首字母大写,全部大写,全部小写 # start以什么开头,end以什么结尾 # find,index 按照元素查找索引 # 公共方法:count,len # replace替换 center 居中 # 索引和切片 # 2.列表 list 可变的数据类型 # 索引和切片 # lit = [1,2,3] # 索引lit[0],切片lit[::2] # 方法 ...
# 场景,角色,类 - 属性和方法 # 站在每个角色的角度上去思考程序执行的流程 import sys class Course: def __init__(self,name,price,period,teacher): self.name = name self.price = price self.period = period self.teacher = teacher class Student: openate_lst = [('查看可选课程', 'show_course'), ('选择课程', 's...
# count = 1; # while count < 11: # if count == 7: # count +=1; # continue # else: # print(count); # count +=1; # # count = 1; # while count < 11: # if count == 7: # count +=1 # print(count); # count +=1; # 输出1-100内的所有偶数 count = 1 while count < 101: if coun...
# eval() 剥去字符串的外衣,运算里面的代码,有返回值 # s1 = '1+3' # print(s1) # print(eval(s1)) # 网络传输的str,input 输入的时候,sql注入等等绝对不能使用eval # exec 与eval几乎一样,代码流 # msg = ''' # for i in range(10): # print(i) # ''' # # print(msg) # exec(msg) # hash 哈希值 # print(hash('jdkjkd')) # help 帮助 # s1 = 'dafdsa' # print(help(str.upper)) # callabl...
#通过代码,将其构建成这种数据类型: # [{'name':'apple','price':10,'amount':3},{'name':'tesla','price':1000000,'amount':1}......] 并计算出总价钱。 l1 = [] l2 = ['name','price','amount'] with open('a.txt',encoding='utf-8') as f1: for old in f1: line_list = old.strip().split() dic = {} for i in range(len(l2)): ...
# 文件操作 class File: lst = [('读文件','read'), ('写文件','write'), ('删除文件','remove'), ('文件的重命名','rename'), ('复制','cpoy')] def __init__(self,filepath): self.filepath = filepath def write(self): print('in write func') def read(self): print('in read func') def remove(self): pri...
''' Created on Oct 27, 2015 @author: Avery ''' import Triple class RoutingTable(object): ''' Table to hold the distance vectors. Each Router will have a RoutingTable ''' #dictionary holding list of vectors vector_list = [] name = "" def __init__(self, name): self.vecto...
# These are the emails you will be censoring. The open() function is opening the text file that the emails are contained in and the .read() method is allowing us to save their contexts to the following variables: email_one = open("email_one.txt", "r").read() email_two = open("email_two.txt", "r").read() email_three = o...
num = int(input("Enter a number: ")) dict1 = {} for x in range(1, num + 1): dict1[x] = x * x print(dict1)