text
stringlengths
5
121k
class No(object): def __init__(self, dado=None): self.dado = dado self._proximo = None self._anterior = None def __str__(self): return str(self.dado) class Pilha(object): def __init__(self): self._inicio = None self._fim = None def isVazia(self): if self._inicio == None: ret...
def fatorial(n): print(f'calculando fatorial de {n}') if n <= 1: return 1 else: return n * fatorial(n - 1) print(fatorial(1)) print(fatorial(7))
class No(object): def __init__(self, dado=None): self.dado = dado self._proximo = None self._anterior = None def __str__(self): return str(self.dado) class Lista(object): def __init__(self): self._inicio = None self._fim = None def isVazia(self): if self._inicio == None: ...
class Dog(): """一次模拟小狗的简单测试""" def __init__(self, name, age): """初始化属性name和age""" self.name = name self.age = age def sit(self): """模拟小狗被命令蹲下""" print(self.name.title() + " is now sitting.") def roll_over(self): """模拟小狗被命令打滚""" ...
number = input("Enter a number, and I'll tell you if it's even or odd:") number = int(number) if number % 2 == 0: print("\nThe number " + str(number) + " is even") else: print("\nThe number " + str(number) + " is odd.")
""" Think Python, 2nd Edition Chapter 7 Exercise 7.3 Description: The mathematician Srinivasa Ramanujan found an infinite series that can be used to generate a numerical approximation of 1/π: https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fi.pinimg.com%2Foriginals%2Fa1%2Ff5%2F81%2Fa1f581c7dc6c3c581...
""" Think Python, 2nd Edition Chapter 6 Exercise 6.3 Description: A palindrome is a word that is spelled the same backward and forward, like “noon” and “redivider”. Recursively, a word is a palindrome if the first and last letters are the same and the middle is a palindrome. The following are functions that take a...
""" Think Python, 2nd Edition Chapter 1 Exercise 1.2 Description: try math operations and answer the questions """ print(42 * 60 + 42) print(10 / 1.61) race_in_miles = 10 / 1.61 race_time_in_sec = (42 * 60 + 42) total_mile_time_in_sec = race_time_in_sec / race_in_miles time_per_mile_in_min = int(total_m...
""" Think Python, 2nd Edition Chapter 6 Exercise 6.2 Description: The Ackermann function, A(m,n), is defined: n + 1 if m = 0 A(m,n) = A(m-1, 1) if m > 0 and n = 0 A(m-1, A(m,n-1)) if m > 0 and n > 0 See http://en.wikipedia.org/wiki/Ackermann_function. Write a function named ac...
""" Think Python, 2nd Edition Chapter 6 Exercise 6.4 Description: A number, a, is a power of b if it is divisible by b and a/b is a power of b. Write a function called is_power that takes parameters a and b and returns True if a is a power of b. Note: you will have to think about the base case. """ def is_power(a...
class Gun: def __init__(self, model): self.model = model self.bullet_count = 0 def add_bullet(self, count): self.bullet_count += count def shoot(self): if self.bullet_count <= 0: print ("[%s]没有子弹了..." % self.model) ret...
def get_prime_numbers(n): prime_numbers = [] for num1 in range(2,n+1): for num2 in range(2, num1): if (num1 % num2 == 0): break; else: prime_numbers.append(num1) return prime_numbers n = 20 get_prime_numbers(n)
import requests from bs4 import BeautifulSoup print("Enter your teacher's name in the format firstInitialLastName. Example: dholmes") teacherName = str(input('Teacher Name (ex. dholmes): ')) print("Enter your term name in the format [fall/spring]year. Example: fall2021") term = str(input("Enter the term (fall2021): ")...
a = input("a: ") b = input("b: ") c = a a = b b = c print("a = " + a) print("b = " + b)
import os from silent_auction_art import logo def clear(): os.system('cls' if os.name == 'nt' else 'clear') auction_record = {} def check_highest_bidder(auction_record): highest_bid = 0 for bidder in auction_record: bid_amount = auction_record[bidder] if bid_amount > hig...
import pandas as pd import datetime as dt import random import smtplib my_email = "isonzo@gmail.com" password = "not_going_to_put_my_password" data = pd.read_csv("birthdays.csv") birthdays = data.to_dict(orient="records") now = dt.datetime.now() for birthday in birthdays: if now.month == birthday["month...
import random from art import logo, vs from game_data import data import os def clear(): os.system('cls' if os.name == 'nt' else 'clear') def higher_lower(): score = 0 game_not_lost = True def pick_celebrity(): """Picks a random celebrity from data""" return rand...
def prime_checker(number): if number == 0 or number == 1: print("This number is neither prime nor composite") return prime = True for integer in range(2, number): if number % integer == 0: prime = False break if prime: print("It's a...
def isPrime(i): for j in range(2,i): if (i%j==0): return False return True num=600851475143 largest=0; for i in range(int("%.0f" % num**(1/2))): if(num%i==0): if(isPrime(i)): largest=i print(largest)
def f(x): return x - ((x ** 2 - 2 * x - 1) / (2 * x - 2)) list = [2.5] i = 0 while (len(list) < 4): list.append(f(list[i])) i += 1 print(list)
def Movement(pos, direction, instruction): action = instruction[0] value = int(instruction[1:]) newPos = pos.copy() newDirection = direction if action == 'N': newPos[1] += value elif action == 'S': newPos[1] -= value elif action == 'E': newPos[0] += value elif ...
points = 0 answer_one = input("Resposta da primeira questão: ") if answer_one.lower() == "B".lower(): points += 1 answer_two = input("Resposta da segunda questão: ") if answer_two.lower() == "A".lower(): points += 1 answer_three = input("Resposta da terceira questão: ") if answer_three.lower() == "D".lower()...
x = [1,2,3,4] x.append(5) print(x) y = [6,7,8,9] print(x + y) x.extend(y) print(x) x.insert(2,99) print(x) print(x.pop()) print(x.count(2)) x.reverse() print(x) x.clear() print(x)
import time iterations = 100 word_list = ["Hello ", "there! ", "How ", "are ", "you ", " doing", " today?"] with open('freebsddictionary.txt', 'r') as file_object: for line in file_object: word_list.append(file_object.readline()) def join_words(words): sentence = '' for word in words: ...
import random from replit import clear import art def answer(): answer = random.choice(range(1, 101)) return answer print(answer) def difficulty(choice): if choose == 'easy': return easy_guess else: return hard_guess player_guess = 0 game_answer = 0 game_over = Fal...
dig1=int(raw_input("")) dig2=int(raw_input("")) dig3=int(raw_input("")) if (dig1>dig2)and(dig1>dig3): largest = dig1 elif (dig2>dig1)and(dig2>dig3): largest = dig2 else: largest= dig3 print(largest)
vrin=int(raw_input("")) e=0 while (vrin!=0): r=vrin%10; e=e*10+r vrin/=10; print(e)
moni=int(input("")) vamp=int(input("")) for i in range(moni+1,vamp): if(i%2 == 0): print(i)
i=int(raw_input("")) if (i%2)==0: print("yes") if (i==1): print("yes") else: print("no")
""" Created on Fri Apr 27 01:37:03 2018 @author: raleigh-littles """ import fractions, unittest def reducedFractionSums(expressions): """ Fairly self-explanatory, just use the built-in fractions package to perform the fraction addition -- they'll be automatically reduced in the end. """ sum_arra...
data = input().split() search = input() counter = 0 data2 = [palindrome for palindrome in data if palindrome == "".join(reversed(palindrome))] print(data2) print(f"Found palindrome {data.count(search)} times")
command = input() map_of_the_seas = {} while not command == "Sail": city, population, gold = command.split("||") if city not in map_of_the_seas: map_of_the_seas[city] = [int(population), int(gold)] else: map_of_the_seas[city][0] += int(population) map_of_the_seas[city][1] += int(gold...
data = [int(i) for i in input().split()] route_1 = data[:len(data) // 2] route_2 = data[len(data) // 2 + 1:] route_2.reverse() total_time_route_1 = 0 total_time_route_2 = 0 for i in route_1: if i == 0: total_time_route_1 *= 0.8 else: total_time_route_1 += i for i in route_2: if i == 0: ...
rooms = int(input()) free_chairs = 0 flag = False for room in range(1, rooms + 1): command = input().split() if len(command[0]) < int(command[1]): print(f"{int(command[1]) - len(command[0])} more chairs needed in room {room}") flag = True else: free_chairs += len(command[0]) - int(co...
n = int(input()) data = {} for i in range(n): command = input().split() if command[0] == "register": username = command[1] plate = command[2] if username not in data: data[username] = plate print(f"{username} registered {plate} successfully") else: ...
string = [int(i) for i in input().split(", ")] counter = 0 for i in range(len(string)): if string[i] == 0: counter += 1 result = [i for i in string if i != 0] for i in range(counter): result.append(0) print(result)
n = int(input()) capacity = 0 for i in range(n): litres = int(input()) if capacity + litres > 255: print("Insufficient capacity!") else: capacity += litres print(capacity)
start_char = int(input()) end_char = int(input()) for char in range(start_char, end_char + 1): print(chr(char), end=" ")
data = input().split("|") energy = 100 coins = 100 for i in range(len(data)): data[i] = data[i].split("-") for i in range(len(data)): if data[i][0] == "rest": if energy + float(data[i][1]) <= 100: energy += float(data[i][1]) print(f"You gained {float(data[i][1]):.0f} energy.")...
num1 = int(input()) num2 = int(input()) num3 = int(input()) num4 = int(input()) print(int((int((num1 + num2) / num3)) * num4))
n = int(input()) best = 0 for i in range(n): snow = int(input()) time = int(input()) quality = int(input()) value = (snow / time) ** quality if value > best: best_snow = snow best_time = time best_quality = quality best = value print(f"{best_snow} : {best_time} = {int...
electrons = int(input()) counter = 1 result = [] while electrons > 0: if electrons - 2 * counter ** 2 >= 0: result.append(2 * counter ** 2) electrons -= 2 * counter ** 2 counter += 1 else: result.append(electrons) break print(result)
def odd_even_sum(num): odd = 0 even = 0 for digit in num: if int(digit) % 2 == 0: even += int(digit) else: odd += int(digit) print(f"Odd sum = {odd}, Even sum = {even}") num = input() odd_even_sum(num)
import re data = input() pattern = r"\b[_]([A-Za-z0-9]+\b)" result = re.findall(pattern, data) print(",".join(result))
__author__ = "Shay Brynes" __license__ = "Apache License 2.0" def print_matrix(matrix): for n in range(0, len(matrix)): for m in range(0, len(matrix[n])): if m == 0: print("(", end="") print(matrix[n][m], end="") if m == len(matrix[n])-1: ...
z=int(input()) while(z>0): a=int(input()) if(a<10): print("What an obedient servant you are!") else: print("-1") z-=1
import classes try: grades = open('grades.txt','r') students = open('students.txt','r') weights = grades.readline().split() weights = weights[1:] for i,weight in enumerate(weights): weights[i] = float(weight)...
""" Created on Thu Sep 8 10:25:11 2016 @author: Camille """ points_str = input("Enter the lead in points: ") points_ahead_int = int(points_str) lead_calculation_float = float(points_ahead_int - 3) has_ball_str = input("Does the lead team have the ball (Yes or No)? ") if has_ball_str == "Yes": lead_calculation...
""" Promblem: Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. Note: The given integer is guaranteed to fit within the range of a 32-bit signed integer. You could assume no leading zero bit in the integer’s binary representation. Example...
from data.data import * class Printer: """this class holds template for format and resources attrbute, estimated resources(calculates resources to be used) and report""" color,greyscale = FORMAT['coloured']['materials']['ink'],FORMAT['greyscale']['materials']['ink'] colored_price,greyscale_price = FORMAT['c...
import re pat = r'\d+' n = input() if bool(re.match(pat, n)): print(n[::-1]) else: print("Invalid")
"""Throws n-number of n-sided dices""" from random import randint def throw_dices(dices, sides): """ Throw given number of seleted-sided dices :param dices: number of dices :param sides: number of sides of dices :return: list of every dice result """ throw = [] dice = 1 while dice...
from time import sleep temp = 10 while temp < 15: temp+=1 print("La temp está "+str(temp)+" grados") print("aumento en 1ºC") sleep(1) print("Temp >= 15ºC")
def total(l): x=0 sum = 0 while(x<10): sum = sum + l[x] x=x+1 return sum def promedio(t): promedio = t/10 return promedio def standarddeviation(l, p): x=0 sum = 0 while(x<10): s = (l[x]-p)**(2.0) sum = sum+s x=x+1 s = (sum/9)**(.5) return s x=0 l=[] print("This is a list of 10 numbers.") while (x<...
import unittest from methods import Admin, SuperAdmin class SuperAdminTests(unittest.TestCase): VALID_EMAIL = 'Correct@email.com' VALID_PASSWORD = 'AQwe12!_' INVALID_EMAIL = 'Incorrect@@email..com' INVALID_PASSWORD = 12345678 def setUp(self): pass de...
''' Lets Understaned Higher Order Function (HOF) HOF if Function which will accept argument as function and return function as well. NOTE : Use Debugger to Understand the flow of code. ''' ''' Example ''' print('\nHigher Order Function\n') def Login(func,username,password): isValid = func(u...
def drops(numero): resultado = "" if numero % 3 == 0: resultado += "Plic" if numero % 5 == 0: resultado += "Plac" if numero % 7 == 0: resultado += "Ploc" return resultado or numero print(drops(int(input("Introduce numero: "))))
"""Программа расчета необходимых для готовки блюд ингридиентов.""" def return_shop_list(cook_book, dishes, person_count): """Расчет необходимых для покупки ингридиентов.""" shop_list = {} for dish in dishes: for ingridient in cook_book[dish]: new_shop_list_item = dict(ingridient) ...
import os ''' Only under os.path.abspath('.'), a file can be distinguish as file. ''' def selectCondition(fileName, toFind, opt, path = '.'): flag = False if opt == 'name': if toFind == fileName.split('.')[0]: flag = True elif toFind == fileName: flag = True elif ...
a="hello world!123" def let_dig(a): l=d=0 for i in range(len(a)): if a[i].isalpha(): l=l+1 elif a[i].isdigit(): d=d+1 print('letters are',l,'\n','digits are',d) let_dig(a)
print("PYTHAGOREAN TRIPLETS: \n") def run(): ar = [] y = 1 x = input("\nEnter the termination value or range of values (initial and final value)\n>>> ") for k in range (len(x)): if x[k] != ',': ar.append(x[k]) x = "".join(ar) l = x.split(" ") if(l.count("")>...
import unittest def binary_search(data, target, low, high) -> int: if low > high: return None else: mid = (low + high) // 2 if target == data[mid]: return mid elif target < data[mid]: return binary_search(data, target, low, mid - 1) else: ...
from pathlib import Path from pprint import pprint WORDS_FILE = '/usr/share/dict/words' def get_words(file_name=WORDS_FILE): try: text = Path(WORDS_FILE).read_text() except FileNotFoundError: print(f'File {file_name} not found.') return None words = text.strip().split('\n') wo...
from bisect import bisect_left def lis(A, return_only_length=False): B = [] for a in A: i = bisect_left(B, a) if i == len(B): B.append(a) else: B[i] = a if return_only_length: return len(B) return B print(lis([3, 1, 5, 2, 4, 3])) print(lis([1]))...
from model.data_structures.Deque import Deque class Queue: """This class represents a queue data structure, reinvented out of the wheel purely for the sake of novelty.""" def __init__(self): """Constructs an empty queue.""" self._deque = Deque() def peek(self): """Peek at the...
""" Author: Heecheon Park Note: Run python3 100x100_mat_generator.py first before running this program. Description: Read numbers from 100x100_matrix.txt Store each line into lists and numpy arrays. Then, benchmarks matrix multiplication. For example, list A and list B are 2-dimensional lists and performs list A ...
""" #Description: This program benchmarks numpy matrix multiplication vs standard python on mpi4py Read numbers from 100x100_matrix.txt Store each line into lists and numpy arrays. Then, benchmarks matrix multiplication. For example, list A and list B are 2-dimensional lists and performs list A * list B. Likewise,...
def timeConversion(s): if "AM" in s: if s.split(':')[0] == '12': return s.replace('12','00').replace('AM','') return s.replace('AM','') else: hours = s.split(':')[0] if hours == '12': return s.replace('PM','') full_time = str((int(hours) + 12)) + ...
import random for x in range(1, 2): die_4 = random.randint(1,4) die_6 = random.randint(1, 6) die_8 = random.randint(1,8) die_10 = random.randint(1,10) die_12 = random.randint(1,12) die_20 = random.randint(1,20) total = die_4 + die_6 + die_8 + die_10 + die_12 + die_20 print("Total=", tot...
def utopianTree(n): k=int(n/2) m= 1 if n % 2 == 0 else 2 return 2 ** (k + m) - m if __name__ == '__main__': t = int(input()) for t_itr in range(t): n = int(input()) result = utopianTree(n) print(result)
l=[10,20,22,30,40,50,55] l = [ 10,20,30] l2=l.copy() l.append(40) print(id(l),id(l2)) print(l,l2)
import requests import tabula import os url= 'url.pdf' pdf = requests.get(url) pdf_name = input("Type the name for the pdf file: ") csv_name = input("Type the name for the csv file: ") open(pdf_name+'.pdf', 'wb').write(pdf.content) tabula.convert_into(pdf_name+".pdf",csv_name+".csv",output_format="csv",pages=...
import json handle=open("json_input.json","r") content = handle.read() d=json.loads(content)
def run_fizzbuzz(ceiling=25): """ Prints out a game of fizzbuzz up to the value of `ceiling`. :param ceiling: maximum value to count up to. :return: None """ for i in range(1, ceiling + 1): message = ''.join(('fizz' if not i % 3 else '', 'buzz' if not i % 5 else '')) print(messag...
z = input() x = open(z) lst = list() count = dict() for lines in x: if lines.startswith('From:'): z= lines.split() y= z[1] lst.append(y) for words in lst: count[words]= count.get(words, 0) +1 print(count)
''' Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times. Example 1: Input: s = "eleetminicoworoep" Output: 13 Explanation: The longest substring is "leetminicowor" which contains two each of...
class Account(object): count = 0 @classmethod def incr_count(cls): cls.count+=1 @classmethod def get_count(cls): return cls.count @staticmethod def print_val(): print("staticmethod in account class") def __init__(self,cust_id,name,initial_balance=0): ...
from math import sqrt from math import floor def is_prime(num): if num<=2: return False if num%2==0: return False for i in range(3,floor(sqrt(num)),2): if num%i==0: return False return True if __name__ == "__main__": print(is_prime(99194853094755497))
""" Implementation of Interpolation Search """ def interpolation_search(sample_input, lowest, highest, item): """ function to search the item in a give list of item :param sample_input: list of number :param lowest: the lowest element on our list :param highest: the highest element on our list ...
import math def kaprekarNumbers(p, q): for i in range(p,q+1): c = list(str(int(math.pow(i,2)))) if len(c)>1: if int(c[0]) + int(c[1]) == i: print(i) if __name__ == '__main__': p = int(input()) q = int(input()) kaprekarNumbers(p, q)
""" Created on Sat May 11 11:57:28 2019 @author: jmat """ ALPHABET=" ABCDEFGHIJKLMNOPQRSTUVWXYZ" def ceasar_crack(cipher_text): for key in range(len(ALPHABET)): plain_text="" for c in cipher_text: index=ALPHABET.find(c) index=(index-key)%len(ALPHABET) ...
""" Simple graph implementation compatible with BokehGraph class. """ class Graph: """Represent a graph as a dictionary of vertices mapping labels to edges.""" def __init__(self): self.vertices = {} self.groups = [] def add_vertex(self, vertex): if vertex in self.vertices: ...
''' Here the TreeView widget is configured as a multi-column listbox with adjustable column width and column-header-click sorting in Python3. ''' from tkinter.ttk import Treeview, Scrollbar, Label, Frame from tkinter.font import Font from tkinter import messagebox class MultiColumnListbox(object): """use a ttk.T...
def PatternMatching(Pattern, Genome): positions = [] i = -1 while True: i = Genome.find(Pattern, i+1) if i != -1: positions.append(i) else: break return positions ''' def PatternMatching(Pattern,Genome): positions = [] for i in range(len(Ge...
def fizzbuzz(n: int) -> None: """Solves the FizzBuzz problem. >>> fizzbuzz(10) 1 2 fizz 4 buzz 6 7 8 fizz buzz """ for i in range(1, n + 1): s = '' if i % 3 == 0: s += 'fizz' if i % 5 == 0: s += 'fuzz' if s ...
from typing import List def digit_root(n: int, base: int=10) -> int: """Returns the digital root for an integer N.""" assert type(n) == 'int' total = 0 while n: total += n % base n //= base return digit_root(total) if total >= base else total def int_to_list(n: int, base: int=10) ...
import copy class Node: def __init__(self, data): self.data = data self.next = None def __str__(self): return str(self.data) def __repr__(self): return repr(self.data) class LinkedList: def __init__(self, data): self.node = Node...
from graph import Graph from util import Stack def earliest_ancestor(ancestors, starting_node): graph = Graph() for parent, child in ancestors: graph.add_vertex(parent) graph.add_vertex(child) for parent, child in ancestors: ...
import random def random_number(): numbers = [] temp_list = [] while True: temp_list.append(random.randint(0,9)) numbers = list(set(temp_list)) if len(numbers) == 4: return numbers def unlike(before_list): if isinstance(before_list,list): list2 = list((se...
from turtle import * from math import sqrt def gwiazdki(): l=50 shape(l) for _ in range(5): x=pos() y=heading() fd(l) lt(18) fd(l) lt(18) shape(l) setpos(x) setheading(y) rt(72) def triangle(a): fd(a) lt(135) fd(a*...
from turtle import * def simple(a,col): pendown() fillcolor(col) begin_fill() lt(30) fd(3*a) lt(120) fd(a) lt(60) fd(2*a) rt(60) fd(2*a) lt(60) fd(a) lt(120) fd(3*a) end_fill() lt(30) penup() def compo(a): c=["brown","orange","yellow"] ...
from turtle import * def element(level, k): fillcolor("red") begin_fill() for _ in range(4): fd(k) lt(90) end_fill() if level>1: for _ in range(3): fd(k) rt(90) element(level - 1, k/2) lt(180) fd(k) lt(90) de...
__author__ = 'apple' from turtle import * from random import randint K = 20 def reg(szer, n): start_position(szer, n) regal(szer, n) fd(K) for _ in range(n): polka(szer // K - 2) up(7) def polka(k): rect(k * K, 6*K, "white") pendown() for _ in range(k): r = ra...
from flask import Flask app = Flask(__name__) @app.route("/") def index(): return( "PRIMERA PAGINA WEB CON FLASK!!!!!") @app.route("/<string:nombre>") def saludar(nombre): nombre = nombre.upper() return("BUENOS DIAS, " + nombre + " <3")
class Point(object): def __init__(self, x, y): self.x = x self.y = y def __str__(self): return '[%.2f;%.2f]' % (self.x, self.y) def __neg__(self): return Point(-self.x, -self.y) def __add__(self, point): return Point(self.x + point.x, self.y + point.y) def __sub__(self, point): return Point(self.x ...
import pandas as pd import numpy as np from sklearn.model_selection import KFold def merge_samples(samples_series, idx, shuffle=True): """ Merge a Series of DataFrames into a single DataFrame, filtered by a Series index. DataFrames can be shuffled before merging. Used to generate an artificial genome ...
import pyglet from square import * class Level(): ''' A class that represents a typical level ''' grid = [] block_size = 30 grid_width = 20 grid_height = 20 def __init__(self): ''' FOR YOU: For each row, create an array and then, for each column, add a new B...
name=input("Product Name:") error="This cannot have numbers" has_errors="" for letter in name: if letter.isdigit()==True: print(error) has_errors="yes" break if has_errors!="yes": print("Continue")
from itertools import product def naive_scan(automaton, chunk): """ Utility function which can be used to implement a naive, slow, but thorough chunk scan for automatons. This method is designed to be directly useable on automaton classes to provide the `scan()` interface. """ for i, bloc...
""" Functions to train a logistic regression model Created on Sun Sep 6 15:57:19 2020 @author: eksalkeld """ from constants import * from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV from sklearn.linear_model import LogisticRegression from sklearn.metrics import c...