text
stringlengths
37
1.41M
""" Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110...
""" What is the first term in the Fibonacci sequence to contain 1000 digits? """ import math import unittest def firstFibDigGtr(n): """ Returns the counter of the first Fibonacci number with # digits greater than n """ f1 = 1 f2 = 1 counter = 2 keepGoing = True while keepGoing: f1, f2 = f2, f1 + f2 counte...
""" Starting in the top left corner of a 22 grid, there are 6 routes (without backtracking) to the bottom right corner. How many routes are there through a 2020 grid? """ import unittest def getMatrix(n): """ Returns an (n+1) by (n+1) matrix result of ways to get from result[i,j] to result[-1,-1] for n = 2, sho...
#!/usr/bin/env python # -*- coding: utf-8 -*- from sympy import * #símbolo, função, valor inicial, número de iterações def pfixo (px, pf, x0, it): x = Symbol(px) f = sympify(pf) print ("f(x) =", pf, "\n") for i in range(0, it): print ("Iteração", i+1) fx0 = f.subs(x, x0).evalf() ...
power_cache = {x: x ** 5 for x in xrange(0, 10)} def get_digits(num): digits = [] while (num >= 10): digit = num % 10 num = num / 10 digits.append(digit) digits.append(num) return digits def sum_digit_powers(num_list): total = 0 for num in num_list: total +...
from abc import ABCMeta, abstractmethod class Component(metaclass=ABCMeta): # variable initiation target = None value = 0 speed = 1 # getter and setter methods def set_target(self, target: object = None): self.target = target def get_target(self): return self.target ...
import turtle myPen = turtle.Turtle() myPen.speed(0) myPen.color("black") side=200 for i in range (1,20): myPen.forward(side) myPen.left(90) side=side-10
def is_multiple(x,y): '''is_multiple(x,y) -> bool returns True is x is a multiple of y, False otherwise''' # check if y divides evenly into x return (x % y == 0) def is_prime(n): '''is_prime(n) -> bool returns True if n is prime, False if n is not prime''' # check every divisor from 2 up to...
from Input import name, position, salary class Employee: """ Keep information of employee and their information. """ def __init__(self, name, position, salary): self.name = name self.position = position self.salary = salary def get_employee_name(self): return "Em...
# map(), filter(), and reduce() from functools import reduce # map() my_list = [1, 2, 3, 4] my_list = list(map(lambda num: num * num, my_list)) # Option 2 not use map() my_list = [1, 2, 3, 4] my_list = [num * num for num in my_list] # filter() my_list = [1, 2, 3, 4] my_even_list = list(filter(lambda x: x % 2 == 0, m...
# Abstract class allows us to create methods that must be created within any child class from abc import ABC, abstractmethod # Abstract Base classes(ABC) from typing import List # You can't initiate an abstract class class Animal(ABC): @abstractmethod def eat(self): pass @abstractmethod def...
import random file = open("/usr/share/dict/words") file = file.read() dictionary_words = file.split() def get_random_words(word_count): sentence = "" for i in range(0,words): random_number = random.randint(0, len(dictionary_words)-1) sentence += dictionary_words[random_number] + " " te...
import os class Atbash(object): def __init__(self, msg, oper): self.msg = msg self.oper = oper def ValidateMsg(self): opers = {"ENCRYPT": lambda: Atbash.Encrypt(self), "DECRYPT": lambda: Atbash.Decrypt(self)} for x in range(len(self.msg) + 1): if x < len(self.msg): check = ord(self.msg[x]) if c...
class Encrypt(object): def __init__(self, key, word): self.key = key self.word = word def errors(self, error): print error pause = raw_input() def encrypt(self): if self.key > 25 or self.key == 0: super(Encrypt, self).errors("key must be: > 0 & < 26") else: LAST_LETTER = 90 numericList = [] ...
import sys print ("CALCULADORA") print ("1. Suma") print ("2. Resta") print ("3. Multiplicacion") print ("4. Division") print ("5. Salir") print ("") def suma(): print ("*****SUMA*****") num1 = int(input("Digite el primer numero: ")) num2 = int(input("Digite el segundo numero: ")) resul = num1 + num2 ...
''' Proj - Memory Game CS5001 Fall 2020 Nolen Belle Bryant Function check_button - Will take the x and y coordinates of the click and will return an integer if the click was 'on a card'. The returned int serves as the index # of where the clicked on card is stored in the deck.box area - a list containing tu...
https://www.luogu.org/problemnew/solution/P1909?page=2 import math ans = 1e9 n = int(input()) for i in range(3): num, price = map(int, input().split()) tmp = math.ceil(n / num) * price if tmp < ans: ans = tmp print(ans) from math import ceil n = int(input()) l = (tuple(map(int, input().split())...
#作者:SunnyMarkLiu #链接:https://www.zhihu.com/question/37146648/answer/80425957 #来源:知乎 #著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 #!/usr/bin/python2.7 # _*_ coding: utf-8 _*_ from matplotlib import pyplot as plt from matplotlib import font_manager # 准备数据 def file2matrix(filename): fr = open(filename) arr...
print('let\'s calculate some squares') for the_num in range(13): print(the_num, 'squared is', the_num**2) print('all done') num_hi = int(input('how many times to say hi?')) for dont_matter in range(num_hi): print('hi!')
keep_going = 'y' while keep_going == 'y': sales = float(input('please enter sales')) comm_rate = float(input('please enter rate')) commission = sales * comm_rate print('commission is', commission) keep_going = input('another? (y for yes)')
from time import time def timer(func): """ Timing wrapper for a generic function. Prints the time spent inside the function to the output. """ def new_func(*args, **kwargs): start = time() val = func(*args,**kwargs) end = time() print('Time taken by function {} is {} seconds'.format(func.__name__, end-sta...
def csOppositeReverse(txt): reversedOrder = txt[::-1] reversedCase = reversedOrder.swapcase() return reversedCase print(csOppositeReverse('Hello World'))
#5 A school decided to replace the desks in three classroom. Each desk sits two students. Given the number of students # in each class ,print the smallest possible number of desks that can be purchased # the program should read three integers. the number of students in each of the three classes a, b and c respectively ...
#WAP to check and print if the number is even or odd for i in range(0,10,1) : if i % 2 == 0: print (f"{i} is even") else: print (f"{i} is odd")
d=float(input("how far did you travel today (in miles)?")) t=float(input("how long did it take you (in hours)?")) speed=d//t km=d*1.609 kmph=km//t print(f"your speed was {speed} miles per hour") print(f"your speed was {kmph} km per hour")
''' STEP 1: Choose the number K of neighbors STEP 2: Take the K nearest neighbors of the new data point, according to your distance metric STEP 3: Among these K neighbors, count the number of data points to each category STEP 4: Assign the new data point to the category where you counted the most neighbors ...
class Piece(object): def __init__(self): self.is_king = False def is_king(self): self.is_king = True class RedPiece(Piece): def disp_color(self): if self.is_king == True: color = "KR" else: color = " R" return color class BlkPiece(Piece): ...
#3.Faça um Programa que peça dois números e imprima a soma. # n1 = int(input("Digite um número: ")) n2 = int(input("Digite um número: ")) result = n1+n2 print("A soma dos dois números é: ", result)
""" Tema: Busqueda Binaria. Curso: Pensamiento computacional. Plataforma: Platzi. Profesor: David Aroesti. Alumno: @edinsonrequena. """ objetivo = int(input('Type a number: ')) epsilon = 0.001 bajo = 0.0 alto = max(1.0, objetivo) respuesta = (alto + bajo) / 2 while abs(respuesta**2 - objetivo) >= epsilon: print...
""" Tema: Resolviendo reto. Curso: Python intermedio. Plataforma: Platzi. Profesor: Facundo García Martoni. Alumno: @edinsonrequena. """ def divisor(num): divisor_list = [] for i in range(1, num + 1): if num % i == 0: divisor_list.append(i) return divisor_list def main(): ...
""" Resolviendo Retos alumno: @edinsonrequena """ def squeares(): arr = [i**2 for i in range(1, 101)] # print(arr) def squeares_divisible_3(): # arr = [i**3 for i in range(1, 101) if i % 3 == 0] arr = [i**2 for i in range(1, 101) if i % 3 is False] print(arr) def squeares_par(): # ...
""" Tema: Listas y mutabilidad. Curso: Pensamiento computacional. Plataforma: Platzi. Profesor: David Aroesti. Alumno: @edinsonrequena. """ a = [1, 2, 3] b = a print(b) # Vemos como los elementos de a pasan a estar en b print(id(a)) # Aca podemos ver como a y b estan en el mismo lugar de print(id(b)) # memoria, lo ...
""" Tema: Herencia. Curso: Curso de python, video 30. Plataforma: Youtube. Profesor: Juan diaz - Pildoras informaticas. Alumno: @edinsonrequena. """ class Vehiculo: def __init__(self, marca, modelo): self.marca = marca self.modelo = modelo self.enmarcha = False self.acelera = Fa...
""" Tema: Algoritmos de busqueda y ordenamiento - Ordenamiento por Inserccion. Curso: Pensamiento Computacional, 2da entrega. Plataforma: Platzi. Profesor: David Aroesti. Alumno: @edinsonrequena. """ import random def ordenamiento_por_insercion(lista): for indice in range(1, len(lista)): valor_actual = l...
""" Tema: Manejo de Excepciones. Curso: Python intermedio. Plataforma: Platzi. Profesor: Facundo García Martoni. Alumno: @edinsonrequena. """ def palindrome(string): try: if len(string) == 0: raise ValueError('No se puede ingresar una cadena vacia') return string == string[::-1] ...
""" Tema: Funciones Lambda Curso: Python intermedio. Plataforma: Platzi. Profesor: Facundo García Martoni. Alumno: @edinsonrequena. """ palindrome = lambda string: string == string[::-1] print(palindrome('ana'))
from random import randint from turtle import* #Turtle 1 attributes t = Turtle() t.speed(0) t.hideturtle() #Turtle 2 attributes t2 = Turtle() t2.speed(0) t2.hideturtle() #Drawing the hangman def draw_gallows(): t.penup() t.goto(0,0) t.pendown() t.setheading(0) t.forward(200) ...
import os import csv def txt_to_csv(txtfile, csvfile=None): ''' Convert txtfile to csvfile Params: txtfile : path to txtfile csvfile : path to new csvfile Return : csvfile : path to saved csvfile ''' if csvfile == None: csvfile_name = txtfile.strip().split('/'...
import random def random_y_for(x): min_y = 0 max_y = 10 if x >= 0: min_y = -10 max_y = 0 return random.randint(min_y, max_y) def label_for(x): return 'o' if x < 0 else 'x' def make_random(): x = random.randint(-10, 10) y = random_y_for(x) return (x, y, label_for(...
#if you wanna study 3d graphs, this is the best example on the pc import matplotlib import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import axes3d matplotlib.rcParams["backend"] = "TkAgg" fig = plt.figure() chart=fig.add_subplot(1,1,1, projection="3d") x =[1,2,3,4,5,6,7,8,9] y...
import re import urllib.request url = "http://dictionary.reference.com/browse/" word = input("Enter your word: ") url = url + word data = urllib.request.urlopen(url).read() data1 = data.decode("utf-8") m = re.search('meta name="description" content="', data1) start = m.end() end = start + 300 newString = data...
''' This program is a simple example of Message Box in Tkinter where you can use various types, in this program we only came across (askquestion & showinfo) ''' from tkinter import * import tkinter.messagebox root=Tk() answer=tkinter.messagebox.askquestion("Question","Do you get offended if i use swear words?"...
#creating a colorful graph import matplotlib.pyplot as pp fig = pp.figure() rect = fig.patch rect.set_facecolor("xkcd:mint green") #changes the color of the background/figure x=[2,4,8,9,9] y=[4,7,6,8,7] graph1=fig.add_subplot(1,1,1) graph1.set_facecolor('xkcd:salmon') #changes the color of plot inside grap...
#random rectrangle generator from tkinter import * import random root=Tk() can=Canvas(root,width=400,height=400) can.pack() def rect(num): #num represents number of rectrangles to be printed for i in range(0,num): x1=random.randrange(400) y1=random.randrang...
number = int(input()) word = input() print(word*number)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 3 09:43:39 2019 @author: abhineet """ import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv('winequality-red.csv', delimiter=';') col = data.columns mean = data.mean() for i in col: if i == 'quality': ...
def countSmallerToTheRight(values): """ Codefights.com interview practice question from Google by the same name. My first submission was to bisect a sorted list, which I new had O(n) insertion time complexity. After a search on the internet, I see how I could index in O(log n), I read nneon...
def list_o_matic(list, input_pasado): while list: if input_pasado in list: list.remove(input_pasado) return print("look at the animals:",list) else: list.append(input_pasado) return print("look at the animals:",list) list.pop() return print(lis...
#Task 1 Create Lists # [ ] create team_names list and populate with 3-5 team name strings team_names=["northface", "lasportiva", "redbull", "bestard", "boreal"] # [ ] print the list print(team_names) # [ ] Create a list mix_list with numbers and strings with 4-6 items mix_list=[5, 2.4, "Banana", 1882, "Hola mundo"] # [...
from tkinter import Tk, Text, Menu, filedialog, Label, Button, END, W, E, FALSE from tkinter.scrolledtext import ScrolledText from src.Solver import Solver class Editor(): def __init__(self, root): self.root = root self.file_path = None self.root.title( 'Prolog Interpreter' ) # C...
list_numbers = list(range(15, 25)) count_even = 0 # количество четных чисел for value in list_numbers: # перебираем все числа if value % 2 == 0: count_even += 1 print(count_even)
# Problem name: Special Pythagorean triplet (problem 9) # Problem url: https://projecteuler.net/problem=9 # Author: Thorvaldur Gautsson # Question: # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # # a^2 + b^2 = c^2 # For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. # There exists exactly ...
mass = [int(ind) for ind in input().split()] n = len(mass) def insertion_sort(mass): count = 0 for j in range(1, n): key = mass[j] i = j - 1 while i >= 0 and mass[i] > key: count += 1 mass[i + 1] = mass[i] i -= 1 mass[i + 1] = key return ma...
import matplotlib.pyplot as plt import pandas as pd import numpy as np def plot_dense_sensordata(dense_data, ax=None, show=True, show_missing=False, time=None, text=None, ylabels=True): """view single patient's worse of dense sensordata, a ndarray or df where the columns are: heart_rate, activity_rank, resp_pa...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/2/27 2:30 PM # @Author : huxiaoman # @File : 3_longest_substring_without_repeating_characters.py # @Package : LeetCode class Solution: """ :type s: str :rtype: int """ def lengthOfLongestSubstring(self, s): max_length, sta...
__author__ = 'My' import time import math #Teams are split up between White team and Black team #White team goes first #To start Timer: # 1) create instance of TimerClass (in = TimerClass()) # 2) immediately call startTimer for that instance (in.TimerClass(in)) #A single turn for a team is 20 seconds (15 secon...
from itertools import permutations import sys N = int(sys.stdin.readline()) lst = [(i + 1) for i in range(N)] value = list(permutations(lst, N)) for element in value: element = list(element) print(' '.join(list(map(str, element))))
import sys class circular_linked_list: def __init__(self): self.head = None self.tail = None self.cursor = None def add(self, node): if self.tail: node.next = self.head node.prev = self.tail self.tail.next = node self.head.prev = n...
# -*- coding: utf-8 -*- """ Created on Wed Aug 5 16:32:41 2020 @author: elin9 """ # combination (pick m elements from n elements) def pick(n, picked, m): if (m == 0): print(picked) return if len(picked) == 0 : smallest = 0 else : smallest = picked[-1] + 1 fo...
from collections import deque def bfs(graph, root, length): visited = [-1 for _ in range(length + 1)] count = 0 queue = deque([[root, count]]) while queue: value = queue.popleft() n = value[0] count = value[1] if visited[n] == -1: visited[n] = count ...
# normal output msg = "Hello" print(msg) print(1, 2, 3, "fu", "*") print(" " + "fu" + " ") # dynamic input name = input("Hi , what is you name") print(" Heyy, ", name) # escape chars # line break print(" 1, \n", 2) # or """ indentation print(""" 1 2 3 """) print(""" 1 \ 2 \ """) # tabs 8 chars print("Tab", "\n3\t4") ...
from abc import ABC, abstractclassmethod # Method Overloading # Method Overriding # Duck Typing # Operator Overloading # Duck Typing class PyCharm: @staticmethod def execute(): print("PyCharm") print("Compile") class VsCode: @staticmethod def execute(): print("VsCode") ...
# import module sys to get the type of exception import sys randomList = ['a', 0, 2] for entry in randomList: try: print("The entry is", entry) r = 1/int(entry) break except: print("Oops!", sys.exc_info()[0], "occured.") print("Next entry.") print() print("The r...
cur_max, last1, last2, last3, last4, last5 = 0, 0, 0, 0, 0, 0 x = int(input()) while x != 0: cur_max = max(cur_max, last1) last1, last2, last3, last4, last5 = last2, last3, last4, last5, x x = int(input()) print(cur_max)
"""Draws a spring consisting of n arches of sizes x""" import turtle import math def fn_draw_arch(radius=50, smooth_factor=30): """Will draw a square of size n""" rotation_angle = 180 / smooth_factor move_distance = radius * math.pi / smooth_factor for _i in range(smooth_factor): turtle.forwar...
num1 = int(input()) num2 = int(input()) def highest_common_divisor(a, b): if a < b: a, b = b, a if b == 0: return a else: return highest_common_divisor(a % b, b) print(highest_common_divisor(num1, num2))
import turtle import time import math # Initialize turtle and bring it to start position turtle.shape("turtle") turtle.color("green") turtle.penup() turtle.goto(-150, -150) turtle.pendown() turtle.speed("fast") # End of initialize def draw_dragon_curve(length=300.00, depth=1): if depth == 1: step = leng...
N = 50 arr = [True] * N for k in range(2, N): if arr[k]: for m in range(k+k, N, k): print(f"m is now {m}") arr[m] = False for i in range(N): print(i, "-", "simple" if arr[i] else "complex")
def display_result(result): initial_sorting_based_on_score =sorted(result,key=lambda x:x['score']) # check if we need to active the kickers add_kickers_to_result=check_to_Show_kickers(initial_sorting_based_on_score) # sorting result sorted_result=sorting_result(add_kickers_to_result) # display...
""" Check if two strings begins with the same letter and print True or you print out some words Make your code generic by using the input function Note: uppercases != lowercases M != m Goodluck! e.g Crocodile == Crab Spider == Snake Bee != Cat """
import math a, b, c = float(input()), float(input()), float(input()) d = b**2 - 4*a*c if d < 0: print("Нет решений!") elif a == 0 and b == 0 and c == 0: print("Деление на 0") elif d == 0: print(-b/(2*a)) else: print(((-b + math.sqrt(d))/(2*a)), " ", ((-b - math.sqrt(d))/(2*a)))
from mapcreator import parse_and_create_map from pathfinding import path_between_points, _path_between_points from hashiterator import find_zero_collision_from_salt def all_together(start_x, start_y, end_x, end_y, coordinates_directory, number_of_zeros, temp_filepath='temporary'): """ Takes the files in the coord...
from bs4 import BeautifulSoup html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a...
""" Prometheus: Text-Based Game A person stuck on an island who has to complete tasks in order to get off of it. """ import random import json #https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/ from os import path #https://www.guru99.com/python-check-if-file-exists.html heroXp = 50 wolfXp = -30 fire...
from random import choice def rps_game(): scores = [0,0] choices = ["Rock", "Paper", "Scissors"] while max(scores) < 3: while True: user_choice = input("1. Rock\n2. Paper\n3. Scissors\n\nPlease enter your weapon: ") if user_choice in ["1", "2", "3"]: break ...
def display_board(board): print(board[1]+'|'+board[2]+'|'+board[3]) print(board[4]+'|'+board[5]+'|'+board[6]) print(board[7]+'|'+board[8]+'|'+board[9]) def player_input(): choice = '' while choice != 'X' or choice != 'O': try: choice = input("player 1:Please pick a marker 'X' or 'O' ").upper() if choice...
class Node(object): def __init__(self, key): self.key = key self.next = None self.prev = None def __repr__(self): return "[{prev} <- [{key}] -> {next}".format(key=self.key, next=self.next.key if self.next else None, ...
class Solution(object): def isPalindrome(self, n): nStr = str(n) for i in range(int(len(nStr) / 2)): if nStr[i] != nStr[~i]: return False return True def getNextHigherPalindrome(self, a, b, current): """ The minute we find a palindrome (a*b) c...
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stk = [] opening = "([{" closing = ")]}" close2open = { ")" : "(", "}" : "{", "]" : "[", } for c in s: if c ...
r""" DNA strings must be labeled when they are consolidated into a database. A commonly used method of string labeling is called FASTA format. In this format, the string is introduced by a line that begins with ">", followed by some information naming and characterizing the string. Subsequent lines contain the string i...
def grph(fasta): r""" Given: A collection of DNA strings in FASTA format having total length at most 10 kbp. Return: The adjacency list corresponding to O3. """ from itertools import product overlap = lambda ((n1, s1),(n2, s2)): n1 != n2 and s1[-3:] == s2[0:3] stringify = lambda ((n1, s...
""" Programa que resolve questões de provas""" pontos = 0 questao = 1 while questao <= 3: resposta = input(f'Resposta da questão {questao}: ').upper() if questao == 1 and resposta == 'b' or resposta == 'B': pontos = pontos + 1 if questao == 2 and resposta == 'c' or resposta == 'C': pontos =...
# Programa 2.2 - Calculo de aumento de salário # Composição de strings utilizando o f'string sal = 750 aum = 15 por = sal + (sal * aum / 100) print(f'O salário base de R${sal} com o aumento de {aum}% foi de: R${por}') # Forma de Composição usando o .format nome = 'Joao' idade = 22 grana = 51.34 print('{} tem {} ...
a = [] a.append(2) a.append(10) a.append(14) for item in a: print(item) b = a.pop() print(b) a.append(15) l = len(a) print(l)
import sqlite3 conn = sqlite3.connect('data/exploitable_db.sqlite') c = conn.cursor() def connect(username, password): query = f""" SELECT * FROM users WHERE users.username = '{username}' AND users.password = '{password}' """ c.execute(query) user = c.fetchone() if user is None: return "U...
""" alphacode.py: CIS 210 assignment 1, Fall 2013 Authors: FIXME: Anthony Plueard Credits: FIXME: list sources and collaborators. If none, delete this line. Convert PIN code to mnemonic alphabetic code """ import argparse # Used in main PROGRAM to get PIN code from command line # # Constants used by this program ...
#!/usr/bin/env python3 # -*- coding: Utf-8 -* # import all the required libraries """ Function to create items in the macgyver-game""" from classes import Items def prep_items(structure): """ The function is use for creation of items objects in the game . Parameters: structure (list): list generate...
class SuccessorWithDelete(object): def __init__(self,N): self._N = N self._suc = [i+1 for i in range(N)] self._suc[N-1] = N-1 self._pred = [i-1 for i in range(N)] self._pred[0] = 0 def remove(self,x): px = self._pred[x] sx = self._suc[x] if sx == x: self._suc[px] = px elif px == x: self._pred...
class IndexMinPQ(object): def __init__(self,N): self._N = N self._n = 0 self._keys = [None] * (self._N+1) self._pq = [None] * (self._N+1) self._qp = [None] * (self._N+1) def show(self): print "Keys:",self._keys print "pq:",self._pq print "qp:",self._qp def findKey(self,index,key): return self._ke...
class InsertionSort(object): def __init__(self,arr): self._arr = arr self._N = len(arr) def sort(self): for i in range(1,self._N): for j in range(i,0,-1): if self._arr[j] < self._arr[j-1]: self._arr[j], self._arr[j-1] = \ self._arr[j-1], self._arr[j] return self._arr if __name__ == '__ma...
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ carry = 0 ...
# a = 21414 # b = 'eghgeojgenafljeijfjaejfalgfnjh' # print(type(str(a))) # list = [',7','efe','34']#sequence:序列类型 # print(3 in list) # print(len(list))#统计列表元素个数 # print(list.count(3))#统计列表中特定元素个数 # # print(max(list))#统计列表最大值 # # print(min(list))#统计列表最小值 # print("a在字符串中的个数:"+str('fahefhaenkjafhea'.count('a')))#统计字符串中某个元...
#!/usr/bin/python # to send an email... # Import smtplib for the actual sending function import smtplib import email from email.mime.multipart import MIMEMultipart # Import the email modules we'll need from email.mime.text import MIMEText #tmsg = MIMEMultipart('alternative') #tmsg = MIMEMultipart() # Open a p...
#!/usr/bin/env python class Player: x=0 y=0 Inventory=[] life=100 gold=0 armed="" inHand="" def addInventory(self,e): if e.desc=="gold": self.gold=self.gold+1 else: self.Inventory.append(e) print self.Inventory
""" Author: Jaineel Vyas Filename: DecisionT.py """ import math class Node: """A decision tree node.""" def __init__(self, examples, maxcols): ''' Initialize a node with examples(data array rows). :param examples: data array :param maxcols: number of columns ...
n = 8 space = ' ' sharp = '#' for i in range(n): print(space*(n-i), end='') # Spaces before hash print(sharp*(i+1) + space*2, end='') # Hashes + space print(sharp*(i+1), end='') # Opposite pyramid print('') # New line
def hello(x): print("Hey") print("Howdy") print("Holla") print(x) x = x + x #print(x) return x x = 5 print("Olá\n") print(x) x = hello(int(input())) print(x)
def greater_num(num): #id_40973454 return (num * 4)[:4] if __name__ == '__main__': quantity = int(input()) array = input().split() array.sort(key=greater_num, reverse=True) print(''.join(array))
class MyQueue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): if self.isEmpty(): print(None) else: print(self.items.pop(0)) def...
class Node: def __init__(self, value, next_item=None): self.value = value self.next_item = next_item # 0 > 1 > 2 > 3 >4 > 5 def solution(node): while node: print(node.value) node = node.next_item def solution2(node, number): asd = [] i = 0 while node: ...