text
stringlengths
37
1.41M
def sort_alphabetically(file_name): with open(file_name) as the_file: lines = the_file.readlines() list_sorted = False while not list_sorted: list_sorted = True for i in range(len(lines) - 1): if lines[i].lower() > lines[i + 1].lower...
def funcion_primo(num): resp = 0 if num == 2: print(f"EL NUMERO {num} ES PRIMO ") else: for i in range(2, num): if num % i == 0: resp = resp + 1 if resp == 0: print(f"EL NUMERO {num} ES PRIMO ") else: print(f"EL NUMERO {num} NO ES PRIMO ") ...
##aliquot number def summation(lis): s=0 for i in lis: s=s+i return s def aliquot(n): l=[] for i in range(1, n): if(n%i==0): l.append(i) return summation(l) print "Enter number" x=int(raw_input()) print aliquot(x) #Output: #Enter number #12 #16
##calculate bishop moves from(x, y) def bishop(x, y): x1,x2,x3 = x,x,x y1,y2,y3 = y,y,y while(x1<8 and y1<8): x1+=1 y1+=1 print x1, y1 while(x2>1 and y2>1): x2-=1 y2-=1 print x2, y2 while(x3>1 and y3<8): x3-=1 y3+=1 print x3,...
class Bicycle(object): """Models bicycles""" def __init__(self, model, weight, cost): self.model=model self.weight=weight self.cost=cost class BikeShop(object): """Models Bike Shops""" def __init__(self, name, inventory, markup, bikesSold, profit): self.name=name self.inventory=inven...
PRINT_BEEJ = 1 HALT = 2 memory = [ PRINT_BEEJ, PRINT_BEEJ, PRINT_BEEJ, PRINT_BEEJ, PRINT_BEEJ, HALT ] pc = 0 running = True while running: instruction = memory[pc] if instruction == PRINT_BEEJ: print("BEEJ!") elif instruction == HALT: running = False else: ...
# Write a Python program to add an item in a tuple. sample_tuple = (1,2,3,4,5) print(sum(sample_tuple))
# 44. Write a Python program to slice a tuple. sample_tuple = ( 1,2,3,4,5) print("Slicing of tuple::") print("For 1st two elements:",sample_tuple[:2]) print("For 3rd element to end::",sample_tuple[3:])
# 24. Write a Python program to clone or copy a list. list_items= [1,(2,4),[1,2,3],'a'] output_items = list_items.copy() print("Original items of list is::",list_items) print("\nClone items of list is::",output_items)
# 10. Write a Python program to print the even numbers from a given list. def even(lst): output_list =[] for i in lst: if i % 2 == 0: output_list.append(i) else: continue return output_list sample_list =[1, 2, 3, 4, 5, 6, 7, 8, 9] print(even(sample...
# 13. Write a Python program to sort a list of tuples using Lambda. sortTuple = lambda lst: sorted(lst,key=lambda ls: ls[0]) sample_list = [(1,2),(5,2),(0,2),(7,0),(2,1),(0,0)] print(sortTuple(sample_list))
# 1. Write a Python program to count the number of characters (character frequency) in a string. Sample String : google.com' input_string = input("Enter a string::") dict_string= {} for i in input_string: if i.isalpha()== True: count=input_string.count(i) dict_string.update({i:count}) print(d...
# 3. Write a Python function to multiply all the numbers in a list. def mul(sample_list): result=1 for item in sample_list: result *= item return result sample_list = [8, -2, 3, -1, 7] print("Multiplication of all the numbers::",mul(sample_list))
# 1. Write a Python function to find the Max of three numbers. def Greatest(num1,num2,num3): if num1<num2: return num3 if num2<num3 else num2 elif num2<num3: return num1 if num3 < num1 else num3 else: return num3 if num1<num3 else num1 print("----------Finding Greatest Number------...
# -*- coding: utf-8 -*- # あとから使うために例外文字列を作っておく。 BalanceError = "現在の口座残高は、 $%9.2f しかありません。" class BankAccount: def __init__(self, initialAmount): self.balance = initialAmount print "口座を開設しました。口座残高は $%9.2f です。" % self.balance def deposit(self, amount): self.balance = self.balance + amou...
# -*- coding: utf-8 -*- def printList(L): # リストが空なら、何もしない if not L: return # 戦闘の項目の型がリストであれば、 # 戦闘の項目を渡してprintListを呼び出す if type(L[0]) == type([]): printList(L[0]) else: # リストでなければ、単純に先頭項目を表示する print L[0] # Lの残りの部分を処理する printList(L[1:])
import math # def定义函数 # 示例:自定义一个求绝对值的函数my_abs() def my_abs(n): if n >= 0: return n else: return -n print(my_abs(-3)) # 空函数 def nop(): pass # pass语句什么也不做,相当于一个占位符,保证语法正确 # 通过isinstance()函数可以对自定义函数的参数做类型检查 def my_abs(n): if not isinstance(n,(int,float)): raise TypeError('bad ope...
# int(x, [base]) 函数可以把字符串转换为整数,base指定int把字符串x视为对应进制来转成十进制 # 示例:将'1010101'当做二进制转换 v = int('1010101',base=2) # print(v) # 如果有大量的二进制需要转换,每调用int都需要指定base=2,我们可以定义下面函数来简化(将base=2作为默认参数): def int2(s,base=2): return int(s,base) # print(int2('1010101')) # 偏函数:借用functools模块的partial帮助我们创建一个偏函数的,不需要我们自己定义int2() # 简单总结functoo...
class Student(object): # def getScore(self): # return self.__score # # def setScore(self, score): # if not isinstance(score, int): # raise ValueError('score type must is int') # if score < 0 or score > 100: # raise ValueError('score value is between 0 and 100...
# help()方法可以查看函数的帮助信息 help(abs) # abs() 求绝对值 print(abs(-88)) print(abs(88)) # 数据转换函数:int()、float()、str()、bool() var = '123' print(int(var)) var = '23.3' print(float(var)) var = 123 print(str(var)) var = 1 print(bool(var)) var = 0 print(bool(var)) var = '' print(bool(var)) # hex():把一个整数转为十六进制表示的字符串 n = 255 print(hex...
class Animal(object): def run(self): print('Animal is running...') class Dog(Animal): def run(self): print('Dog is running...') class Cat(Animal): def run(self): print('Cat is running...') # 静态语言VS动态语言 # - 对于静态语言(如Java)来说,如果需要传入Animal类型,则传入的对象必须是Animal类型或其子类 # - 对于Python等动态语言来说,不一...
# ############################## sorted ################################## # sorted(iterable,key,reverse) # - 通过key指定的函数,作用到iterable上,并根据key函数返回的结果进行排序 # - reverse=True,反向排序 # 示例1:根据绝对值排序 L = [36, 5, -12, 9, -21] # print(sorted(L,key=abs)) # 示例2:忽略大小写,按照字母序排序 L = ['bob', 'about', 'Zoo', 'Credit'] print(sorted(L)) # 默...
import sys def threeSumClosest(numbers, target): result = 2**31 - 1 length = len(numbers) if length < 3: return result numbers.sort() larger_count = 0 for i, item_i in enumerate(numbers): start = i + 1 end = length - 1 # o...
import unittest import re from exercise_04.PasswordGenerator import PasswordGenerator class TestPasswordGenerator(unittest.TestCase): def test_should_be_callable(self): self.assertTrue(callable(PasswordGenerator), 'Should be callable') def test_should_return_a_string(self): generator = PasswordGenerator() p...
''' A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given a non-empty string containing only digits, determine the total number of ways to decode it. Example 1: Input: "12" Output: 2 Explanation: It could be decoded as "AB" (1 2) or "L" (12)...
''' A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). Now consider if some obstacles are added to ...
''' Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. Example 1: Input: [1,3,4,2,2] Output: 2 Example 2: Input: [3,1,3,4,2] Output: 3 索引的方法:数组A 中如果...
'''Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] ''' def groupAngrams(strs): dicts={} for s in strs: ones=list(s) l=list(s) l.sort() s1=''.join(l) ...
''' Input: Binary tree: [1,2,3,4] 1 / \ 2 3 / 4 Output: "1(2(4))(3)" Explanation: Originallay it needs to be "1(2(4)())(3()())", but you need to omit all the unnecessary empty parenthesis pairs. And it will be "1(2(4))(3)". Example 2: Input: Binary tree: [1,2,3,null,4] 1 ...
#Input: 1->2->3->4->5->NULL #Output: 1->3->5->2->4->NULL def oddEvenList(head): if head==None or head.next==None: return head p0=head p1=head.next while p1.next!=None: p0.next=p1.next p0=p0.next if p0.next !=None: p1.next=p0.next p1=p...
''' Write a program to find the n-th ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. Example: Input: n = 10 Output: 12 Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. ''' from collections import deque def uglyNumber(n): nums=deque([...
''' Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. Example: Input: 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 Output: 4 ''' def maximalSquare(matrix): """ :type matrix: List[List[str]] :rtype: int """ l=len(matrix) if l<1:return 0...
''' There are a total of n courses you have to take, labeled from 0 to n-1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all cour...
import numpy as np from matplotlib import pyplot as plt plt.style.use('seaborn') # x = np.arange(-5, 5, 0.01) # y = x ** 2 # # print(x) # # print(y) # plt.plot(x, y) # plt.xlabel("X-axis") # plt.ylabel("Y-axis") # plt.title('Simple 2d Plot') # plt.show() x = np.arange(0, 2 * np.pi, 0.1) y = np.cos(x) # plt.plo...
import turtle def draw_art(): window = turtle.Screen() window.bgcolor("red") brad = turtle.Turtle() brad.shape("turtle") brad.color("yellow") brad.speed(1) n=4 m=0 while(m<n): brad.forward(100) brad.right(90) m=m+1 #brad.forw...
import random class Square: def __init__(self, row, col, game): self.is_mine = False self.is_revealed = False self.is_flagged = False self.neighboring_mines = 0 self.row = row self.col = col self.game = game self.neighbors = [] def find_neighbo...
import pdb import re from edge import Edge """ The Graph class works by maintaining a map where in the keys of the map are nodes and the values are lists of edges originating from that node. """ class Graph(): def __init__(self, edges=[]): self.graph_map = {} self.edges = [] """ populate edge list ...
#-*- coding:utf8 -*- __author__ = 'admin' # 应用: # # 典型的,函数在执行时,要带上所有必要的参数进行调用。 # # 然后,有时参数可以在函数被调用之前提前获知。 # # 这种情况下,一个函数有一个或多个参数预先就能用上,以便函数能用更少的参数进行调用。 def partial(func, *args, **keywords): def newfunc(*fargs, **fkeywords): newkeywords = keywords.copy() newkeywords.update(fkeywords) return ...
#!/usr/bin/evn python #-*- coding:utf-8 -*- __author__ = 'admin' #类静态变量 class Super: def __init__(self,x): self.key = x class Sub(Super): def __init__(self,x,y): Super.__init__(self,x) self.value = y super1 = Super('key') print super1.key sub = Sub('key','value') print sub.key print sub.value #一定要带object cla...
#!/usr/bin/evn python #-*- coding:utf-8 -*- __author__ = 'admin' #类静态变量 class ShareData: spam = 3 x = ShareData() y = ShareData() print x.spam print y.spam print ShareData.spam ShareData.spam = 24 print x.spam print y.spam print ShareData.spam class ShareData: data = "spam" def __init__(self, value): self.d...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by iFantastic on 15-2-14 __author__ = 'cluo' import urllib2 # map 这一小巧精致的函数是简捷实现 Python 程序并行化的关键。 # map 源于 Lisp 这类函数式编程语言。它可以通过一个序列实现两个函数之间的映射。 urls = ['http://www.yahoo.com', 'http://www.reddit.com'] results = map(urllib2.urlopen, urls) print results # 上面的这两行代...
class ElementId(object): """ The ElementId object is used as a unique identification for an element within a single project. ElementId(parameterId: BuiltInParameter) ElementId(categoryId: BuiltInCategory) ElementId(id: int) """ def Compare(self,id): """ Compare(self: ElementId,id: Ele...
class DigitGroupingSymbol(Enum,IComparable,IFormattable,IConvertible): """ The symbol used to separate groups of digits when numbers are formatted with digit grouping. enum DigitGroupingSymbol,values: Apostrophe (3),Comma (1),Dot (0),Space (2),Tick (3) """ def __eq__(self,*args): """ x.__eq__(y) <==...
class Arc(object,IEquatable[Arc],IEpsilonComparable[Arc]): """ Represents the value of a plane,two angles and a radius in a subcurve of a three-dimensional circle. The curve is parameterized by an angle expressed in radians. For an IsValid arc the total subtended angle AngleRadians()=Do...
#datos de entrada print("ingrsar el presio del producto:") pp=input() pp=float(pp) print("ingrasr la cantidad de unidades adquiridas:") ua=input() ua=int(ua) #proceso ic=pp*ua pd=0.10*ic sd=0.10*(ic-pd) dt=pd+sd ip=ic-dt #salida print("importe de la compra es:",ic) print("importe del descuento total es:",dt) print("i...
var1 = raw_input("Please input single character?") varLength=len(var1) print "the length or input variable -", var1, "is ", varLength if varLength > 1: print "False and it is not single character." elif varLength < 1: print "False and empty character is not acceptable." else: print "True and thanks."
## Class 10 Homework: Model Evaluation import pandas as pd import numpy as np from sklearn.linear_model import LogisticRegression import matplotlib.pyplot as plt from sklearn.cross_validation import train_test_split from sklearn.cross_validation import cross_val_score from nltk import ConfusionMatrix #set headers...
x = int(input(" enter number 1 : ")) y = int(input(" enter number 2 : ")) z =int(input(" enter number 3 : ")) if (x < y + z) & (y < x + z) & (z < y + x): print("true ") else: print("false")
d = 6 r = input("press r to roll, q to quit:") if r == "r": print("you got:", d) d = 2 r = input("press r to roll, q to quit:") if r== "r": print("you got:", d) d = 3 r = input("press r to roll, q to quit:") if r== "r": print("you got:",d) d = 6 r = input("press r to roll, q to quit:") if r== "r": print("you g...
def function1(): n=int(input("Enter a number: ")) if n>0: print("the number is a positive number") elif n<0: print("the number is negative") elif n==0: print("the number is zero") function1()
n=int(input("Give a number:")) if n%2==1: print(n,"is an odd number.") else: print(n,"ia an even number.")
import pygame from model.CarregadorImagem import load_image class Wall(pygame.sprite.Sprite): """This class represents the bar at the bottom that the player controls """ def __init__(self, x, y, width, height): """ Constructor function """ # Call the parent's constructor pygame.sprite.S...
# Visualize the data # Here are the first 9 images in the training dataset. As you can see, label 1 is "dog" and label 0 is "cat". import matplotlib.pyplot as plt plt.figure(figsize=(10, 10)) for images, labels in train_ds.take(1): for i in range(9): ax = plt.subplot(3, 3, i + 1) plt.imshow(images...
"""[ITC106 - Programming Principles] Assignment A4 by Gavin Eke """ #Variables #Program Metadata __author__ = "Gavin Eke" __version__ = "$Revision: 1.0 $" # Car Names car_name = ["Toyota Kluger","Nisson Patrol","Ford Territory"] number_of_cars = len(car_name) # Calculate Number of Cars based on list length # Config...
# load the iris dataset import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap #import seaborn as sns from sklearn.datasets import load_iris iris = load_iris() # store the feature matrix (X) and response vector (y) X = iris.data y = iris.target ...
word = 'abcdefghij' print(word[:3] + word[3:]) """ it prints the whole word word[:3] => excludes the third index element and prints from 0 to 2 index word[3:] => prints the rest staring frm index 3 concatenation results in whole word """
""" circle """ from math import pi class circle(): def __init__(self,r=1): self.r=r def perimeter(self): return 2*pi*self.r def area(self): return pi*(self.r ** 2) if __name__ == "__main__": c = circle(int(input("Enter the radius of the circle"))) print("Area is {}".format(c.area())) ...
""" iterate over dictionaries using for loops. """ dict={'1':1,'2':2,'3':3} for key,value in dict.items(): print(key,value)
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def upside_down(root): res = root while res.left: res = res.left helper(root) return res def helper(root): if root.left: ...
# 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 longestConsecutive(self, root): """ :type root: TreeNode :rtype: int """ # dfs ...
def unique(list1): # insert the list to the set list_set = set(list1) # convert the set to the list unique_list = (list(list_set)) for x in unique_list: print(x) # driver code list1 = [10, 20, 10, 30, 40, 40] print("the unique values from 1st list is") unique(list1)
print("ALUMNOS Y EDADES") bandera=False numalumnos=0 contmax=0 mayores=[] lista=[] cont=0 contedad=1 contnombre=0 listaedades=[] listaedades2=[] max=0 suma=0 nombre=str(input("Escribe el nombre del alumno: ")) while nombre != "*": numalumnos=numalumnos+1 edad=int(input("Escribe la edad del alumno %s: " % nombre)) li...
print("SUBCADENA") cad1=str(input("Escrbie una cadena: ")) cad2=str(input("Escrbie una segunda cadena: ")) if cad2 in cad1: print("La segunda cadena es una subcadena de la primera") else: print("La segunda cadena no es una subcadena de la primera")
print("MISMAS PALABRAS") num=int(input("¿Cuántas palabras quieres que tenga la primera lista?: ")) cont=1 lista1=[] lista2=[] encontrado=[] primera=[] segunda=[] contador=0 for i in range(num): palabra=str(input("Escribe la palabra %d: " % cont)) cont=cont+1 lista1.append(palabra) print("La primera lista es:", lista...
print("SUBCADENA") cad=str(input("Escribe una cadena: ")) bool=False comprobar=cad.upper() for i in cad: if comprobar.count(i)>=2: bool=True if bool: print("La cadena '%s' tiene caracteres repetidos"%cad) else: print("La cadena '%s' NO contiene caracteres repetidos"%cad)
import unittest import shunting_yard as sy class TokenizeTest(unittest.TestCase): def test_single_operator(self): tokens = list(sy.tokenize('1+2')) self.assertListEqual(tokens, ['1', '+', '2']) def test_multiple_operators(self): tokens = list(sy.tokenize('1+2-3')) s...
# lambda аргументууд: илэрхийлэл x = lambda a: a*a for i in range(5, 7): print(x(i)) # Үр дүн: 25 # 36 # 2 аргументтай ламбда y = lambda a, b: a + b print(y(25, 30)) # 55 print(y(22.5, 100)) # 122.5 # lambda def evenOrOdd(x): return lambda x: x> 0 value = evenOrOdd(-5) print(v...
# set үүсгэх colors = {'улаан', 'ногоон', 'шар'} print(colors) # {'улаан', 'шар', 'ногоон'} # давталт for x in colors: print(x) # ногоон # улаан # шар print('улаан' in colors) # True # add() colors.add('цэнхэр') print(colors) # {'шар', 'ногоон', 'цэнхэр', 'улаан'} # update() color...
# list жагсаалт = ['элемент1', 'элемент2', 'элемент3'] print(жагсаалт) # ['элемент1', 'элемент2', 'элемент3'] newlist = list(('элемент1', 'элемент2')) print(newlist) # ['элемент1', 'элемент2'] weekdays = ['Даваа', 'Мягмар', 'Лхагва', 'Пүрэв', 'Баасан'] print(weekdays[0]) # Даваа print(weekdays[4]) # Б...
#! /usr/local/bin/python3 d = {'jcw':26, 'jxr': 10, 'yyr': 10} print('d["jcw"]:', d["jcw"]) print('d["yyr"]:', d.get("yyr")) d.pop("yyr") #print('d["yyr"]:', d["yyr"]) print('d["yyr"]:', d.get("yyr"))
#! /usr/local/bin/python3 def add_end(L = []): L.append("END") return L def add_end2(L = None): if L is None: L = [] L.append("END") return L
#! /usr/local/bin/python3 # -*- coding:utf-8 -*- class Student(object): @property def score(self): return self._score @score.setter def score(self, value): if not isinstance(value, int): raise ValueError('score must be an integer') if value < 0 or value > 100: raise ValueError('score must between 0 an...
b=int(input("ingrese el valor del angulo: ")) if b == 0: print("nulo") elif 0<b<90: print("agudo") elif b==90: print("recto") elif 90<b<180: print("obtuso") elif b==180: print("llano") elif 180<b>360: print("concavo") elif b==360: print("completo") else: print("no encontrado")
num = int(input("Please enter a Number")) list_d = [] for n in range(2,num+1): if num%n == 0: list_d.append(n) print(list_d)
from bs4 import BeautifulSoup import requests # It works but not complete Artical is there # html_url = "https://www.vanityfair.com/style/society/2014/06/monica-lewinsky-humiliation-culture" html_url = 'https://en.wikipedia.org/wiki/Salman_Khan' def download_html(url): r = requests.get(url) return r def pras...
import random NUM_I=1 NUM_L=9 while True: print("Type 'exit' to quit application") random_number=random.randint(NUM_I,NUM_L+1) num =input("Guess a Number Shriman :) :\t") if num == 'exit': print("exiting now") break if int(num) > random_number: print("You guess too high ", r...
#!/usr/bin/env python3 def climbing_stairs1(n): if n <= 2: return n else: return climbing_stairs1(n-1) + climbing_stairs1(n-2) def climbing_stairs2(n): num = [0, 1, 2] if n <= 2: return num[n] else: for i in range(3, n+1): num.append(num[i-1] + num[i-2]...
bilar = [] while True: menu = input("Val: ") if menu == "1": for l in bilar: print(l) elif menu == "2": bilen = {} bilen["brand"] = input("Brand: ") bilen["model"] = input("Model: ") bilen["year"] = input("Year: ") bilar.append(bilen) else...
# 机器学习实战 学习记录 # Chapter 4 基于概率论的分类方法:朴素贝叶斯 # coding='UTF-8' ''' 优 点 :在数据较少的情况下仍然有效,可以处理多类别问题。 缺 点 :对于输入数据的准备方式较为敏感。 适用数据类型:标称型数据 ''' ''' 使用朴素贝叶斯进行文档分类 朴素:意味着两个假设: 1. 特征的独立性,对于文本来说即:一个特征或单词出现的可能性与其他单词没有关系 2. 每个特征同等重要 这两个假设实际中均存在问题,但实际效果不错 ''' # 从文本中构建词向量: # 考虑所有文档中出现的单词,决定将那些放入到词汇表中; # 将每篇文档转换为词汇表上的向量 # 简单的示例1:鱼分类 def ...
#abs() # print(abs(-5)) # max() 函数 :求最大值 max(数据) # lst = [2,1,6,3,4] # ret = max(lst) # print(ret) # lst2 = [-2,5,-8,3,6,1] # def abs(num): # if num>0: # return num # else: # return -1*num #求绝对值最大的数 -8 # ret = max(lst2,key=abs) #[2,5,8,3,6,1] # print(ret) #练习: # lst3 = [2,6,-10,50] #求相反数...
# 测试多线程的效率 在单线程中数 8 千万个数和在两个线程中分别数 8 千万个数, # 哪个效率更高?速度更快? import threading import time def func1(): start = time.time() for i in range(140000000): i+=1 end = time.time() print("func1-->total_time:{}".format(end-start)) # if __name__ == '__main__': # t1 = threading.Thread(target=func1) # ...
# 重命名文件 os.rename(旧文件名,新文件名) import os # # os.rename("demo_02/1.txt","demo_02/111.txt") # os.rename("demo_02/2.txt","222.txt") # 2.删除文件 os.remove(文件名) #删除demo_02/3.txt # os.remove("demo_02/3.txt") # 3.创建单层目录 os.mkdir(目录名) #创建test1目录 # os.mkdir("test1") # 创建多级目录 os.makedirs(目录名) # os.makedirs("a/b/c/d") # 删除单层目录...
class Shopping: instance = None #记录创建的对象,None说明是第一次创建对象 has_init = False #记录是否进行过初始化 def __new__(cls, *args, **kwargs): #第一次调用new方法,创建对象并记录 #第2-n次调用new方式时,不创建对象,而是直接放回记录的对象 #判断是否是第一次创建对象 if cls.instance==None: cls.instance = object.__new__(cls) return c...
# set1 = {3,2,6,4,1,3,6} # # set1 = {3,2,6,4,1,3,6,[2]} #集合中的元素只能是不可变类型 # print(set1) #去除列表中重复的元素 # lst = [1,2,2,3,3,5,6,3] # print(set(lst)) #集合增加 # set1 = {1,2} # # # set1.add(3) # # set2 = {2,3} # # set1.update(set2) # set1.clear() # print(set1) # print(dir(set1)) # lst = [1,2] # help(lst.remove) #集合数学运算 # set...
# 函数的相互调用和嵌套. #相互调用 # def func1(): # print("--before func1--") # print("--after func1--") # # def func2(): # print("--before func2--") # func1() # print("--after func2--") # func2() #嵌套 # 在函数中又定义函数 def func1(): print("func1..") def func2(): print("func2...") func2() func1()
#下班太晚,和女朋友说一万次对不起 # print("对不起!") #相同或者相似的事情可以用循环解决 # num = 1 # while num<=10000: # print("对不起!-",num) # num+=1 #输出1-10之间的数字 # num = 1 # while num<=10: # print(num,end=' ') # num+=1 #售票:一个窗口一天售出10张票,卖完下班 # ticket = 10 # while ticket>0: # print("卖出一张票:",ticket,"号票") # ticket-=1 #循环从控制台输入5个数,...
#增加 lst = ["张伟强","刘江","徐伟明","刘伟超"] #在列表尾部增加 “梁国赞”append lst.append("梁国赞") # print(lst) #extend # lst2 = ["梁国赞","张威"] # lst.extend(lst2) # print(lst) # lst = ["张伟强","刘江","徐伟明","刘伟超"] #insert #将"梁国赞"插入到“刘江”的前面 # lst.insert(1,"梁国赞") # print(lst) #将"梁国赞"插入到“刘伟超”的前面 # lst.insert(-1,"梁国赞") # print(lst) #将"梁国赞"插入到“刘伟超”的后面 #...
# 1.将字符串‘my name is zhangWeiqiang’中的每个单词输出一样,要求单词首字母大写效果如下 # content = "my name is zhangqeiqiang" #My Name Is Zhangweiqiang # content = "my name is zhangqeiqiang" # new_content = content.title() # print(new_content) # 2.判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 # num = input("请输入一个整数:") # if num.isdigit(): # if ...
# def func(): # a = 1 # print("内部a的值:",a) # func() # print("外部a的值:",a) # def func(): # a = 1 # print("内部a的值:",a) # return a # # # print(func()) # a = func() # print("外部a的值:",a) #可以返回多个数据 def func(): a = 1 b = 2 return a,b # print(func()) a,b = func() print(a,b)
# 注意:先完成课堂讲解案例,再尽量完成下列练习 # # 1.输入一个考试分数,判断考试结果是否为通过,如果分数>= 60,通过, # 否则,结果为不通过(使用双分支和三元条件表达式各做一遍) # score = int(input("请输入一个分数:")) # # if score>=60: # # print("通过") # # else: # # print("不通过") # ret = "通过" if score>=60 else "不通过" # print(ret) # 2.求1-100之间所有偶数的和 # num = 1 # sum_num = 0 # while num<=100: # if n...
# - L-->local(函数内部) 局部作用域 # - E-->Enclosing 嵌套作用域 # - G-->Global 全局作用域 # - B--built-in 內建作用域 # name = "张伟强" # def outter(): # name = "张威" # def inner(): # # name = "刘江" # print(name) # inner() # outter() #1.调用自己内部inner的name #2.注释掉name = "刘江",调用父函数中的name # 3.注释掉name = "张威",调用全局name, # -...
#向控制台输出3,2,1 def out_num(num): """功能:。。""" if num==0: return print(num) num-=1 out_num(num) out_num(3)
""" 综合案例:管理员管理课程 - 管理员,添加课程,查看课程 ,删除课程,修改课程 - 分析 - 数据类Date - 属性:课程数据courses_dict,以字典形式保存,类属性 - 用户类User - 属性:用户名,密码,昵称,邮箱,电话 - 管理员类Admin - 属性:继承用户类 - 方法:添加课程add_course,调用课程保存的方法 ​ 查看课程check_course,调用数据库类属性 ​ 修改课程update_course,调用课程修改的方法 ​ 删除课程delete_course,调用课程删除的方法 ...
'''功能选项''' #登录前选项输入 def zhuce_xuanxiang(): while True: choose = input("请输入您的选项:") if choose == "1": pass elif choose == "2": pass elif choose == "3": pass else: print("您的输入有误!!!按任意键继续>>>") #商品分类 def fenlei_xuanxiang(): whi...
# #定义人类:可以跳舞,可以玩,在玩的过程中跳舞 # #实现多态:老年人跳广场舞 # class Person: # """人的类型""" # # def dance(self): # print("跳舞") # # def play(self): # self.dance() # # class OldMan(Person): # """老年人类型""" # def dance(self): # print("跳广场舞") # # # per1 = Person() # # per1.play() # old = OldMan() # o...
#单分支 #判断一个人是否可以去网吧 #如果大于等于18岁,可以去 # age = 15 # if age>=18: # print("可以去网吧") # print("一天过去了!") #双分支 #判断一个人是否可以去网吧 #如果大于等于18岁,可以去,否则回家写作业 # age = 15 # if age>=18: # print("可以去网吧嗨皮!") # else: #else中不写条件语句 # print("回家写作业!") # print("一天过去了!") #判断一个人是否可以去网吧 #如果大于等于18岁,并且是男生,可以去,否则回家写作业 # age = 19 # gender = 0...
from cs50 import get_int def main(): # Get user input for height while True: h = get_int("Height: ") if 1 <= h <= 8: break # Print lines for i in range(h): space(h - i - 1) sign(i + 1) space(2) sign(i + 1) print() # Print spaces ...
def hex_output(hex_humber): decimal_number = 0 for index, digit in enumerate(reversed(hex_humber)): decimal_number += int(digit, 16) * 16**index return decimal_number print(hex_output("123"))
# !/usr/bin/env python # encoding: utf-8 """ This is an implementation of Prim's algorithm, as found in: Skiena, Steven. The Algorithm Design Manual, 2nd ed. London: Springer-Verlag, 2008. -------------------------------------------- Prim's algorithm: Select an arbitrary vertex to start while (there are fringe verti...
import numpy as np import matplotlib.pyplot as plt import util class Model: def __init__(self, layers, in_size, units, weight_init_range, bias_init_range=None, nonlins=None, loss="MSE", lr=0.001, decay_rate=0, normalization=None, name="Basic NN Model"): """ :param layers:...