text stringlengths 5 121k |
|---|
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
m = len(board)
n = len(board[0])
dx = [-1,-1,-1,0,1,1, 1, 0]
dy = [-1, 0, 1,1,1,0,-1,-1]
... |
from collections import defaultdict
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
ans = defaultdict(list)
for string in strs:
count = [0]*26
for c in string:
count[ord(c) - ord('a')] += 1
ans[tuple(count)].appe... |
dominoarea = 2
linha, coluna = input().split()
linha = int(linha)
coluna = int(coluna)
area = linha*coluna
dominos = area//dominoarea
print(dominos)
|
active = True
while active:
num1 = int(input('Enter first number: '))
oper = input('Enter operations: ')
num2 = int(input('Enter second number: '))
if oper == '+':
print(num1+num2)
elif oper == '-':
print(num1-num2)
else:
if oper == '*':
print(num1*num2... |
def euler_method(dy_times_dx_func, x_start, x_end, y0, n_steps):
h = float(x_end - x_start) / float(n_steps)
x = x_start
y = y0
for _ in range(n_steps):
y = y + h * dy_times_dx_func(x, y)
x = x + h
return y
def newton_method(func, derivative_func, x_start, n_iterations, m=1):
... |
from numpy import dot
from math import sqrt
def cosine(a,b):
return dot(a,b) / (sqrt(dot(a,a))*sqrt(dot(b,b)))
print(cosine((1,1,1), (-1,1,1))) |
import random
from typing import List
def mean(lst: List[int]) -> int:
return sum(lst) / len(lst)
print(mean([random.randint(10, 90) for _ in range(20)])) |
from nltk.corpus import stopwords
sw = stopwords.words("english")
from Functions.functions import iterative_levenshtein as lev
from Functions.functions import get_key
def create_work_dictionary(out_path, dictionary, input_list):
def leven_score(name, elem_list, min_ = 1):
... |
import random
def intcheck(question):
while True:
response = input(question)
round_error = "Please type either <enter> or an " \
"integer that is more than 0\n"
if response != "":
try:
response = int(response)
... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
'''
Part 1: UFO
'''
ufo = pd.read_csv('https://raw.githubusercontent.com/sinanuozdemir/SF_DAT_17/master/data/ufo.csv')
ufo.columns = [x.replace(" ", "").lower() for x in ufo.columns]
ufo.head()
ufo.count(axis = 1)
ufo['shapereported']... |
"""
Created on Tue Mar 12 12:59:00 2019
@author: macbook
"""
from textblob import TextBlob
import re
import string
def clean_data(tweet):
tweet = re.sub(r'\&\w*;', '', tweet)
tweet = tweet.lower()
tweet = re.sub('@[^\s]+','AT_USER',tweet)
tweet = re.sub(r'[' + string.punctuation.r... |
print("Word Problem 1")
print("If a group of 5 students work on a project for 70 hours and they")
print("split the work evenly, how many hours does each student work?")
input("Press enter to find out.")
print("70 / 5 =", 70 // 5)
print("")
print("Word Problem 2")
print("If George orders 6 whole pizza cut into 12 slice... |
opc=0
max=3
while(opc!= max):
print("############### MENU ##############")
print("#1. agregar area triangulo")
print("#2. agregar area trapecio ")
print("#3. salir ")
opc=libreria.pedir_numero("Ingreso la opcion:", 1, 3)
if (opc==1):
opcionareatriangulo()
if (opc==2):
... |
import libreria
opc=0
max=3
while(opc!= max):
print("############### MENU ##############")
print("#1. pedir RUC ")
print("#2. Mostrar monto")
print("#3. Salir")
opc=libreria.pedir_numero("Ingreso la opcion:", 1, 3)
if (opc==1):
pedirRUC()
if (opc==2):
mostrarmont... |
import libreria
opc=0
max=3
def agregar_uni():
input("Ingresar universidad: ")
def agregar_carrera():
input("Ingresar carrera profesional: ")
while (opc!=max):
print("########## MENU #############")
print("#1. Universidad #")
print("#2. Carrera profesion #")
print("#3. Salir... |
import random
from things import Player
class RandoMan(Player):
"""A player that decides what to do with a dice."""
def next_step(self, things, t):
action = random.choice(('move', 'attack', 'heal'))
if action in ('attack', 'heal'):
self.status = action + 'ing'
target... |
import random
print('Hello. What is your nombre?')
nombre = input()
print('Well, ' + nombre + ', I am thining of a numero between Uno(1) y Veinte(20)')
secretNumber =random.randint(1,20)
for guessesTaken in range(0, 6):
print ('Take a guess:' )
guess = int(input())
if guess < secretNumber:
print ('Your guess i... |
class Customer:
def setcustomerid(self,customerid):
self.__customerid=customerid
def getcustomerid(self):
return self.__customerid
def setcustomername(self,customername):
self.__customername=customername
def getcustomername(self):
return self.__customername
class... |
int_val = 4
str_val = 'GeeksforGeeks'
flt_val = 24.56
print("The integer hash value is : " + str(hash(int_val)))
print("The string hash value is : " + str(hash(str_val)))
print("The float hash value is : " + str(hash(flt_val)))
|
class c1:
def __init__(self,a,b):
print(self)
self.a=a
self.b=b
def area(self):
print(self.a*self.b)
print(self)
class c2(c1):
def __init__(self,a,b,c):
self.a=a
self.b=b
self.c=c
print(self)
def vol(self):
pr... |
from enum import Enum
class TokenType(Enum):
INT = "int"
double = "double"
BOOLEAN = "boolean"
STRING = "string"
POSITION = "position"
MOVEABLE = "moveable"
DEF = "def"
WHILE = "while"
IF = "if"
ELSE = "else"
RETURN = "return"
NULL = "null"
VAR = "var"
TRUE = "tr... |
def mul(x,y):
return x*y
print(mul(5,3)) |
num1=19
num2=3.5
num3=0x2342FABCDEBDA
print(type(num1))
print(type(num2))
print(type(num3))
phrase="Hello there!"
print(type(phrase))
num=len(phrase)
print(phrase[3:7])
print(phrase[6:])
print(phrase*2)
phrase = phrase + "Goodbye"
print(phrase)
print(phrase[2:num-1])
while "there" in phrase:
print("t... |
def create_cards_facingdown(n):
empty_dic = {}
for i in range(1,n):
empty_dic[i] = False
return empty_dic
cards_set = create_cards_facingdown(101)
def card_turn(start):
current = cards_set
while start < 101:
for i in range(start,101,start):
if current[i] == False:
current[i] = T... |
def proc1(p):
p[0] = p[1]
def proc2(p):
p = p + [1]
def proc3(p):
q = p
p.append(3)
q.pop()
def proc4(p):
q = []
while p:
q.append(p.pop())
while q:
p.append(q.pop())
p = [1, 2, 3]
proc1(p)
print(p)
p = [1, 2, 3]
proc2(p)
print(p)
p = [1, 2, 3]
proc3(p)
print(p... |
'''
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
n * (n + 1) / 2;
求第一个拥有超过500个因子的三角数?
'''
import math
print(int(math.sqrt(15)))
def divisors(integer):
'''
算法理由:如果一个数,能够整除某个数的平方根,那么肯定有一个比它大的数也能够整除;
所以只需检查interge... |
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
head2=head
freqDict={}
while head2:
if head2.val in freqDict:
... |
class Solution:
def helper(self,s):
length=len(s)
s=''.join(s)
s=s.replace('--','+')
s=s.replace('+-','-')
s=[x for x in s if x!='#']
s=['+']+s[1:-1]+['+']
tmp=0
lastsign=0
for i in range(1,len(s)):
if i==1 and... |
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
tmp=x^y
res=0
while tmp!=0:
if tmp%2!=0:
res+=1
tmp=tmp>>1
return res |
class Solution(object):
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
if num==0:
return "0"
flag=True if num>0 else False
num=abs(num)
res=[]
while num:
res.append(str(num%7))
num=num//7
... |
"""
------------------------------------------
|Luhn Algorithm by Brian Oliver, 07/15/19 |
------------------------------------------
The Luhn Algorithm is commonly used to verify credit card numbers, IMEI numbers, etc...
Luhn makes it possible to check numbers (credit card, SIRET, etc.) via a control key (... |
import re
def abbreviate(palabras):
regex = "[A-Z]+['a-z]*|['a-z]+"
return ''.join(word[0].upper() for word in re.findall(regex, palabras))
|
from string import ascii_lowercase
def is_pangram(oracion):
return all(char in oracion.lower() for char in ascii_lowercase)
|
'''
This will read in data from data.json and convert it into a dict
Then will create or rewrite populate_db.py with the insert statements
to insert all the data that was in the JSON file to the expenses table
'''
import json
import time
json_data = open('data.json')
data = json.load(json_data)
sql = ''
for expe... |
def h_distinct_attacks(queen_state):
'''Groups attack pairs together if they share a common queen and returns the number of groups'''
def have_queen_in_common(queen_list_a, queen_list_b):
return len(set(queen_list_a + queen_list_b)) < len(queen_list_a) + len(queen_list_b)
attacking_pairs = q... |
"""
Huffman Tree used for compression
上海交大翁老师的:
https://www.bilibili.com/video/BV18t411U7tH?from=search&seid=14727695894489847315
青岛大学王卓老师的:
https://www.bilibili.com/video/BV18t411U7tz/?spm_id_from=trigger_reload
https://www.bilibili.com/video/BV18t411U7tz/?spm_id_from=trigger_reload
"""
class TreeNode(object):
"... |
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
if not nums or len(nums) == 0:
return False
left, right = 0, len(nums) - 1
while left <= right:
mid = int(left ... |
"""
@author : Yx
"""
import queue
import threading
import time
import random
class DiningPhilosopher(threading.Thread):
def __init__(self, philosopher, fork_locks, q, eat_times=1, *args, **kwargs):
super().__init__(*args, **kwargs)
self.philosopher_num = philosopher
self.... |
import re
file = open("test1.txt", 'r',encoding='utf-8').read()
words={}
slist=file.replace("\W+",'').split(" ")
for element in slist:
if element in words:
words[element]+= 1
else:
words[element]=1
words
lowest = min(words.values())
highest = max(words.values())
for word,freq in words.items():... |
x = 3
y = 22
def ff(z):
x = z+3
print("+++ in func ff, x = %s; y = %s; z = %s") %(x,y,z)
return(x)
print("+++ before excuting ff, x = %s; y = %s") %(x,y)
y = ff(x)
print("+++ after excuting ff, x = %s; y = %s") %(x,y)
|
from pizzapy import *
print('Bienvenue au DPPD')
print('Nous avons besoin de quelques informations avant de vous livrer')
name = input('Entrer votre nom (Premom et nom de famille seulement)')
email = input('Entrer votre email: ')
phone = input('Entrer votre numero de telephone')
addresse = input('Entrer votre adresse... |
import math
import os
import random
import re
import sys
def maximumToys(prices, k):
s = 0
for i in prices:
if i <= k:
s += 1
k -= i
else:
break
return s
if __name__ == '__main__':
n,k = map(int,input().split())
prices = sorted(ma... |
import math
import os
import random
import re
import sys
def jimOrders(orders):
s = sorted(enumerate(orders,1),key=lambda x:sum(x[1]))
return (i[0] for i in s)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
orders = []
for _ in... |
numbers = int(input("Введите число > "))
print(f"{numbers}", "+", f"{numbers}" * 2, "+", f"{numbers}" * 3, "=",
int(f"{numbers}") + int(f"{numbers}" * 2) + int(f"{numbers}" * 3))
|
"""
find_kth_book_2 fonksiyounda onceki parttan farkli olarak, oncekinde midlerin toplamina
bagli olarak ikisini ayri ayri olarak boluyorduk(logm + logn).Burada ikisini ayni
birlikte gibi dusunup bolme islemi yapiyoruz(log k).
"""
def find_kth_book_2(m, n, k):
if(len(m) == 0):
return n[k - 1]
if (l... |
def find_longest_word(input_string):
maxlen = 0
maxword = ""
input_list = input_string.split()
for word in input_list:
if len(word) >= maxlen:
maxlen = len(word)
maxword = word
return maxword
print (find_longest_word("salam in ye matn azmayeshi baraye test matnibebozorgiein ast")) |
def _vowels_ (simple_string):
number = 0
simple_string = simple_string.lower()
vowels_character_list = ['a', 'e', 'o', 'i', 'u']
for char in simple_string:
if char in vowels_character_list:
number = number + 1
return number |
def _dictionary_of_vowel_counts_sample_(sample_string):
sample_string_nospace = sample_string.replace(' ', '')
sample_string_nospace_lower = sample_string_nospace.lower()
vowels_character_list = ['a', 'e', 'o', 'i', 'u']
out_dict = {}
for character in sample_string_nospace_lower:
if character in vowels_character... |
def adadezoj(a, b):
i = a
mylist = []
while (i >= a) and (i < b):
if (i%2) == 0 :
mylist.append(i)
i = i+1
return mylist |
def crazy_list(some_list):
mylist = some_list
lenlist = len(mylist)
aval = 0
akhar = -1
natije = 0
for i in range(0,lenlist):
if mylist[aval] != mylist[akhar]:
natije = natije + 1
aval = aval + 1
akhar = akhar - 1
if natije == 0:
return True
else:
return False
listam = [5, 6, 8, 7, '... |
def single_insert_or_delete(s1,s2):
if len(s1) == len(s2):
s1 = s1.lower()
s2 = s2.lower()
if s1 == s2:
return 0
else:
return 2
elif (len(s1) == len(s2)-1) or (len(s1) == len(s2)+1):
return 1
else:
return 2 |
def unique_list_sample(A, B):
mylist = A + B
newlist = []
for element in mylist:
if element not in newlist:
newlist.append(element)
return newlist |
my_str='Computer science'
print (my_str.split ('e'))
x="frequency of letters"
print (x.split("e",2))
x="Mississippi"
print (x.split("s",3))
|
import numpy
import pandas
myarray = numpy.array([[1, 2, 3], [4, 5, 6]])
rownames = ['a', 'b']
colnames = ['one', 'two', 'three']
mydataframe = pandas.DataFrame(myarray, index=rownames, columns=colnames)
print('myarray:')
print(myarray)
print('rownames:')
print(rownames)
print('colnames:')
print(colnames)
print('... |
print("Hello world!")
liczba = "ala"
liczba = 0
liczba = 0.01
imie = "ala"
print(imie)
print(type(imie))
print(type(5))
print(type(5.5))
print(type(True))
imie= str("Ala")
liczba= str(100) |
myDict1 = {'Name':'Nilesh', 'RollNo':69, 'Dept':'IT', 'Age':18}
print("\nDictionary elements : ", myDict1)
print("Student department : ", myDict1['Dept'])
myDict1['Dept']="CSE"
print("After Editing dictionary elements : " , myDict1)
myDict1['College'] = 'SVCE'
print("After appending : ", myDict1)
print("Numbe... |
class Student:
def get_details(self):
self.name = input("Enter you name : ")
self.rollNo = input("Enter roll number : ")
self.dept = input("Enter Department : ")
def show_details(self):
print("\nStudent name : ", self.name)
print("Student roll number : ", self.rollNo)
... |
class Base:
def __init__(self, a, b):
self.a = a
self.b = b
class Derived(Base):
def addNumbers(self):
self.Add = self.a + self.b
return self.Add
def subNumbers(self):
self.Diff = self.a - self.b
return self.Diff
def main():
Obj = Derived(5, 2... |
class TreeNode(object):
def __init__(self,data=0,left=0,right=0):
self.data=data
self.left=left
self.right=right
class BTree(object):
def __init__(self,root=0):
self.root=root
def preOrder(self,treenode):
if treenode is 0:
return
print(treenode.da... |
import os
def chmod (**kwargs):
"""
CHMOD User Commands CHMOD
NAME
chmod - changes the permissions of file or directory
SYNOPSIS
chmod MODIFIER [FILE...]
DESCRIPTION
chmod changes the permissions of FILE, or directory, with MODIFI... |
import numpy as np
import matplotlib.pyplot as plt
def softmax(inputs):
softmax_scores = [np.exp(x)/float(np.sum(np.exp(inputs))) for x in inputs]
return softmax_scores
def plot(x,y):
plt.plot(x, y, 'r--')
plt.show()
t = np.arange(-10., 10., 0.1)
print(t)
print(softmax(t))
print(np.sum(softmax(... |
class A(object):
def __init__(self):
self.n = 10
def minus(self, m):
self.n -= m
class B(A):
def __init__(self):
self.n = 7
def minus(self, m):
super(B, self).minus(m)
self.n -= 2
class C(A):
def __init__(self):
self.n = 12
def minus(self, m):
... |
print("range(1,5)")
for value in range(1, 5):
print(value)
print("range(0,7)")
for value in range(0, 7):
print(value)
print("range(7)")
for value in range(7):
print(value)
print("range(3,7)")
for value in range(3, 7):
print(value)
print("range(-1,2)")
for value in range(-1, 2):
print(value)
num... |
age = 42
if age >= 40 and age <= 46:
print('Age is in range')
if (age >= 40) and (age <= 46):
print('Age is in range')
if age < 40 or age > 46:
print('Age is older or younger')
age = 39
if age < 40 or age > 46:
print('Age is older or younger')
age = 56
if age < 40 or age > 46:
print('Age is o... |
def unique_in_order(iterable):
if not iterable:
return []
if len(iterable) < 2:
return list(iterable)
result = [iterable[0]]
for x in iterable[1:]:
if result[-1] != x:
result.append(x)
return result
|
def pig_it(text):
return ' '.join(
word[1:] + word[0] + 'ay'
if all(x.isalpha() for x in word)
else word
for word in text.split(' ')
)
|
"Module to show how to handle text files"
from __future__ import print_function
import sys
import codecs
def ReadFileComplete( filename ):
"Read the whole contents of the file to a variable"
f = open( filename, 'rU' )
lines = f.read()
f.close()
return lines
def ReadFileList( filename ):
"Read th... |
class Person(object):
def __init__(self,name,age,):
self.name=name
self.age=age
def getVar(self,v):
print(self(v))
return self(v)
def getName(self):
return self.name |
import Keys
txtInput = input()
class Encrypt(object):
def strToNum(self, txt):
num = []
a = ''
for i in range(len(txt)):
num.append(ord(txt[i]))
a = a.join(map(str, num))
return int(a)
def encMaths(self, asciiTxt):
nums = pow(a... |
'''
Name: Exceptions
Tasks: Read a string, S, and print its integer value; if S cannot be converted to an integer, print Bad String.
Sample Input:
3
Sample Output:
3
Sample Input:
za
Sample Output:
Bad string
'''
import sys
S = input().strip()
try:
value = int(S)
print (S)
except:
print ('Bad Str... |
'''
Name: Grading Students
Task:
- If the difference between the grade and the next multiple of 5 is less than 3, round grade up to the next multiple of 5.
- If the value of grade is less than 38, no rounding occurs as the result will still be a failing grade.
Example:
grade = 84 will be rounded to 85
grade = 29 will ... |
'''
Name: Bon Appetit
Task:
Anna and Brian order n items at a restaurant, but Anna declines to eat any of the kth item (where 0 <= k <= n) due to
an allergy. When the check comes, they decide to spit the cost of all the items they shared; however, Brian may have forgotten
that they didn't split the kth item and accide... |
import sys
def productOfPages(a, b, c, d, p, q):
if(p == a): a = 1
elif(p == b): b = 1
elif(p == c): c = 1
elif(p == d): d = 1
if(q == a): a = 1
elif(q == b): b = 1
elif(q == c): c = 1
elif(q == d): d = 1
product = a * b * c * d
r... |
'''
Name: Count Sub-Strings
Task:
Given a string, S, and a substring - count the number of times the substring appears.
Sample Input:
ABCDCDC
CDC
Sample Output:
2
'''
def count_substring(string,sub_string):
counter = 0
length = len(sub_string)
for i in range(len(string)):
if (string[i] == sub_st... |
'''
Name: What's Your Name?
Task: You are given the first name and last name of a person on two different lines. Your task is to read them and print the following:
Hello <firstname> <lastname>! You just delved into python.
Sample Input:
Guido
Rossum
Sample Output:
Hello Guido Rossum! You just delved into python.
'... |
def solution(numbers):
answer = []
for i in range(len(numbers)-1):
for num in numbers[i+1:]:
tmp = numbers[i] + num
if tmp not in answer:
answer.append(tmp)
answer.sort()
return answer
if __name__ == "__main__":
numbers = [2,1,3,4,1]
answer = s... |
def solution(array, commands):
answer = []
for i,j,k in commands:
answer.append(sorted(array[i-1:j])[k-1])
return answer
def solution2(array, commands):
answer = []
for i, j, k in commands:
target = array[i-1:j]
target.sort()
answer.append(target[k-1])
retu... |
def solution(n):
ternery = ""
answer = 0
while n > 2:
n, rest = divmod(n, 3)
ternery += str(rest)
ternery += str(n)
answer = int(ternery, 3)
return answer
if __name__ == "__main__":
n = 45
answer = solution(n)
print(answer) |
def solution(name, yearning, photo):
answer = []
for people in photo:
score = 0
for j in people:
try:
score += yearning[name.index(j)]
except ValueError:
continue
answer.append(score)
return answer
def shorten(name, yearning,... |
"""
--- Day 1: Calorie Counting ---
Santa's reindeer typically eat regular reindeer food, but they need a lot of
magical energy to deliver presents on Christmas. For that, their favorite snack
is a special type of star fruit that only grows deep in the jungle. The Elves
have brought you on their annual expedition to t... |
import abc
class Event(object):
__metaclass__ = abc.ABCMeta
def __init__(self, x, y):
self.x = x
self.y = y
@abc.abstractmethod
def Handle(self, queue, beachline, dcel):
return
def ToString(self):
return '("+x+", "+y+")'
|
from numpy import *
import plotly as py
from plotly.graph_objs import *
theta = linspace(0,2*pi,100)
phi = linspace(0,pi,100)
x = outer(cos(theta),sin(phi))
y = outer(sin(theta),sin(phi))
z = outer(ones(100),cos(phi))
data = Data([
Surface(
x=x,
y=y,
z=z
)
])
layout = Layout(
ti... |
import collections
class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
set = collections.Counter(s)
return ''.join([n * m for m, n in sorted([(k, j) for j, k in list(zip(set.keys(), set.values()))], reverse=-1)])
|
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
self.value = nums
number = len(self.value) + 1
whole_list = list(range(number))
return int(list(set(whole_list)-set(self.value))[0])
|
from itertools import count
inp = open('day10.input').read().strip().split('\n')
class Point:
def __init__(self, x, y, vx, vy):
self.x, self.y, self.vx, self.vy = x, y, vx, vy
def parse(inp):
for line in inp:
line = line[10:].split(',')
x = int(line[0])
y = int(line[1].split(... |
import calculadora_indices as calc
peso=float(input("Ingrese el peso de la persona en kilogramos:"))
altura=float(input("Ingrese la altura de la persona en metros:"))
edad=int(input("Ingrese la edad de la persona: "))
v_genero=float(input("Ingrese el 10.8 si el genero es masculino o de lo contrario cero:"))
prin... |
from typing import List
from structure.sentence import Sentence
class Document:
def __init__(self):
self._id = ''
self._bodies: List[Sentence] = list()
self._gold_summaries: List[Example] = list()
@property
def gold_summaries(self)->list:
return self._gold_summaries
... |
def reverse_string(s):
reversed = ""
for i in s:
reversed = i + reversed
return reversed
def normalize(s):
normalized = ""
for ch in s:
if ch.isalpha():
normalized += ch.lower()
return normalized
def is_palindrome(s):
normalized = normalize(s)
rev = reverse_... |
s = ['a','b','c']
def get_cmb(s):
r = []
for i in range(len(s)-1):
for y in range(i+1,len(s)):
v = [s[i],s[y]]
if v not in r:
r.append(v)
return r
print(get_cmb(s))
|
import sys
def grid_distance(location):
return abs(location[0]) + abs(location[1])
input = open(sys.argv[1], 'r').readlines()[0]
directions = input.split(", ")
heading = 90
current = (0, 0)
headquarters = None
visited = []
visited.append(current)
for direction in directions:
heading += -90 if directio... |
class Backpack:
def __init__(self):
self.backpack_storage = []
self.max_weight = 0
def get_element_by_index(self, index):
return self.backpack_storage[index]
def add_item(self, item):
self.backpack_storage.append(item)
def get_backpack(self):
return self.backp... |
print("\tI'm\tyours")
class TaxCalc:
@classmethod
def class_method(cls, price):
assert cls.__name__ == TaxCalc.__name__
return int(price * 0.08)
@staticmethod
def static_method(price):
return int(price * 0.08)
print(TaxCalc.class_method(1000))
print(TaxCalc.static_method(1... |
print(1 + 2.4)
print(1 + 3,4)
print(1.5 - 0.5)
print(45 * 2.4)
print(12.0 / 4.0 )
print(12.0 % 4.0)
print(12.0 / 7.0 )
print(12.0 // 7.0)
age = int(input("Inserta de tu edad: "), 12)
print(age)
new_age = age + 5
print(f"Dentro de un lustro tendras estas {new_age} edad")
|
print("Hola mundo")
print(type("hola mundo"))
print("hola mundo " + "Yolo")
a=10
print(a); print(type(a))
b=12.5
print(b); print(type(b))
True
False
print(type(True))
[10 ,20 ,12,True]
["Hola", "adios" , "buema suerte"]
print(type([12 , -3]))
(10,34,5)
()
print(type((4,6)))
print(type(
{
"name":'Cris... |
v=int(input("dati varsta Anei "))
print ("greutatea perfecta a Anei este de",2*v+8,"kg")
print ("inaltimea perfecta a Anei este de",5*v+80,"cm") |
import matplotlib.pyplot as plt
population_ages = [22, 55, 62, 45, 34, 77, 4, 8, 14, 80, 65, 54, 43, 48, 24, 18, 13, 67]
min_age = 0
max_age = 140
age_step_by = 20
bins = [x for x in range(0, 141, 20)]
plt.hist(population_ages, bins, histtype='bar', rwidth=0.8)
plt.xlabel('x')
plt.ylabel('y')
plt.show()
|
def binary_search(x, lst):
'''
Usage: The function applies the generic binary search algorithm to search if the value
x exists in the lst, and returns a list contains: TRUE/FAlSE depends on whether the x value has been found,
x value, and x position indice in list
Argument:
x:... |
class Displayer():
def display(self, message):
print(message)
class LoggerMixin():
def log(self, message, filename='logfile.txt'):
message ='\n' + message
with open(filename, 'a') as fh:
fh.write(message)
def display(self, message):
super().display(message)
... |
def fact(x):
if x == 1:
return 1
else:
return x * fact(x-1)
x = fact(5)
print(x) |
input = [4, 6, 2, 9, 1]
def selection_sort(array):
n = len(array)
for i in range(n-1):
min = array[i]
for j in range(i,n):
if min > array[j]:
min = j
array[i], array[min] = array[min], array[i]
return array
selection_sort(input)
print(input) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.