text
stringlengths
37
1.41M
# -*- coding:utf-8 -*- # 把变量从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling # 局限:只能用于python,并且可能不同版本的Python彼此都不兼容 # dumps():把任意对象序列化成一个bytes //dump(),直接把对象序列化后写入一个file-like Object: # loads(): 把序列化的对象反序列化写入内存 //load(),从一个file-like Object中直接反序列化出对象 import pickle d = dict(name='Bob', age=20, score=88) print(pickle.dumps(d)...
#Lynijah Russell #Challenge! # Program that shows Fibonacci numbers up to 100th term. count = 0 numOfTerms=100 number1, number2 = 0, 1 print("Fibonacci sequence:") while (count < numOfTerms): print(number1) counting = number1 + number2 number1 = number2 number2 = counting count += 1
###1 ## ##def what_day_is_it(x): ## if x==0: ## print("Today is Sunday") ## elif x==1: ## print("Today is Monday") ## elif x==2: ## print("Today is Tuesday") ## elif x==3: ## print("Today is Wednesday") ## elif x==4: ## print("Today is Thursday") ## elif x==5: ## ...
# The following is/are string manipulation name = "My Name is Jesh Amera Founder and CEO of GMN" print(name) print(name.lower()) print(name.upper()) print(name.upper().isupper()) print(name.upper().islower()) print(len(name)) print(name.index("J")) print(name[10:22]) print(name.replace("GMN", "Grand Media Network")) ...
#!/usr/bin/python3 import math # Define the function f = lambda x : x*math.log(x) a = 1.0 # from b = 2.0 # to n = 4 # number of points -1 h = (b - a) / n odd_sum = 0.0 even_sum = 0.0 # Summing the f(x_{2j}), ie the even j numbers for j in range(2, n-1, 2): even_sum += f(a + j*h) # Summing the f(x_...
# -*- coding: utf-8 -*- """ Created on Tue Mar 26 15:00:00 2019 @author: sachin0922 """ class Greeter(object): lastName="" def __init__(self,name): self.name=name self.lastName=" Champ" def sayHi(self): print("Hi "+self.name+self.lastName) def sayBye(self): ...
def two_sum(list, k): subtracted = set() # we create a set containing all possible k - num # since we are looking for a num in list that fulfills # num + x = k we can store all possible k - num # then, if another num2 = k - num we know that num + num2 = k for num in list: if num in subtracted: return Tr...
from collections import defaultdict def processInstructions(filename): '''Takes in a file with instructions in the form 'reg op value if reg comparison value'. Executes the operations and returns the maximum register value at the end of the program, and the maximum register value ever reache...
def minMaxChecksum(filename): '''Reads in a file containing lines of numeric values seperated by whitespace. Returns a 'checksum' found by summing the difference between the max and the min value in each row''' with open(filename, 'r') as f: lines = f.read().splitlines() rows = [co...
# for i in range(10): # if i == 4: # continue # print(i) # 函数/方法,自定义方法 def checkname(username): """ 自动判断账号长度时5-8位,且账号必须以小写字母开头 """ if len(username)>=5 and len(username)<=8: if username[0] in "qwertyuioplkjhgfdsazxcvbnm": print(ok) else: print("账...
# indexing/slicing in numpy array import numpy as np arr = np.array([[-1, 2, 0, 4], [4, -0.5, 6, 0], [2.6, 0, 7, 8], [3, -7, 4, 2.0] ]) print('Initial Array: ') print(arr) sliced_arr = arr[:2, ::2] print('Array with first two rows ' 'and alternate ...
import random def num_guess(): print("Guess a number between 1 and 100 inclusive.") randNum = random.randint(1,100) counter = 0 while True: try: numGuess = int(input("> ")) except: print("Please enter an integer.") break counter += 1 if numGuess < 1 or numGuess > 100: print('Please enter a val...
import random numberofGuesses = 0 number = random.randint(1,100) name = raw_input("Hello! Who are you? ") print (name + ", I have random numbers between 1 to 100. Can you guess what number it is?") while numberofGuesses < 10: guess = raw_input("Take a guess") guess = int(guess) numberofGuesses += 1; gue...
import random guess_num = random.randint(1,50) user_guess =input("what number did you guess?") while (int(user_guess) != guess_num): print("Ouch!it's wrong") if(int(user_guess) > guess_num): print ("Guess is high") user_guess =input("Will you try guessing again?") elif(int(user_guess) < gue...
# -*- coding: utf-8 -*- """ Created on Fri Jul 13 19:48:06 2018 @author: ntf-42 """ class Enemy: life = 3 def attack(self): print('ouch') self.life -= 1 def checkLife(self): if self.life <= 0: print("dead") else: print(str(self.life)) ...
# 1. Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем. Об # окончании ввода данных свидетельствует пустая строка. try: with open(r'files/task1.txt', "w", encoding='utf8') as task1: while True: string = input( "Введите строку дл...
# 5. Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает # фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки). Выведите соответствующее # сообщение. Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение пр...
# Jaden Smith, the son of Will Smith, is the star of # films such as The Karate Kid (2010) and After Earth # (2013). Jaden is also known for some of his philosophy # that he delivers via Twitter. When writing on Twitter, # he is known for almost always capitalizing every word. # For simplicity, you'll have to capi...
# template for "Stopwatch: The Game" import simplegui # define global variables counter = 0 stop_time = 0 suc_time = 0 is_run = False # define helper function format that converts time # in tenths of seconds into formatted string A:BC.D def format(t): #pass int_D = t % 10 int_BC = t // 10 if int_BC >=...
# class Employee: # pass # emp=Employee() # em2=Employee() # emp='lohit' # em2='susumu terashi' # print(emp) # print(em2) # print('________________________') # # emp="Lohit" # print(emp) # print('________________________') # class Person: # pass # name=Person() # email=Person() # address=Person() # phon...
def lohit(dictionary): for key,val in dictionary.items(): print(f'Im a {key} and this is {val}') lohit_pgram= {} while True: lohit_name= input('enter name of programming') lohit_frame=input('enter the name of frame work') lohit_pgram[lohit_name]=[lohit_frame] another=input('add another pr...
def belt_count(dictionary): belts = list(dictionary.values()) for belt in belts: num = belts.count(belt) print(f'there are {num} {belt} belts ') lohit_belts = {} while True: lohit_program = input('enter name of belt :') lohit_frame = input('enter the name of belt color: ') lohit_b...
# this program is to increase the number of empployees each time the new emp is add class emplpyee: add_emp=0 increase=2 def __init__(self,pay,name,age): self.pay=pay self.name=name self.age=age emplpyee.add_emp+=1 def fullname(self): return '{} {}'.format(s...
# name=input('hello is from me:') # age=input('my age is:') # variabe=mane # print(name, age,variabe) # print(name+age) # print("helllo") name=input('tell me your name:') age=input(' and you are age is :') print("hello there" + name , "and your age is", age, 'this')
def main(): print("Python Guessing Game") print("====================\n") ans = "zebra" while True: print("I'm thinking of an animal.\n") guess = input("Enter the name of an animal: ").strip().lower() if guess == ans: print("\nCongratulations, you win!") f...
"""lambdata - helper functions for cleaning dataframes""" import pandas as pd import numpy as np from sklearn.model_selection import train_test_split def null_count(df): """ Returns total amount of null values in the DataFrame. """ nulls = df.isnull().sum() return nulls def tra...
#!/usr/bin/python from Crypto.Cipher import AES # import AES Chiper Algorithm from termcolor import cprint #import cprint to print text with colors from Crypto.Util import Counter #import Counter to use in CTR AES mode. file_to_save = raw_input("[~]Please enter file name to save the cipher text >> ") #file to save the ...
class Dog: paws = 4 def __init__(self, name, age): self.name = name self.age = age @classmethod def bark(cls, times): print('The dog barks {} times and has {} paws'.format( times, cls.paws)) @staticmethod def get_description(): return 'Собака - млекопита...
import math class Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return '({}, {})'.format(self.x, self.y) p1 = Point(-2, 2) p2 = Point(5, 5) class Line(Point): delta_x = -3 # сдвиг всего отрезка по оси ОХ: если значение положительное - вправо, отрицател...
from random import randint opciones = { 1: 'Piedra', 2: 'Papel', 3: 'Tijeras' } rival = opciones[randint(1, 3)] miOpcion= input() if miOpcion=='Piedra': if rival=='Piedra': print("EMPATE, Rival: {}".format(rival)) if rival=='Papel': print("GANA EL RIVAL, Rival: {}".format(rival)) if rival=='...
# connect4.py # --------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to Clemson University and the authors. # # Authors: Pei Xu (pei...
# Multiple Linear Regression # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, -1].values print(X) # Encoding categorical data from sklearn.compose impor...
class Tool(object): # 使用赋值语句定义类属性,记录创建工具对象的总数 count = 0 def __init__(self,name): self.name = name # 让类属性的值+1 Tool.count += 1 @classmethod def tool_show_count(cls): print("创建了%d"%Tool.count) print("创建了%d"%cls.count) # 1.创建工具对象 tool1 = Tool("斧头") tool2 = Tool("榔头") tool3 = Tool("水桶") Tool.tool_show_co...
class Dog(): # __init__ 叫初始化化方法 魔法方法(系统方法) def __init__(self,new_name): # 属性 self.name = new_name def print_self_name(self): print(self.name) def print_self_color(self,color): return color dog1 = Dog('张三') dog1.print_self_name() dog1.color = "yellow" print(id...
class Car(): def move(self): print('移动') def stop(self): print('停止') bwm = Car() bwm.move() bwm.stop() print('*'*20) bc = Car() bc.move() bc.stop() print('*'*20) qq = Car() qq.move() qq.stop()
class SweetPotato(object): """烤地瓜类""" def __init__(self): # 这个属性是地瓜的生熟程度 self.cookedLever = 0 # 返回给用户的字符串 self.cookedString = "生的" # 地瓜的配料列表 self.condiments = [] def __str__(self): msg = "" if len(self.condiments) >0: for...
from datetime import datetime data = [] with open('/home/pi/Programming/AdventOfCode/2020/Day10/test_input_short.txt','r') as f: data = [int(i.strip()) for i in f.readlines()] data.append(0) data.sort() volt_dict = {1:0,3:1} # 3:1 exists because our phone has a default +3 setting previous_voltage = 0 for ...
import time def set_up(data): nodeA = Node(data[0]) prevNode = nodeA lastNode = None for i in range(1,len(data)): newNode = Node(data[i]) prevNode.right = newNode prevNode = newNode lastNode = newNode lastNode.right = nodeA nodeA.left = lastNode return nodeA ...
import math directions = { 'E':{ 'move':(1,0), 'degrees':90 }, 'W':{ 'move':(-1,0), 'degrees':270 }, 'N':{ 'move':(0,-1), 'degrees':0 }, 'S':{ 'move':(0,1), 'degrees':180 } } directions_two = { 'E':{ 'move':...
xiaoming_dic = {"name": "小明", "age": 18, "gender": True, "height": 1.75} # 1、从字典中取值 print(xiaoming_dic["name"]) # 2、增加/修改 xiaoming_dic["age"] = 19 xiaoming_dic["name1"] = "小小明" # 3、删除 xiaoming_dic.pop("name") # 统计键值对数量 print(len(xiaoming_dic)) # 合并字典 temp_d...
# -*- coding: utf-8 -*- """ Created on Mon Feb 10 01:12:01 2020 @author: Logan Rowe Given an array of integers, find the maximal absolute difference between any two of its adjacent elements. Example For inputArray = [2, 4, 1, 0], the output should be arrayMaximalAdjacentDifference(inputArray) = 3. Input/Output [...
# -*- coding: utf-8 -*- """ Created on Thu Feb 27 23:56:31 2020 @author: Logan Rowe Given two arrays of integers a and b, obtain the array formed by the elements of a followed by the elements of b. Example For a = [2, 2, 1] and b = [10, 11], the output should be concatenateArrays(a, b) = [2, 2, 1, 10, 11]. Input/O...
# -*- coding: utf-8 -*- """ Created on Mon Feb 10 01:03:45 2020 @author: Logan Rowe Call two arms equally strong if the heaviest weights they each are able to lift are equal. Call two people equally strong if their strongest arms are equally strong (the strongest arm can be both the right and the left), and so are ...
# -*- coding: utf-8 -*- """ Created on Mon Feb 10 00:57:59 2020 @author: Logan Rowe Given a string, find out if its characters can be rearranged to form a palindrome. Example For inputString = "aabb", the output should be palindromeRearranging(inputString) = true. We can rearrange "aabb" to make "abba", which is a...
# -*- coding: utf-8 -*- """ Created on Mon Feb 10 23:39:18 2020 @author: Logan Rowe Given an array of equal-length strings, you'd like to know if it's possible to rearrange the order of the elements in such a way that each consecutive pair of strings differ by exactly one character. Return true if it's possible, an...
# -*- coding: utf-8 -*- """ Created on Wed Feb 12 14:23:10 2020 @author: Logan Rowe Given a string, return its encoding defined as follows: First, the string is divided into the least possible number of disjoint substrings consisting of identical characters for example, "aabbbc" is divided into ["aa", "bbb", "c"] N...
# -*- coding: utf-8 -*- """ Created on Sun Feb 9 17:24:15 2020 @author: Logan Rowe Given an array of strings, return another array containing all of its longest strings. Example For inputArray = ["aba", "aa", "ad", "vcd", "aba"], the output should be allLongestStrings(inputArray) = ["aba", "vcd", "aba"]. Input/Ou...
# -*- coding: utf-8 -*- """ Created on Thu Feb 27 23:58:56 2020 @author: Logan Rowe Remove a part of a given array between given 0-based indexes l and r (inclusive). Example For inputArray = [2, 3, 2, 3, 4, 5], l = 2, and r = 4, the output should be removeArrayPart(inputArray, l, r) = [2, 3, 5]. Input/Output [exe...
# -*- coding: utf-8 -*- """ Created on Mon Feb 10 22:09:37 2020 @author: Logan Rowe Check if all digits of the given integer are even. Example For n = 248622, the output should be evenDigitsOnly(n) = true; For n = 642386, the output should be evenDigitsOnly(n) = false. Input/Output [execution time limit] 4 seconds...
# -*- coding: utf-8 -*- """ Created on Mon Feb 10 00:22:32 2020 @author: Logan Rowe Given a rectangular matrix of characters, add a border of asterisks(*) to it. Example For picture = ["abc", "ded"] the output should be addBorder(picture) = ["*****", "*abc*", ...
# -*- coding: utf-8 -*- """ Created on Sun Feb 16 13:09:37 2020 @author: Logan Rowe You are given an array of up to four non-negative integers, each less than 256. Your task is to pack these integers into one number M in the following way: The first element of the array occupies the first 8 bits of M; The second el...
# -*- coding: utf-8 -*- """ Created on Tue Feb 11 17:31:25 2020 @author: Logan Rowe Given the positions of a white bishop and a black pawn on the standard chess board, determine whether the bishop can capture the pawn in one move. The bishop has no restrictions in distance for each move, but is limited to diagonal...
# -*- coding: utf-8 -*- """ Created on Fri Feb 28 23:40:11 2020 @author: Logan Rowe Find the number of ways to express n as sum of some (at least two) consecutive positive integers. Example For n = 9, the output should be isSumOfConsecutive2(n) = 2. There are two ways to represent n = 9: 2 + 3 + 4 = 9 and 4 + 5 = ...
# -*- coding: utf-8 -*- """ Created on Tue Feb 11 17:19:34 2020 @author: Logan Rowe Given a string, output its longest prefix which contains only digits. Example For inputString = "123aa1", the output should be longestDigitsPrefix(inputString) = "123". Input/Output [execution time limit] 4 seconds (py3) [input] ...
# -*- coding: utf-8 -*- """ Created on Thu Feb 6 00:03:30 2020 @author: Logan Rowe Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return...
#!/bin/python import os #The fields are separated by commas (hence the "csv" suffix on the filename: csv stands for Comma Separated Values) #Print out the gene names for all genes from the species Drosophila melanogaster or Drosophila simulans. #Print out the gene names for all genes that are between 90 and 110 bases...
n1 = int(input("Digite um numero: ")) n2 = int(input("Digite outro numero: ")) n3 = int(input("Digite outro numero: ")) resto = ((n3*2)+(n2*3)+(n1*4))%11 resultado = 11 - resto print ('Digito verificador: {}'.format(resultado))
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def getData(self): return self.data def setData(self, newData): self.data = newData def getNext(self): return self.next def setNext(self, ne...
#Required modules have been imported import math as mt from scipy.special import lambertw import warnings #Function to check which radius is to be chosen from two radii according to critical radius def rad_check_condition(r1,r2,critical_radius): if (((r1<critical_radius)and(r2<critical_radius))or((r1>critica...
number = 23 running = True while running: guess = int(input('Введите целое число')) if guess == number: print('Поздравляю вы победили') running = False elif guess < number: print('Число немного больше этого') else: print('Число меньше заданного') else: print('Цикл Wh...
you = "hello" if you == "": roobot_brain = "I can't hear you, try again" elif you == "hello": roobot_brain = "Hello Su" elif you == "today": roobot_brain = "thu 6" else: roobot_brain = "I'm fine thank you and you" print(roobot_brain)
import random; def GenerateRandomKey (numberOfElements, minValue, maxValue) : randomList = []; while len(randomList) <= numberOfElements-1 : randomElement = random.randint(minValue, maxValue); if randomElement in randomList : continue; randomList.append(randomElement);...
#Question - https://leetcode.com/problems/binary-tree-paths class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: if root is None: return [] def helper(root,curr_list,result): if root is None: return curr_...
#Question - https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/570/week-2-december-8th-december-14th/3563/ class Solution: def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode: def getDepthAndTargetSubtree(root): if not root: return (0, None) ...
class TreeNode: def __init__(self, key): self.left = None self.right = None self.val = key def is_bst(root): print(root.val) if root: if root.left and root.val<root.left.val: return False if root.right and root.val<root.right.val: return False if is_bst(root.left)==False or is_bst(root.rig...
#Question - https://leetcode.com/problems/design-parking-system class ParkingSystem: def __init__(self, big: int, medium: int, small: int): self.big=big self.medium=medium self.small=small def addCar(self, carType: int) -> bool: if carType==1 and self.big>0: self.b...
class Solution: def reverseWords(self, string): ans='' arr=string.split(' ') for word in arr: ans+=word[::-1]+' ' return ans print(Solution().reverseWords("The cat in the hat")) # ehT tac ni eht tah
""" Solution to the Word Search Problem -> https://leetcode.com/problems/word-search/ Solution is very similiar to the Gold Mine Based on backtracking and recursion Return True if solution is found """ class Solution: def exist(self, board: List[List[str]], word: str) -> bool: ans=False ...
#Question - https://leetcode.com/problems/prime-palindrome/ class Solution: def primePalindrome(self, N: int) -> int: if N<=2: return 2 def isPalidrome(n): for i in range(len(n)//2): if n[i]!=n[len(n)-i-1]: return False ...
""" Explanation Approach 1 - Store left elements and right elements in two different lists check for the occurence of each number till it satisfy the conditions """ class Solution: def findJudge(self, N: int, trust: List[List[int]]) -> int: if (N==1): return N """ Approach 1- ...
x = input("Enter a string") y = input("Enter a string") z = input("Enter a string") for i in range(10): print("This is some output from the lab ",i) print("Your input was " + x) print("Your input was " + y) print("Your input was " + z)
class LNode: """ 定义链表对象 """ def __init__(self, x): self.data = x self.next = None """ 题目描述: 将Head->1->2->3->4->5->6->7->8逆序 为head->8->7->6->5->4->3->2->1 方法:就地逆序 """ def NofirstNodeReverse(head): if head is None or head.next is None: return cur = None pre = None next = None #处理第一个节点 ...
#队列:入队列、出队列、查看队列首尾元素、查看队列是否为空、查看队列大小等功能、清空队列。先进先出 #方法:链表实现 #front指向队列首,rear指向队列尾 #新元素加在链表尾部,出队列时将第一个节点的值返回并删掉该节点 class LNode: def __init__(self,arg): self.data=arg self.next=None class MyQueue: #模拟队列 def __init__(self): #phead=LNode(None) self.data=None self.next=None self.front=self#指向队列首 ...
""" 给定一个数组[3,4,7,10,20,9,8],可以找出两个数队(3,8),(4,7)=>3+7=8+4 """ import random class Pair: """docstring for pair""" def __init__(self,first,second): self.first=first self.second=second def findPairs(arr): Dict={} i=0 n=len(arr) while i<n: j=i+1 while j<n: pair=Pair(arr[i],arr[j]) sum=...
class SqQueue(object): def __init__(self, maxsize): self.queue = [None] * maxsize self.maxsize = maxsize self.front = 0 self.rear = 0 """ ------------------ 队列的存储结构中使用的最多的是循环队列。循环队列包括两个指针, front 指针指向队头元素, rear 指针指向队尾元素的下一个位置。 队列为空的判断条件是: front ==...
import random class LNode: def __init__(self,arg): self.data=arg self.next=None """ 题目描述: 给定链表Head->1->1->3->3->5->7->7->8 单链表倒数第k=3个元素为7 要求: 方法:建立两个指针slow和fast,fast先于slow k步,当fast指向链表最后一个元素时,slow刚好指向倒数第k个元素 """ def creatLink(x): i = 1 head = LNode(None) tmp = None cur = head while i <= x: ...
import random class LNode: def __init__(self,arg): self.data=arg self.next=None """ 题目描述: 给定链表Head->1->2->3->4->5->7->7->8 反转为链Head->2->1->4->3->7->5->8->7 要求: 方法:建立两个指针slow和fast,fast比slow快一步,步长均为2,两个一组,在pre和next进行交换。 """ def creatLink(x): i = 1 head = LNode(None) tmp = None cur = head whil...
import os import csv filename = "budget_data.csv" #open and read csv with open(filename) as csvfile: csvreader = csv.reader(csvfile,delimiter=",") #skip the headers next(csvreader) #create an empty list to store the date months=[] #create a variable to store the net_total net_total ...
class HuffmanFactory: """Class used to create a Huffman tree and compress the input text based on that huffman tree. >>> import HuffmanCompression >>> sample_input = "sample" >>> huff = HuffmanCompression.HuffmanFactory(sample_input) >>> print(huff.compressed_string) 1001010100111110 ...
import psycopg2 def db_get_connection(): """ Return a database connection or None if error occurs """ try: connection = psycopg2.connect(user="duong", password="P@ssw0rd", host="127.0.0.1", port="5432", ...
import random import math def fill(minsize, maxsize, constant, random_on_x = False, random_range = 10) -> set: size = random.randint(minsize, maxsize) answer = set() while len(answer) < size: random_value = random.randint(0, random_range) if random_on_x: value = (random_val...
from Cell import Cell class Path: def __init__(self, begin_cell : Cell, reversed_direction = False): pass self.instructions = [] temp = begin_cell self.add_node(begin_cell, reversed_direction) while temp.previous is not None: self.add_node(temp.previous, reverse...
def partition(A, p, r): x = A[r] i = p-1 for j in range(p, r): if A[j] <= x: i = i + 1 temp = A[i] A[i] = A[j] A[j] = temp temp = A[i+1] A[i+1] = A[r] A[r] = temp return i + 1 def quicksort(A, p, r): if p < r: q = partit...
def check_pass(password): double_number = False for i in range(1, len(password)): if password[i - 1] > password[i]: return False if password[i - 1] == password[i]: double_number = True return double_number def check_pass_not_in_quad(password): double_number = [...
''' Description: Version: 1.0 Author: hqh Date: 2021-05-11 10:31:13 LastEditors: hqh LastEditTime: 2021-05-11 10:51:04 ''' # # @lc app=leetcode.cn id=653 lang=python3 # # [653] 两数之和 IV - 输入 BST # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=N...
''' Description: Version: 1.0 Author: hqh Date: 2021-05-15 23:13:08 LastEditors: hqh LastEditTime: 2021-05-15 23:26:14 ''' # # @lc app=leetcode.cn id=705 lang=python3 # # [705] 设计哈希集合 # # @lc code=start class MyHashSet: def __init__(self): """ Initialize your data structure here. """ ...
''' Description: Version: 1.0 Author: hqh Date: 2021-05-10 00:09:34 LastEditors: hqh LastEditTime: 2021-05-10 00:36:25 ''' # # @lc app=leetcode.cn id=606 lang=python3 # # [606] 根据二叉树创建字符串 # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): ...
# # @lc app=leetcode.cn id=20 lang=python3 # # [20] 有效的括号 # # @lc code=start class Solution: def isValid(self, s: str) -> bool: st = [] for i in s: if i == '(' or i == '[' or i == '{': st.append(i) if i == ')': if st != [] and st[-1] == '(': ...
def get_next(m, x, y): for next_y in range(y+1, 9): if m[x][next_y] == 0: return x, next_y for next_x in range(x+1, 9): for next_y in range(0, 9): if m[next_x][next_y] == 0: return next_x, next_y return -1, -1 def value(m, x, y): i, j = ...
#! /usr/bin/python3 import time class Timer(): """Usage: with Timer(verbose=True) as t: timing_function() """ def __init__(self, verbose=False): self.verbose = verbose def __enter__(self): self.start = time.time() return self def __exit__(self, exc_type, exc_...
## Hacer un programa que dado un número de DNI obtenga la letra del NIF. ## La letra correspondiente a un número de DNI se calcula mediante el ## siguiente algoritmo: ## a) Se obtiene el resto de dividir el número de DNI entre 23. ## b) El número resultante nos indica la posición de la letra ## correspondient...
# coding = utf-8 class Cliente: def __init__(self, nombre, apellidos, direccion, telefono, nif, saldo=0): self.nombre = nombre self.apellidos = apellidos self.direccion = direccion self.telefono = telefono self.nif = nif self.saldo = saldo def __repr__(self): return self.nombre + " " + self.apellidos ...
# Escribe un programa que pida por teclado el radio de una circunferencia, y que a continuación # calcule y escriba en pantalla la longitud de la circunferencia y del área del círculo. # # Autor: Luis Cifre # # Casos tipo: # # Radio = 5, Longuitud = 2·pi·Radio, Área = pi·Radio^2 import math radio = int(input("Escrib...
#-*- coding: UTF-8 -*- tal = raw_input('Captcha? ') #submit the number given talc = len(tal)/2 q = len(tal) - 1 svar = 0 for i in range(len(tal)): global svar if (i + talc) <= q: if tal[i] == tal[i+talc]: svar += int(tal[i]) else: if tal[i] == tal[i-talc]: ...
"""CSC111 Winter 2021 Assignment 3: Graphs, Recommender Systems, and Clustering (Part 1) Instructions (READ THIS FIRST!) =============================== This Python module contains the modified graph and vertex classes you'll be using as the basis for this assignment, as well as additional functions for you to comple...
num = input() first = 0 second = 0 third = 0 for i in range(0, len(num)): if num[i] == '1': first += 1 elif num[i] == '2': second += 1 elif num[i] == '3': third += 1 x = "1+"*first + "2+"*second + "3+"*third print(x[:-1])
#operacion-INDEXACION_14 # 0 10 20 30 40 # 01234567890123456789012345678901234567890123 str="abcdefghijklmnñopqrstuvwxyz0123456789@#+-*/" #No se que decir print("#"*25) print(" "*7+str.upper()[20]+str.upper()[8]+str.upper()[13]+str.upper()[2]+str.upper()[0]+" "+str.upper()[5] +...
#Ejericicio-ITERACION 08 msg="La serpiente generalmente causa temor en la mayoria" contador_a=0 contador_e=0 contador_i=0 contador_o=0 contador_u=0 for letra in msg: if (letra == 'a'): contador_a+=1 if (letra == 'e'): contador_e+=1 if (letra == 'i'): contador_i+=1 if (letra == '...
-*- coding: utf-8 -*- import pandas as pd from email.parser import Parser def parse_email(row, attribute): email = Parser().parsestr(row['message']) if attribute == 'content': return email.get_payload() else: return email[attribute] def split_email_addresses(line): """To separate m...
import random import random class SimuladorDeDado: def __init__(self): self.valor_minimo = 1 self.valor_maximo = 6 def Iniciar(self): # ler os valores da tela self.eventos, self.valores = self.janela.Read() # fazer alguma coisa com esses valores ...