text stringlengths 5 121k |
|---|
import random
numList = list(range(1,101))
numBomb = random.choice(numList)
print(numBomb)
while True:
try:
number1 = input("Please select a number between 1 and 100:")
number1 = int(number1)
print(number1)
if number1 == numBomb:
print("Congr... |
import os
os.path.join('folder1', 'folder2', 'folder3', 'file.png')
os.sep
os.getcwd()
os.chdir('c:\\')
os.getcwd()
os.path.abspath('spam.png')
os.path.abspath('..\\..\spam.png')
os.path.isabs('..\\..\\spam.png')
os.path.relpath('c:\\folder1\\folder2\\spam.png', 'c:\\folder1')
os.path.dirname('c:\\... |
from typing import List
class Stack:
def __init__(self):
self.stack: List[str] = []
@property
def stack(self) -> List[str]:
return self._stack
@stack.setter
def stack(self, new_stack: List[str]) -> None:
if isinstance(new_stack, List):
... |
class HashTable:
def __init__(self,length):
self.length=length
self.data=[[] for i in range(self.length)]
def Get_Array(self):
return self.data
def __Get_Hash(self,key):
Hash_key=0
for i in key:
Hash_key+=ord(i)
return Hash_key%... |
class Contacto:
def __init__(self, name, phone, email):
self._name = name
self._phone = name
self._email = email
class ContactoBook:
def __init__(self):
self._contactos = []
def add(self):
name = str(input("Ingrese el nombre: "))
phone = str(input("Ingrese e... |
import math
def dist(p1, p2):
return math.hypot(p2[1] - p1[1], p2[0] - p1[0])
class Vector:
def __init__(self, p1, p2):
self.x = p2[0] - p1[0]
self.y = p2[1] - p1[1]
def compare(self, v2):
return Vector(self.x, self.y, v2.x, v2.y)
def show(self):
print (str(self.x) +... |
"""
Given two arrays, write a function to compute their intersection.
"""
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1.sort()
nums2.sort()
index1 = 0
index2 = 0
output = []
while index1 < len(nums1) a... |
"""
There are N network nodes, labelled 1 to N.
Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node, v is the target node, and w is the time it takes for a signal to travel from source to target.
Now, we send a signal from a certain node K. How long will it take for ... |
myComputer = {
"brand": "Apple",
"color": "Grey",
"size": 15.4,
"language": "English"
}
print(myComputer)
myBag = {
"color": "Black",
"brand": "MM6",
"bagWidth": 22,
"bagHeight": 42
}
print(myBag)
myApartment = {
"location": "New York City",
"type": "studio",
"... |
class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.buckets = [None] * 10
def add(self, key):
while len(self.buckets) <= key:
self.buckets = self.buckets + [None] * len(self.buckets)
self.buckets[key] = key
d... |
__author__ = 'guang'
from bst import TreeNode
class Solution(object):
def is_leaf(self, node):
return node and node.left is None and node.right is None
def path_sum(self, node):
"""
>>> s = Solution()
>>> s.path_sum(None)
(0, -2147483648)
>>> s.path_sum(TreeNod... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeDuplicateNodes(self, head: ListNode) -> ListNode:
seen = set()
sentinel = ListNode(0)
sentinel.next = head
prev = sentinel
node = prev.next
while ... |
class Solution:
def convert(self, email):
localname, domain = email.split("@")
name = ""
for char in localname:
if char == '.':
continue
elif char == '+':
break
else:
name = name + char
return name + ... |
from bst import TreeNode
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
>>> s = Solution()
>>> root = TreeNode(None).from_string("1,2,3")
>>> s.preorderTraversal(root)
[1, 2, 3]
>>> root = TreeNod... |
class Solution:
def generateParenthesis(self, n):
if n == 1:
return ["()"]
elif n == 2:
return ["()()", "(())"]
else:
result = set()
for parenthesis in self.generateParenthesis(n-1):
result.add("({})".format(parenthesis))
... |
__author__ = 'guang'
class Solution(object):
def palindrome(self, s):
"""
:param s:
:return:
>>> s = Solution()
>>> s.palindrome("A")
True
>>> s.palindrome("")
True
"""
if len(s) == 0:
return True
i, j = 0, len(s)... |
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
class Solution:
def indexof(self, head, node):
current = head
index = 0
while current:
if current == node:
... |
__author__ = 'guang'
__author__ = 'guang'
from bst import TreeNode
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
>>> s = Solution()
>>> three, nine, twenty, fifty, seven = TreeNode(3), TreeNode(9), TreeNode(20), ... |
class Solution:
def thirdMax(self, nums):
stack = []
remain = []
for num in nums:
if len(stack) == 0:
stack.append(num)
else:
while len(stack) > 0:
top = stack[-1]
if top < num:
... |
__author__ = 'guang'
from linklist import LinkedList, ListNode
class Solution(object):
def empty(self, ls):
head, tail = ls
return head is None and tail is None
def append(self, node, ls):
"""
>>> s = Solution()
>>> node = ListNode(3)
>>> head = LinkedList.from... |
class Solution:
def stretchy(self, word, string):
index, prev, count, stretch, length = 0, None, 0, False, len(word)
for char in string:
if index < length and char == word[index]:
if stretch and count < 3:
return False
stret... |
class Solution:
def merge(self, nums1, m, nums2, n):
"""
Do not return anything, modify nums1 in-place instead.
"""
last, i, j = m + n - 1, m - 1, n - 1
while last >= 0:
if i >= 0 and j >= 0:
if nums1[i] >= nums2[j]:
nums1[la... |
import string
class Solution:
def word_count(self, word):
result = {}
for char in word:
char = char.lower()
if char in string.ascii_lowercase:
result[char] = result.get(char, 0) + 1
return result
def contains(self, current, words):
for ... |
class Solution:
def word_count(self, word):
count = {}
for char in word:
count[char] = count.get(char, 0) + 1
return count
def all_is_subset(self, sets, word):
target = self.word_count(word)
sources = [self.word_count(item) for item in sets]
... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
acc = 0
class Solution:
def dfs(self, root):
global acc
if root is None:
return
if root.right:
self.dfs(root.right)
print(f"{root.val}->{root... |
class Solution:
def mostCommonWord(self, paragraph, banned):
count = {}
result, maximum = "", 0
p = ""
for char in paragraph:
if char in (["!", "?", "'", ",", ";", "."]):
p = p + " "
else:
p = p + char.lower()
p = p.... |
class Solution:
def rotate(self, nums, k):
length = len(nums)
tmp = nums[:]
for index, num in enumerate(nums):
new_index = (index + k) % length
nums[new_index] = tmp[index]
print(nums)
if __name__ == '__main__':
s = Solution()
s.rotate([1, 2, 3, ... |
class Solution:
def calculateRight(self, arr, length, left):
j = left + 1
if j >= length:
return length - 1
if arr[j] > arr[left]:
while j < length and arr[j] > arr[j-1]:
j = j + 1
return j - 1
else:
retur... |
class Solution(object):
def to_result(self, sign, result):
if (sign == '+' and result > 2147483647) or (sign == '-' and result >= 2147483647):
return 2147483647
if sign == '+':
return result
else:
return -result
def divide(self, dividend, divisor)... |
__author__ = 'guang'
from bst import TreeNode
class Solution(object):
def is_mirror(self, tree_a, tree_b):
"""
>>> s = Solution()
>>> two, three, four = TreeNode(2), TreeNode(3), TreeNode(4)
>>> two.left, two.right = three, four
>>> another_two, another_three, another_four ... |
class Solution:
def toLowerCase(self, text):
if len(text) == 0:
return ""
result = ""
for char in text:
result = result + char.lower()
return result
|
class Solution:
def isOneBitCharacter(self, bits):
if len(bits) == 0:
return False
start, end = 0, len(bits)
while start < end:
if bits[start] == 1:
step = 2
start = start + step
else:
step = 1
... |
class Solution:
def longestWord(self, words):
words = sorted(words, key=len)
prefix = set()
result, maxlen = "", 0
for word in words:
length, flag = len(word), False
if length == 1:
prefix.add(word)
flag = True
... |
class Complex(object):
def to_int(self, number):
if len(number) == 0:
return 0
else:
return int(number)
def virtual_to_int(self, virtual):
if len(virtual) == 0:
return 0
assert 'i' in virtual
virtual = virtual.strip('i')
if... |
class Solution:
def hIndex(self, citations):
if len(citations) == 0:
return 0
citations = sorted(citations, reverse=True)
count, seen = {}, set()
acc = 0
for citation in citations:
if citation not in seen:
seen.add(citation)
... |
import string
class MagicDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.origin = {}
def buildDict(self, words):
"""
Build a dictionary through a list of words
"""
for word in words:
length = len(... |
class Solution:
def can_divide(self, string, pattern):
len_string = len(string)
len_pattern = len(pattern)
if len_string < len_pattern:
return False
elif len_string == len_pattern:
return string == pattern
elif len_string % len_pattern != 0:
... |
class Solution:
def minArray(self, numbers):
length = len(numbers)
left, right = 0, length - 1
while left < right:
mid = (left + right) // 2
if (mid-1 >= 0 and numbers[mid-1] > numbers[mid]) and\
(mid+1 < length and numbers[mid+1] > numbers[mid]):
... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def bfs(self, node):
if node is None:
return 0
height = 0
level = [None, node]
while len(level) > 0:
node = level.pop(... |
class Solution:
def bit_plus(self, a, b, carry):
return (a ^ b) ^ carry, (a & b) | (a ^ b) & carry
def getSum(self, a, b):
digit, carry, result = 1, 0, 0
while True:
a_bit = a & digit
b_bit = b & digit
if a_bit == 0 and b_bit == 0:
b... |
__author__ = 'guang'
from linklist import LinkedList
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
>>> s = Solution()
>>> head = LinkedList.fromList([1, 2, 6, 3, 4, 5, 6])
>>> result = s... |
class Solution:
def isValid(self, sub, result):
if sub[0] == '0':
if sub != '0':
return False
number = int(sub)
if number < 0 or number > 2**31 - 1:
return False
length = len(result)
if length >= 2:
if int(result[-2]) + i... |
class Solution:
def numJewelsInStones(self, jewels, stones):
return len([stone for stone in stones if stone in jewels])
if __name__ == "__main__":
s = Solution()
r = s.numJewelsInStones("aA", "aAAbbbb")
print(r)
assert r == 3
|
class Solution:
def countSegments(self, s):
if s == '':
return 0
s = s.strip()
return len([word for word in s.strip().split(' ') if len(word) > 0])
if __name__ == '__main__':
s = Solution()
r = s.countSegments(", , , , a, eaefa")
assert r == 6
r = s.... |
def sayHello(name):
print(f'Hola {name}')
sayHello('Carlitos')
def sayHello(name='Muchachicho'):
print(f'Hola {name}')
sayHello()
def getSum(num1, num2):
total = num1 + num2
return total
num = getSum(3, 14)
print(num)
getSum = lambda num1, num2 : num1 + num2
print(getSum(10, 17)) |
from sheet import Sheet
from utils import insertRectangles, showNestedDiagram
n = int(input("Enter the number of rectangles : "))
input_rect = []
sheetLength, sheetBreadth = 0, 0
print('Enter length and breadth of each rectangle separated by space eg, : 100 20')
for i in range(n):
s = input("rect {} length... |
from math import factorial
from itertools import count
def fibo_gen():
for el in count(1):
yield factorial(el)
x = 0
for i in fibo_gen():
print('Factorial {} - {}'.format(x + 1, i))
if x == 14:
break
x += 1 |
from numpy import ones, fill_diagonal
feromonas = ones((6, 6), int)
fill_diagonal(feromonas, 0)
feromonas = list([list(_) for _ in feromonas])
distancias = list()
distancias.append([0, 20, 10, 33, 8, 2])
distancias.append([20, 0, 6, 15, 5, 3])
distancias.append([10, 6, 0, 24, 23, 13])
distancias.append([33, 15... |
import random
import time
from threading import Thread, Condition
class JobsAndUsers:
def __init__(self, number_of_users, number_of_resources, job_size):
self.n = number_of_users
self.r = number_of_resources
self.m = job_size
self.resources = [Condition() for _ in range(number_of_r... |
temperatures = {
'София': -14,
'Новосибирск': -31,
'Таити': 30,
'Таити1': [30, 2],
'Варна': {22, 3},
'Русе': {
"temperature": -23,
"humidity": 90,
},
'ловдив': None,
'Пазарджик': None
}
print("-" * 20)
print(temperatures)
print(temperatures['София'])
print(temperatur... |
import math
MAX_LETTERS = 20
def collect_data(text: str) -> dict:
if not text:
raise ValueError('The text is empty.')
letters = {}
for ch in text.upper():
if ch.isalpha():
if ch not in letters:
letters[ch] = 0
letters[ch] += 1
return letters... |
input = 33
real_andy = 11
real_abc = "ab"
if real == input:
print("hoe")
elif real_andy == input:
print("hey andy")
else:
print("you are not a hoe")
|
xValue= 20
while xValue>=10:
print(xValue)
xValue= xValue - .5
for i in range(25):
import math
print(math.sqrt(i))
vaild= False
while not vaild:
value= int(input("number please"))
if value > 0 and value < 100:
valid= True
else:
print("CORRECT!") |
def showNumbers(limit):
for number in range(0, limit+1):
if number % 2 == 0:
print(f'{number} EVEN')
else:
print(f'{number} ODD')
showNumbers(5)
|
a=0
b=1
print(a,b)
n=int(input("enter a number"))
for i in range (n-2):
c=a+b
a=b
b=c
print(c)
|
print("Geben Sie ein Datum ein (TT.MM.JJJJ):")
x = input()
z = x[6] + x[7] + x[8] + x[9] + x[3] + x[4] + x[0] + x[1]
filename = z+".txt"
f = open(filename, "r")
print(f.read())
|
import sys
import json
with open(sys.argv[1], "r") as JSON:
json_dict = json.load(JSON)
letters, alph = sys.argv[2], "qwertyuiopasdfghjklzxcvbnm"
required, additional = letters[0], letters[1:]
common = set(json_dict[required])
for letter in additional:
letter_set = set(json_dict[letter])
intersection = common.... |
def rotateArray(A,k):
if k == 0 or k == len(A):
return print(A)
elif k > len(A):
return print(A)
else:
output = []
output = A[-k:]
output.extend(A[0:-k])
return print(output)
rotateArray([1,2,3,4,5,6,7,8,9,10],2)
rotateArray([1,2,3,4,5,6,7,8,9,10],0)
rotateAr... |
import sqlite3
conn = sqlite3.connect("customer.db")
c = conn.cursor()
c.execute("SELECT rowid,* FROM customers ORDER BY rowid ")
c.execute("SELECT rowid,* FROM customers ORDER BY rowid DESC")
items = c.fetchall()
for item in items:
print(item)
conn.close()
|
y=int(input())
z=int(input())
for num in range(y,z):
order = len(str(num))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if num == sum:
print(num)
|
username = input()
password = input()
new_password = input()
while new_password != password:
new_password = input()
print(f"Welcome {username}!") |
month = input()
hours = int(input())
people_in_group = int(input())
time_of_the_day = input()
per_hour = 0
if month == "march" or month == "april" or month == "may":
if time_of_the_day == "day":
per_hour = 10.50
elif time_of_the_day == "night":
per_hour = 8.40
elif month == "june" or month == ... |
import math
width = float(input())
lenght = float(input())
high = float(input())
astronaught_h = float(input())
rocket_s = width * lenght * high
room_s = (astronaught_h + 0.4) * 2 * 2
persons = rocket_s / room_s
persons = math.floor(persons)
if persons <= 2:
print(f"The spacecraft is too small.")
elif 3 <= person... |
product = input()
day = input()
quantity = float(input())
if day == "Saturday" or day == "Sunday":
if product == 'banana':
banana_cost = 2.70 * quantity
print(f'{banana_cost:.2f}')
elif product == 'apple':
apple_cost = 1.25 * quantity
print(f'{apple_cost:.2f}')
elif product ... |
import math
wall_h = int(input())
wall_w = int(input())
percentage_wp = int(input())
total_area = wall_h * wall_w * 4
area_for_painting = total_area - (total_area * percentage_wp / 100)
while True:
painted = input()
if painted == "Tired!":
print(f"{math.ceil(area_for_painting)} quadratic m left.")
... |
fruit = input()
size = input()
quantity = int(input())
if fruit == "Watermelon":
if size == "small":
small_W_price = quantity * 2 * 56
if small_W_price < 400:
print(f'{small_W_price:.2f} lv.')
elif 400 <= small_W_price <= 1000:
final_price = small_W_price - small_W_p... |
import math
w = float(input())
h = float(input())
height = h * 100 - 100
h_desk = math.floor(height / 70)
wide = w * 100
w_desk = math.floor(wide / 120)
total_desks = h_desk * w_desk - 3
print(total_desks) |
width = int(input())
lenght = int(input())
hight = int(input())
volume = width * lenght * hight
command = input()
while command != 'Done':
boxes = int(command)
volume -= boxes
if volume <= 0:
print(f'No more free space! You need {abs(volume)} Cubic meters more.')
break
command = inpu... |
import sys
numbers = int(input())
bigger_n = -sys.maxsize
smaller_n = sys.maxsize
for n in range(1, numbers+1):
number = int(input())
if number < smaller_n:
smaller_n = number
if number > bigger_n:
bigger_n = number
print(f'Max number: {bigger_n}')
print(f'Min number: {smaller_n}') |
mackerel_price = float(input())
caca_price = float(input())
bonito_kg = float(input())
horse_mackerel_kg = float(input())
mussels_kg = float(input())
bonito_price = mackerel_price * 1.6
horse_mackerel_price = caca_price * 1.8
sum_bonito = bonito_price * bonito_kg
sum_horse_mackerel = horse_mackerel_price * horse_macke... |
days = int(input())
money_won = 0
total_wins = 0
total_loses = 0
for day in range(1, days+1):
result = input()
money_won_per_day = 0
wins = 0
loses = 0
while result != "Finish":
result = input()
if result == "win":
wins += 1
money_won_per_day += 20
el... |
company = input()
tickets_adult = int(input())
tickets_kids = int(input())
ticket_price = float(input())
fee = float(input())
kid_t_price = ticket_price * 0.3
tickets_adult_total = ticket_price + fee
tickets_kids_total = kid_t_price + fee
total_t_price = tickets_adult_total * tickets_adult + tickets_kids_total * ticke... |
n1 = int(input())
n2 = int(input())
operatora = input()
result = 0
result_type = ''
if n2 == 0 and operatora == '/' or n2 == 0 and operatora == '%':
print(f"Cannot divide {n1} by zero")
quit()
if operatora == '+':
result = n1 + n2
elif operatora == '-':
result = n1 - n2
elif operatora == '*':
res... |
import math
def calc_variance(dataset):
mean = sum(dataset)/len(dataset)
variances = []
for value in dataset:
variances.append((value - mean)**2)
variance = sum(variances)/len(dataset)
return variance
def calc_std(variance):
return math.sqrt(variance)
def print_spread(dataset):
va... |
import math
bottle = []
def vol():
pi = math.pi
bottle.append(bottle[1]*pi*(bottle[0]**2))
bottle.append((bottle[2]/bottle[3])*100)
bottle[3] = round(bottle[3], 2)
bottle[4] = round(bottle[4], 2)
if bottle[4] > 100:
bottle.append("overflow")
else:
bottle.append("")
... |
s1 = "2021"
s2 = "03"
s3 = "21"
n1 = 12345.12345
n2 = 54321.54321
print("(1) Today is {}/{}/{}" .format(s1, s2, s3))
print("(2) n1={}, n2={}" .format(n1, n2))
print("(3) n1={:!^40.3f}" .format(n1))
print("(4) n2={:15.3e}" .format(n2))
print("(5) n1={:%<10.2f}" .format(n1))
|
st1 = input("Enter the first string:")
st2 = input("Enter the second string:")
st1 = list(st1)
st2 = list(st2)
if sorted(st1) == sorted(st2):
print("%s, %s is anagram." %(str(''.join(st1)),str(''.join(st2))))
else :
print("%s, %s is not anagram." %(str(''.join(st1)),str(''.join(st2))))
|
input1_ = input('Enter the first string:')
input2_ = input('Enter the second string:')
input_1 = list(input1_)
input_2 = list(input2_)
if (sorted(input_1) == sorted(input_2)) and (len(input_1) == len(input_2)):
print(input1_, ',', input2_, 'is anagram.')
else:
print(input1_, ',', input2_, 'is not anagram... |
n1, n2 = map(int, input("Enter N1, N2(0 < N1 <= N2) : ").split())
n3 = 0
for i in range(n1, n2+1):
if (i % 2) == 0 :
n3 = n3 + i
else :
continue
print("Sum of even numbers between %d and %d is %d." %(n1, n2, n3))
|
def operation(in1):
ft1, ft2, ft3 = in1.split()
ft1 = float(ft1)
ft3 = float(ft3)
result = 0
flag = 0
if ft2 == "+":
result = ft1 + ft3
elif ft2 == "-":
result = ft1 - ft3
elif ft2 == "*":
result = ft1 * ft3
elif ft2 == "/":
if ft3 == 0:
f... |
s = "Sogang University"
print("original_s:", s)
for i in range(len(s)-1, -1, -1):
print(s[i], end="")
print()
|
"""
Find the first four consecutive integers to have four distinct prime
factors each. What is the first of these numbers?
"""
from math import sqrt
def is_prime_from_list(n):
global prime_list
if len(prime_list) == 0:
return True
for p in prime_list:
if n%p == 0:
return False... |
"""
Created on Sat May 30 13:18:25 2020
@author: israel
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Which starting number, under one million, produces the longest chain?
"""
def get_sequence(number):
count = 0
n = number
w... |
"""
Created on Sat Jun 6 18:24:43 2020
@author: israel
The number, 197, is called a circular prime because all rotations
of the digits: 197, 971, and 719, are themselves prime.
How many circular primes are there below one million?
"""
def is_prime_number(n):
if n < 0:
return False
start = in... |
"""
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
primes = [2,3,5,7]
def get_factors(n):
if n in primes:
return [int(n)]
else:
for i in range (2,int(n)):
if int(n)%i == 0:
resto = g... |
"""
Find the sum of the only eleven primes that are both truncatable
from left to right and right to left.
"""
def is_prime_number(n):
if n < 2:
return False
start = int(n**0.5)
for i in range(start, 1, -1):
if n%i == 0:
return False
return True
def all_primes(numbers):
... |
"""
Created on Wed May 27 19:32:24 2020
@author: israel
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def is_palindrome(number):
st = str(number)
size = len(st)
for i in range(0,int(size/2)):
if (st[i] != st[size-i-1]):
return False
return True
... |
"""
A number that never forms a palindrome through the reverse and add process is called a Lychrel number.
How many Lychrel numbers are there below ten-thousand?
"""
def is_palindrome(number):
st_n = str(number)
st_r = ''
for i in range(len(st_n)-1,-1,-1):
st_r += st_n[i]
return st_n == st_r
... |
employees = []
while True:
print("1. Add employee")
print("2. Delete employee")
print("3. Search employee")
print("4. Display all employee")
print("5. Change a employee name in the list")
print("6. exit")
ch = int(input("Enter your choice: "))
if ch is None:
print("no data present in Employees")
elif ch =... |
from random import randint
def sorteio(lista):
print(f'Sorteando 5 valores da lista: ',end='')
for i in range(0,5):
x= randint(1,10)
lista.append(x)
print(f'{x} ', end='', flush=True)
print('PRONTO!')
def somaPar(lista):
soma=0
for i in lista:
if i % 2 == 0:
... |
def leiaint(msg):
bol = False
value = 0
while True:
x = str(input(msg))
if x.isnumeric():
value = int(x)
bol = True
else:
print('\033[0;31mErro! Digite um número inteiro válido\033[m')
if bol:
break
return value
n = leiain... |
import random
import string
def hangman():
word =random.choice(["pugger","littlepugger","monkey","lemon","tamarind"
,"apple","mango","fruits","ginger","tiger","thor",
"avengers","ironman"])
validletters=string.ascii_lowercase
turns=10
guessmade=''
while len(word)... |
import re
frequency = {}
first_list = []
second_list = []
document_text = open('frankenstein.txt', 'r')
text_string = document_text.read().lower()
match_pattern = re.findall(r'\b[a-z]{1,15}\b', text_string)
for word in match_pattern:
count = frequency.get(word, 0)
frequency[word] = count + 1
first_list.... |
class Solution:
def getIntersectionNode(self, headA, headB):
pA, pB = headA, headB
tailA, tailB = False, False
while pA and pB:
if pA == pB:
return pA
pA = pA.next
if not pA and n... |
class Solution:
"""
@param height: A list of integer
@return: The area of largest rectangle in the histogram
"""
def largestRectangleArea(self, height):
if not height:
return 0
length = len(height)
stack = []
ans = float('-inf')
f... |
class Solution:
"""
@params s1, s2, s3: Three strings as description.
@return: return True if s3 is formed by the interleaving of
s1 and s2 or False if not.
@hint: you can use [[True] * m for i in range (n)] to allocate a n*m matrix.
"""
def isInterleave(self, s1, s2, s3):
... |
class Solution:
def mergekSortedArrays(self, arrays):
def merge(list1, list2):
if not list1:
return list2
if not list2:
return list1
len1, len2 = len(list1), len(list2)
start1, start2 = 0, 0
... |
class Solution:
def isPalindrome(self, head):
def reverse(root):
cur = None
while root:
tmp = root.next
root.next = cur
cur = root
root = tmp
return cur
if n... |
import heapq
class Solution:
"""
@param nums: A list of integers.
@return: The median of numbers
"""
def medianII(self, nums):
if not nums:
return []
maxlen, minlen = 0, 0
maxheap, minheap = [], []
ans = []
for n in nums:... |
"""
Definition of ArrayReader:
class ArrayReader:
def get(self, index):
# this would return the number on the given index
# if there is no number on that index, return -1
"""
class Solution:
def searchBigSortedArray(self, reader, target):
if not reader:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.