text
stringlengths
37
1.41M
import facile # The list comprehension mechanism is always helpful! [s, e, n, d, m, o, r, y] = [facile.variable(range(10)) for i in range(8)] # A shortcut letters = [s, e, n, d, m, o, r, y] # Retenues [c0, c1, c2] = [facile.variable([0, 1]) for i in range(3)] # Constraints facile.constraint(s > 0) facile.constraint...
''' a=1 b=a print(id(a),id(b)) a=2 print(id(a),id(b)) c=2 print(id(a),id(c)) if a==c: print("=====") ''' # a=1 # a=1 # b=2 # a是变量 b也是变量 # 变量做为左值 就表示 变量 #变量做为右值 表示 取变量的值 赋值给左值 # a=b # print(a,b)
#Exercise: 5.12 Stefan-Boltzmann constant #Written By: Nina Inman import numpy as np import matplotlib.pyplot as plt #go into interactive mode plt.ion() #Use Latex fonts plt.rc('text',usetex=True) plt.rc('font', family='serif') #initializing constants: boltzmann = 1.38 * 10**(-23) h_bar = 1.054 * 10*...
#!/usr/bin/env python3 import random alphabet = "abcdefghijklmnopqrstuvwxyz" # zyxwvutsrqponmlkjihgfedcba def generateKey(): start = random.randint(1,25) key = "".join([alphabet[start:], alphabet[0:start-1]]) return key def encrypt(plain, key): ciphertext = "" for k in range(len(plain)): ...
# THIS CODE IS NOT SO USEFUL, BUT IT REQUIRES SKILLFUL PLAYING WITH DATA SETS. #I created it just to help my little brother solve his homework def get(allsum, length): ''' input: allsum: the sum of all digits in a number. length: the number of digits that the number consists of. output: the larg...
# This code prints out the numeber of vowels in a given word NV=0 for char in s: if char=='a' or char=='e' or char=='i' or char=='o' or char=='u': NV+=1 print("Number of vowels: " + str(NV))
#!/usr/bin/env python import pygame LEFT = 1 RIGHT = 3 running = 1 screen = pygame.display.set_mode((320, 200)) while running: event = pygame.event.poll() if event.type == pygame.QUIT: running = 0 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT: print "You pressed the l...
print('-'*80) print('Temperature Bot') print() Temperature = input('What is the temperature in Fahrenheit?') Temperature = int(Temperature) if Temperature <= 32: print('Itz bRick, wear ya jacket.') else: print('Itz not bRick, enjoy ya day.') print('-'*80)
# coding=utf-8 # 列表 L1 = [] L2 = [0, 1, 2, 3] L3 = ['adb', ['def', 'ghi']] i = 1 j = 0 print L2[i] print L3[i][j] print L2[1:3] print len(L3) L1 = L1 + L2 print L1 print L1 * 3 L4 = [x + 10 for x in L2] print L4 L2.append(4) L2.extend([5, 6, 7]) L2.index(1) L2.insert(1, 8) L2.reverse() L2.sort() # 删除最后一个,必须用del或pop,...
# 一个简单的装饰器 面向切面的编程 def log(func): def wrapper(): print("%s is running" % func.__name__) return func() return wrapper def foo(): print('i am a foo') foo = log(foo) foo() # 语法糖 def slice1(): def slice2(*argv, *kwargs): print('It's in slice 2')
#Problem 2: Even Fibonacci numbers:: def main(): prev_prev_value = current_value = sum = 0 prev_value = 1 four_million = 4000000 while(current_value <= four_million+1): current_value = prev_prev_value + prev_value if(current_value%2 == 0): sum = sum + current_valu...
#!/usr/bin/env python import random, sys # How many times do you need to toss a coin to be 85% sure you'll see tails at least once? # Answer: at least 3 g_total = int(sys.argv[1]) if len(sys.argv)>1 else 100000 def fact(n): return 1 if n<=1 else n*fact(n-1) def choose(n,k): return fact(n)/(fact(k)*fact(n-k...
''' https://stepik.org/lesson/24470/step/7?unit=6776 Вам дана последовательность строк. Выведите строки, содержащие "cat" в качестве подстроки хотя бы два раза. Примечание: Считать все строки по одной из стандартного потока ввода вы можете, например, так Sample Input: catcat cat and cat catac cat ccaatt Sample Output...
''' https://stepik.org/lesson/24463/step/6?unit=6771 Вашей программе будет доступна функция foo, которая может бросать исключения. Вам необходимо написать код, который запускает эту функцию, затем ловит исключения ArithmeticError, AssertionError, ZeroDivisionError и выводит имя пойманного исключения. Пример решения, к...
''' https://stepik.org/lesson/24470/step/15?unit=6776 Вам дана последовательность строк. В каждой строке замените все вхождения нескольких одинаковых букв на одну букву. Буквой считается символ из группы \w. Sample Input: attraction buzzzz Sample Output: atraction buz ''' import re import sys for line in sys.stdin: ...
import socket addr = input("[+] Insert your ip: ") port = 22 wordlist = input("[+] Insert your worldlist: ") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #This line of code doesn´t work for me, so i will do another bellow #with open(wordlist, "r") as word_list: # for word in word_list: # ...
#Escribí un programa que solicite al usuario ingresar la cantidad de kilómetros recorridos por una motocicleta y la cantidad de litros de combustible que consumió durante ese recorrido. # Mostrar el consumo de combustible por kilómetro. import time km = int (input ("Introduce la cantidad de Kilómetros recorridos: "))...
#Predefinimos nuestras variables a usar global productos productos = {} global price price = 0 global total total = 0 #Añadimos una funcion que nos guarda los datos def entrada (): product = str(input("Ingrese el nombre de producto: ")) global cantidad cantidad = int(input("Ingrese la cantidad: ")) g...
word = input("Insert a word with a coma: ") if "," in word: word = word.split(", ") print (word) print ("Lo introcido es ", word, ".")
#Escribí un programa que solicite al usuario ingresar tres números # para luego mostrarle el promedio de los tres. n1 = float(input ("Ingrese el primer número: ")) n2 = float(input ("Ingrese el segundo número: ")) n3 = float(input ("Ingrese el tercer número: ")) print ("El promedio de los tres números ingres...
#Escribí un programa que solicite al usuario el ingreso de una temperatura en escala Fahrenheit (debe permitir decimales) # #y le muestre el equivalente en grados Celsius. La fórmula de conversión que se usa para este cálculo es: # # _Celsius = (5/9) * (Fahrenheit-32)_ import time f = float (input ("Introduce su t...
from matplotlib import pyplot as plt letter_to_number = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7, 'H': 8, 'I': 9, 'J': 10, 'K': 11, 'L': 12, 'M': 13, 'N': 14, 'O': 15, 'P': 16, 'Q': 17, 'R': 18, 'S': 19, 'T': 20, 'U': 21, 'V': 22, 'W': 23, 'X': 24, 'Y': 25, 'Z': 26} temp = [] concatenated = '' pixel...
n = int(input('Enter the number of students: ')) Scores=[] R = 0 i=0 for i in range(0,n): item=int(input()) Scores.append(item) for i in range(0,n): sum=Scores[i]+R R=sum Av=sum/n print("average is",Av) for i in range(0,n-2): if Scores[i]>=Scores[i+1]: maxItem=Scores[i] ...
#------------------------------------------------------------------------- # # Copyright (c) 2017, J. Michael Beaver # # This software may be distributed in accordance with the MIT License. # See the accompanying LICENSE or https://opensource.org/licenses/MIT. # #--------------------------------------------------...
x = 0 y = 10 if x > 5: print("A") if y * 3 > 10: print("B") if x / 3 > 10: print("C") if y + 3 >= 7: print("D") if x * y > 0: print("E")
import numpy as np import matplotlib.pyplot as plt from scipy import stats pagespeeds = np.random.normal(3.0,1.0,100) purchaseAmount = 100 - (pagespeeds + np.random.normal(0,0.1,100))*3 slope, intercept, r_value, p_value, std_err = stats.linregress(pagespeeds,purchaseAmount) print("slope: %f , intercept: %f...
# -*- coding: utf-8 -*- maximum = None minimum = None while True: enter = raw_input('Enter number:') #user input value if enter == 'done': break #skip to print statements #check for valid input, give error if empty or letters try: number = int(enter) #convert input to integer ...
__author__ = 'martinpettersson' def commercial_price(): commercial = tuple(int(x.strip()) for x in raw_input().split(' ')) return commercial def listeners(): listeners = list(int(x.strip()) for x in raw_input().split(' ')) return listeners def max_subarray(A, max_ending_here): max_so_far = max_en...
import os import pdb import random from pick import pick from itertools import cycle def clear(): os.system("cls" if os.name == "nt" else "clear") class Deck: """Generates a deck of cards, using class variables , numbers and suits""" numbers = [ 'Ace', '2', '3', '4', '5', '6', '7', '8', '9', '...
# !/usr/bin/env python3 # -*- coding: utf-8 -*-from datetime import date # Написать программу, которая считывает текст из файла и выводит на экран только цитаты, # то есть предложения, заключенные в кавычки. import re if __name__ == '__main__': with open('lol.txt', 'r', encoding='utf-8') as f: text = f.re...
# coding: utf-8 # # <font color='navy' size=6><b>Introdution</b></font> # <p><font size=3>Classification of data is a main problem in machine learning, it is used in day to day problems, it can be very helpful and save time and money, in our problem here it is required to classify the the handwritten numbers into its...
# Sweeney # Assignment: Calories Burned # initializes number of calories burned per minute using a treadmill calPerMinute = 4.2 # loop that executes starting at 10, ending at 31 which means it really ends at 30, and increasing start by 5 till 30 is reached for calBurned in range(10, 31, 5): # prints caloi...
def main(): # sets user_input to value returned from function get_user_input user_input = get_user_input() # runs function count_most_frequent_letters with user_input passed as argument count_most_frequent_letters(user_input) def get_user_input(): # gets a string from the user use...
num, money = map(int,input().split()) count = 0 unit_group =[] for i in range(num): unit = int(input()) unit_group.append(unit) unit_group.reverse() for coin in unit_group: if money >= coin: count += money//coin money %= coin elif money==0: break print(count)
''' #Unit 10-1 person = ['james', 17, 175.3, True] a = list(range(10)) print(a) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] b = list(range(-1, 5, 4)) print(b) # [-1, 3] ''' #------------- ''' #Unit 10-2 a = 38, # 1개짜리 튜플 b = [1, 2, 3] print(b,type(b)) # [1, 2, 3] <class 'list'> b = tuple(b) print(b,type(b)) #...
""" # 마린 : 공격 유닛, 군인, 총 사용 name= 'marine' # Unit name hp = 40 # Unit Hp damage = 5 # power of Unit print(f"{name} 유닛이 생성되었습니다.") print(f"체력 {hp}, 공격력 {damage}\n") # 탱크 : 공격 유닛, 탱크, 포를 쏠 수 있음. 일반모드 / 시즈모드 tank_name = "tank" tank_hp = 150 tank_damage = 35 print(f"{tank_name} 유닛이 생성되었습니다.") print(f"체력 {t...
import os def LimpaTela(): os.system('cls') print(" +----------------------------------------------------------------------------+") print(" | << Gerador de dados para Etiqueta V.1.0 - Desenvolvido Miguel Jr. >> |") print(" +------------------------------------------------------------------...
import threading #定义线程要调用的方法,*add可接收多个以非关键字方式传入的参数 def action(*add): for arc in add: #调用 getName() 方法获取当前执行该程序的线程名 print(threading.current_thread().getName() +" "+ arc) #定义为线程方法传入的参数 my_tuple = ("http://c.biancheng.net/python/",\ "http://c.biancheng.net/shell/",\ "http://c.bi...
botellas0 = input ("cuantas botellas de menos de 1 litro has comprado") botellas1 = input ("cuantas botellas de mas de 1 litro has comprado") deposito0 = (0.10*int(botellas0)) deposito1 = (0.25*int(botellas1)) print ("tienes que devolver un total de " + str(float(deposito0) + float(deposito1)) + "centimos")
import string import re import nltk from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from nltk.stem import PorterStemmer from nltk.tokenize import word_tokenize stemmer = PorterStemmer() nltk.download("stopwords") nltk.download("punkt") input_str = """If you want a hotel that is faraway fro...
import string import re import nltk from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from nltk.stem import PorterStemmer from nltk.tokenize import word_tokenize stemmer = PorterStemmer() nltk.download("stopwords") nltk.download("punkt") input_str ="""A great and lovely hotel for couples and...
# fibonnacci def bottom_up(n): f = [1, 1] for k in range(2, n): f.append(f[k-1]+f[k-2]) return f[-1],f, len(f) f = bottom_up(100) print(f) def k_last_digit(n, k): return n%10**k d = k_last_digit(787, 2) #print(d) # repeating unit digit ld = [] for n in f[1]: ld.append(k_last_digit(n...
class Alphabet: def __init__(self): self._value = 123 @property def value1(self): print("getting value", self._value) return self._value @value1.setter def value1(self,value): print('Setting value to') self._value = value # deleting the values @valu...
# a = ["1",1,"2", 2] # new_dict = {x:1 for x in a} # print(new_dict) # # # create nested dict # # a = {"a":[{"b":1}]} # print(a) from datetime import date, timedelta,datetime today = datetime.now() today += timedelta(days=10, hours=14) print("Today's date:", today)
#!/usr/bin/env python #This module helps to read input/output files of Fortran programs import numpy as np from struct import unpack class FortranUnformattedFile(object): ''' Deal with a Fortran unformatted file Note this file must be in ACCESS="SEQUENTIAL" mode, which is default some programs like vas...
import cores def inserirNome(): try: nome = input("Digite seu nome: ").strip().title() except KeyboardInterrupt: print(cores.aviso("\nAção interronpida pelo usuário.")) return None else: if not nome: return None return nome def inserirConta(): while...
answer = input("Do you want to hear a joke? ").upper() # can also use .casefold() to strip case sensitivity if answer == "YES": print("I'm against picketing, but I don't know how to show it.") elif answer == "NO": print("Bye.") else: print("idk")
# Shakespeare analysis using functional words import re import urllib2 from pprint import pprint import itertools fwords = urllib2.urlopen("https://fling.seas.upenn.edu/~maeisen/wiki/functionwords.txt").read().split(" ") def getdistance(list1, list2): pairs = itertools.product(list1, list2) distances = [abs(t[0] -...
num1 = int(input("Digite el primer numero : " )) num2 = int(input("Digite el segundo numero :")) if num1>num2: print("El numero 1 : ", num1 , "es mayor que el numero 2: ", num2) else: print("El numero 2 : ", num2 , "es mayor que el numero 1: " ,num1)
#5: Написать функцию, которая принимает строку в качестве аргумента и возвращает строку, # в которой все строчные буквы заменены на заглавные и наоборот. #Пример: swap_case(‘Hello World’) >> ‘hELLO wORLD’ def swap_case(s): return s.swapcase() a = 'Hello World' a1 = 'SMALL big' print(swap_case(a)) print(swap_case...
#4. Написать программу, которая принимает два аргумента: месяц и год в формате целых чисел, # а на выходе возвращает календарь для переданных данных, например: 2019, 12 (декабрь 19-го года): import calendar try: y = int(input('Enter year :')) m = int(input('Enter the number of month : ')) a = calendar.T...
# 6: Написать функцию, которая принимает в качестве аргумента список и возвращает в качестве результата список с # уникальными отсортированными значениями в обратном порядке. П # ример: [19, 12, 4, 12, 7, 9, 5, 8, 3, 17, 8, 19, 12, 3, 6, 15, 15, 16, 11, 13, 19, 16, 11, 12, 20, 2, 16, 7, 15, 2, 6, 15, 17, 15, 19, 4, # 1...
#8: Написать функцию, которая принимает в качестве аргумента строку. Функция должна проверять и возвращать True, # если переданная строка является палиндромом, в противном случае - False. #Пример: check_palindrome(‘Never odd or even’) >> True def testPalindrom(s): s = s.replace(' ', '').lower() if s == s[::-1]...
# 1: Написать программу, которая в качестве аргумента принимает объект данных datettime, # необходимо найти сколько времени с времени переданного объекта в днях, часах, минутах. import datetime try: a = input('Input date at format (yyyy-mm-dd): ') d = datetime.datetime.today()-datetime.datetime(*map(int, a.spl...
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Copyright © 2020 Patrick Nanys <patrick.nanys2000@gmail.com> # # Distributed under terms of the MIT license. from lab_solutions.lab01_qsort import swap def bubblesort(l): for i in range(len(l)): for j in range(len(l)-i-1): if l[j] > l[j+1]: ...
# (\x(\y xy))y # ["app",["lam","x",["lam","y",["var","xy"]]],["var","y"]] def replacement(exp, count): return ["var", str(count)] def replace_all(exp, a): # exp = ["xy"] # a = {'x' : 1, 'y' : 2} for r in a: exp = exp.replace(r, str(a[r])) return exp def rename(exp, a={}, count=0): i...
from datetime import datetime def clock_in(): start = datetime.now() print(f"Time start at {start.time()}") return start def diff(start, end=None): if end == None: current = datetime.now() difference = current - start return difference else: current...
Dic={3:'mandar',4:'Ankita',1:'Nagesh',2:'rahul'} for key, value in Dic.items(): print(key,":",value)
class util: def splitandlist(input): l = [] for i in input: try: l.append(int(i)) except: print(i + " is not a number") return l
x=int(input("Enter Value for n:")) if(x!=0): dic={1:1} for i in range(1,x+1): dic[i]=i*i else: print("cant create dictionary since n=",x) print(dic)
import calendar year=input("Enter year:") month=input("Enter month:") print(calendar.month(int(year),int(month),2,1))
l=['mandar','naruto','kiba','kisame','guy','itachi','orochimaru','tsunade','jiraiya'] finallist=[] sel=int(input('Enter length for word selection:')) for i in l: if(len(i)>sel): finallist.append(i) print(finallist)
class Card: def __init__(self, suit, rank): self.suit = suit self.rank = rank def __str__(self): return self.rank + " of " + self.suit class Deck: def __init__(self): self.deck = [] for s in suits: for r in ranks: s...
def titan_intro(dict): for key,val in dict.items(): print(f'I am a {key}, and I possess {val} skill') titan_skills = {} while True: titan_name = input('enter a titan name ') titan_skill = input('enter a skill of the titan ') titan_skills[titan_name] = titan_skill theother = input ('any ...
''' Hangman.py Sept 11, 19 Augustine Valdez partner: Preston McIllece ''' import sys import random class Hangman: ''' Initializes the words list ''' def __init__(self): file = open('words.txt','r') self.words = [] self.wordguess = [] for line in file: self...
"""You're going to write a binary search function. You should use an iterative approach - meaning using loops. Your function should take two inputs: a Python list to search through, and the value you're searching for. Assume the list only has distinct elements, meaning there are no repeated values, and elements are in...
PIZZAS = ( { "name": "Cheese Pizza", "cost": 5.00 }, { "name": "Pepperoni Pizza", "cost": 7.50 }, ) my_pizzas = [] def display_invalid_option(menu_selection): if menu_selection.isdigit(): print("\n{} is an invalid option, please try again".format(menu_select...
#!/usr/bin/python3 def divisible_by_2(my_list=[]): if my_list is None or len(my_list) == 0: return (None) l = len(my_list) - 1 i = 0 new = my_list[:] while i <= l: if my_list[i] % 2 == 0: new[i] = True else: new[i] = False i = i + 1 return ...
#!/usr/bin/python3 """ Returns true if the object is the same instance or inherited""" def is_kind_of_class(obj, a_class): """Returns true if same instance or inherited, otherwise false""" if isinstance(obj, a_class): return True else: return False
#!/usr/bin/python3 def print_matrix_integer(matrix=[[]]): for count in matrix: new = [] for count2 in count: new.append(' '.join('{:d}'.format(count2))) print(' '.join(new))
#Import and Init import pandas as pd import matplotlib.pyplot as plt import numpy as np #Making sure the csv is read, and the console is initialized console = 0 data = pd.read_csv("comicmovies.csv") #This function will display the prompt for the user to type something def start(): print(">>> Type any one of the p...
class Employee: """ Initialize variables""" def __init__(self, name, phone, email, address): self.__name = name self.__phone = phone self.__email = email self.__address = address """All the getters and setters are used because we use private variables with __""" """The s...
# Class inheriting ValueError class class NotEnough(ValueError): def __init__(self, pay): super().__init__(f"You only make ${pay}, you need to make at " f"least 20000.\nI am sorry you don't get a bonus...") self.pay = pay class IsNegative(ArithmeticError): def __init__...
from shape.polygon import Polygon from shape.shapes import Shapes """Import the file_location.filename and class""" class Triangle(Polygon, Shapes): """returns area of a triangle Inheritance (Inherits all the variables for the Polygon class)""" def get_tri_area(self): return int(self.get_width() *...
for i in range(7): for a in range(1, i + 1): print(a, end=" ") print()
class Room: def __init__(self): self.__square_feet = {} self.__water = False self.__gas = False def set_square_feet(self, square_feet): self.__square_feet = square_feet def set_water(self, water): if water == 'yes': water = True else: ...
# ure "simple regular expressions" DEBUG: int class _RegEx: def match(self, string: str) -> _Match: "Similar to the module-level functions match() and search(). Using methods is (much) more efficient if the same regex is applied to multiple strings." pass def search(self, string: str) -> _Ma...
#Read info from json file import json with open('info.json') as json_file: data = json.load(json_file) user = data["user"] paswd = data["pass"] print(user) print(paswd) #elements = json.loads(file.read()) #print(elements['user']) #print(elements['pass'])
""" Filename: wiki_crawler.py Author: Jeff Gladstone Date: 6/29/2017 Description: This program consists of two Web crawling games that scrape links by parsing HTML from Wikipedia pages. The first game allows the user to travel down a path of links for a predetermined number of steps....
# C-1.22 # Write a short Python program that takes two arrays a and b of length n storing int values, # and returns the dot product of a and b. That is, it returns an array c of length n such that # c[i] = a[i]·b[i], # for i = 0,...,n−1. first = [1, 2, 3, 4] second = [1, 2, 3, 4] def dot_product(a, b): ...
# R-1.11 # Demonstrate how to use Python's list comprehension syntax to produce the list # [1, 2, 4, 8, 16, 32, 64, 128, 256]. print([pow(2, k) for k in range(0, 9, +1)])
#!/usr/bin/env python3 def validate_iso8601(ts): """Check validity of a timestamp in ISO 8601 format.""" digits = [0, 1, 2, 3, 5, 6, 8, 9, 11, 12, 14, 15, 17, 18, 20, 21, 22] try: assert len(ts) == 24 assert all([ts[i].isdigit() for i in digits]) assert int(ts[5:7]) <= 12 a...
print("your name") name=input() print(name[-2]) name="bristi biswas" print(name[1]) print(name[-2]) print(name[1:-1] print(len(name)) print(name.title()) print(name.strip())
import pygame import random pygame.init() white = (255, 255, 255) black = (0, 0, 0) yellow = (255, 255, 100) red = (210, 50, 80) green = (50, 170, 80) width = 400 height = 400 display = pygame.display.set_mode((width, height)) pygame.display.set_caption('Snake Game') clock = pygame.time.Clock() ending_font = pyga...
str = input("enter string\n") a = [0]*256 for i in str: if a[ord(i)]==0: a[ord(i)]==1 print(i,end="")
import numpy as np # mathamatical library import matplotlib.pyplot as plt ## Plot chart import pandas as pd # import data set and manage dataset # Importing the dataset dataset = pd.read_csv('Data.csv') x = dataset.iloc[:,:-1].values y = dataset.iloc[:,1].values # Training and Test Set Data need to divide :::: f...
""" reads command-line arguments """ import argparse import logging import default def parse_arguments(args): """ reads command-line arguments """ edu_parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) edu_parser.add_argument( "-f", "--file", ...
# alex = { # 'name': 'alex', # 'sex': '不详', # 'job': 'it man', # 'level': 0, # 'hp': 250, # 'atk': 10 # } # dog = { # 'name': '太白', # 'sex': 'man', # 'level': 0, # 'hp': 250, # 'atk': 5 # } # 保证所有的玩具初始化的时候拥有相同的数学 # 每来一个新玩家,都手动创建一个字段,然后向字典中传值 def Persion(name, sex, job, hp,...
for i in range(1, 10): for j in range (1, i+1): print(f"{j}x{i}={i*j}".ljust(6),end=' ') print("")
""" datetime 模块:日期与时间 封装了一些和日期,时间相关的类 date time timedelta """ import time import datetime # date类 # print 2019-12-31 d = datetime.date(2019, 12, 31) # 获取d 对象的各个属性 print(d.year, d.month, d.day) # time类 t = datetime.time(12, 59, 59) print(t.hour, t.minute, t.second) # datetime类 datetime 模块中的类,主要是用于数学计算 dt = datet...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: choos_ball.py Description : date: 2019-10-21 ------------------------------------------------- """ red_balls = [] blue_balls = [] while True: if len(red_balls) < 6: ball_num ...
class MyListIterator(object): def __init__(self, data): self.data = data self.now = 0 def __iter__(self): return self def __next__(self): while self.now < self.data: self.now += 1 return self.now - 1 raise StopIteration my_list = MyListIte...
""" time 模块 """ # 与时间相关的操作,封装了获取时间戳和字符串形式的时间的一些方法。 import time print(time.time()) # 获取时间戳 1577770013.073893 ,表示从1970年1月1日0时0分0秒 到现在经过的秒数 #格式:time.struct_time(tm_year=2019, tm_mon=12, tm_mday=31, tm_hour=5, tm_min=33, tm_sec=17, tm_wday=1, tm_yday=365, tm_isdst=0(夏令时) ) #print(time.gmtime()) # 输出格式化时间戳后的时间信息 格林威治时间...
import random random.seed(1) # 设置随机数种子 print(random.random()) # [0.0,1.0) 范围内浮点数 print(random.randint(1, 10)) # 获取[a,b] 范围内的一个整数 print(random.uniform(1, 10)) # 获取[a,b) 范围内的一个浮点数 x = [1, 2, 3, 4, 5] print(random.shuffle(x)) # 把参数指定的数据中的元素打乱,参数必须是一个可变的数据类型 print(x) k = ['a', 'b', 'c', 'd', 'e'] k = random.sample(...
# 装饰器:完全遵循开放封闭原则 ,在不改变原函数代码,以及调用方式的前提下,为其增加新的功能。 # 装饰器就是一个函数。装饰器的本质就是闭包 import time #版本一 # def index(): # """有很多操作""" # print("欢迎登陆首页") # time.sleep(2) # print("登陆成功") # # def picture(): # """有很多操作""" # print("欢迎登陆图片页") # time.sleep(2) # print("登陆成功") #现在写一些代码,测试一下index函数的执行效率。 # star...
# 封闭的东西: 保证数据的安全。 # ll = [] # l1 = [] # def make_avg(new_value): # ll.append(new_value) # total = sum(ll) # avg = total / len(ll) # return avg # ll.append(50) # print(make_avg(10000)) # print(make_avg(12000)) # 由于ll 是全局变量,并不能保证数据安全,当我们有多行代码,对ll进行误操作,就会出现问题。 def make_averager(): ll = [] def a...
#!/usr/bin/env python """ Given an unsorted integer array, find the first missing positive integer. For example, Given [1,2,0] return 3, and [3,4,-1,1] return 2. Your algorithm should run in O(n) time and uses constant space. """ class Solution(object): def firstMissingPositive(self, nums): """ :...
#!/usr/bin/env python """ Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in O(n) complexity. https://discuss.leetco...
#!/usr/bin/env python """ Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given "pwwkew", the answer is "wke", with the length of 3. Note that the an...
# -*- coding: utf-8 -*- """ Created on Mon May 4 21:25:56 2020 @author: Kunal Jani """ import numpy as np import pandas as pd import matplotlib.pyplot as plt #REading the data and storing them into the x and y variables. train_dataset=pd.read_csv('train.csv') y=train_dataset.iloc[:,0].values x=tra...