text stringlengths 37 1.41M |
|---|
palavra = str(input("Digite uma palavra:\n"))
while palavra.isalpha() is False:
print("\nPor favor, digite apenas letras!\n".upper())
palavra =str(input("Digite uma palavra:\n"))
else:
print("\nMuito bem, você digitou apenas letras!") |
from random import randint
quantidade = int(input("Digite qual a quantidade de termos da sua lista!"))
lista_gerada = []
def bubble_sort(lista_parametro):
"""
Método de ordenação bubble sort que consiste em comparar dois valores subsequentes de uma lista
e trocá_los de lugar caso o valor de i+1 seja maio... |
def maximum(n):
l=len(n)
for i in range(l-1):
for j in range(i+1,l):
if n[i]>n[j]:
max=n[i]
else:
max=n[j]
print("the largest number is " + str(max))
limit = int(input("Enter the size of the list "))
n = list(int(num) for num in input("Enter th... |
"""
It is possible to return the value in the form of HTML.
Flask will try to find the HTML file in the 'templates' folder;
The 'templates' folder should go with this python script in the same folder;
by using render_template(), the Jinga2 template engine will turn the initial HTML into the final HTML;
"""
from flask i... |
# Задача-2: Исходные значения двух переменных запросить у пользователя.
# Поменять значения переменных местами. Вывести новые значения на экран.
# Решите задачу, используя только две переменные.
# Подсказки:
# * постарайтесь сделать решение через действия над числами;
# * при желании и понимании воспользуйтесь синтакси... |
# Задание-2:
# Дан шестизначный номер билета. Определить, является ли билет счастливым.
# Решение реализовать в виде функции.
# Билет считается счастливым, если сумма его первых и последних цифр равны.
# !!!P.S.: функция не должна НИЧЕГО print'ить
def lucky_ticket(ticket_number):
lst_tn = list(str(ticket_number))
... |
# Задача-1:
# Дан список фруктов.
# Напишите программу, выводящую фрукты в виде нумерованного списка,
# выровненного по правой стороне.
fruits = ['апельсин', 'яблоко', 'груша', 'манго']
for i, fruit in enumerate(fruits):
print(f'{i+1}. - {fruit:>10}') |
import networkx
import matplotlib.pyplot as plot
import random
import math
"""This module is a graph-based social network model using networkx with a dictionaries of dictionaries
implementation. Please make sure to install the following dependencies before running:
- networkx: pip3 install networkx
... |
alien_0 = {'color':'green'}
print(f"The alien is {alien_0['color']}.")
alien_0['color'] = 'yellow'
print(f"The alien is now {alien_0['color']}.")
# country
country_codes = {'Finland': 'fi', 'South Africa': 'za','Nepal': 'np'}
print(country_codes)
print(len(country_codes))
if country_codes:
print('country_codes is... |
#CONDITIONS (15PTS TOTAL)
# PROBLEM 1 (GPA - 4pts)
# Grades are values between 0 and 100
# We will translate grades to letters using:
# http://www.collegeboard.com/html/academicTracker-howtoconvert.html
# Make a variable for your percentage grade.
# Make a series of if/elif/else statements to print the letter grade.
#... |
#!/usr/bin/python3
for letters in range(97, 123):
if not letters == 101 and not letters == 113:
print("{}".format(chr(letters)), end="")
|
import os
import uu
import sqlite3
import base64
import cv2
import getpass
"""
This script will run in the terminal/shell and works in an interactive manner (input & output)
The 'encodeFiles' function below is used to gather directory & file information, input commands, and
store or recover files/folders in/... |
"""
Helper functions to find files in the various directories
"""
import os
################################################################################
def add_first_date_and_reformat(date_list):
new_list = []
for date in date_list:
year = int(date[:4])
month = int(date[4:6])
... |
#!/usr/local/bin/python3
from PIL import Image
import random
# Define the size of the image
width = 800
height = 800
# Create a new image with the given size
img = Image.new('RGB', (width, height))
# Access the pixel data
pixels = img.load()
# Iterate over each pixel
for i in range(width):
for j in range(heigh... |
#!/usr/local/bin/python3
import os
import random
import argparse
from PIL import Image
def get_palette_from_images(folder):
"""Extract the color palette from the images in a folder."""
palette = []
for filename in os.listdir(folder):
if not filename.endswith(('jpg', 'png', 'jpeg')):
co... |
"""
Chat Server - RSA Assignment.
Beth Cooper
Shawn Zamechek
Qing Xie
Threaded Chat Server. There is a thread to read from the keyboard and
write to the socket and another thread to read from the socket and print to the screen.
The send thread sends the public key to the server while the recv thread receives the clie... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Yu Zhou
# ****************
# Descrption:
# 101. Symmetric Tree
# Given a binary tree, check whether it is a mirror of itself
# (ie, symmetric around its center).
# ****************
# 思路:
# 这道题只要知道一个规律,就是左边Child要等于右边Child,就很容易了
# 先解决Root的Edge,之后在对其他进行一个统一处理,我选择写一个Hel... |
# --------------
import pandas as pd
import os
import numpy as np
import warnings
warnings.filterwarnings("ignore")
# path_train : location of test file
# Code starts here
#Loading data
df = pd.read_csv(path_train)
print(df.head())
#Function to create new column
def label_race (row):
if row['foo... |
# This file reads my name and prints out hello my name
# Author: Lonan Keane
name = input('enter your name:')
print('Hello ' + name + '\nNice to meeet you')
#Modifying to say "nice to meet you" after saying hello
|
class Terrain:
def __init__(self):
self.symbol = '#'
class Map:
def __init__(self, x, y, start_terrain):
self.map_array = []
self.x = x
self.y = y
for i in range(0, y):
self.map_array.append([])
for j in range(0, x):
self.map_array[... |
import unittest
class TreeBase:
"""
Abstract base class
"""
class Position:
def element(self):
raise NotImplementedError
def __eq__(self, other):
raise NotImplementedError
def __ne__(self, other):
return not (self == other)
def root(s... |
class ListNode:
prev = None
next = None
data = None
def __init__(self, prev, next, data):
self.prev = prev
self.next = next
self.data = data
class LList:
head = ListNode(None,None,None)
tail = ListNode(None,None,None)
def __init__(self, startdata):
... |
from matplotlib import pyplot as plt
population_ages=[10,15,20,30,35,45,50]
bins=[10,20,30,40,50,60,70]
plt.hist(population_ages,bins,histtype='bar',rwidth=0.8)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Histogram')
plt.show() |
#Algoritmo de Huffman
#Carlos Triana - FIME, ITS
def main():
frec = [] #Para poner las frecuencias de los caracteres
newtext = []
corleone = []
'''
El formato de las frecuencias es la frecuencia, seguido del caracter correspondiente
'''
texto = raw_input('Ingresar cadena: ')
print texto
miLista = list(tex... |
# valid_list = [':)', ':D', ';-D', ':~)', ';D', ':-D', ':-)', ';~)']
class SmileFace:
def smile_face_check(self, faces_list: list):
_result = 0
for face in faces_list:
if self._has_eyes(face) and self._has_noses(face) and self._has_smile(face):
_result += 1
retu... |
from __future__ import generators
from math import sqrt
from array import array
def is_prime(n):
if n < 0:
n = -n
if n < 2:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0:
return False
limit = int(sqrt(n)+1)
for x in range(3, limit, 2):
if n ... |
#Gemma Buckle
#18/09/2014
#converting denary to binary to hexadecimal
denary_value = int(input("Please enter a denary integer: "))
binary_string = ""
while denary_value > 0:
denary_string = CStr(denary_value)
binary_string = Cstr(denary_value%2)
denary_value = denary_value//2
endwhile
print("The b... |
# Exercise 10
import random
exit_keys = ("n", "e", "ex", "exi", "exit") # Use these keys to exit.
while True: # Loop forever or until exit key is typed.
print(44 * '-')
print('exit keys: ', exit_keys)
print(44 * '-')
print('\nPlease wait while the machine generates two random lists...')
alpha... |
import math
from collections import Counter
def combination(n, r, coma=False):
nf = math.factorial(n)
rf = math.factorial(r)
m = n - r
mf = math.factorial(m)
tf = mf * rf
result = nf / tf
if coma: return (f"{int(result):,}")
elif coma == False: return int(result)
def permu... |
# -*- coding: utf8 -*-
import random
import json
#fonction pour lire le fichier characters.json et le convertir en liste
def read_values_from_json(file, key):
values = [] # Create a new empty list
with open(file) as f:# Open a json file with my objects
data = json.load(f) # load all the d... |
#!/usr/bin/python3
import random
number = random.randint(-10000, 10000)
last_digit = number % 10
if last_digit > 5:
print("{} and is greater than 5".format(last_digit))
elif last_digit == 0:
print("{} and is 0".format(last_digit))
else:
print("{} and is less than 6 and not 0".format(last_digit))
|
#encoding:UTF-8
class ListNode:
def __init__(self, key, value, prev = None, next = None):
self.key = key
self.value = value
self.prev = prev
self.next = next
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.size = 0
self.head = ... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def fir_order(root,res_list):
if root != None:
res_list.append(root.val)
fir_order(root.left, res_list)
fir_order(root.right, res_list)
else:
return
if __name__ == ... |
#encoding:UTF-8
#用到了三向切分,可以过AC快排,但是过不了插入排序,不知道怎么shuffle
from myList import *
from time import clock
import random
def sortList_quick(head, tail):
if head is tail:
return
prev = head
if prev.next == tail or prev.next.next == tail:#0-1 Node
return
else:
curr = prev.next
pivot ... |
dic={'final':['A','B','C'],
'A':['a','b'],
'B':['c','d'],
'a':['aa','bb'],
'C':['a','e'],
'aa':['o','p'],
'p':['hi','h'],
'bb':['5','10'],
'h':['hey'],
'b':['x']
}
l=[]
#root(dic) function is to find the primary target table in the dictionary
def root(dic):
keys=dic.keys()
values=dic.values(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#--------------------
#Program name:
#N queen solver
#
#import multiprocessing
from board import *
import time
nodos_visitados = 0
def conflict(state,X):
"""This function checks for any conflicts when placing a
Queen on the board.The state variable is a tuple which co... |
#Words combination
#Create a program that reads an input string and then creates and prints 5 random strings from characters of the input string.
import random
some_str = ''.join((random.choice('abcdefghijklmnopqrstuvwxyz') for i in range(5)))
print(some_str) |
__author__ = 'Adam'
import sys
import time
from board import Board
from termcolor import colored
from player import Player
from bot3435 import Bot3435
class Game:
def __init__(self):
self.player_1 = Player("white")
self.player_2 = Bot3435("black")
self.board = Board()
self.choices ... |
board=[["X","O","#"],["X","X","X"],["#","#","#"]]
def board_to_string(board):
count=0
result1=''
for i in board:
count=0
for j in i:
if count in range(0,2):
result1+='|'
result1+=' '
result1+=str(j)
result1+=' '
... |
n=int(input("Enter count of numbers: "))
count=1
numbers=[]
while count<=n:
number=int(input("Please enter a number: "))
numbers=numbers+[number]
count+=1
numbers.sort()
print(numbers[-1]) |
n=int(input("Enter count of numbers to input: "))
count=1
numbers=[]
while count<=n:
number=int(input("Enter a number: "))
numbers=numbers+[number]
count+=1
print(numbers) |
word=str(input("Please insert a word to search: "))
n=int(input("Please enter the number of words to search in: "))
count=1
words=[]
founder=0
while count<=n:
wordsEL=input("Please enter a word: ")
words=words+[wordsEL]
count+=1
for i in words:
if i==word:
founder+=1
print("{} if found {} times.".format(word,foun... |
def is_string_palindrome(string):
strcheck='abcdefghijklmnopqrstuvwxyz'
string=string.lower()
letonly=''
res=''
for i in string:
if i in strcheck:
letonly+=i
res=i+res
return letonly==res
def main():
if __name__=='__main__':
main()
|
import random
a=1
b=int(input("Enter sides: "))
def roll(a,b):
rnd=1
collector=0
while rnd<4:
print()
input("Press ENTER to roll the dice...")
print()
turn=random.randint(a,b)
if rnd==1:
print("First roll: {}".format(turn))
#print(turn)
... |
n=int(input("Моля въведете броя на блоковете: "))
m=0
blocks=[]
while m<n:
blocks+=[int(input("Моля въведете височината на блоковете:"))]
m+=1
#print(blocks)
highest=0
seen=[]
for i in blocks:
if i>highest:
seen+=[i]
highest=i
print("Блоковете, които ще видите са с височина съответно {}".format(seen))
|
n=int(input("Please insert th number of elements: "))
start=0
items=[]
while start<n:
elem=input("Please insert an element: ")
items+=[elem]
start+=1
def countEL(items):
counter=0
for i in items:
counter+=1
return counter
print("count_elements({}) == {}".format(items,countEL(items))) |
n=int(input("\nPlease enter a number: "))
m=n
collector=''
while n>0:
collector+=str(n%10)
n=n//10
print("\nThe reverse int of {} without leading zero is :".format(m),end=' '),print(int(collector)) |
print("I will count to 10")
input("press ENTER to start:")
turn=0
while turn<10:
turn+=1
print(turn) |
#!/bin/env python
""" Advent of code """
def part_1(input_lengths):
"Day 10 Algorithm"
circular_list = list(range(256))
current_position = 0
skip_size = 0
# Knot Hash Algorithm Round
for length in input_lengths:
print_list(circular_list, current_position)
print("\nLength is ... |
#!/usr/bin/env python3
""" Advent of code """
from collections import defaultdict
def part_1(fh):
two_count, three_count = 0, 0
for line in fh:
c2, c3 = part_1_sub(line)
if c2 == 1:
two_count += 1
if c3 == 1:
three_count += 1
return (two_count, three_count)... |
# find the i-th smallest element of an array of distinct integers
# where the 0th smallest element is the minimum
import random
def randomized_select(A,p,r,i):
# finds the i'th smallest element A between indices p and r
if p == r:
return A[p]
q = randomized_partition(A,p,r)
#q = partition(A,p,r)
k = q-p+1
if ... |
# insertion sort
def insertion_sort(A,p,r): # sort the list A of integers between indices p and r
for i in range(p+1,r+1):
temp = A[i]
j = i-1
while j >= p and A[j] > temp:
A[j+1] = A[j]
j-=1
A[j+1] = temp
# if instead use the following for loop, merge sort faster than insertion on sorted list
# ... |
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if nums == []:
return None
# take pointers for each number
idx0 = 0
idx2 = len(nums) - 1
... |
class Solution(object):
def isOneBitCharacter(self, bits):
"""
:type bits: List[int]
:rtype: bool
"""
'''
Time Complexity: O(n)
Space Complexity: O(1)
'''
i = 0
flag = True
while i < len(bits):
if bits[i] == 1 and ... |
class Solution:
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
'''
Time Complexity: O(v+e)
Space Complexity: O(n)
'''
if root is None:
return False
bfs_nodes = [root]
#... |
'''
Time Complexity: O(n^2)
Space Complexity: O(1)
'''
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
# lenght of LPS for every letter would be 1 minimum
max_length = 1
idx = 0
# iterate through all elements ... |
"""
Time Complexity: O(n^n)
"""
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort() # time complexity = O(nlogn)
ans = []
for i in xrange(len(nums) - 2):
if i > 0 and nums[i] == nums... |
import sqlite3
class ItemModel:
def __init__(self, name, price):
self.name = name
self.price = price
def json(self):
return {'name': self.name, 'price':self.price}
@classmethod
def find_by_name(cls,name):
connection = sqlite3.connect("mydata.db")
cursor = conne... |
"""
Car类
"""
class Car(object):
description = ['大众','丰田','广本','沃尔沃','凯迪拉克']
def __init__(self, l, w, h, brand):
self.L = l
self.W = w
self.H = h
self.brand = brand
def modify_des(self):
if self.description != None:
return self.description
else:
... |
# @author Alexander Skeba
class Pokemon():
#create an intitialization function for each new pokemon
def __init__(self, name, type, nature, level, attack, defense, speed, max_health, moves = ["-----","-----","-----","-----"]):
"""
Parameters:
name (string): Name of Pokemon... |
import re
def read_template(root):
"""
read a file from a root
give an exception if it not found
"""
try:
with open (root , "r") as file:
content=file.read().strip()
return content
except FileNotFoundError:
raise FileNotFoundError('The file not found')
... |
from collections import Counter
from HuffmanCoding import *
if __name__ == '__main__':
frequencies = Counter()
nodes = {}
while raw_input('Enter new word? [y/n] ') == 'y':
word = raw_input('Enter word: ')
for symbol in word:
frequencies[symbol] += 1
for e, f ... |
import json
class Config:
'''
Config is a class used to import variables from a JSON config file at runtime.
Attributes:
serverIP (str): IP address of the host computer running the CVSensorSimulator application.
tagID (int): Tag ID number of the AprilTag on this robot.
label ... |
# This problem was asked by Uber.
# Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
# For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our i... |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 13 08:19:03 2020
@author: TokTam
"""
myList = input("Enter a string: ")
abcList=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for i in range(0,26):
print(myList[i]," is: " ,myList.count(abcList[i])... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 26 18:42:45 2020
@author: USER
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def hasCycle(self, head: ListNode):
s = set()
while head:
if head in s:
return Tru... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 22 10:30:31 2020
@author: USER
"""
def permute(nums):
def backtrack(first=0):
# 所有数填完
if first == n:
res.append(nums[:])
for i in range(first, n):
# 做选择
nums[first], nums[i] = nums[i], nums[first]
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 20 15:45:20 2020
@author: USER
"""
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseListIteration(self, head):
pre = None
cur = head
while cur:
tmp = cur.next
cur.ne... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 25 00:35:21 2020
@author: USER
"""
def hasCycle(head, k)
slow = fast = head
while k > 0:
k -= 1
fast = fast.next
// 上面的代码类似 hasCycle 函数
slow = head
while (slow != fast):
fast = fast.next
slow = slow.next
return slow |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 2 21:50:10 2020
@author: USER
"""
def searchSmallest(letters, target):
size = len(letters);
l = 0;
r = size - 1;
while (l <= r):
mid = (r + l) // 2
if (target < letters[mid]):
r = mid - 1;
else:
l = mid + 1... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import copy
# reading data from csv
def read_data():
df = pd.read_csv("../data/classification.csv", header=None)
X_org = np.array(df.iloc[:, 0:3])
#print(X_org.shape)
X = X_org.reshape(X_org.shape[0],-1).T
#print(X.shape)
Y_... |
"""
# Author: Kwok Moon Ho
# Date: July 14 2020
# Time: 19 mins 42 sec
#Task:
Find non repreated char and arragement
e.g: Bubble -> uleBbb
Quqqltteqa -> uleaQqqttq
Bubbule -> lBuubue
"""
#assume: no empty input and input is string.
def main():
my_dict = {}
my_list = []
user_input = input("Please enter a s... |
#!/usr/bin/python3
number_one = int(input("Enter First Number: "))
number_two = int(input("Enter Second Number: "))
addition_numbers = number_one + number_two
number_mean = addition_numbers / 2
print ("The mean of both numbers is: ", number_mean)
|
#!/usr/bin/python3
import pandas as pd
import numpy as np
s = pd.Series(np.random.randn(10))
print (s)
print (s.sample(n=3))
df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))
print (df)
# remember frac is float, percentage :)
print (df.sample(frac=0.1, replace=True))
|
"""
Module to deal with base operating system.
Programmed by: Dante Signal31
email: dante.signal31@gmail.com
"""
import sys
def verify_python_version(major_version, minor_revision):
""" Check if current python interpreter version is what we need.
Compare current interpreter version with the one is prov... |
#
# @lc app=leetcode id=979 lang=python3
#
# [979] Distribute Coins in Binary Tree
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def distributeCoins(self, root: TreeNode) -> int:
... |
#
# @lc app=leetcode id=865 lang=python3
#
# [865] Smallest Subtree with all the Deepest Nodes
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def subtreeWithAllDeepest(self, root: Tr... |
print('программа для расчёта прогресса в днях')
day_start = int(input('введите текущий результат в км.'))
day_success = int(input('введите желаемый результат в км.'))
count = 1
while day_success > day_start:
day_start *= 1.1
count += 1
print(count)
|
import csv
import math
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import numpy as np
# read the data
csvfile=open("weightedX.csv", 'r')
x = list(csv.reader(csvfile))
csvfile=open("weightedY.csv", 'r')
y = list(csv.reader(csvfile))
m=len(x)
n=1
x3=[]
y2=[]
for i in range(m):
... |
#!usr/bin/python3
'''
計算固定中的支出,媽媽每天會將家裡的花費記錄下來,並且計算本週的花費總和
顯示:
請輸入星期1 的支出567
請輸入星期2 的支出456
請輸入星期3 的支出567
請輸入星期4 的支出890
請輸入星期5 的支出345
請輸入星期6 的支出534
請輸入星期日 的支出678
本星期的支出為:4037元
'''
sum = 0;
i = 1;
while(True):
if(i==7):
n = int(input('請輸入星期日的支出:'))
break
else:
output = "請輸入星期" + str(i) +... |
learning_map_dict= {}
def run():
x = True
while True:
ui()
def ui():
a = input('What do you want to do? \n Select \n "1" to add \n "2" to view: ')
if a == "1":
user_input1 = input('Do You want to add a new skill or add a studied skill? \n Select \n "1" to add new skill \n "2" to add studie... |
from random import randint
exp = [
'GVG',
'TGT',
'OG',
'MSG',
'JTU',
'KFT',
'KNC',
'WW',
'BDP',
'RR',
'ROE',
]
num = len(exp)
block = []
while len(block) < 3:
r = randint(0, num)
if r not in block:
block.append(r)
for (b in block):
print(exp[b]) |
"""
Binary Trees
author: Chris Lee
created: October 11, 2013
"""
"""
Implementing Binary Trees
"""
import numpy.random as rand
import itertools
class BinaryTree:
def __init__ (self, depth = 0, parent = None):
self.depth = depth
self.assignValue()
self.parent = parent
self.left = BinaryTree(depth = depth - ... |
#
##################################################
# Author: Leyla Saadi
# Copyright: Copyright 2020, IAAC
# Credits: [Institute for Advanced Architecture of Catalonia - IAAC, Advanced Architecture group]
# License: Apache License Version 2.0
# Version: 1.0.0
# Maintainer: Leyla Saadi
# Email: leyla.saadi@student.ia... |
##################################################
# Author: Alberto Browne
# Copyright: Copyright 2020, IAAC
# Credits: [Institute for Advanced Architecture of Catalonia - IAAC, Advanced Architecture group]
# License: Apache License Version 2.0
# Version: 1.0.0
# Maintainer: Alberto Browne
# Email: alberto.eugenio.br... |
import matplotlib.pylab as plt
import datetime
class Solution:
"""This code will import the list models, which contains model objects
created in model.py and graph the solution by calling the function graph.
:param models: list[Model] contain models to be graphed.
Each model will have attributes assoc... |
# Time Complexity : O(logn)
#
# Space Complexity : O(1)
#
# Did this code successfully run on Leetcode : Yes
#
# Any problem you faced while coding this : It took me a lot of time develop get the intution that we can solve this using Binary Serach
#
# Problem Approach
# 1. Check if the first element is the peak or n... |
#!/usr/bin/env python3
import socket
import sys
def printUsage():
print("[ERROR]: Invalid number of arguments!")
print(
"\nUSAGE:\n"+
"______\n\n"+
"$ ./client.py [Host IP to connect to] [port to connect to]\n"+
"[NOTE] You need to be root for using port below 1025\n\n")
sys.exit()
def errorExit():
client_so... |
def trim(s):
l=len(s)
if len(s) == 0:
return s
if s[0] != ' ' and s[-1] != ' ':
return s
i=0
while i < len(s)-1 and s[i] == ' ' :
i = i + 1
if s[0] == ' ':
s = s[i:]
j=-1
while len(s) > 0 and len(s) >= abs(j) and s[j] == ' ' :
... |
from datetime import datetime, timedelta, timezone
#获取当前日期和时间
now = datetime.now()
print(now)
print(type(now))
# 获取指定日期和时间
dt = datetime(2018, 8, 13, 16, 51, 33)
print(dt)
#datetime转换为timestamp
ts = dt.timestamp()
print(ts)
# timestamp转换为datetime
t = now.timestamp()
print(datetime.fromtimestamp(t))
print(datetim... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
def run(self):
print('Dog is running...')
def eat(self):
print('Dog is eating...')
class Cat(Animal):
def run(self):
print('Cat is run... |
class Vehicle:
def __init__(self, make, model, fuel="gas"):
self.make = make
self.model = model
self.fuel = fuel
def __str__(self):
return f"I drive {self.make} {self.model}. It runs on {self.fuel}."
class Car(Vehicle):
number_of_wheels = 4
class Truck(Vehicle):
number_of_wheels = 6
... |
SUM=0
n=0
status=True
while status == True:
x=float(input())
if x == -1:
status = False
else:
SUM+=x
n+=1
if n==0:
print("No Data")
else:
print(SUM/n) |
class Card:
def __init__(self, value, suit):
self.value=value
self.suit=suit
self.Index=["3","4","5","6","7","8","9","10","J","Q","K","A","2"]
self.IndexSuit=["club","diamond","heart","spade"]
def __str__(self):
return "("+self.value+" "+self.suit+")"
def next1(self):
if self.IndexSuit.index(self.suit)==... |
x=int(input())-543
print("29" if (x%4==0 and x%100!=0) or x%400==0 else "28") |
data=[set([i.strip() for i in input().strip().split()]) for i in range(int(input().strip()))]
if data==[]:
print("0")
print("0")
else:
Union=data[0]
Intersection=data[0]
for i in range(1,len(data)):
Union=Union.union(data[i])
Intersection=Intersection.intersection(data[i])
print(len(Union))
print(len(Interse... |
x=int(input())
for i in range(2,(x//2)+1):
st=False
for j in range(2,(i//2)+1):
if i%j == 0 and i!=j :
st=True
if st==False and x%i==0:
print(i,end=" ")
st=False
for i in range(2,(x//2)+1):
if x%i == 0 and x!=i :
st=True
if st==False and x>1:
print(x,end=" ") |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
l = []
def increasingBST(self, root: TreeNode) -> TreeNode:
self.l = []
if not root:return None
self.inorder(... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
h = ListNode(None)
ph = h
while head and head.next:
f = False
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def averageOfLevels(self, root: TreeNode) -> List[float]:
if not root:return []
res = []
cur_level = [root]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.