text
stringlengths
37
1.41M
#!/usr/bin/python # _*_ coding: utf-8 _*_ #打印1-9三角形阵列 for i in range(1,11): for k in range(1,i): print(k, end="") k += 1 i += 1 print("")
#!/usr/bin/python # _*_ coding: utf-8 _*_ rows = int(input('输入列数:')) i =i = j = k = 1 #声明变量,i用于控制外层循环(图形行数),j用于控制空格的个数,k用于控制*的个数 #等腰直角三角形1 print('等腰直角三角形1') for i in range(0,rows): for k in range(0,rows-i): print('*',end='') k += 1 i += 1 print(' ') print('======...
#!/usr/bin/python # _ * _ coding:utf-8 _ * _ a = 10 b = 20 list = [ 1,2,3,4,5 ]; print(list) if( a in list): print('1-变量a在给定的列表list中') else: print('1-变量a不在给定的列表list中') if( b not in list): print('2-变量b不在给定的列表list中') else: print('2-变量b在给定的列表list中') #修改变量a的值 a = 2 if(a in list): ...
#!/usr/bin/python # _*_ coding: utf-8 _*_ #打印菱形 rows = int(input('输入列数:')) i = j = k = 1 print('打印空心等菱形,这里去掉if-else条件判断就是实心的') for i in range(rows): #变量i控制行数 for j in range(rows - i): #(1,rows-i) print(' ',end=' ') j += 1 for k in range(2 * i - 1): #(1,2*i) if k == 0 or k...
# 期中大作业 崔若瑶 # 化学与分子工程学院 学号:1800011755 import turtle import math a=math.pi wn = turtle.Screen() wn.bgcolor("black") turtle.setup(width=1.0,height=1.0) sun= turtle.Turtle() sun.speed(0) sun.penup() sun.setpos(32,0) sun.pendown() sun.dot(35,"yellow") venus = turtle.Turtle() mercury = turtle.Turtle() earth = turtle....
import datetime dt = datetime.datetime.now() time = dt.strftime("%H:%M:%S") to = datetime.date.today() print("The current time is ",time) print("The current Date is ",to)
'''In this challenge, you are tasked with helping a small, rural town modernize its vote-counting process. (Up until now, Uncle Cleetus had been trustfully tallying them one-by-one, but unfortunately, his concentration isn't what it used to be.) You will be given two sets of poll data (election_data_1.csv and election...
#!/usr/bin/env python # Alex Harris # CS160 from Card import Card #---------------------------------------------------------------------- import random import os #---------------------------------------------------------------------- class CardDeck: """ class for representing a deck of cards...
def solution(priorities, location): answer = 0 pmax=0 while location>=0: pmax=max(priorities) if priorities[0] < pmax: priorities.append(priorities.pop(0)) if location ==0: location=len(priorities)-1 continue else: p...
grid = [ ["1","1","0","0","0"], ["1","1","0","0","0"], ["0","0","1","0","0"], ["0","0","0","1","1"] ] def numIslands1(grid): count = 0 visited = [] island = [] for i in range(len(grid)): for j in range(len(grid[0])): if [i, j] in visited: pass elif grid[i][j] =...
def mergeSort(A): def merge(left, right): # [1,2,9,8] and [3,6,5] result = [] i, j = 0, 0 while i< len(left) and j < len(right): if left[i] < right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) ...
import csv import io from lodstorage.lod import LOD class CSV(LOD): ''' helper for converting data in csv format to list of dicts (LoD) and vice versa ''' @staticmethod def restoreFromCSVFile(filePath:str, headerNames:list=None, withPostfix:bool=False): ''' restore LOD from given...
# Leia um valor inteiro correspondente à idade de uma pessoa em dias e # informe-a em anos, meses e dias # Obs.: apenas para facilitar o cálculo, considere todo ano com 365 dias # e todo mês com 30 dias. Nos casos de teste nunca haverá uma situação # que permite 12 meses e alguns dias, como 360, 363 ou 364. Este é ...
# Joaozinho quer calcular e mostrar a quantidade de litros de combustível # gastos em uma viagem, ao utilizar um automóvel que faz 12 KM/L. Para isso, # ele gostaria que você o auxiliasse através de um simples programa. Para # efetuar o cálculo, deve-se fornecer o tempo gasto na viagem (em horas) e # a velocidade m...
x = 0 for i in range(0, 6): valor = float(input()) if valor > 0: x += 1 print("{} valores positivos".format(x))
# Leia os quatro valores correspondentes aos eixos x e y de dois pontos # quaisquer no plano, p1(x1,y1) e p2(x2,y2) e calcule a distância entre # eles, mostrando 4 casas decimais após a vírgula, segundo a fórmula de distância # O arquivo de entrada contém duas linhas de dados. A primeira linha contém # dois valores...
#!/usr/bin/env python # -*- coding: utf-8 -*- class Singleton(object): def __new__(cls, *args, **kw): if not hasattr(cls, '_instance'): orig = super(Singleton, cls) cls._instance = orig.__new__(cls, *args, **kw) return cls._instance class MyClass(Singleton): def __ini...
# coding=utf-8 # Licensed Materials - Property of IBM # Copyright IBM Corp. 2015,2017 from __future__ import print_function import sys # Print function that flushes def print_flush(v): """ Prints argument to stdout flushing after each tuple. :returns: None """ print(v) sys.stdout.flush() def ...
# Licensed Materials - Property of IBM # Copyright IBM Corp. 2016 from __future__ import print_function import sys from streamsx.topology.topology import Topology import streamsx.topology.context def main(): """ Sample filtering echo topology application. This Python application builds a simple topology t...
print("Tabel KODE ASSCII") print("-----------------") ## Nilai variabel kode akan berubah secara otomatis mulai dari 32 sampai 126 for kode in range(32,126): print("%3c | %4d | %12s | %6s |" %( kode, kode, bin(kode), hex(kode) ) ) print("-----------------")
# This code, sorts a linked list using merge sort where items in odd positions are sorted ascendingly # and items in even poistions are sorted descendingly class Node: def __init__(self, val): self.val = val self.next = None class LinkedList: def __init__(self): self.head = None # Insert a node a...
import cs50 while True: print ("Height: ", end="") Height = cs50.get_int() if Height > 0 and Height < 22: break for rows in range(Height): print(" " *(Height - rows-1), end ="") print("#" * (rows + 2))
n = int(input()) fibonacci = [0] num = 0 aux = 1 for i in range(60) : aux2 = num num += aux aux = aux2 fibonacci.append(num) for num in range(n): x = int(input()) print("Fib(%d) = %d" % (x, fibonacci[x]))
def reverse(lista): nova_lista = [] for item in lista: novo_item = "" for i in range(len(item)-1,-1,-1): novo_item += item[i] nova_lista.append(novo_item) return nova_lista t = ["Maçã", "Arara", "Uva"] print(reverse(t))
while True: try: entrada = input() I_fechado = True B_fechado = True for letra in entrada: if "_" in letra: if I_fechado: letra = letra.replace("_","<i>") I_fechado = False else: l...
def middle(lista): new_list = lista[1:-1] return new_list t = [1, 2, 3, 4] print(middle(t))
nome = str(input("Qual é seu nome")).lower().strip() if nome == "gustavo": print("Que nome bonito") elif nome == "pedro" or nome == "maria" or nome == "joão": print ("O seu nome é bem popular") elif nome == "ana katarina": print ("que nome feio") else: print("Seu nome é bem chato")
# Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua área e a quantidade de tinta # necessária para pintá-la, sabendo que cada litro de tinta pinta uma área de 2m² a = float(input("Digite a altura da sua parede:")) l = float(input("Digite a largura da sua parede:")) area = a * l li...
# Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ela pode comprar real = float(input("Quantos reais você possui R$")) dolar = real / 3.27 print('COM R${:.2f} você pode comprar US${:.2f}'.format(real,dolar))
#Desenvolva um programa que leia seis números inteiros e mostre a smora apenas daqueles que forem pares. Se o valor digitado for impar. desconsidere-o. soma = 0 cont = 0 for c in range (1, 7): n = int(input("Digite qualquer número inteiro: ")) if n % 2 == 0: soma = soma + n cont = cont + 1 pri...
# Escreva um programa que leia a velocidade de um carro # Se ele ultrapassar 80km/h, mostre uma mensagem dizendo que ele foi multado # a multa vai custar 7,00 por cada km acima do limite vel = float(input("Digite a velocidade detectada: ")) multa = (vel - 70) * 7.0 if vel > 70 : print("sua velocidade foi de {}, v...
### report additions #In addition to the future directions mentioned above, I was also curious about what the #distribution of average scores would look like separated by if a student completed a test preparation course #if we separated scores into typical letter grade bins such as A(80-100), B(70-80), C(60-70), D(50-...
import pandas as pd import matplotlib.pyplot as plt import numpy as np df = pd.read_csv("Salary_Data.csv") df.head(5) df.shape df.describe() # Scatter plot of all the data points included in the dataset plt.scatter(df['YearsExperience'], df['Salary'], color="red") plt.title("Salary based on Years of Experience") plt...
from bs4 import BeautifulSoup import urllib import os desired_fields = ['Model Number', 'Event Date', 'Event Type', 'Patient Outcome', 'Event Description', 'Manufacturer Narrative', 'Brand Name', 'Type of Device', 'Device Event Key', 'MDR Report Key', 'Event Key', 'Report Number', 'Device Sequence Number', 'Product Co...
# 622.design circular queue class MyCircularQueue: def __init__(self, k: int): self.q = [None] * k self.maxlen = k self.p1 = 0 self.p2 = 0 def enQueue(self, value: int) -> bool: if self.q[self.p2] is None: self.q[self.p2] = value self.p...
from typing import List def combine(n: int, k: int) -> List[List[int]]: res = [] def dfs(elements, start: int, k: int): if k == 0: res.append(elements[:]) # 자신 이전의 모든 값을 고정하여 재귀 호출 for i in range(start, n + 1): elements.append(i) dfs(e...
from typing import List import heapq # 힙큐 매서드를 이용한 풀이 def findKthLargest(nums: List[int], k: int) -> int: return heapq.nlargest(k, nums)[-1] # -1은 k번째 인덱스가 된다 # 정렬을 이용한 풀이 def findKthLargest(nums: List[int], k: int) -> int: return sorted(nums, reverse=True)[k - 1]
numbers = [-4, -1, -1, 0, 1, 2] numbers.sort() threeSum = [] for i in range(len(numbers) - 2): if i > 0 and numbers[i] == numbers[i - 1]: print("i range") print("number[%i]:" %i, numbers[i]) continue for j in range(i + 1, len(numbers) - 1): if j > i + 1 and numbers[j] ...
# 24. swap nodes in pairs_2 # 연결 리스트를 입력받아 페어 단위로 스왑. # 반복 구조로 스왑 from LinkedList import Node def swapPairs(head: Node) -> Node: root = prev = Node(None) prev.next = head while head and head.next: b = head.next head.next = b.next b.next = head prev.next = b ...
# 92. reverse linked list2 from LinkedList import Node def reverseBetween(head: Node, m: int, n: int) -> Node: # except if not head or m == n: return head root = st = Node(None) root.next = head # st, end 지정 for _ in range(m - 1): st = st.next end = st.next ...
from tkinter import * window=Tk() #opening window window.geometry("550x400") #window size label1 =Label(window,text="Entente Project",font="times 24 bold") ...
################################################################# ##Praktisch Tentamen Python I#################################### ##Richard Jansen, HAN University of Applied Sciences, Nijmegen### ## 16-01-2015#################################################### ########################################################...
class ExploreGoal: def __init__(self): self.distThreshFollow = 5 # min size of ball for switching from wall-follow to ball-follow self.distThreshSetGoal = 1 # min size of ball for transitioning to from this goal to the get-ball goal def getName(self): return "GOAL_EXPLORE" ...
abb = "lol" if abb == "lol": print("Laughing Out loud") elif abb == "asap": print("As soon As Possible") elif abb == "smh": print("Shaking my head") elif abb == "ttyl": print("Talk to you Later")
# -*- coding: utf-8 -*- """ Rename multiple files within directory """ # importing os module import os # current path to directory with files path = os.getcwd()+"/Rename_dir/" # Function to rename multiple files def rename_files(path, new_name): ''' Renames all files in specified directory to one standard n...
''' 315. Count of Smaller Numbers After Self Total Accepted: 28018 Total Submissions: 82765 Difficulty: Hard Contributors: Admin You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the ri...
""" 437. Path Sum III Total Accepted: 20441 Total Submissions: 52428 Difficulty: Easy Contributors: Stomach_ache You are given a binary tree in which each node contains an integer value. Find the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf,...
''' 481. Magical String Description Submission Solutions Total Accepted: 4905 Total Submissions: 10644 Difficulty: Medium Contributors: DonaldTrump A magical string S consists of only '1' and '2' and obeys the following rules: The string S is magical because concatenating the number of contiguous oc...
M = [[" " for c in range(3)] for i in range(3)] # "X", "O" in a row: tx = ['X', 'X', 'X'] to = ['O', 'O', 'O'] def state(): print('''--------- | {} {} {} | | {} {} {} | | {} {} {} | ---------'''.format(M[0][0], M[0][1], M[0][2], M[1][0], M[1][1], M[1][2], M[2][0], M[2][1], M[2][2])) def field():...
import random from Functions.create_spells_and_items import create_magic class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' class Person: def __...
''' Write a script that handles opening a non-existing file, 'unknown_file.txt', and prints the message File not found. to the user. Use try ... except clauses. Print the user message inside except clause. ''' try: f=open('unknown_file.txt',"r") except FileNotFoundError as e: print("File not found.")
grade =int(input("정수를 입력하세요")) if grade>=90: print("당신의 학점은 A입니다") elif grade>=80: print("당신의 학점은 B입니다") elif grade>=70: print("당신의 학점은 C입니다") elif grade>=60: print("당신의 학점은 D입니다") else: print("당신의 학점은 F입니다")
import webbrowser name = "Ella" subjects = ["Math", "Latin", "English", "Science", "History"] print("Hello " + name) for i in subjects: print("One of my classes is " + i) tvshows = ["Grey's Anatomy", "Glee", "The Good Place", "New Girl", "Stranger Things"] for i in tvshows: if i == "Grey's...
import time print("Write a noun") noun1 = input() print("write an adjective") adjective1 = input() print("Write a country") country1 = input() print("Write a time period in history") timeperiod1 = input() print("Write a plural noun") noun2 = input() print("Write another noun") noun3 = input(...
def calclen(num1,num2): a = len(num1) b = len(num2) if a!=b : if a>b: for _ in range(a-b): num2='0'+num2 else: for _ in range(b-a): num1='0'+num1 return num1,num2 def calcor(num1,num2): numor="" for i in range(len(num1)): ...
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' Тестовое задание 11. Решите задание, введите ответ в виде числа с клавиатуры. Имеется две колоды из 6 карт каждая. Карты, содержащиеся в каждой колоде, одинаковые. В первой колоде фиксирован порядок карт. Количество способов, которыми можно уложить карты во второй ...
from math import * name = input('Введите имя и фамилию ученика : ') marks = input('Введите его оценки за контрольные и самостоятельные : ') marks_1 = list(marks) new_marks = input('Введите оценки за работу на уроках : ') marks_1.extend(new_marks) marks_1.sort() marks_1.insert(0, name) marks_1.insert(1, ':') one = marks...
login = input("Login:")#programa irá ficar parado até o usuário digitar e der ENTER senha = input("Senha:") print("O usuário informado foi %s com senha %s" %(login,senha))
""" Groups (clusters) similar lines together from a text file using k-means clustering algorithm. Also does some simple cleaning (such as removing white space and replacing numbers with (N)). Example: python cluster_lines.py --clusters 20 invalid_dates.txt Required libs: click sklearn https://gist.gith...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Triangle Project Code. # Triangle analyzes the lengths of the sides of a triangle # (represented by a, b and c) and returns the type of triangle. # # It returns: # 'equilateral' if all sides are equal # 'isosceles' if exactly 2 sides are equal # 'scalene' ...
class Node(object): def __init__(self, next_node, previous_node, data): self.next_node = next_node self.previous_node = previous_node self.data = data class CycleList(object): def __init__(self): self.pointer = None def push(self, data): """Pushes the node <node> a...
# PYTHON TUTORIALS 3 """ INFORMAL INTRODUCTION TO PYTHON """ # this is the first comment spam = 1 # and this is the second comment # ... and now a third! text = "# This is not a comment because it's inside quotes." # Numbers a = 2 + 2 b = 50 - 5*6 c = (50- 5*6) / 4 8 / 5 2**2 13//4 # Strings print("...
'''this code generates buy and sell signals based on the historical prices using filter rule it takes in a list of close prices as an argument it outputs a list of signals the signal is represented by a string of a single letter, b=buy, s=sell, n=neither ''' #listofclose is the original data containing clo...
class Node: def __init__(self, info): self.info = info self.left = None self.right = None def __str__(self): return str(self.info) def preOrder(root): if root == None: return print(root.info, end=" ") preOrder(root.left) preOrder(root.right) class Bi...
class Solution: def search(self, nums, target): n = len(nums) start, end = 0, n-1 while start < end: mid = (start + end) // 2 if nums[start] < nums[mid]: if nums[start] <= target <= nums[mid]: end = mid else: ...
#iterative approach #time complexity - O(n) class LinkedListNode: def __init__(self, value): self.value = value self.next = None class TreeNode: def __init__(self, value): self.value = value self.left = None self.right = None def ListofDepths(root): q = [] if ro...
class Node: def __init__(self, data): self.data = data self.next = None class linkedlist: def __init__(self, head = None): self.head = head def __str__(self): res = "" ptr = self.head while ptr: res += str(ptr.data) + ", " ptr = ptr....
#time complexity - O(p + k**2) #its slow #string concatenation operates in O(n**2) def StringCompression(str1): count = 0 compressed_str = "" for i in range(0, len(str1)): count += 1 if (i+1 >= len(str1)) or str1[i] != str1[i+1]: compressed_str += "" + str(str1[i]) + str(count) ...
def waiter(number, q): A_before = number A = [] B = [] lower = 2 upper = 10000 prime = [i for i in range(lower, upper + 1) if all(i % j != 0 for j in range(2, i))] for i in range(q): while len(A_before) != 0: poped_item = A_before.pop() if poped_item % pr...
class Node: def __init__(self,data): self.data = data self.left = None self.right = None def insert(root,val): if root is None: root = Node(val) elif root.data>val: root.left = insert(root.left, val) else: root.right = insert(root.right, val) return ...
#space efficient #use additional stack to keep track of the mins import sys class StackWithMin: def __init__(self): self.s1 = [] self.s2 = [] def isEmpty(self): return len(self.s1) == 0 def getmin(self): if len(self.s2) == 0: return sys.maxsize else: ...
from .packet import Packet class PacketBuilder(): ''' Builds a command packet using the builder design pattern ''' def __init__(self, ip, port): self.ip = ip self.port = port self.cmd = None self.args = list() self.params = list() self.keys = dict() def add...
# >>>> https://github.com/Draylon/CHEBYSHEV_polinomios <<<<< import math import matplotlib.pyplot as plt import numpy as np from sympy import * x= symbols('x') def chebyshev_primeira_ordem(n): if n <= 0: return '1' if n == 1: return 'x' return '((2*x)*('+chebyshev_primeira...
from turtle import * import time import math shape('turtle') length = 25 def mountain(half_base): left(90) forward(length*half_base) right(90) for i in range((2*half_base)-1): if i % 2 == 0: right(45) forward(math.sqrt(length*length*2)) else: left(45) forward(length) right(135) for i in ran...
from re import match,compile variables={} class InvalidExpression(Exception): pass class UnknownVariableException(Exception): pass def parse(cmd): """ if cmd is a number return number else raise exception """ try: return list(map(float,cmd.split(" "))) except: retu...
#Don't forget to rename this file after copying the template #for a new program! """ Student Name: Jamie Lu Program Title: Girl Guide Cookie Sell-Off Program Description: This program will print the guide list and prizes for the annual Girl Guide cookie sale event """ #Making a function to input the ...
1.format=”%s%d” % (str1,num) print format 2.str1=”hello” str2=”world” result=str1+str2 3 字符串截取可以通过索引/切片,也可以通过split函数。 4 通过切片截取字符串: word=”world” print word[0:3] 5 python使用==和!=来进行字符串比较。如果比较的两个变量的类型不相同,那么结果必然为不同。
#1. python的类型相比go而言少很多 int float #1. 字符串转int data = "21" int_data = int(data, 16) print(type(int_data), int_data) #2. int转字符串 data_str = str(int_data) print(type(data_str), data_str) #3. float类型转换 data_float = float("3.1415") print(type(data_float), data_float) float_str = str(data_float) print(type(float_str), floa...
import json def add(a, b): total = a + b return total #现在想把add函数放到另一台服务器上去调用 #网络 web框架 #json http请求 #json 就是协议 json是一种数据格式 协议 json.dumps() 序列化 json.loads() 反序列化 成dict list class Company: name = "慕课网" address = "北京市" class Student: name = "bobby" company = Company() def to_json(self): ...
#封装的问题 #栈 class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def size(self): return len(self.items) #既然有了列表为什么我们还要基于list去实现一个栈呢 -...
#go语言的接口(protol 协议)设计是参考了鸭子类型(python)和java的接口 #什么是鸭子类型? 什么叫协议 #当看到一只鸟走起来像鸭子、游泳起来像鸭子、叫起来也像鸭子,那么这只鸟就可以被称为鸭子 #采用的是面向对象的类继承 class Animal: def born(self): pass def walk(self): pass class Dog(): def born(self): pass def walk(self): pass class Cat(Animal): pass dog = Dog(...
#!/usr/bin/env python # input if types int equality comparison numbers mod # Ask the user for a number. Depending on whether the # number is even or odd, print out an appropriate message # to the user. # Hint: how does an even / odd number react differently when divided by 2? # a = int(input("Enter the N...
students=["Irene","Maureen","Laureen","Mary","Leah","Joice","Julia","Jane","Liz","Eve",] for i in range(10): print("What is the name of student {}:{}".format(i,students[i])) students=["Irene","Maureen","Laureen","Mary","Leah","Joice","Julia","Jane","Liz","Eve",] welcome_str="Welcome Ms {}" print (welcome_str.form...
value_1=input("Enter value1") value_2=input("Enter value2") if value_1>value_2: print("value1 is greater") else: print("value2 is greater")
marks=input("what did the student score:") marks=int(marks) if marks>90: print("A") elif marks>70: print("B") elif marks>50: print("C") else: print ("D")
with open('Test1.txt','r') as reader: content = reader.readlines()#reading the data reversed(content) #The dta got reversed with open('Test1.txt','w') as writer: for text in content: writer.write(text) #write the data
""" :Author: Pravallika :Description: Implement int sqrt(int x). Compute and return the square root of x. """ class Sqrt(object): def findSqrt(self, x): """ :type x: int :rtype: int """ if x < 1: return 0 if x < 4: return 1 right = x//2 left = 2 while left <= right: mid = (lef...
""" :Author: Pravallika :Description: Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. :Note: The solution set must not contain duplicate triplets :Explanation: For example, given array S = [-1, 0, 1, 2, -1, -4], ...
""" :Author: Pravallika :Description: Given a set of distinct integers, nums, return all possible subsets. :Explanation: For example, If nums = [1,2,3], a solution is: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] """ class Subsets(object): def subsets(self, nums): """ :type n...
""" :Author: Pravallika :Description: Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). :Explanation: For example: Given binary tree [3,9,20,null,null,15,7] 3 / \ 9 20 ...
""" :Author: Pravallika :Description: Given an array nums, move all 0's to end while maintaining the relative order of non-zero elements :Explanation: nums = [0,1,0,3,12] resulting nums = [1,3,12,0,0] """ class MoveZeroes(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: List[int] """ f...
class ListNode(object): def __init__(self,x): self.val = x self.next = None def __repr__(self): if self: return "{} -> {}".format(self.val, repr(self.next)) class Solution(object): def reverseList(self,head): """ :type head: ListNode :rtype: ListNode """ if head == None: return None if he...
# 关键字参数,允许传入0或任意多个含参数名的参数,这些关键字参数在函数内部自动组装成一个dict def person(name, age, **kw): print('name:', name, '--- age:', age, '--- other:', kw) person('zhangsan', 32) person('lisi', 23, city = 'nanjing') person('wangwu', 34, gender = 'M', job = 'programer') extra = {'city': 'nanjing', 'job': 'taofen'} person('mazi', 25, **ex...
# 生成器(generator)-一边循环一遍计算的机制 # 创建generator最简单的方法:将一个列表生成式的[]改为() l = [x * x for x in list(range(10))] g = (x * x for x in list(range(10))) print(l) print(g) # print(next(g)) # print(next(g)) # print(next(g)) # print(next(g)) # print(next(g)) # print(next(g)) # print(next(g)) # print(next(g)) # print(next(g)) # print(ne...
from datetime import datetime, timedelta now = datetime.now() print(now) # 指定日期时间 dt = datetime(2017, 11, 5, 12, 00) print(dt) # datetime转为时间戳(timestamp),注意Python中的时间戳是秒数,js中的时间戳是毫秒数 dt = dt.timestamp() print(dt) # timestamp转为datetime ts = 1475650043 print(datetime.fromtimestamp(ts)) # string转为datetime print(dateti...
# 字典-dict(map结构),key不能是可变的,与list相比,数据无序,查找速度快,占用内存大 d = {'zhangsan': 12, 'lisi': 98, 'wangwu': 100} print(d['zhangsan']) ### key不存在会报错,避免方式有两种 # 1.判断存在再操作 if 'mazi' in d: print(d['mazi']) else: print('mazi is not exist in d.') # 2.第二个参数表示默认返回值,不代表复制,并不改变原有dict print(d.get('mazi', 0)) # 删除某项值 d.pop('zhangsan') prin...
# 命名关键字参数,限制关键字参数的名字,只接收city和job作为关键字参数 # 分隔符*后面的参数视为命名关键字参数 def person(name, age, *, city, job): print(name, age, city, job) #若函数中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*了 def person2(name, age, *args, city, job): print(name, age, args, city, job) # 命名关键字参数必须传入参数名,否则将被视为位置参数 person('zhangsan', 23, city = 'nanjing', jo...
from session import Session import math class Course(object): """ Representation of a course in a schedule """ def __init__(self, name, course_id, lecture, tutorial, practicum, max_students_lecture, max_students_tutorial, max_students_practicum, expected_students, df...
# For simpler reading x is red, o is yellow class game(object): ''' The console version of the game, implements all Connect 4 game mechanics ''' # Print msgs and errors if cout is True, players is a list of two player objects def __init__(self, players, cout=True): # (0,0) is top left corne...
price = 123 bonus = 23 bonus_granted = False ''' if bonus_granted: price -= bonus print(price) ''' dodanyBonus = price -bonus if bonus_granted else price print(dodanyBonus) rating = 5 ''' if rating == 5: print('very good') elif rating == 4: print('good') else: print('week') ''' print('very good...