text
stringlengths
37
1.41M
# Import OS & CSV Modules import os import csv import sys # # Create list for each column month = [] profit = [] monthly_change =[] profit_change = [] # Create path from the Resources folder filepath = os.path.join ('..', 'Resources', 'budget_data.csv') # Read in CSV File with Delimiter commas with open(filepath, 'r...
#import API import requests def recipe_search(ingredient): # Register to get an APP ID and key https://developer.edamam.com/ import os app_id = os.environ.get("APP_ID") app_key = os.environ.get("APP_KEY") result = requests.get('https://api.edamam.com/search?q={}&app_id={}&app_key={}'.format(ingredien...
#Rectangle length = 5 breadth = 2 area = length*breadth print 'Area is',area print 'Perimeter is',2*(length+breadth)
''' Created on Dec 11, 2013 @author: nonlinear ''' def maxsum(sequence): """Return maximum sum.""" maxsofar, maxendinghere = 0, 0 for x in sequence: # invariant: ``maxendinghere`` and ``maxsofar`` are accurate for ``x[0..i-1]`` maxendinghere = max(maxendinghere + x, 0) ma...
from os import path import wget def DownloadFile(url, name=None, target_dir=None): ''' Check if file exists and download to working directory if it does not. Returns str of filename given to file. Arguments: url = str_of_fully_qualified_url, name=str_of_name_you_want TODO: 2019-07-16 Check if s...
#!/usr/bin/python3 list1, list2 = ['Google', 'Taobao', 'Runoob'], [456, 700, 200] print ("list1 最小元素值 : ", min(list1)) print ("list2 最小元素值 : ", min(list2)) print ("list1 最大元素值 : ", max(list1)) print ("list2 最大元素值 : ", max(list2)) aTuple = (123, 'Google', 'Runoob', 'Taobao') list1 = list(aTuple) print ("Tuple列表元素 : ...
#! /home/sudeep/anaconda3/bin/python3.6 import sqlite3 import create_db connection = sqlite3.connect("schools.sqlite") cursor = connection.cursor() school = str(input("Enter the name of school : \n")) school_id = create_db.select_school(school) student_list = [row [0] for row in cursor.execute("""SELECT name from...
import unittest # 1.1 Is Unique: Check if a string has all unique characters def is_unique(s): return len(set([x for x in s])) == len(s) # 1.2 Check Permutation: Check if one string is a permutation of the other def are_permutations(a, b): counts = {} for c in a: if c not in counts: ...
words = "It's thanksgiving day. It's my birthday,too!" print(words.find('day')) words = words.replace("day","mouth") print(words) x = [2,54,-2,7,12,98] print(max(x)) print(min(x)) x = ["hello",2,54,-2,7,12,98,"world"] print(x[0], x[-1]) new_x = [x[0], x[-1]] print(new_x) x = [19,2,54,-2,7,12,98,32,10,-3,6] ...
#!/usr/bin/python # pull request import argparse import math def find_max_profit(prices): temp = math.inf * -1 for x in range(0,len(prices)): for y in range(x+1, len(prices)): difference = prices [y] - prices[x] if difference > temp: temp = difference return temp if __name__ == '__mai...
def forall(lst): def predicate(p): for x in lst: if not p(x): return False return True return predicate def exists(lst): def predicate(p): for x in lst: if p(x): return True return False return predicate
# Invertir una palabra introducida por el usuario while True: print("Invertir palabra o frase (En blanco para salir)") frase = input("Digite la palabra/frase que desa invertir: ") if len(frase) <=0: break frase_invertida = "" for i in range(len(frase)-1,-1,-1): frase_invertida = f...
def sumar(*numeros): return sum(numeros) def restar(a,b): return (a-b) def multiplicar(a,b): return a*b def dividir(a,b): if b == 0: raise ValueError('Intenta dividir entre 0') else: return a/b
from .Funciones_aridmeticas import sumar,restar,multiplicar,dividir def menu(): print('Seleccione una opcon:') print('1) Sumar') print('2) Restar') print('3) Multiplicar') print('4) Dividir') print('0) Salir') print() def main(): while True: menu() while ...
list11 = [1, 2, 3, 4, 5, 6] list12 = [7, 2, 1, 14, 5, 16,8] list3 = [] list4 = [] for i in range(0, len(list11), 1):# remplir le deuxieme list par les elemnts d'indice impaire de liste11 if i % 2 != 0: list3.append(i+1) for i in range(0, len(list12), 1): if i % 2 == 0: # remplir le premier list par les elemnt...
for number in range(1, 8): i = '1' print(i * number)
def count_elem(lst): n = 0 for i in lst: n += 1 return n lst1 = [1, 2, 3, 4, 5, 6] print(count_elem(lst1))
num = int(input("Print number: ")) def func_0(num): if -10 < num < 10: num += 5 return num else: num -= 10 return num print(func_0(num))
#!/usr/bin/python f = open("test.txt", "r+") #str = f.read(11) #print str #line = f.readline() #while line != "": # print line # line = f.readline() # f.write("1111") f.flush() f.close() f = open("test.txt", "r+") lines = f.readlines() print lines for line in lines: print line f.close() #dic = {1:2, ...
import random i = random.randint(1,10) g=1 answer= 0 while( answer != i and g <= 3): temp = input("请猜数(1~10):") answer = int(temp) if (answer > i): print("猜大了") g+=1 elif (answer < i ): print("猜小了") g= g+1 else: print("你猜对啦,真有默契") if g > 3: print("四次机会你都没...
class Stack: def __init__(self): self.stack = [] self.len = len(self.stack) def isEmpty(self): if self.stack == []: return True else: return False def push(self,x): self.stack.append(x) def pop(self): return self.stack.pop() def...
def int_input(): try: a = int(input('请输入一个整数:')) except ValueError : print('出错,您输入的不是整数。') int_input() return a number = int_input()
#3 oportunidades para elegir la opcion correcta #adivinar la pregunta from random import randrange palabras = [{'palabra':'MANZANA','pregunta':['¿Viene de un arbol y es roja?','¿Es el logo de las MacBook?']}, {'palabra':'ARBOL','pregunta':['¿Tiene hojas y es verde y grande?','¿Tiene muchos frutos y ...
import sqlite3 conn = sqlite3.connect("test.db") cursor = conn.cursor() # cursor.execute("CREATE TABLE usuarios(nombre VARCHAR(100), edad INTEGER, email VARCHAR(100))") # cursor.execute("INSERT INTO usuarios VALUES ('matia bd',27,'elgato@gmail.com')") cursor.execute("SELECT *FROM usuarios") # print(cursor) usu...
1.Question 1 In the following code, print(98.6) What is "98.6"? <A> A variable <B> A constant <C> An iteration / loop statement <D> A conditional statement AnS: <B> A constant 2.Question 2 What does the following code print out? print("123" + "abc") <A> 123abc <B> This is a syntax error because ...
#!/usr/bin/env python # -*- coding: utf-8 -*- #Author:YangShuang import logging class logger(): def __init__(self,path,consoleLevel,logFile,fileLevel): #创建logger对象 self.logger=logging.getLogger(path) #设置默认log级别 self.logger.setLevel(logging.DEBUG) #定义输出handler的格式 fmt=...
import collections import battle_engine import choose_grid import create_character import abilities import enemies import items import weapons DIFFICULTY = 'easy' BOSSES = { 'papa roach': enemies.PapaRoach, 'horn dog': enemies.HornDog, } def create_battle(anzacel, encounter): battle_enemies = [] if not e...
my_list=['','O',''] from random import shuffle def user_guess(): guess='' while guess not in ['1','2','3']: guess=input("Pick ball position no.- 1 / 2 /3: ") return int(guess) def shuffle_list(): shuffle(my_list) return my_list def check_guess(gussed_index,mixedup_list): ...
def run(): my_list = [1, "Hello", True, 4.5] my_dict = {"firstname": "Gio", "lastname": "Morales"} super_list = [ {"firstname": "Gio", "lastname": "Morales"}, {"firstname": "Erick", "lastname": "Bustamante"}, {"firstname": "Javier", "lastname": "Castro"}, {"firstname": "Tony...
def rotate_left3(nums): first = nums[0] for i in range(0, len(nums) - 1): nums[i] = nums[i + 1] nums[len(nums) - 1] = first return nums
def string_match(a, b): count = 0 max = min (len(a), len(b)) for i in range(0, max - 1): if a[i:i + 2] == b[i:i + 2]: count += 1 return count
import math """Regular Polygon class""" class RegularPoly: """Class to create a regular polygon""" def __init__(self, vert_count, radius): """Initialize the RegulaPoly class attributes""" self.vert_count = vert_count # Number of vertices of polygon self.radius = radius # Circumradi...
from collections import namedtuple from datetime import datetime, timedelta from typing import Union, Iterator, Optional from dateutil.relativedelta import relativedelta # Defines begin and end dates Window = namedtuple("Window", ["start", "end"]) def validate_date(date: Union[str, datetime, timedelta, relativedelta...
#!/usr/bin/env python # coding: utf-8 # In[8]: def sum_of_digits(n): if n >= 0 and n <= 9: return n else: return n%10 + sum_of_digits(n//10) number = int(input()) print(sum_of_digits(number)) # In[ ]:
#!/usr/bin/env python # coding: utf-8 # In[7]: def isprime(x): if x == 1 or x == 0: return False for i in range(2, x): if x % i == 0: return False return True number = int(input()) if isprime(number): print('YES') else: print('NO') # In[ ]:
#!/usr/bin/env python # coding: utf-8 # In[2]: numbers_1 = list(map(int, input().split())) numbers_2 = list(map(int, input().split())) result = tuple(set(numbers_1) & set(numbers_2)) print(*result, sep=" ") # In[ ]:
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: if not root: return [] if not root.left and not root.rig...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: if not head: return None prev = head current = head.next while current: ...
class Solution: def searchInsert(self, nums: [int], target: int) -> int: if len(nums) == 1: if target > nums[0]: return 1 else: return 0 for i in range(1, len(nums)): if target > nums[i-1] and target <= nums[i]: re...
string = raw_input("Enter a word or sentence(s) to see what it looks like backwards:\n") print string,"backwards is: \"", string[::-1],"\""
## Codigo exemplo para a Escola de Matematica Aplicada, minicurso Deep Learning ## Exemplo de rede neural com uma unica camada ## ## Moacir A. Ponti (ICMC/USP), Janeiro de 2018 ## Referencia: Everything you wanted to know about Deep Learning for Computer Vision but were afraid to ask. Moacir A. Ponti, Leonardo S. F. Ri...
from tkinter import * root = Tk() button1 = Button(root, text = "Click") button1.pack() button2 = Button(root, text = "Click", state = DISABLED) button2.pack() button3 = Button(root, text= "Click", padx = 50, pady = 50) button3.pack() root.mainloop()
import turtle from time import sleep t = turtle t.pen() def rectangle(size): t.reset() for x in range(2): t.forward(size + (size/2)) t.left(90) t.forward(size) t.left(90) def triangle(size): t.reset() for x in range(3): t.forward(size) t.left(120) def re...
# look for a number 10 digits all digits are # used 0,1,2,3,4,5,6,7,8,9 # and in each position the number, counting from the start (left) # is a multiple of the digit at the position. # 10 Zahl # python recursive script WE 22.March 2020 ########################################## z=['1','2','3','4','5','6','7','8','...
''' Conor O'Donovan December 2018 Udemy - Complete Python Bootcamp Milestone Project 1 - Tic Tac Toe Creating a two-player Tic Tac Toe game Steps: 1. We need to print a board. 2. Take in player input. 3. Place their input on the board. 4. Check if the game is won,tied, lost, or ongoing. 5. Repeat c and...
import csv from pathlib import Path inpath = Path("sample.csv") with inpath.open("r", newline="", encoding="utf-8-sig") as infile: reader = csv.DictReader(infile) for row in reader: fullname = f"{row['First name']} {row['Middle name']} {row['Last name']}" print(fullname)
array = [3,6,9,12,23] square=[] for i in range(0,5) : square.append(array[i]*array[i]) print(square[i])
# Student ID : 1201200309 # Student Name : Alvin Chen # get input from user to withdraw money # if balance is less RM10, alert the user that there is no sufficient fund. # and display the current balance # use the keyboard else: to of the current balance is sufficient and # display the new current balance. c...
from random import choice, randint from collections import Counter text = "Kovach" symbols = [chr(x) for x in range(65,91)] # A - Z symbols += [chr(x) for x in range(97,123)] # a - z # A - z while True: keys = [randint(1,100) for x in range(len(text))] k = Counter(keys) switch = 0; n = 0 for l in k: if k[keys[n]...
import random def empty(board): mas = list() for i in range(9): if (board[i] == ' '): mas.append(i) return(mas) def printBoard(board): print(board[0] + '|' + board[1] + '|' + board[2]) print('-+-+-') print(board[3] + '|' + board[4] + '|' + board[5]) print('-+-+-') ...
import sqlite3 import os os.remove('PLdatabase.db') connection = sqlite3.connect('PLdatabase.db') cursor = connection.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS friendship(person1 TEXT, person2 TEXT)') cursor.execute('CREATE TABLE IF NOT EXISTS houses(name TEXT, ' 'person1 Text, person2 TEXT, ...
""" 1. Python syntax can be executed by writing directly in the Command Line python terminal: Lets Go directly to terminal and see 2. Indentation Lets see the appropriate example 3. Comment Comments start with a #, and Python will render the rest of the line as a comment """
age = int(input("Enter your age")) if age>=18: print("Do you have a nid") nid = int(input("Give your nid")) Id = int(input("Give your student id")) if nid == 1: print("you can give vote") elif Id == 1: print("you can give exam") else: print("you can't vote") else: pr...
#문제1. 키보드로 정수 수치를 입력 받아 그것이 3의배수인지 판단하세요 num=input("수를 입력하세요 : ") if(num.isdigit()): num=int(num) if(num%3==0): print("3의 배수 입니다.") else: print("3의 배수가 아닙니다.") else: print("정수가 아닙니다.")
""" Life The Game Dots are represented as tuples: (x, y) where x is an absciss and y is an ordinate. Keep in mind that iteration often comes through i and j where i is a row num and j - column num. """ import random import argparse from typing import List, Dict, Tuple, Union, Any # Default configuration ROWS = 15 C...
num = int(input("Informe um numero: ")) u = num // 1 % 10 d = num // 10 % 10 c = num // 100 % 10 m = num // 1000 %10 print('Analisando o numero {}'. format(num)) print('unidade {}'.format([u])) print('Dezena {} '.format([d])) print('Centea {}'.format([c])) print('milhar {}'.format([m]))
import random a1=input("digite o nome do primeiro aluno: ") a2=input('digite o nome do segundo aluno: ') a3=input('digite o nome do terceiro aluno') a4=input('digite o nome do quarto aluno: ') lista=[a4,a3,a2,a1] sort= random.choice(lista) print(' oa aluno escolhido foi: {}'.format(sort))
km=float(input('Qantos km foram percorridos?')) dias=int(input('quantos dias de locação?')) total=(dias*60)+(km*0.15) print('Ovalor a pagar será de R${:.2f}'.format(total))
ten_things = "apples oranges crows telephone light suger" print("Wait there are not 10 things in that list, Let's fix that.") stuff = ten_things.split(' ') #单引号之间必须加空格,否则报错 more_stuff = ["day","night","song","frisbee","corn","banana","girl","boy"] while len(stuff) != 10: next_one = more_stuff.pop() print("a...
# Python 3.5.1 # » Documentation » The Python Standard Library # » 6. Text Processing Services # » 6.2. re — Regular expression operations # » 6.2.3 Regular Expression Objects # Compiled regular expression objects support the following methods # and attributes: # If you want to locate a fullmatch anywhere in string, ...
import datetime import hashlib import array import json """ Title: Python Block Chain Author: Bradley K. Hnatow Description: A simple block chain program devloped in python later to be used and updated for more complex projects. """ class block(): def __init__(self, prevHash, dataArray, proof, nonce=0): ...
from PyDictionary import PyDictionary class Mydictionary: word='' def __init__(self,word): self.word=word def giveMeaning(self): dictionary=PyDictionary() x=dictionary.meaning(self.word) xx=str(x['Noun'][0]) print(f'meaning: {xx}') return (x['Noun...
myage = 22 user_age = int(("enter your age")) if(user_age > myage) print("your are older than me") elif(user_age == myage) print(" you and my are same age) else(user_age < myage print("you are younger than me")
my_name = "siva" my_age = "22" my_percentage = "6.5" if (my_name == siva): print("name: %s","my_name") if (my_age == 22): print("age: %d","my_age") if (my_percentage = "6.5") print("percentage %f","my_percentage")
import nltk import string from nltk.collocations import ngrams #words = nltk.word_tokenize(my_text) #my_bigrams = nltk.bigrams(words) #my_trigrams = nltk.trigrams(words) bigramslist = [] trigramslist = [] with open("Penfed_updated.txt", encoding = "utf-8") as file: for line in file.readlines(): ...
# Домашка """ - делать все на функциях - должно работать со всеми Iterable: списки, генераторы, проч. - по возможности возвращать генератор (ленивый объект) - тесты на pytest + pytest-doctest, покрыть как можно больше кейсов - в помощь: itertools, collections, funcy, google """ from typing import Iterable from colle...
class ChessBoard: def __init__(self): self.board = [[1] * 8 for i in range(8)] rook = Rook("R", []) self.board.insert(rook, [0][0]) def show(): print(self.board) class Piece: # TODO: Most likely create a class for each different piece inheriting Piece class # Then ...
""" Case014: decompose a number to prime factors. For example, input 90, output 90=? """ def decomposeNumber(number, list:list): for i in range(2, number+1): if number%i == 0: list.append(i) if int(number/i) == 1: return list if len(list)>1 else [1, list[0]] ...
""" If add an integer I with 100, the result is a perfect square. And the result plus 168 can equal another perfect square. What is the number? """ import math I = 0 while (I+1)**2-I**2 <= 168: I+=1 for i in range((I+1)**2): if (i+100)**0.5-math.floor((i+100)**0.5)==0 and (i+100+168)**0.5-math.floor((i+...
from sys import exit import pyglet class Notification: """ A simple notification on the top right border. It needs a background image, 'notification.png', which is 150x50 in size. To use, do the following in the window class: 1. Add a list 'self.notifications' 2. Add the following 2 methods...
#!/usr/bin/env python import wx # The CoolerFrame in this lesson is similar to the last lesson with a few additions. # But the main program is different. # Be sure you run the program to see what it does class CoolerFrame(wx.Frame): # Remember __init__ is the constructor function. It sets up or "initializes" the new...
# 5203.py 베이비진 게임 def is_babygin(i, c): if c[i] == 3: # run return True # triplet if -1 < i - 1 and c[i - 1]: if -1 < i - 2 and c[i - 2]: return True # i-2,i-1,i elif i + 1 < 10 and c[i + 1]: return True # i-1,i,i+1 if i < 8 and c[i + 1] and c[i + 2]: ...
# 부분집합 생성 코드 예제) 교재에서! arr = [3, 6, 7, 1, 5, 4] n = len(arr) # n: 원소의 개수 for i in range(1<<n) : # 1<<n: 부분집합의 개수 for j in range(n+1): # 원소의 수만큼 비트 비교 if i & (1<<j): # i의 j번째 비트가 1이면 j번째 원소 출력 print(arr[j], end=", ") print()
#reduce #reduce(func_name,iterable_obj) from functools import reduce fac= lambda a,b:a*b li = [1,2,3,5] mul= reduce(fac,li) #1*2*3*5=30 maxi= reduce(lambda a,b:a if a>b else b , li) #passing lambda expression #reduce(max,li) print('sum of li: {}'.format(mul),end=' and ') print('maximum element: {}'.format(maxi))
#project #stone_paper_scissor #python import random def gameplay(): dic={ 1:'Stone', 2:'Paper', 3:'Scissor'} print('\n\nYour play') for i in dic: print(i,' ',dic[i]) op= int(input()) print('You choose: ',dic[op]) keys=list(dic.keys()) bot= random.choice(keys) print('Bot choose: ',dic[bot],end='\n') print(...
def find_fac(num): if num == 1: result = 1 return result else: result = num * find_fac(num - 1) return result def main(): num = int(input("Enter the number: ")) result = find_fac(num) print("Factorial is: ", result ) if __name__ == "__main__": main()
#Question 1 import math print(math.pi) #Question 2 x = 5 for i in range(x): x = x + i print(x, end=" ") #Question 5 text = "Enjoy the test" result = text.strip().split()[0] print("\n" + result) #Question 6 def fn(x, y): z = x + y print(fn(1, 2)) #Question 10 try: x = int("zero") print(10 / x) e...
import re """ A Utility class to provide means to test the validity of keys and values in the received payload. """ class ComplianceChecks: def __init__(self, payload): """ Constructor for the compliance check class Parameters ---------- payload : the customer information...
#!/usr/bin/env python # # Author: Ying Xiong. # Created: Mar 18, 2014. """Utility functions for quaternion and spatial rotation. A quaternion is represented by a 4-vector `q` as:: q = q[0] + q[1]*i + q[2]*j + q[3]*k. The validity of input to the utility functions are not explicitly checked for efficiency reasons....
# 2. Для списка реализовать обмен значений соседних элементов, # т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. # При нечетном количестве элементов последний сохранить на своем месте. # Для заполнения списка элементов необходимо использовать функцию input(). count = 0 x = 0 a = "" my_list ...
#Importing the Libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the Dataset dataset = pd.read_csv('Academic_Data.csv') #Create the matrix of features and Dependent Variables vector X = dataset.iloc[:, :-1].values #creating the dependent variable vector y = dataset.iloc[:, 1...
# Input the number N = int(input()) max1 = result = 0 # Counting consecutive 1 when converting the number to binary while N > 0: if N % 2 == 1: result += 1 if result > max1: max1 = result else: result = 0 N = N//2 print(max1)
# Reverse import random import sys WIDTH = 8 # Game field has 8 cells in width. HEIGHT = 8 # Game field has 8 cells in height. def drawBoard(board): # Display game field, don't return anything. print(' 12345678') print(' +---------+') for y in range(HEIGHT): print('%s|' % (y+1), end='') for x in range(WIDTH):...
''' 3.1 运算符 做除法返回的是浮点数,并且都是向下取整 //为整除,所以返回的是整数部分,并不是整数类型。当除数与被除数有为浮点数 的时候 返回的是整数部分的浮点数 取余也是先遵循向下取整的规则,divmod(x//y, x%y)-->divmod(商,余数) ''' # 1.算术元运算符 print(10/3) # 3.3333333333333335 a = divmod(10, 3) # Return the tuple (x//y, x%y) print(a) b = 0.1 + 0.1 + 0.1 - 0.3 print(b) ...
''' 练习1.请搭建一个逻辑管理系统 1. 需要用户输入姓名,身份证号码以及电话号码 2. 如果用户选择打印输入信息,则打印输出“欢迎***同学加入逻辑教育, 您的身份证号是***,您的电话是***。我们将诚心为您服务。”否则输出 “感谢您使用该系统。”(注意这一块会使用到简单的条件判断语句,根据 课堂上讲解的知识够用,字符串拼接可以使用多种方式) 练习2.花式打印 输出**有**辆车子;但他只能开**辆 注意:这两句话通过一个print()的参数,使其进行换行输出(至少两种方式) ''' # name = input("请输入您的姓名") # ID_number = input("请输入您的身份证号码")...
# 4. 线程同步, condition ''' 天猫精灵:小爱同学 小爱同学:在 天猫精灵:现在几点了? 小爱同学:你猜猜现在几点了 ''' import threading class XiaiAi(threading.Thread): def __init__(self, cond): super().__init__(name="小爱同学") # self.lock = lock self.cond = cond def run(self): with self.cond: p...
# 1. "ax" < "xa"是True if "ax" < "xa": print('True') else: print('False') # 2. 如果输入666,输出: if 执行了 # if "666" == "Yes": # print('1') # else: # print(0) # temp = input("请输入:") # if temp == "YES" or "yes": # 非空字符串都是True,左边是False右边是True # print("if 执行了") # else: # print("else执行了") ...
# @ Time : 2020/1/2 # @Author : JiaJia # 3.with 语句 try: f = open('test.txt', 'w') # print("code") raise KeyError except KeyError as e: print('Key Error') f.close() except IndexError as e: print("IndexError") f.close() except Exception as e: print(e) f.close() f...
''' 1.用户输入哪一个页面,我就去跳转到那个页面 getattr() getattr(x, 'y') is equivalent to x.y. # res = getattr(views,'signin') # views.signin # res() hasattr() setattr() delattr() ''' # import views # # # def run(): # ipt = input("请输入您要访问的页面:").strip() # signin-->print("登录页") # # ipt() # signin() # if hasatt...
#1. *args,**keargs 参数是什么? '''python中规定参数前带 * 的,称为可变位置参数,通常称这个可变位置参数为*args。 *args:是一个元组,传入的参数会被放进元组里。 python中规定参数前 带 ** 的,称为可变关键字参数,通常用**kwargs表示。 **kwargs:是一个字典,传入的参数以键值对的形式存放到字典里。''' # def add(*args): # sum = 0 # for i in args: # sum = sum + i # print(sum) # add(1,2,4) # # def dic(**kwa...
class A: def __init__(self): print('A') class B(A): def __init__(self): print('B') # python 2 # super(B, self).__init__() super().__init__() # 1. 重写了B的构造函数 为什么还要去调用super # 数据冗余 # b = B() class People(object): def __init__(self, name, age, weight):...
# if True: # a = 5 # # print(a) # # for i in range(3): # print('hello world') # # print(i) # 2 # # # def test(): # # 局部变量 只能在函数体内部使用 # b = 5 # return b # # # b = test() # 5 # print(b) # name 'b' is not defined # a = 200 # global # # # def tes...
import time ''' 避免重复造轮子 ''' # def test2(): # start = time.time() # print("----1----") # time.sleep(1) # end = time.time() # print("花了{}".format(end-start)) # # def test3(): # start = time.time() # print("----1----") # time.sleep(1) # end = time.time() # print("花了{...
''' 5.线程间通讯--多线程共享全局变量 5.1 修改全局变量一定要加global吗 修改了指向,id变了,就需要加global += 是不会修改指向的,但是数据是不可变类型,所以一定会变 a = a+[] 会修改指向 ''' import threading import time # num = 100 # lis = [11, 22] # # def demo(): # global num # num += 100 # # # def demo1(): # lis.append(33) # # def demo2(): # glob...
# -*- coding: utf-8 -*- from tkinter import * class adress: def __init__(self): self.label = Label(window, text="Ваш адрес:", font="Arial 14", bg="yellow") self.text = Entry(window,width=20,bd=3) self.label1 = Label(window, text="Комментарий:", font="Arial 10") self.text...
import os import csv # Variables needed: # total number of months included in the dataset # total net amount of "Profit/Losses" over the entire period #The average change in "Profit/Losses" btw months over the entire period #The greatest increase in profits (date and amt) over the entire period #The greatest decre...
n = int(input("Enter a number = ")) fact = 1 for i in range(n,1,-1): fact = fact * i print("Factorial = ",fact)
""" List Operations """ z = [1,12,33,4,5,5] print(z) z.sort(reverse=True) print(z) print(z.count(5)) z = ["C","c","a","A","b","B"] z.sort() print(z) z.sort(reverse=True) print(z) z.sort(key=str.lower) print(z) z = [1,12,33,4,5,5] z.reverse() print(z) z.append("and so on") z.append([33,22,11]) print(z) z = [1,12,33,4,5,...
""" set operations """ z = {1,2,3,3,2,1,2,3} print(z) x = {1,2,3} y ={4,5,6,2,3} print(x|y) # Union print(x&y) # Intersection print(x-y) # remove y duplicte elements print(y-x) # remove x duplicte elements y ={4,5,6,2,3} y.add(7) print(y) y.remove(7) print(y) y.pop() #pops first element print(y)
from sklearn.feature_extraction.text import CountVectorizer from sklearn.metrics.pairwise import cosine_similarity import pandas as pd import numpy as np import pickle from sklearn.externals import joblib def get_title_from_index(index): return df[df.index == index]["title"].values[0] def get_index_from_title(ti...