text stringlengths 37 1.41M |
|---|
#The basic of a dictionary is a key is linked to a value
my_dict={"k1":"My data",7:"other data"}
#Dictionaries are key oriented not index oriented
#Lists and tuples are index oriented
print(my_dict["k1"])
print(my_dict[7])
#you cna change a dictionary unlike a tuple
my_dict[7]="ivbiebvav"
print(my_dict[7])
people_wei... |
# Assignment 2:
"""
create a function called separate() that accepts a string as an argument
and returns a list containing each of the characters of
the string separated as individual items in the list.
Make sure to test the function.
"""
# Your Code Below:
def seperater(string):
return list(string... |
print ("Hello world")
print("This is the next statement")
number=3468
print('number')#This will print ou the string number and not the actual value
print (number)
weight=23
my_answer=number+weight
print(my_answer)
#my_name="Michael Rizzo"
first_name="Michael"
last_name="Rizzo"
my_name=first_name+last_name
pri... |
#There are 4 basic data types
#str,int,boolean value, and float ar the basic data types.
data_type=type(12)
print (f"Data type is {data_type}")
data_type_two=type(12.08)
print (f"Data type is {data_type_two}")
data_type_three=type("this ia a string")
print (f"Data type is {data_type_three}")
boolean_value=True
... |
def sum(number1,number2):
if type(number1)!=int:
number1=int(input("Please enter a number"))
sum(number1,number2)
elif type(number2)!=int:
print("number is not there")
else:
print(number1+number2)
number1=input("Please enter a number\n")
#use try and exept when the situation... |
# +++ START YOUR IMPLEMENTATION
def longest_palindrome(s):
# Write a function to return the length of the longest palindrome
# in an input string.
# Ex:
# longest_palindrome('aab') => 2
# longest_palindrome('Aaab') => 2
# longest_palindrome('') => 0
# longest_palindrome('fuasdfjh123454321ddd') ... |
from recommendation_data import dataset
from math import sqrt
def similarity_score(person1,person2):
# Returns ratio Euclidean distance score of person1 and person2
both_viewed = {} # To get both rated items by person1 and person2
for item in dataset[person1]:
if item in dataset[person2]:
both... |
import paramiko
class SSHClient(object):
""" A basic SSH Client
This class simplifies paramiko's SSHClient so that we can use python's
built in 'with' statement.
NOTE: This client will not work without the `with` statement.
Example:
with SSHClient(host, username, password) as ssh:
ssh.... |
known_users = ['Alice', 'Bob', 'Claire', 'Dan', 'Enma', 'Fred', 'Georgie', 'Harry']
print(len(known_users))
while True:
print('Hi! My name is Travis')
name = input('What is your name?: ')
if name in known_users:
print('name recognised')
else:
print('name NOT recognised') |
def extraLongFactorials(n):
multVals = list(range(1, n+1))
outVal = 1
for val in multVals:
outVal *= val
return outVal
# HackerRank practice challenge : https://www.hackerrank.com/challenges/extra-long-factorials/problem
fact = extraLongFactorials(5)
print(fact) |
### Greedy Algorithm
### Creado por Vinicio Valbuena
### REF: https://doc.lagout.org/science/0_Computer%20Science/2_Algorithms/Approximation%20Algorithms%20%5BVazirani%202010-12-01%5D.pdf#page=31
import math
class Greedy:
INDEX = 0
SET = 1
def __init__(self, n_group, n_elem, cost, dataset, debug=False):... |
# 1. Create an empty set named showroom.
# 2. Add four of your favorite car model names to the set.
# 3. Print the length of your set.
# 4. Pick one of the items in your show room and add it to the set again.
# 5. Print your showroom. Notice how there's still only one instance of that model in there.
# 6. Using update(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Ascensor
cambiarplanta="S"
while cambiarplanta=="S":
print ("Se encuentra en el primer piso")
print ("Seleccione una opcion")
print ("a:Subir un piso")
print ("b:Subir dos pisos")
print ("c:Bajar un piso")
print ("d:Bajar dos pisos")
print ("x:Salir del ascensor")
... |
numbers = [1]
next_2 = 0
next_5 = 0
for i in xrange(100):
mult_2 = numbers[next_2]*2
mult_5 = numbers[next_5]*5
if mult_2 < mult_5:
next = mult_2
next_2 += 1
else:
next = mult_5
next_5 += 1
# The comparison here is to avoid appending duplicates
if next... |
#Bibliotecas importadas
from bs4 import BeautifulSoup
import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from time import sleep
import os
#Função para consultar os dados da página por meio do webscraping e criar o json dos dados
def execWebScraping():
#Consult... |
from Definitions import itemDesc, townDesc, npcDesc
def inventory_Menu():
print('\nInv: Access your inventory' + '\t' + 'Menu: Access menu')
class Item():
"""Class that creates a new item for player(Weapon, armor, card, etc)"""
def __init__(self, name, itemType, stats, isEquipped):
self.name = ... |
class Employee_Salary:
def __init__(self,name,salary):
self.name=name
self.salary=salary
def __mul__(self,other):
return self.salary*other.days
class Employee_Days:
def __init__(self,name,days):
self.name=name
self.days=days
es=Employee_Salary("Arif Ali",700)
ed=Employee_Days("Arif Ali",30)... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import pandas as pd
# In[2]:
# Input
n_simulation = 21 # choose the number of simulation
A_0 = 1000.0 # g, mass of A at t=0
B_0 = 50.0 # g, mass of B at t=0
C_0 = 10.0 # g, mass... |
#!/usr/bin/env python
# coding: utf-8
# ## About this Groundwater Course and Contents
#
# The contents provided in this website that forms an interactive book, is based on the Groundwater course created and lectured by
# Prof. Rudolf Liedl from the [Institute of Groundwater Manangement](https://tu-dresden.de/bu/umwe... |
def filter_integers_greater_than(list,n):
if list==[]:
result=None
else:
result=[]
for i in list:
if i>n:
result.append(i)
if len(result)==0:
result=None
return result
l=([0,3,5,-2,9,8])
filter_integers_greater_than(l,4) |
def is_a_conditions_true(list):
if list == [] :
result=None
else:
result=False
for i in list:
if i==True:
result=True
return result
is_a_conditions_true([True,True])
|
"""Cubefall sample application"""
import time
import random
import pygame
import sys
import os
from quaternion import from_rotation_vector
from pyxyz import *
GRAVITY = -9.8
class FallingCube(Object3d):
"""Falling cube 3d object"""
def __init__(self, mesh):
super().__init__("FallingCube")
# ... |
import sqlite3
import sys
import datetime
conn = sqlite3.connect("test.db")
cur = conn.cursor()
# cur.execute('CREATE TABLE stocks (data text, trans text, symbol text, qty real, price real)')
cur.execute("INSERT INTO stocks VALUES ('%s', 'BUY', 'RHAT', 150,35.2)" %datetime.datetime.today().strftime("%Y-%m-%d"))
cur.ex... |
import tkinter as tk
from platform import python_version
def teste(self):
return 1
def main(args):
root = tk.Tk(className='Python')
root.geometry("1000x600+90+90")
l1= tk.Label(root, text="Programa para Urna", bg="red", fg="white").grid(row=0,column=0)
l2= tk.Label(root, text="Texto intermediário", bg="yello... |
from random import randint
usuario = []
sistema = []
print('''
Loteria do Azar!!!
*Atenção para jogar digite 6 numeros de 0 a 20!*
''')
for i in range (0,6):
num = int(input('Digite um numero: '))
usuario.append(num)
sis = randint(0,20)
sistema.append(sis)
print('''
Seus numeros: %s
... |
class Funcoes:
def aplcicacao(self):
resposta = input('Deseja sair da aplicação?(S/N): ')
if resposta.upper() == 'N':
return True
else:
return False
def calcular (self):
print('Calcular potencia!!!')
num = int(input('Informe um numero: '))
... |
lista = ['arlindo', 'feijao', 'coxinha', 'inteiro', 'vinagre', 'juropinga', 'goole', 'tubo',
'vermelho', 'creiton', 'pedro', 'neine']
vLetra = input('informe uma letra: ')
for palavra in lista:
for letra in palavra:
if letra == vLetra:
print(' ' + palavra + ';')
break |
from Urna import *
print("Bem vindo!\nIniciar urna?(S ou N)")
while True:
Ligar = input(">").upper()
if Ligar == "S":
ligar = True
print("Iniciando sistema\n")
break
elif Ligar == "N":
ligar = False
print("Fechando sistema")
break
else:
... |
print('''
Q1 - No Phyton como se chama uma 'caixa' usada para armazenar dados?
a - texto
b - variavel
c - uma caixa de sapatos
''')
resposta = input().lower()
if resposta == "a":
print (" Não - texto é um tipo de dado :( ")
elif resposta == "b":
print(" Correto! :) ")
elif resposta == "c":
print(" Não... |
"""
created by nzh
Date: 2020-01-11 14:54
"""
import numpy as np
import pandas as pd
# 学习查看DataFrame
# 先构造一个示例DataFrame
data = {
'A': np.arange(start=1, stop=11, step=1),
'B': np.arange(start=11, stop=21, step=1),
'C': np.arange(start=21, stop=31, step=1),
'D': np.arange(start=31, stop=41, step=1)
}
... |
class NameArray:
# constructor template for NameArray:
# nameArray = NameArray(5)
# Interpretation:
# We initialize an dictionary nameArray where vertex is the key and value is the name label
def __init__(self):
self.nameArray = {}
# Assigns name label to every vertex(element)... |
def is_valid_1(n):
digits = str(n)
return sorted(digits) == list(digits) and len(set(digits)) < len(digits)
print('Part 1:', sum(is_valid_1(x) for x in range(372304, 847061)))
from collections import Counter
def is_valid_2(n):
digits = str(n)
return sorted(digits) == list(digits) and 2 in Counter(di... |
#!/usr/bin/env python
import math
def make_chocolate(small, big, goal):
return make_chocolate2(small, big, goal)
def make_chocolate1(small, big, goal):
# 99 200 100 = -11
# we could use 20 bars
# but we have 200
# pick the minimum... 20 ... thats the number of big bars you'd use
# how ma... |
#
# https://leetcode.com/problems/linked-list-cycle-ii/
#
def detect_cycle(head):
slow = fast = head
#
# we need to check for both because,
#
# fast itself can be None (head is None (or) fast was previously one node
# earlier to tail and on doing, fast.next.next(fast.next will be tail in this... |
def simple_generator():
yield 1
yield 2
yield 3
for no in simple_generator():
print no
if 2 == no:
break
for no in simple_generator():
""" New one """
print 'New one'
print no
|
def next_term(term):
res = ''
count = 1
prev = term[0]
n = len(term)
for i in range(1, n):
if term[i] == prev:
count += 1
else:
res += '{}{}'.format(str(count), prev)
count = 1
prev = term[i]
res += '{}{}'.format(str(count), prev)
... |
def get_max_sum(array):
max_sum = array[0]
running_sum = max_sum
for index in range(1, len(array)-1):
running_sum += array[index]
# If individual element itself overpowers running sum, then running sum
# changes to be the element(running sum starts from the element). Else,
# ... |
colors = ['red', 'yellow', 'green', 'yellow', 'blue']
# get default values to a dictionary, without checking(for a KeyError) if the
# key is present
d = dict()
for color in colors:
d[color] = d.get(color, 0) + 1
print d
# same using defaultdict
from collections import defaultdict
dd = defaultdict(int)
for col... |
import sys
import interval
# prompt_user is the main function that a user interacts with to create intervals
def prompt_user():
"""get list of intervals to start, then get one more interval at a time.
'quit' or ctrl+c exits"""
active_intervals = []
while True:
try:
user_input = inp... |
import unittest
from interval import interval,mergeIntervals,mergeOverlapping,insert
"""This is test function for the class interval and the functions
mergeIntervals(), mergeOverlapping(), and insert()"""
class interval_test(unittest.TestCase):
def setUp(self):
pass
def test_interval1(self):
... |
import sys
from interval import *
def main():
'''
A program that uses interval class and functions to prompts the user
for a list of intervals, reads a string from the user, and creates a list
containing these intervals
'''
while True:
try:
user_input = input("List of inter... |
'''
Created on Nov 14, 2016
@author: muriel820
'''
class IntervalErrors(Exception):
'''Superclass of Exceptions'''
pass
class InputNotString(IntervalErrors):
def __str__(self):
return 'Please input as a string'
class MissingBracket(IntervalErrors):
def __str__(self):
return 'Your input ... |
import re
from typing import List, Any
class IntervalError(Exception):
"""Base Interval exception class."""
pass
class ParsingException(IntervalError):
"""Raised when unable to parse user-defined Interval."""
def __init__(self, interval):
self.interval = interval
def __str__(self):
... |
import unittest
from interval import interval, insert, mergeIntervals, mergeOverlapping
class Test(unittest.TestCase):
def setup(self):
pass
#test for class interval
def test_init(self):
self.assertEqual(interval("[1,4]").lower, 1)
self.assertEqual(interval("[1,4]").upp... |
import unittest
from Interval import InputTypeException, InputValueException, MergeException, Interval, mergeIntervals, mergeOverlapping, insert
class TestInterval(unittest.TestCase):
def test_valid_interval(self):
self.assertEqual(str(Interval('(2, 5)')), '(2,5)')
def test_invalid_interval(self):
... |
'''
Created on Nov 11, 2016
@author: Fanglin Chen
'''
from interval import *
from merge import *
while True:
try:
intervals_initial = input('List of intervals? \n> ') # Prompt the user for a list of intervals
if intervals_initial == 'quit':
break
else:
# Create a... |
import re
class interval:
valid_string = 1 #to check if the input interval is valid ornot
to_form_list = 1
def __init__(self, x, to_print_or_not): # the second argument (to_print_or_not) is to print the error message only when the function is called. It is not printed when it is run for test cases
... |
class MergeError(Exception):
def __str__(self):
return 'Cannot merge intervals: gap between two intervals.'
class Interval():
def __init__ (self, user_input):
# user_input=user_input.replace(' ','')
''' check the validity of the user input string,
take input strings ... |
import exceptions
from interval import *
from functions import *
interval_input = input('List of Intervals?')
intervals = []
for i in list(interval_input.split(', ')): #read input
intervals.append(interval(i))
while True:
newint_input = input('Interval?')
if newint_input == 'quit':
break
el... |
'''
Created on 2016.11.14
@author: xulei
'''
from assignment7 import Interval
from Merge import *
from exceptionClass import *
def main():
#The first loop get a list of intervals
while True:
try:
input_str=input('List of Intervals? use comma then space to separate t... |
import unittest
from assignment7 import *
class test_interval(unittest.TestCase):
def test_interval_class(self):
with self.assertRaises(InvalidUserInputException):
interval(3)
with self.assertRaises(InvalidUserInputException):
interval("asdfg")
with self.assertRaise... |
# Solution for DS-GA 1007 Assignment#7
# Author: Jiaming Dong (jd3405@nyu.edu)
# NYU Center for Data Science
from errors import *
from interval import interval
def mergeIntervals(int1, int2):
"""Merge two intervals and return the merged interval"""
# first check whether they are mergeable
if not isMergeable(int1, ... |
'''
Created on Nov 14, 2016
@author: Caroline
'''
import unittest
import interval_class as i
import functions as m
#test 0: Interval class
#is there a better way to test the Interval class?
class Interval_test_case(unittest.TestCase):
def setUp(self):
print('In interval class setUp')
self.input... |
'''
Main program for assignment 7
@author: jonathanatoy
'''
[]
from interval import *
def isMergeable(int1, int2):
"""Determines whether two intervals are overlapping or adjacent"""
mergeable = True
if (int2.lower_bound > int1.upper_bound) or (int1.lower_bound > int2.lower_bound):
mergeable = False... |
'''
Interval Class
@author: jonathanatoy
'''
class interval(object):
'''
Class represents an interval of integers, i.e. [1,4) represents {1,2,3}
'''
def __init__(self, lower_bound, upper_bound, exclusive_lower, exclusive_upper):
'''
Constructor for interval class
inputs:
... |
def factorial(n): ##defines factorial string
if n == 0: ##if n is equal to 0
return 1 ##return 0
else: ## else
return n * factorial(n-1) ##returns the multiply of n times the factorial minus - 1
n=int(input("Input a number to compute the factorial :")) ##Tells the user to input a number
print(factorial(n)) ##Prin... |
def unique_list(l): ##defines uniqe_list as l
x = [] ## x equals to items in square brackets
for a in l: ##for a in list on unique_list
if a not in x: ##if a is not in x
x.append(a) ##x appends to a
return x ##returns x
print(unique_list([1,2,3,3,3,3,4,5])) ##prints the number of items with no repeated numbers... |
# https://leetcode.com/problems/majority-element/
import math
# returns the frequency of the ith element
def getFreq(nums, i):
# checks and maintains a count as to how many elements are similar to ith element
x = nums[i]
count = 1
i += 1
while i < len(nums):
if nums[i] == x:
... |
# function to implement the cyclic sort algorithm
def cyclicSort(arr):
# we try to put the elements in the correct indices
# index = value - 1
# if an element is at its correct index, we move forward
# else, as long as the element is not at its correct index, we try to put it in its correct index
... |
# https://leetcode.com/problems/valid-palindrome-ii/
def isPalindrome(s):
start = 0
end = len(s) - 1
while start <= end:
if s[start] == s[end]:
start += 1
end -= 1
else:
return False
return True
# TLE
def validPalindrome(s):
# check the st... |
def getMaxIndex(arr, start, end):
max = 0
for i in range(start, end+1):
if arr[i] > arr[max]:
max = i
return max
def selectionSort(arr):
for i in range(len(arr)):
last = len(arr) - i -1
max = getMaxIndex(arr, 0, last)
arr[max], arr[last] = arr[last], arr[... |
# https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/
def search(arr, x):
start = 0
end = len(arr) - 1
while start <= end:
mid = start + (end-start)//2
if arr[mid] == x:
return True
elif x > arr[mid]:
start = mid + 1
... |
# https://leetcode.com/problems/count-items-matching-a-rule/
def countMatches(items, ruleKey: str, ruleValue: str) -> int:
c = 0
j = -1
if(ruleKey == 'type'):
j = 0
elif(ruleKey == 'color'):
j = 1
elif(ruleKey == 'name'):
j = 2
for i in range(len(items)):
i... |
# https://leetcode.com/problems/determine-if-string-halves-are-alike/
def checkIfThereAreEvenNumberOfVowels(s):
# convert the string entirely to lower/upper case
# count the number of vowels in the string
# if the number of vowels is even, count the number of vowels in the first and second half of the... |
def countBits(n):
bitStr = "{0:b}".format(n)
count = 0
for str_i in range(0, len(bitStr)):
if bitStr[str_i] == "1":
count += 1
return count
|
import itertools
def next_bigger(n):
nums = []
possibilities = []
possibility = ""
nums = list(str(n))
for subset in itertools.permutations(nums, len(str(n))):
possibility = int("".join(list(subset)))
if possibilities.count(possibility) == 0:
possibilities.inse... |
class Automaton(object):
def __init__(self):
self.states = ["q1", "q2", "q3"]
self.currentState = self.states[0]
def read_commands(self, commands):
for command in commands:
assert(command == "1" or command == "0")
if self.currentState == "q1":
if... |
def solution(args):
recent = []
ranges = []
result = ""
last = args[0]
for argument in args:
if argument == last+1 or argument == last-1:
recent.insert(0,argument)
else:
if(len(recent) > 0):
ranges.append(appendRange(recent))
r... |
cube = lambda x: pow(x,3)
def fibonacci(n):
if n >= 0:
lst = [0]
if n >= 1:
lst.append(1)
if n >= 2:
for i in range(2,n+1):
lst.append(lst[-1]+ lst[-2])
return lst[:n]
if __name__ == '__main__':
n = int(input())
print(list(map(cube, fibonacci(n)))) |
from math import sqrt, exp, pi, erf
from statistics import mean
def cdf(x, mu, sigma):
"""
Cumulative distribution function for a function with normal distribution
Args:
x (int/float): the value to evaluate the normal distribution
mu (int/float): mean (or expectation) of the dist... |
# https://leetcode.com/problems/contains-duplicate/
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
result = len(nums) != len(set(nums))
return result
in1 = [1,2,3,1]
in2 = [1,2,3,4]
in3 = [1,1,1,3,3,4,3,2,4,2]
s = Solution()
s.containsDuplicate(in1) # True
s.containsDup... |
#!/usr/bin/env python3
# https://www.hackerrank.com/challenges/nested-list/
if __name__ == '__main__':
nested_list = []
for _ in range(int(input())):
name = input()
score = float(input())
nested_list.append([name, score])
student_dict = dict(nested_list)
student_dict = di... |
# floating numbers language
N = {"S", "A", "B", "C", "D", "E", "F"}
SIG = {"0", "1", "2", "3", "4" ,"5" ,"6" ,"7", "8" ,"9" ,"+" ,"-" , ".", "e"}
grammer = \
{"S": ["+A", "-A","A"],
"A": ["0A", "1A", "2A", "3A", "4A", "5A", "6A", "7A", "8A", "9A", "B", ".B"],
"B": ["0C", "1C", "2C", "3C", "4C", "5C", "6C", "7C", ... |
"""
Problem 2: Get input from the user
In the following problem you will be asked to get input from the user.
"""
print("EXAMPLE")
age = input("How old are you? ")
print("You are " + str(age) + " years old!")
# Task 2.1 - Write a program that asks the user for her name. Then print the name.
|
#Algorithms for mathematical problems
def factorial_normal(n):
if n == 0 or n == 1 or n == 2:
return 1
else:
product = 1
for i in range(n, 1, -1):
product *= i
return product
def factorial_recursive(n):
if n == 0 or n == 1:
return 1
else:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 23 18:13:35 2018
@author: h.t
"""
"""import json
with open ('arquivo_texto.json','r') as arquivo:
texto = arquivo.read()
dicionario = json.loads(texto)"""
from firebase import firebase
firebase = firebase.FirebaseApplication('https://ep-henrique... |
# File: MagicSquares.py
# Description: HW13: Magic Squares
# Student's Name: Mengyuan Dong
# Student's UT EID: md42252
# Identifier: BadyElephant
# Course Name: CS 303E
# Unique Number: 51205
#
# Date Created: 11/15
# Date Last Modified: 11/16
class MagicSquare():
def __init__(self,sideLength,grid):
... |
"""
des: 使用turtle绘制tree
author: Mr_52Hz
date: 2020-06-11 2:04 PM
"""
import turtle
t = turtle.Turtle()
def draw_square():
for i in range(4):
t.forward(100)
t.right(90)
def draw_tree(high):
# high 树干的长度
if high > 5:
t.forward(high)
t.right(20)
draw_tree(high - 15)... |
from .animal import Animal
class Pinguino(Animal):
def __init__(self, nombre, edad, nivel_salud=10, nivel_felicidad=10):
super().__init__(nombre, edad, nivel_salud, nivel_felicidad)
self.reproduccion = 'Oviparo'
def display_info(self):
print('-'*15,"Tipo: ",self.__class__.__name__,'-'*... |
for _ in range(int(input())):
d, n, s, p = map(int, input().split())
if d + p*n == n*s:
print("does not matter")
elif d + p*n > n*s:
print("do not parallelize")
else:
print("parallelize") |
def golbange_print_ㅋ(N):
answer = ['' for _ in range(N * 5)]
for idx in range(N*5):
if idx < N or (2 * N - 1 < idx < 2 * N + N):
answer[idx] = "@" * (N * 5)
else:
answer[idx] = "@" * N
return "\n".join(answer)
if __name__ == "__main__":
N = int(input())
print(... |
a,r=int(input()),0
if a%2<1:
if a//2%2>0:
r=1
else:
r=2
print(r) |
for _ in range(int(input())):
li = list(map(int, input().split()))[1:]
odd = even = 0
for n in li:
if n%2 == 1:
odd += n
else:
even += n
if odd == even:
print("TIE")
elif odd > even:
print("ODD")
else:
print("EVEN")
|
# encoding:utf-8
from random import choice
class RandomWolk():
""" 随机漫步数据类"""
# 类的三个属性 随机漫步次数 随机漫步经过的x和y坐标
def __init__(self, num_points=5000):
# 初始化随机漫步属性
self.num_points = num_points
# 所有随机漫步都始于(0,0)
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
""" 计算随机漫步包含的所有点 """
# 不断漫步 直到达到指... |
class Schedule:
def __init__(self , task_name , n ,arrival_time, quantum , burst_time):
self.task_name = task_name # List of the names given to all tasks.
self.n = n # Number of tasks.
self.arrival_time = arrival_time # List of arrival time of every t... |
#
# @lc app=leetcode id=125 lang=python3
#
# [125] Valid Palindrome
#
# @lc code=start
import re
class Solution:
def isPalindrome(self, s: str) -> bool:
lower = re.sub('[^a-z0-9]', "", s.lower())
if lower == lower[::-1]:
return True
else:
return False
# @lc... |
annual_salary = int(input("Enter the yearly salary: "))
monthly_salary = annual_salary/12
semi_annual_raise = .07
annual_return_rate = .04
monthly_return_rate = annual_return_rate / 12
number_of_months = 36
down_payment = 250000
total_earned = 0
for month in range(1,37):
this_months_return = total_earned * monthly_r... |
thistuple = ("apple", "banana", "cherry")
print(thistuple[0])
print(thistuple[1])
print(thistuple[2])
print(thistuple[-1])
print(thistuple[-2])
print(thistuple[-3])
print(thistuple[1:]) |
class Number:
def __init__(self, value):
self.value = value
def __repr__(self):
return f"{self.value}"
def evaluate(self, environment):
return self
class Boolean:
def __init__(self, value):
self.value = value
def __repr__(self):
return f"{self.value}"
... |
'''
The Simulation of a Continuous Uniform R.V.
Using the histogram avaliable in python.
'''
import math
import random
import matplotlib.pyplot as plt
n = 1000000
x = [] # Empty List for uniform
y = [] # Empty List for exponential
Lambda = 0.5 # Parameter in exponential distribution
# ... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
import collections
n = int(input())
counter = 0
WordsList = []
while counter != n:
WordsList.append(input())
counter +=1
x = collections.Counter(WordsList)
print(len(x))
for i in x.values():
print(i,end = ' ')
|
def average(array):
# your code goes here
total = 0
PlantsHeight = set(array)
for i in PlantsHeight:
total += i
return total / len(PlantsHeight)
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
res = ['MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY','SUNDAY']
import datetime
pointer = list(map(int, input().split()))
print(res[datetime.date(pointer[2],pointer[0],pointer[1]).weekday()])
|
import re
pattern = r'^(4|5|6)(\d){3}[-]?(\d){4}[-]?(\d){4}[-]?(\d){4}$'
for i in range(int(input())):
string = input()
v = re.match(pattern,string)
if v == None:
print("Invalid")
else:
v2 = re.split(r'-',v.group())
v3 = ''.join(v2)
res = re.search(r'(00|11|22|33|4... |
import re
n = int(input())
pattern = r'^(7|8|9)\d{9}$'
for i in range(n):
string = input()
res = re.match(pattern,string)
if res:
print("YES")
else:
print("NO") |
def wrapper(f):
def fun(l):
s = "+91 "
for i in range(len(l)):
if len(l[i]) == 10:
l[i] = s + l[i][:5] + " " + l[i][5:]
elif l[i][0] == '+':
l[i] = s + l[i][3:8] + " " + l[i][8:]
elif l[i][0] == '0':
l[i] = s + l[i]... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the anagram function below.
def anagram(s):
if len(s) % 2 == 1:
return -1
buff = dict()
for i in range(int(len(s)/2)):
if s[i] not in buff.keys():
buff[s[i]] = 1
else:
bu... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
N,X = map(int,input().split())
data = []
for i in range(X):
data.append(list(map(float,input().split())))
Sum = list(zip(*data))
for i in range(N):
print(format(sum(Sum[i])/X,"0.1f"))
|
cube = lambda x:pow(x,3)
def fibonacci(n):
if n == 0:
res = []
elif n == 1:
res = [0]
else:
res = [0,1]
counter = 2
while counter != n:
res.append(res[-1]+res[-2])
counter += 1
return res
|
#! usr/bin/env python3
# -*-coding:utf-8-*-
'heros-1.0'
__author__='nanhua'
import random
class Hero(object):
def __init__(self,usr,pwd):
self.name = usr
self.pwd = pwd
self.hp = 100
def change_Pwd(self):
while True:
old_Pwd = input('please input old password:')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.