text
stringlengths
37
1.41M
print(" Palabra Secreta") nombre = input("Ingrese el nombre: ") palabra_secreta = "azul" print("Hola! " + nombre) print("Intenta adivinar la palabra que va en el espacio de la oracion. Tienes 3 intentos.") print("Mi color favorito es sereno y calmante. El color es: ") intentos = 0 while intentos < 2:...
number_1, number_2 = input().split() count = 0 for i in range(int(number_1)): string = input() for j in range(int(number_2)): if (string[j] == "*"): count += 1 print(count)
score = int(input()) travel_days = int(input()) if (travel_days == 0): print(20) elif (travel_days == 7): print(score) else: output = score - travel_days if (output < 0): print(0) else: print(output)
# Number Guessing Game Objectives: # Include an ASCII art logo. # Allow the player to submit a guess for a number between 1 and 100. # Check user's guess against actual answer. Print "Too high." or "Too low." depending on the user's answer. # If they got the answer correct, show the actual answer to the player. # Trac...
from replit import clear import art # HINT: You can call clear() to clear the output in the console. print(art.logo) list_for_name_and_bid = {} while True: name = input("What is your name? ") bid = int(input("Your bid? $")) list_for_name_and_bid[name] = bid continue_input = input("Are there any other...
##################### Extra Hard Starting Project ###################### # 1. Update the birthdays.csv # 2. Check if today matches a birthday in the birthdays.csv import pandas import datetime as dt import random import smtplib data = pandas.read_csv("birthdays.csv", dtype={"month": int, "day": int}, squeeze=True).t...
# Given a string, you have to return a string in which each character (case-sensitive) is repeated once. def double_char(s): new_s = [] for char in s: new_s.append(char) new_s.append(char) seperator = '' return(seperator.join(new_s))
import sys try: first = float(input()) second = float(input()) except: print() sys.exit() if first > second: print('First is bigger') elif first == second: print('First is equal second') else: print('Second is bigger')
# Parent Class OR Base Class # Sometimes, it can be referred to as Superclass - super links to # whatever is written inside the parens of the child class # class Product: # def __init__(self, name, price): # self.name = name # self.price = price # self.discount = 0 #discount # You could also ...
num = int(input("hhh: ")) if num > 0: for i in range(2, num//2): if((num%i )== 0): print(num, " is not prime") break else: print("is prime") else: print(num, "is not prime")
import numpy as np import matplotlib.pylab as plt import math as math ################################################################################ # This is how we define our own function ################################################################################ def Gaussian(x,mean,width): y = (1.0/(wid...
class node: def __init__(self, data): self.data = data self.next = None class Linked_List: def __init__(self): self.head = None def print_n_count(self): counter = 0 tmp = self.head print(" Data entered in the list are :") while tmp: print("Data: " + str(tmp.data)) cou...
class node: def __init__(self, data): self.data = data self.left = None self.right = None def count(root): if root is None: return 0 else: return 1 + count(root.left) + count(root.right) if __name__ == '__main__': root = node(5) root.left = node(4) root.right = node(3) ...
def palindrome(a, descender, climber=0): if (a[climber] != a[descender]): return False if climber> descender: return True if climber==descender: return True else: return palindrome(a, descender-1, climber+1) UserString= "geeks" check = palindrome(UserString, len(UserString)-1) if check: print...
from random import randint, random from operator import add #Create an individual member of the population def individual(length, min, max): return [randint(min,max) for x in xrange(length)] #Creates a population of individuals def population(count, length, min, max): return [individual(length, min, max) for x in x...
''' datetime ''' from datetime import datetime, date def now(format='%Y-%m-%d %H:%M:%S'): ''' 获取当前的时间字符串。 ''' n = datetime.now() return n.strftime(format) def today(format='%Y-%m-%d'): ''' 获取今天的时间字符串。 ''' t = date.today() return t.strftime(format)
class MathDojo(int): def __add__(self, other): return {} + {} def __sub__(self, other): self.first = first self.second = second result = self.first - self.second return result md = MathDojo() md.add(0, 2) #part 1 # class MathDojo(object): # def __init__(self): # ...
Mixed = ['magical unicorns',19,'hello',98.98,'world'] Num = [2,3,1,7,4,12] Str = ['magical','unicorns'] def listType(list): newlist = "" total = 0 for value in list: if isinstance(value, int) or isinstance(value, float): total += value elif isinstance(value, str): n...
c=input() if(c.isAlpha()==True): if(c=='a' or c=='e' or c=='i' or c=='o' or c=='u'): print("Vowles") elif(c!='a' or c!='e' or c!='i' or c!='o' or c!='u'): print("Consonant") else: print("Invalid")
def reader(): ##Start up import time import file_integrity filename = 'testing_doc.csv' #set target filename integ = 0 ##File integrity integ = file_integrity.checker(filename,integ) time.sleep(1.5) if integ == 1: proc1 = raw_input("Would you like to ope...
import turtle as t import random t.shape("turtle") t.speed(0) t.pensize(3) t.up() t.goto(-250,250) t.down() for x in range(4): #먼저 사각형을 그립니다. t.fd(500) t.rt(90) t.up() t.circle(10) #거북이를 별모양 안으로 집어넣는 장애물입니다. t.home() #거북이를 원위치 시킵니다. t.up() t.goto(-125,125) t.down() t.begin_fill() t...
#!/usr/bin/python #coding: utf-8 months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] endings = ['st', 'nd', 'rd'] + 17 * ['th'] \ + ['st', 'nd', 'rd'] + 7 * ['th'] \ + ['st'] #˴Щʾʺ׺Ӣʹ㣠#11,12,13th֮,1st,nd,rd,th #200-30...
num = int(input('Digite o número: ')) res = 1 fat = '' while num != 0: res *= num if num > 1: fat += str(num) + 'x' else: fat += str(num) + '=' num -= 1 print('{} {}'.format(fat, res))
brasileirao = ('Fluminense', 'São Paulo', 'Botafogo', 'Cruzeiro', 'Grêmio', 'Internacional', 'Santos', 'Palmeiras', 'Bahia', 'Fortaleza', 'Chapecoense', 'A...
palavras = ('Laptop', 'Mouse', 'Celular', 'Mochila', 'Melatonina') for i in palavras: print(f'\nNa palavra {i.upper()} temos ', end='') for letra in i: if letra.lower() in 'aeiou': print(letra, end=' ')
def leiaInt(msg): num = input(msg) while not num.isnumeric(): print('\033[31mERRO: Digite um número inteiro\033[0;0m') num = input(msg) return num n = leiaInt('Digite um número: ') print(f'Você digitou o número {n}')
s = 0 for i in range(1, 7): n = int(input('Digite o {}º número: '.format(i))) if n%2 == 0: s += n print('A soma dos números pares digitados é: {}'.format(s))
# exp = list() exp = (str(input('Digite a expressão: '))) ab = exp.split('(') fe = exp.split(')') if len(ab) == len(fe): print('Expressão válida!') else: print('Expressão inválida =(')
val = float(input('Diz aí, quantos reais você tem? R$ ')) print('Com esse valor dá pra comprar', end=' US$ ') print('{:.2f}'.format(val/3.27))
num = int(input('Digite o número que deseja saber a tabuada de 1 a 10: ')) for i in range(1, 11): print('{} X {} = {}'.format(num, i, num*i))
from datetime import date cadastro = dict() cadastro['nome'] = str(input('Nome: ').strip()) ano = int(input('Ano de nascimento: ')) cadastro['idade'] = date.today().year - ano cadastro['ctps'] = str(input('Carteira de trabalho [caso não tenha, digite 0]: ')) cadastro['aposenta'] = cadastro['idade'] + 35 if cadastro['ct...
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] pares = soma = maior = 0 for i in range(0, 3): for j in range(0, 3): matriz[i][j] = int(input(f'Digite um valor para [{i}][{j}]: ')) if matriz[i][j] % 2 == 0: pares += matriz[i][j] if i == 1: if maior < matriz[i][j]: ...
from math import hypot cat = float(input('Digite o valor do cateto: ')) adj = float(input('Digite o valor do adjacente: ')) hip = hypot(cat, adj) print('A hpotenusa vale: {}'.format(hip))
boletim = [] while True: aluno = [] notas = [] aluno.append(str(input('Digite o nome: ').strip())) notas.append(float(input('Digite a primeira nota: '))) notas.append(float(input('Digite a segunda nota: '))) aluno.append(notas[:]) boletim.append(aluno[:]) aluno.clear() notas.clear() ...
Machine Learning - Scatter Plot Scatter Plot A scatter plot is a diagram where each value in the data set is represented by a dot. The Matplotlib module has a method for drawing scatter plots, it needs two arrays of the same length, one for the values of the x-axis, and one for the values of the y-axis: x = [...
# 리스트에서 특정 값의 원소 모두 제거 arr = [1, 2, 3, 4, 5, 5] remove_set = {3, 5} result = [i for i in arr if i not in remove_set] # [1, 2, 4] # 리스트에서 특정 값의 원소 모두 제거2 score = [90, 85, 77, 65, 97] chetting_list = {2, 4} result_ = [] for i in range(len(score)): if i+1 in chetting_list: continue if score[i] >= 80: ...
def dfs(graph, start): result, visit = [], [] visit.append(start) while visit: node = visit.pop() if node not in result: result.append(node) visit.extend(graph[node]) return len(result) # Test Code graph = dict() graph[0] = [1, 2] graph[1] = [0, 3, 4] graph[2]...
__author__ = "Daniel Jean-Baptiste" __copyright__ = "Copyright 2017, The Smarter Engineering Project" __license__ = "GPL" __version__ = "1.0.1" __maintainer__ = "Daniel Jean-Baptiste" __status__ = "Production" def writeFibonaci(filename,max_int): a,b = 0,1 fh = open(filename,"w") #While loop while b...
### # Scrapes all repo urls from an organization # TIP: This would be a great precursor to a hamburglar.py script ### import json def getRepos(d): repos = [] for user, info in d["users"].items(): for repo, repoVal in info["repos"].items(): repos.append(repoVal["url"]) return list(se...
# takes %d value in a string x = "There are %d types of people." % 10 # set values for binary and do_not as strings binary = "binary" do_not = "don't" # uses variables inside a string y = "Those who know %s and those who %s." % (binary, do_not) # 4 #prints thw whole thing print x print y print "I said: %r." % x # 2 ...
print("Welcome to Granny Hounted House!") name = input("What is your name?: ") age = int(input("What is your age?: ")) health = 10 print(f"Hello {name}, welcome to your worse dream!") if age >= 18: print("You are eligible to enter this house compound.") want_to_play = input("Do you want to play? ...
import numpy as np import geopandas as gpd from shapely import geometry from shapely.ops import polygonize from scipy.spatial import Voronoi, ConvexHull def clouds(X: np.ndarray, radius: list, num_points: float=8): ''' Create a set of points around each point in a 2D array X. Args: param X: Array...
#balance - the outstanding balance on the credit card #annualInterestRate - annual interest rate as a decimal #monthlyPaymentRate - minimum monthly payment rate as a decimal #example: balance = 42; annualInterestRate = 0.2; monthlyPaymentRate = 0.04 # Expected remaining balance: 31.38 def month(balance, InRa, monPay...
#!/usr/bin/python3 """ A small program to convert a bitmap containing font map into assembly code. The data is saved in the following format: character 0 - row 0 character 1 - row 0 character 2 - row 0 character 3 - row 0 character 4 - row 0 character 5 - row 0 character 6 - row 0 charac...
"""PDF Merger Project This Python program is designed to receive multiple PDF files from the user and output a single PDF file. Example: The following code placed into the Terminal will produce one single file called outputfile.pdf. It will combine all the files entered before it in the order that the use...
# -*- coding: utf-8 -*- """ Fibonacci Finder! General idea: User inputs a number and the function created checks whether the number belongs to the Fibonacci sequence or not. Libraries used: math, termcolor """ import math from termcolor import colored as cl def fibNum(n): goldenRatio = 1.61803...
import csv from sys import argv, exit from cs50 import SQL # Check the length of arguments if len(argv) == 2 and argv[1].endswith('.csv'): # Open the file for SQLite db = SQL("sqlite:///students.db") #Open file file = open(argv[1], 'r') reader = csv.DictReader(file) #iterate the file for...
# coding: utf-8 # In[ ]: # order printer function to take a customer name, and check # all their current orders def order_printer(customer, customers, orders): # customer is the customer's first name # check the customer is in the dictionary if customer in customers: # check that the length of the orders value ...
# David Ziama # Class ID 3 # Create a Tic Tac Toegame board = [0,1,2,3,4,5,6,7,8] def printboard(): print("----------") print(board[6],"|",board[7],"|",board[8]) print("----------") print(board[3],"|",board[4],"|",board[5]) print("----------") print(board[0],"|",board[1],"|",boar...
#David Ziama - ClassID #3 #Lesson 1 #Lab Assignment 1b #Take length and breadth of a rectangle from user and print perimeter of the same. print("This program will take length and breadth of a rectangle from user and print perimeter of the same.") print("\n") length = int(input("Enter length: ")) breadth = ...
#David Ziama #ClassID # 3 #June 23, 2017 #1.Draw a Game board. # This one is 3x3 (like in tic tac toe). # Obviously, they come in many other sizes (8x8 for chess, 19x19 for Go, and many more). # Ask the user what size game board they want to draw, and draw it for them to the screen using Python’s print statemen...
# David Ziama # Class ID 3 # Write a function to replace dictionary values with their sum. Use a list which contains three dictionaries. For example [{},{},{}]. Then sum the values of the dictionaries if they are integer. # July 6, 2017 # Our User Inout user_input = [{'course': 'python', 'LastGPA' : 90, 'CurrentGPA' ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 30 07:23:58 2019 @author: manpreetsaluja """ import pandas as pd import numpy as np import seaborn as sns from matplotlib import pyplot as plt from sklearn.datasets import load_boston #LOADING DATASET TO DATAFRAME dataset=load_boston() boston=pd.D...
# s = (a+b+c)/2 # A = sqrt[s * (s-a) * (s-b) * (s-c) # a = 6 # b = 8 # c = 10 # s = (a + b + c)/2 # area = (s * (s-a) * (s-b) * (s-c)) ** 0.5 # print (area) x1 = int (input('輸入x1: ')) y1 = int (input('輸入y1: ')) x2 = int (input('輸入x2: ')) y2 = int (input('輸入y2: ')) x3 = int (input('輸入x3: ')) y3 = int (input('輸入y3: ')...
def maxi(a,b): if a > b: return a else: return b def isPrime(x): if x < 2: return 0 if x > 2: if x % 2 == 0: return 0 d = 3 while d * d <= x: if x % d == 0: return 0 d += 2 return 1 i = 0 while i < 10: if isPrime(i) == 1: print i i += 1
lista = [ {8: "Tymoteusz", 5: "Kazimierz", 4: "Wiola"}, {12: "Johny", 14: "Stanislaw", 18: "Marian"}, {23: "Zbych", 28: "Andrej", 21: "Katarina"} ] for record in lista: for key in record: print("W pokoju nr %i mieszka %s" % (key, record[key]))
def myLog(x, b): ''' x: a positive integer b: a positive integer; b >= 2 returns: log_b(x), or, the logarithm of x relative to a base b. ''' # Your Code Here i = 0 while True: if b**i == x: return i elif b**i > x: return i - 1 else: ...
from typing import List, Any from point import Point from triangle import Triangle from utils import Utils from random import choice class Node(object): def __init__(self, value: Any): self.left = None self.data = value self.right = None def __repr__(self): return f"{self.dat...
import ctypes class DynamicArray(object): def __init__(self): self.n = 0 self.capacity = 1 self.A = self.make_array(self.capacity) def __len__(self): return self.n def __getitem__(self, k): if not 0 <= k < self.n: return IndexError('K is out of bounds'...
""" Implementation of a Bubble Sort The bubble sort makes multiple passes through a list. It compares adjacent items and exchanges those that are out of order. Each pass through the list places the next largest value in its proper place. In essence, each item “bubbles” up to the location where it belongs. Resources fo...
import collections """ Tree Level Order Print - SOLUTION Given a binary tree of integers, print it in level order. The output will contain space between the numbers in the same level, and new line between different levels. For example, if the tree is: title The output should be: 1 2 3 4 5 6 Solution It won’t be p...
def quick_sort(arr): quick_sort_help(arr, 0, len(arr)-1) def quick_sort_help(arr, first, last): if first<last: splitpoint = partition(arr, first, last) print(splitpoint) quick_sort_help(arr, first, splitpoint-1) quick_sort_help(arr, splitpoint+1, last) def partition(arr, first,...
class Node(object): def __init__(self, value): self.value = value self.next_node = None def reversal(node): current_node = node previous_node = None next_node = None while current_node: next_node = current_node.next_node current_node.next_node = previous_node ...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- #class Cesar(object): import copy class Cesar(object): def __init__(self): ''' Se definen los alfabetos que se deben utilizar para el cifrado y descifrado dependiendo si se utiliza un texto o un archivo con su respectivo idima para los textos ''' self.ca...
fibonacci_cache = {} def fibonacci(n): if type(n) != int: raise TypeError("n must be a positive ineger") if n < 1: raise ValueError("n must be a postive ineger") # If we have cached the value, then return it if n in fibonacci_cache: return fibonacci_cache[n] # Compute th...
class Solution(object): def findComplement(self, num): t = num c = 1 << 31 count = 0 while t&c != c: count += 1 t = t << 1 m=0 for i in range(32 - count): m = m << 1 m += 1 return m^num solution = Solution() num...
x=input("请输入分数") score=eval(x) if score>=60.0 and score <70.0: grade='D' print(score,grade) elif score>=70.0 and score <80.0: grade = 'C' print(score, grade) elif score>=80.0 and score <90.0: grade = 'B' print(score, grade) elif score>=90.0: grade = 'A' print(score, grade)
# -*- coding: utf-8 -*- import time import datetime def calculate_diff_seconds(date_from, date_to): date_to = date_to + datetime.timedelta(seconds=-1)# TOを指定日以内に丸めて扱う delta = date_to - date_from return (delta.days * 24 * 60 * 60) + delta.seconds size = 100000000 date_from = datetime.datetime.strptime("20170101...
""" 1 Create an abstract base class called "Human".Give it an abstract function called "run" 2. Create an abstract base class called "Robot". Give it an abstract function called vacuum 3. Create a subclass which inherits from both "Human" and "Robots" called cyborg and create an instance of cyborg """ fro...
#!/usr/bin/python import time class Node(object): """ Simple node for a tree structure. Note that value must be hashable to use this class.""" def __init__(self, parent, value): self.parent = parent self.value = value self.children = {} if parent is not None: self.p...
from queue import PriorityQueue class MyPriorityQueue(PriorityQueue): def __init__(self): PriorityQueue.__init__(self) self.counter = 0 def insert(self,priority, item): PriorityQueue.put(self, (priority, self.counter, item)) self.counter += 1 def remove(self, *args, **kwar...
#coding=utf-8 ''' Created on 2016年4月15日 @author: PI ''' 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 ...
# BOLETA DE VENTA DE UN AVION cliente = input ( " INGRESO EL NOMBRE DEL PASAJERO: " ) dni = int ( input ( " INGRESE EL DNI DEL PASAJERO: " )) hora = input ( " INGRESO LA HORA DE VUELO: " ) destino = input ( " INGRESO EL DESTINO QUE DESEA IR " ) horas_de_vuelo = int ( input ( " INGRESO EL NUMERO DE HORAS DE VUELO: ...
# CALCULO DEL AREA DE UN TRIANGULO base, altura = 0.0 , 0.0 # ASIGNACION DE LOS VALORES base = 12 altura = 6 # CALCULO area_del_triangulo = (base * altura) / 2 # MOSTRAR VALORES print ( " La base del triangulo es: " + str (base)) print ( " La altura del triangulo es: " + str (altura)) print ( " El area del triangulo...
# CONVERSIONES A REALES # convertir la cadena "32.44" a real base = " 32.44 " a = flotante (base) print (a, tipo (a)) # convertir la cadena "10" a real altura = " 10 " a = flotador (altura) print (a, tipo (a)) # convertir la cadena "59.9" a real fuerza = " 59.9 " a = flotador (fuerza) print (a, tipo (...
#! python3 # coding=utf-8 list = ['北京', '上海', '广州', '深圳'] print(list[3]) print(list) len = len(list) print(len) list1 = [1,5,2,11,8,9] print(list1) list1.sort() print(list1)
#this is how you can interface with an SMTP server using python from smtplib import SMTP, SMTPAuthenticationError from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText host = "smtp.gmail.com" port = 587 username = "spinning.leak@gmail.com" password = "noneofyourdamnbusiness" from_email =...
""" Activité de cryptographie """ import numpy as np import random as rd from Ciphers import Cipher def caesar_decoder(cipher: str, key: int, alph: str, MAP: dict): """caesar_decoder Fonction pour décoder le chiffrement de Caesar Args: cipher (str): Chiffrement à décoder key (int): Clé à ...
#!/usr/bin/env python #The MIT License (MIT) #Copyright (c) 2016 Massimiliano Patacchiola # #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF #MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ...
#!/usr/bin/env python3 import csv import os import sys ENCODING = 'iso-8859-1' FIELDNAMES = ['Registration Number', 'Premises Name', 'Address', 'Classification', 'Total Number Rooms', 'Lat', 'Lng'] def make_address(row): address_text = "{} {} {} Ireland".format(row[3], row[4], row[5]) return address_text ...
perm = [1, 2, 3, 4] def permutations(n): if n == 0: print(perm) else: for i in range(n): perm[i], perm[n - 1] = perm[n - 1], perm[i] permutations(n-1) perm[i], perm[n - 1] = perm[n - 1], perm[i] if __name__ == "__main__": permutations(3)
import datetime #FUNCTIONS TO GET EACH TYPE OF SPEECH def get_a_noun(): print("Please enter a noun.") given_noun = str(input()) return given_noun def get_a_verb(): print("Please enter a verb.") given_verb = str(input()) return given_verb def get_an_adjective(): print("Please e...
#!/usr/bin/python # -*- coding: UTF-8 -*- # 打开一个文件 fo = open("foo.txt", "wb") print "文件名: ", fo.name print "是否已关闭 : ", fo.closed print "访问模式 : ", fo.mode print "末尾是否强制加空格 : ", fo.softspace fo.close() fo = open("foo.txt", "wb") print "文件名: ", fo.name # 关闭打开的文件 fo.close() fo = open("foo.txt", "wb") fo.writ...
#!/usr/bin/python # -*- coding: UTF-8 -*- import time # 引入time模块 # import inspect # inspect.getmoduleinfo(time) localtime = time.localtime(time.time()) print "本地时间为 :", localtime ticks = time.time() print "当前时间戳为:", ticks localtime = time.asctime( time.localtime(time.time()) ) print "本地时间为 :", localtime print tim...
#first code num1 = 1.0 num2 = 4.0 def sumup_two_numbers(num1,num2): return float(num1+num2) print(num1+num2) #(I added the "print" to see it in the command line) #second code (if I have no argument or only one) num1 = 1 num2 = 4 def sumup_numbers(num1=0,num2=0): return float(num1+num2)...
import random as rand def shot(): '''simulates a basketball shot with a 50% probability of succeeding, returns whether or not the shot was successful None -> bool''' return bool(rand.randint(0,1)) #A 50% chance of any shot being made def lbj_steal(prob): '''simulates Lebron stealing steali...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): ''' Check height of each subtree as we recurse down from the root. On each node, we recursively get the heig...
class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ # O(n^2) time and O(1) space max_len, start, s_len = 1, 0, len(s) low, high = 0, 0 # Consider each char or pair of char as center for odd & even ...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def plusOne(self, head): """ :type head: ListNode :rtype: ListNode """ small_bit = None cur = head # ...
import random class RandomizedSet(object): ''' Keep track of the index of the added elements, so when we remove them, we copy the last one into it. ''' def __init__(self): self.nums = [] self.pos = {} # store indices def insert(self, val): if val not in self.pos: ...
import sys import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation def main(): fig, ax = plt.subplots() #xdata, ydata = [], [] x = np.linspace(0, 2*np.pi, 128) y = np.sin(x) ln, = ax.plot(x, y, 'r--', linewidth = 4, markersize = 3, animated=True) line, = ax...
dictionary = ['all', 'an', 'and', 'as', 'closely', 'correct', 'equivocal', 'examine', 'indication', 'is', 'means', 'minutely', 'or', 'scrutinize', 'sign', 'the', 'to', 'uncertain'] input_ = input().split() input1 = [] for i in input_: if i not in dictionary: input1.append(i) if ...
import csv def make_list_from_data_frame(data_frame): data_list = [] number_list = data_frame['number'] review_list = data_frame['review'] review_type_list = data_frame['review_type'] for row in range(0, len(number_list)): row_data = {'number':number_list[row],'review':review_list[row], '...
import sys def NJ(filename): matrix=[] opened= open(filename, 'r') r=0 #reads in file line by line until end of file while True: line = opened.readline() if not line: break #removes line breaks row=line.rstrip('\n') matrix.append(row.split(" ")) ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # parzyste.py # """ def main(args): a = int(input("podaj liczbe: ")) b = int(input("podaj druga liczbe: ")) for liczba in range(a,b): if not liczba % 2 == 0: print(liczba) return 0 """ def main(args): start = int(inpu...
from math import sqrt, floor def isFactor(dividend, divisor): if dividend % divisor == 0: return True return False def isPrime(n): for i in range(2, floor(sqrt(n)) + 1): if isFactor(n, i): return False return True def genPrimes(k): primeCounter = 0 seqCounter = 2 ...
from math import sin, pi, cos, tan class Make_points(): def calc_side_length(self, rad_mul, num_sides): """Side length given the radius (circumradius): i/e the distance from the center to a vertex """ side_length = 2 * (rad_mul / 2) * sin(pi / num_sides) # Apothem, i/e dis...
def search4vowels(word:str) -> set: """Return any vowels found in supplied word.""" vowels = set('aeiou') return vowels.intersection(set(word)) def search4letters(phrase:str, letters:str='aeiou') -> set: """Checks a provided phrase for any of the search letters provided""" return set(letters).inter...
#!/usr/bin/env python3 number = 0 text = 0 space = 0 other = 0 with open ('data.txt') as f: lines = f.readlines() print(lines) for line in lines: for char in line: if char.isalpha(): text +=1 elif char.isdigit(): number +=1 elif char.isspace(): ...
#!/usr/bin/python3 words = { "spring", "table", "cup", "bottle", "coin" } word = 'cup' if (word in words): print("{0} is present in the set".format(word)) else: print("{0} is not present in the set".format(word)) word = 'tree' if (word not in words): print("{0} is not present in the set".format(wor...