text stringlengths 5 121k |
|---|
y = input('Ingrese por favor su Nombre:')
print('hello, {}.'.format(y))
x = input('Ingrese por favor su Nombre:')
print('hello, {}.'.format(x)) |
two_digit_number = input("Type a two digit number: ")
print(type(two_digit_number))
a = int(two_digit_number [0])
b = int(two_digit_number [1])
print (a + b)
|
from datetime import datetime
print(datetime.now())
dt = datetime(2000, 8, 8, 13, 45, 6)
print('dt =',dt)
time_stamp = dt.timestamp()
print('dt.timestamp =', time_stamp)
print('now.timestamp =', datetime.now().timestamp())
now_timestamp = datetime.now().timestamp();
print('now_timestamp =', now_timestamp)
print... |
print()
print('list test...')
classmates = ['Michael','Bob', 'Tracy']
print('classmates =', classmates)
print('len(classmates) =', len(classmates))
print('classmates[1] =', classmates[1])
print('classmates[-1] =', classmates[-1])
print(classmates.append('Alert'), classmates)
print(classmates.insert(2,'Bella'), c... |
from PIL import Image
im = Image.open('test.jpg')
w,h = im.size
print('Original image size: %s:%s' % (w, h))
im.thumbnail((w//2, h//2))
im.save('thumbanil.jpg', 'jpeg') |
print("this is string")
print(123)
print(0.000012)
print(False)
print(5 > 3)
print(None)
print("10 / 3 =", 10 / 3)
print("10 // 3=", 10 // 3)
'''
this is string
123
1.2e-05
False
True
None
10 / 3 = 3.3333333333333335
10 // 3= 3
''' |
L = []
with open('1.txt', 'r') as file:
content = file.readline()
content = file.readline()
while content:
print(content[0:-1].split('\t'))
L.append(content[0:-1].split('\t'))
content = file.readline()
for x in range(len(L)):
for y in range(x+1, len(L)):
item1 = L[x]... |
import json
import csv
def convert_to_csv(received_data, filename):
'''
DESCRIPTION
-------------
Writes a JSON file from IBM Watson STT API to a CSV file saved to the root directory, with headers: WORD, SPEAKER, FROM, TO.
WORD = specific word spoken
SPEAKER = speaker label
FROM = timest... |
"""Plotting functions
This class provides objects and methods to simplify plotting"""
__author__ = "Nils Wenzler"
__copyright__ = "Nils Wenzler"
__version__ = '1'
__maintainer__ = "Nils Wenzler"
__email__ = "wenzlern@ethz.ch"
import matplotlib.pyplot as plt
from numpy import *
class _DataItem():
... |
import random
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.valToIndex = dict()
self.valList = list()
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already cont... |
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head
dummyHead1 = ListNode(None)
dummyHead2 = ListNode(None)
thisTail = dummyHead1
... |
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummyHead = ListNode(None)
dummyHead.next = head
node = dummyHead
while node.next and node.next.next:
next1 = node.next
nex... |
from math import sqrt
class Solution(object):
resultCache = [0, 1, 2, 3]
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
while len(self.resultCache) <= n:
m = len(self.resultCache)
sqrtm = int(sqrt(m))
if m == sqrtm**2:
... |
class WordDistance(object):
def __init__(self, words):
"""
initialize your data structure here.
:type words: List[str]
"""
self.wordToIndices = dict()
for i,w in enumerate(words):
self.wordToIndices.setdefault( w, [] )
self.wordToIndices[ w ].... |
class Solution(object):
def verifyPreorder(self, preorder):
"""
:type preorder: List[int]
:rtype: bool
"""
LB = float("-inf")
stack = []
for x in preorder:
if x < LB:
return False
while stack and x > stack[-1... |
class NestedIterator(object):
def __init__(self, nestedList):
"""
Initialize your data structure here.
:type nestedList: List[NestedInteger]
"""
self.stack = [ [nestedList, 0] ]
def _moveToValid(self):
"""
move stack to a valid po... |
from heapq import heappush, heappop
class Solution(object):
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
n -= 1
UNs = [1]
heap = [(p, p, 0) for p in [2,3,5]]
while n >= len(UNs):
nextUN, p, UNidx = heappop(... |
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums or target<nums[0]:
return 0
if target > nums[-1]:
return len(nums)
Min = 0... |
class Solution(object):
def isBalancedHelper(self, root):
"""
return a pair (isBal, depth)
"""
if root is None:
return (True, 0)
leftIsBal, leftDepth = self.isBalancedHelper(root.left)
if not leftIsBal:
return (False, 0)
rightI... |
class Solution(object):
def depthSumInverseHelper(self, nestedList, currLevel, levelSums):
for e in nestedList:
if e.isInteger():
while currLevel >= len(levelSums):
levelSums.append(0)
levelSums[currLevel] += e.getInteg... |
import argparse
import random
import math
def generate_file(file_name):
"""
Here's my docstring for my generate file. If this doesn't get filled in I get - 5.
Positional Arguments:
file_name is the name of the file,
'w' is for writing,
encoding is 'utf-8' because we're usin... |
'''
Multiplication generator table is cool. User can specify both the number and up
to which multiple. For example user should to input that he/she wants to seea table
listing of the first 15 multiples of 3.
Because we want to print the multiplication table from 1 to m, we have a foor loop
at (1) that iterates over ... |
ch=input()
l=['a','e','i','o','u']
if ch not in l:
print("Consonant")
elif ch in l:
print("Vowel")
else:
print("Invalid")
|
a = int(input())
b = int(input())
c = int(input())
if a > 100:
pa = round((a - 100) * 0.25 + b * 0.15 + c * 0.20, 2)
else:
pa = round(b * 0.15 + c * 0.20, 2)
if a > 250:
pb = round((a - 250) * 0.45+b*0.35+c*0.25, 2)
else:
pb = round(b*0.35+c*0.25, 2)
print("Plan A costs " + str(pa))
print("Plan B costs " + str... |
to = int(input())
v = input()
a = 0
b = 0
for x in v:
if x == "A":
a += 1
elif x == "B":
b += 1
if a == b:
print("Tie")
elif a > b:
print("A")
else:
print("B") |
i = 0
n = 0
while i < 6:
inp = input()
if inp == "W":
n += 1
i += 1
if n > 4:
print("1")
if n == 4 or n == 3:
print("2")
if n == 1 or n == 2:
print("3")
if n == 0:
print("-1") |
a = int(input())
b = int(input())
c = int(input())
an = 91 + (a*1+b*3+c*1)
print("The 1-3-sum is " + str(an)) |
class Operand():
operand = {
1: 'One',
2: 'Two',
3: 'Three',
4: 'Four',
5: 'Five',
6: 'Six',
7: 'Seven',
8: 'Eight',
9: 'Nine'
}
class OperandString(Operand):
op = 0
... |
"""Description of diodes and transistors.
"""
import math
class UnsetPinError(Exception):
def __init__(self, msg_prefix):
self.message = '{} must be set.'.format(msg_prefix)
class Pin(object):
def __init__(self):
self.__voltage = None
def __str__(self):
ret = '{} Volts'.form... |
x=int(input())
for i in range (1,x+1):
print(i,end="")
|
name = input('Enter customer name\n')
print('How may items store have?')
number = int(input()) * len(name)
print('-------------------')
print('Welcome {name}!\nOur store have {number} items'.format(name = name, number = number)) |
class MyClass():
x = 5
def showNumber(n):
print('Number')
my = MyClass()
my.showNumber()
class Animal():
def __init__(self, name, isFlying):
self.__name = name
self.__isFlying = isFlying
def __str__(self):
return f'{self.name} is an Animal'
@property
def name(self):
retu... |
height = int(input('Triangle height? '))
width = 1
for row in range(height):
print(' ' * height + '*' * width + ' ' * height)
width += 2
height -= 1
|
string = input('Input text to convert to l33tspeak: ')
leetDict = {
'A': '4',
'E': '3',
'G': '6',
'I': '1',
'O': '0',
'S': '5',
'T': '7'
}
stringLeet = ''
for character in string:
if character.upper() in leetDict:
stringLeet += leetDict[character.upper()]
else:
strin... |
factorMe = int(input('What number to factorize? '))
for factor in range(1, factorMe+1):
if factorMe % factor == 0:
print(factor)
print(-factor)
|
for multiplicand in range(1, 11):
for multiplier in range(1, 11):
product = multiplicand * multiplier
print(str(multiplicand) + ' X ' + str(multiplier) + ' = ' + str(product))
|
print('Please fill in the blanks below:')
print('Hello, my name is ____(name)____, and today, I\'m going to ____(verb)____.')
name = input('What is your name? ')
verb = input('What action do you take? ' )
print('Hello, my name is {}, and today, I\'m going to {}.'.format(name, verb))
|
class HashMap:
def __init__(self):
self.size = 2
self.hash_map = [None]*self.size
self.vals = [None]*self.size
self.next_free = 0
def add(self, key, val):
if self.next_free >= self.size:
print("Something went wrong")
return
index = hash(... |
from multiprocessing import Process, Queue
import time
"""
Found this beauty on reddit. Cheers to the orig author.
"""
class Pool(object):
"""Very basic process pool with timeout."""
def __init__(self, size=None, timeout=15):
"""Create new `Pool` of `size` concurrent processes.
Args:
... |
from tkinter import *
a=Tk()
a.title("untitled - notepad")
a.geometry("500x500+100+100")
m1=Menu()
l1=Menu()
l1.add_command(label="New")
l1.add_command(label="New Window")
l1.add_command(label="Open...")
l1.add_command(label="Save")
l1.add_command(label="Save As...")
l1.add_command(label="Page-setup...")
l... |
def fact(number):
factorial = 1
for i in range(1,number+1):
factorial = factorial*i
print(factorial)
fact(4)
|
def marketitem(*shoppinglist):
for elements in shoppinglist:
print("you brought:", elements)
shoppinglist = []
while True:
a = input(shoppinglist)
print(a, "you buy from market if you leave enter quit:")
if shoppinglist == "quit":
break
shoppinglist.append(a)
... |
a =int(input("enter first value:"))
b =int(input("enter second value:"))
operator =input("enter operator:")
if operator=="+":
print("answer=",a+b)
elif operator=="-":
print("answer=",a-b)
elif operator=="*":
print("answer=",a*b)
elif operator=="/":
print("answer=",a/b)
elif operator=="**":
... |
"""
Given a string, find the length of the longest substring without repeating characters.
"""
"""
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
"""
def lengthOfLongestSubstring(s: str) -> int:
letter_locs = {}
cur, best, from_ind = 0, 0, 0
... |
"""
This problem was asked by Two Sigma.
Using a function rand5() that returns an integer from 1 to 5 (inclusive) with uniform probability,
implement a function rand7() that returns an integer from 1 to 7 (inclusive).
"""
from random import randint
def rand5():
return randint(1, 5)
def rand7... |
from interval import Interval
def slots_in_interval(length, interval, step=None):
step = length if step == None else step
return (Interval(s, s + length)
for s in range(interval.start, interval.end, step)
if s + length <= interval.end)
def interval_overlaps(interval, intervals):
... |
import matplotlib.pyplot as plt
days=[1,2,3,4,5,6,7]
max_t=[50,51,52,48,47,49,46]
min_t=[43,42,40,44,33,35,37]
avg_t=[45,48,48,46,40,42,41]
plt.plot(days,max_t,label ='Maximum Temperature')
plt.plot(days,min_t, label = 'Minimum Temperature')
plt.plot(days,avg_t, label ='Average Temperature')
plt.xlabel("Day... |
a = 1
b = "2"
print(int(2.5))
"""
PS E:\Python-Projects\Python-Projects\ErrorDebugging> python exceptions.py
File "exceptions.py", line 4
print(a+b)
^
SyntaxError: invalid syntax
"""
print(a+b) |
from tkinter import *
window = Tk()
"""
def km_to_miles():
print(e1_value.get())
miles = float(e1_value.get())*1.6
t1.insert(END,miles)
b1=Button(window,text="Execute",command=km_to_miles)
# pack & grid are used to make these button to visible
b1.grid(row=0,column=0)
e1_value=StringVar()
e1=Entry(wi... |
a,b,c=input().split()
a=int(a)
b=int(b)
c=int(c)
if a%2 == 0:
print("even")
else:
print("odd")
if b%2 == 0:
print("even")
else:
print("odd")
if c%2 == 0:
print("even")
else:
print("odd")
|
def say_hello(name='default'):
print(f'hello {name}')
say_hello('Meetali')
|
import pygame
import math
class Point:
def __init__(self, x,y):
self.x=x
self.y=y
def set_pos(self, position):
self.x=position[0]
self.y=position[1]
class Cross(Point):
def __init__(self, x,y, color):
Point.__init__(self, x,y)
self.color=c... |
"""
Merge sort is an O(n log n) comparison-based sorting algorithm.
Most implementations produce a stable sort, which means that the implementation
preserves the input order of equal elements in the sorted output. Mergesort is a
divide and conquer algorithm that was invented by John von Neumann in 1945.
Conceptually... |
numero = 3738
suma = 0
"""la letra i solo define un valor, puede ser cualquier letra"""
for i in range(1, numero, 1):
if (numero % i) ==0:
print (i, 'es divisor')
suma += i
print ('la suma de los divisores es: ', suma)
|
print('--------------------------------------------------')
N = int(input("How many first prime numbes you want to show: "))
nFound=0
num=2
while nFound<N:
isPrime=1
for i in range(2,num):
if (num % i)==0:
isPrime=0
break
if isPrime==1:
nFound=nFound+1
print... |
prime_numbers = {}
def isPrime(number):
for i in range(2,number):
if number % i == 0:
return False
return True
number = 50
answer_found = 0
for i in range(2, number):
first = isPrime(i)
second = isPrime(number - i)
if (first and second):
prin... |
""" A classifier that makes random predictions. Useful as a mockup. """
import random
import classifier
class RandomClassifier(classifier.Classifier):
def __init__(self, classes, **parameters):
super(RandomClassifier, self).__init__(**parameters)
self.classes = classes
def _classify(s... |
import itertools as it
import math
from random import *
from .compat import *
def prob_choice(iterable, key=None):
""" choice by probability
Choose an element from iterable according to its probability.
Interface can be used similarly to max, min, sorted, etc:
* If given an iterable of (probabil... |
var=1
while (var<=10):
print("Hi i am ", var)
var=var+1
print("")
print("Good Bye!")
|
def quicksort(liste):
if liste == []:
return []
pivot = liste.pop(0)
bigger = list(filter(lambda x: x > pivot, liste))
smaller = list(filter(lambda x: x <= pivot, liste))
return (quicksort(smaller) + [pivot] + quicksort(bigger))
|
def composition(dict_1: dict) -> list:
'''
:param dict_1: Input dictionary
:return: A new list of keys and values in the dictionary
'''
result = []
for k, v in dict_1.items():
result.append(k)
result.append(v)
return result
|
num_str = input("num?\n")
if not isinstance(int(num_str), int):
raise TypeError("not a int")
len = len(num_str)
ans = 0
for i in range(len):
ans += int(num_str[i])
print(ans)
|
""" Command class """
import argparse
import sys
import importlib
import pprint
class Command():
"""
This is a Command class to process subcommands for the cli.
Attributes:
None
"""
def __init__(self):
"""
Constructor for Command class that parses cli subcommands
a... |
"""
乱序字符串是指一个字符串只是另一个字符串的重新排列。例如,'heart' 和 'earth' 是乱序字符串。'python' 和 'typhon' 也是。为了简单起见,我们假设所讨论的两个字符串具有相等的长度,并且他们由 26 个小写字母集合组成。
"""
def anagramSolution1(s1, s2):
a_list = list(s2)
pos1 = 0
stillOK = True
while pos1 < len(s1) and stillOK:
pos2 = 0
found = False
while pos2 < ... |
class Solution:
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n < 0:
return False
hasOne = False
while n > 0:
if n & 1:
if hasOne:
return False
else:
... |
class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
num = int(''.join([str(t) for t in digits]))
num += 1
return [int(s) for s in str(num)]
if __name__ == '__main__':
so = Solution()
... |
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return sorted(s) == sorted(t)
class Solution2(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
... |
def gcd(a,b):
while b:
r = a%b
a = b
b = r
return a
while 1:
try:
numbers = input()
tmpn1 = int(numbers.split()[0])
tmpn2 = int(numbers.split()[1])
print(gcd(tmpn1,tmpn2))
except:
break |
a = input()
b = a.split()
m = b[0]
d = b[1]
s = (int(m)*2+int(d))%3
if s == 0:
print("普通")
if s == 1:
print("吉")
if s == 2:
print("大吉") |
import datetime
import random
class job():
def __init__(self, id_number, salary_per_month, distance, entrance_date,
working_hours):
self.id_number = id_number
self.salary_per_month = salary_per_month
self.distance = distance
self.entrance_date = entrance_date
... |
string = str(input())
ans = ""
for s in string:
if(s.islower()):
ans += s.upper()
else:
ans += s.lower()
print(ans) |
cost = float(input())
tip_per = int(input())
tax_per = int(input())
tip = cost * tip_per / 100
tax = cost * tax_per / 100
total = cost + tip + tax
print("The total meal cost is %d dollars." % round(total))
|
n = int(input())
dic = {}
for i in range(0, n):
line = input().split()
name = line[0]
a = float(line[1])
b = float(line[2])
c = float(line[3])
ave = (a + b + c) / 3
dic[name] = ave
key = str(input())
print("%.2f" % dic[key])
|
from pathlib import Path
import string
ANSWER = "dunno_yet"
print("Welcome to Level 3.")
print("Caeser cipher from a mysterious text file")
print("---\n")
""" There is text living in: files/mysterious.txt
You've got to try and figure out what the secret message contained in it is.
The enemy have hidden it in b... |
from datetime import datetime
from Sorter import Sorter
class TimerSorter(Sorter):
def timerSort(self, list_):
start = datetime.now()
self.sort(obj)
end = datetime.now()
print("time:"+(end - start))
|
with open("rosalind_fib.txt", "r") as f:
n, k = (int(value) for value in f.read().split())
pairs_1, pairs_2 = 1, 1
for i in range(n-2):
pairs_1, pairs_2 = pairs_2, pairs_1*k + pairs_2
print(pairs_2) |
"""
python的内建模块itertools
"""
import itertools
def test1():
"""
无限的迭代
:return:
"""
natuals = itertools.count(1)
for i in natuals:
print(i)
def test2():
"""
重复迭代
"""
cs = itertools.cycle("abc")
def test3():
natuals = itertools.count(1)
ns = itertools.tak... |
"""
ORM框架
"""
class user2(object):
def __init__(self, id, name):
self.id = id
self.name = name
from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class user2(Base):... |
aa = (1, 2, 3, 4)
print(type(aa))
bb = {1, 2, 3, 4, 5}
print(type(bb))
cc = set([1, 2])
print(cc)
dd = dict(na='a', d='c')
print(dd['d'])
tree = {'root': {'chil1': {'grandson1': 'maxiu', 'grandson2': 'liyliy'}, 'child2': 'jerry'}}
print(tree.keys())
print(tree.values())
tree2 = list(tree.values())
print(tree2)
print(... |
"""
判断有无重复数字,
先排序再判断
"""
class Solution:
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
nums.sort()
length = len(nums)
if length == 0:
return False
if length == 2 and nums[0] == nums[1]:
return T... |
arr = [2, 3, 1, 1, 35, 6]
for a in iter(arr):
print('a', a)
import numpy as np
aa = np.array([1, 1])
|
"""
实现单层神经网络
"""
import numpy as np
def load_dataset():
pass
def ReLU(z):
mz, nz = z.shape
zero = np.zeros(mz, nz)
return np.maximum(zero, z)
def sigmoid(z):
return 1.0 / (1 + np.exp(z))
def tansformArray(inX):
shape = inX.shape
shape1 = shape[1] * shape[2] * shape[3]
tra... |
"""
线性回归,对代价函数使用梯度下降法
"""
import numpy as np
def errorFunc(theta, x, y):
"""
代价函数,使用的是距离
:param theta:
:param x:
:param y:
:return:
"""
m = len(theta)
diff = np.dot(theta, x.T) - y
return (1 / 2) * (1 / m) * diff ** 2
def derivativesFunc(theta, x, y):
"""
计算代价函数的导函数
... |
class Solution:
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
n = len(nums)
for i in range(0, n):
for j in range(i + 1, n):
if nums[i] > nums[j]:
... |
def get_rows(puzzle_string):
list_of_strings = []
for i in range(10):
start = i * 10
end = (i+1) * 10
row_string = get_row(puzzle_string, start, end)
list_of_strings.append(row_string)
return list_of_strings
def get_row(puzzle_string, start, end):
string_o... |
from finder_funcs import *
def main():
puzzle_string = input()
list_of_words = input()
print("Puzzle:\n")
list_of_puzzle = get_rows(puzzle_string)
for characters in list_of_puzzle:
print(characters)
print("")
list_words = list_of_words.split(" ")
for index in range(len(lis... |
number = 600851475143
import math
def isPrime(n):
for j in range(int(n/2)+1,2,-1):
if n % j == 0:
return False
return True
i = int(math.sqrt(number))
while i:
if number % i == 0:
if isPrime(i):
print(i)
break
i -=1 |
import math
import os
import random
import re
import sys
def compareTriplets(a, b):
ascore = 0
bscore = 0
for i in range (0, 3, +1):
if a[i]>b[i]:
ascore = ascore + 1
elif a[i]<b[i]:
bscore = bscore + 1
nums = []
nums.insert(0,ascore)
... |
class Test():
def __init__(self, a, b):
self.a = int(a)
self.b = int(b)
def print_out(self):
print("print_out:", self.a + self.b)
@classmethod
def classmethod_sum(cls, a, b):
cls.a = int(a)
cls.b = int(b)
print('classmethod_sum:', cls.a + cls.b)
@st... |
import sys
def read_theta():
try:
with open("data/theta.csv", "r") as theta_file:
theta_file.readline()
theta_list = theta_file.readline().split(",")
theta0 = float(theta_list[0])
theta1 = float(theta_list[1])
theta_file.close()
except:
... |
with open("name.txt", "w") as f:
f.write("hello")
with open("name.txt", "a") as f:
f.write("Aisha")
with open("name.txt") as f:
print(f.read())
|
"""
Problem 4: Your Initials Here, Please...
"""
name = input( "Input name: " )
splitAt = name.find( " " )
print( "Hello {}!".format( name[0].upper() + name[splitAt+1].upper() ) ) |
"""
Problem 1: Squares.
"""
n = max( 1, int( input( "Provide square length: " ) ) )
for i in range( n ):
for j in range( n ):
if j == 0 or j == n - 1:
print( "*", end="" )
elif i == 0 or i == n - 1:
print( "*", end="" )
else:
print( " ", end="" )
print() |
'''
Write a program which takes 5 strings as inputs and appends them to a list l. Swap each element in l with its mirror - that is, for some element at index i, swap l[i] with l[4-i] if i < 3.
For instance, if l = ['Alex', 'Bob', 'Charlie', 'David', 'Ethan'], then after swapping, l should read
['Ethan', 'David', 'Char... |
'''
Given a string *s* of length 5, write a function to determine if *s* is palindromic.
'''
def isPalindromic(s):
for i in range (0, 2):
if s[i] != s[4-i]:
return False
return True
def main():
s = input()
print(isPalindromic(s))
if __name__ == '__main__':
main() |
from utils import is_palindromic
def problem_004(n_digits: int = 3):
"""
In a loop from sqrt(n) to 1 check if i is factor of n and i is a prime number.
- O(n^2) time-complexity
- O(1) space-complexity
"""
result = 0
for i in range(10**n_digits - 1, 10**(n_digits - 1) - 1, -1):
for... |
def problem_009(n: int = 1000) -> int:
"""
Use loop over a with nested loop over b (express c = n - a - b).
- O(n^2) time-complexity
- O(1) space-complexity
"""
for a in range(1, n // 2 + 1):
for b in range(1, n // 2 + 1):
c = n - a - b
if a**2 + b**2 == c**2:
... |
import time
timenow = time.localtime(time.time())
year,month,day,hour,minute = timenow[0:5]
print(str(day) + "/" + str(month) + "/" + str(year))
print(str(hour) + ":" + str(minute))
|
class Friend:
def __init__(self):
self.job = "None"
def getJob(self):
return self.job
def setJob(self, job):
self.job = job
Alice = Friend()
Bob = Friend()
Alice.setJob("Carpenter")
Bob.setJob("Builder")
print(Bob.job)
print(Alice.job)
|
resultado = 1
def Operacion(resultado):
if resultado <= 100:
print (resultado)
return (Operacion(resultado+1))
Operacion(resultado)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.