text stringlengths 37 1.41M |
|---|
# ============== Set row and col to None ==========
# Time: O((mn)^2)
# Space: O(1)
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
if not matrix or not matrix[0]:
... |
"""
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
For example,
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
######## Resursion ############
# Best time: 48ms
# Time Complexity: O(n)
# Space Complexity: O(n)
class Solution:
# @param {TreeNode} root
# @retur... |
"""
Given an circular integer array (the next element of the last element is the first element), find a continuous subarray in it, where the sum of numbers is the biggest. Your code should return the index of the first number and the index of the last number.
If duplicate answers exist, return any of them.
Have you m... |
# ======== Pointers ==============
# Time: O(n)
# Space: O(n)
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
s_list = list(s)
l = 0
r = len(s_list) - 1
while l < r:
s_list[l], s_list[r] = s_list[r], s_l... |
"""
Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt.
Example 1:
Input: 16
Returns: True
Example 2:
Input: 14
Returns: False
Credits:
Special thanks to @elmirap for adding this problem and creating al... |
"""
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
How we serialize an undirected graph:
Nodes are labeled uniquely.
We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import sys
class Solution(object):
prev = TreeNode(-sys.maxint - 1)
node1 = None
node2 = None
def recoverTree(self, root):
... |
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import norm
def gaussian(x,x0,xsig):
'''
function to calculate the gaussian probability (its normed to Pmax and given in log)
INPUT:
x = where is the data point or parameter value
x0 = mu
xsig = sigma
'''
factor = 1. / (np.sq... |
import numpy as np
def slope_imf(x,p1,p2,p3,kn1,kn2):
'''
Is calculating a three slope IMF
INPUT:
x = An array of masses for which the IMF should be calculated
p1..p3 = the slopes of the power law
kn1, kn2 = Where the breaks of the power law are
OUTPUT:
An array o... |
import math
import random
def pow_mod(g, e, p):
''' calculate (g**e)%p efficiently '''
oe = e
result = 1
g %= p
while e > 0:
if e & 1:
result = (result *g)%p
e >>= 1
g = (g*g)%p
result %= p
return result
def gcd(a, b):
''' return the greatest common ... |
<<<<<<< HEAD
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
MONTH_CONVERT = {
'january': 1,
'february': 2,
'march': 3,
'april': 4,
'may': 5,
'june': 6,... |
1.
class Laptop:
def __init__(self):
battery = Battery('This is charge for battery')
self.battery = [battery]
class Battery:
def __init__(self, charge):
self.charge = charge
laptop = Laptop()
2.
class Guitar:
def __init__(self, guitarstring):
self.guitarstring = guit... |
import pymysql
def connectDB():
"""Ansluter till databas"""
db = pymysql.connect(host="localhost",
user="root",
passwd="",
db="yourgeo",
cursorclass=pymysql.cursors.DictCursor)
"""Skapar en cursor för datab... |
def create_dictionary(filename):
ratings = open(filename)
restaurants = {}
for line in ratings:
name, rating = line.rstrip().split(":")
restaurants[name] = rating
ratings.close()
return restaurants
def sort_and_print(filename):
input_dict = create_dictionary(filename)
... |
# A single node of a singly linked list
class Node:
def __init__(self,data):
# constructor
self.data = data
self.next = None
# A Linked List class
class LinkedList:
# constructor
def __init__(self):
self.head = None
# Return string to representation of the object
... |
# https://snakify.org/en/lessons/print_input_numbers/problems/
# A school decided to replace the desks in three classrooms. Each desk sits two students. Given the number of students in each class, print the smallest
# possible number of desks that can be purchased.
# The program should read three integers: the number... |
# https://snakify.org/en/lessons/integer_float_numbers/problems/
# Given a positive real number, print its fractional part.
import math
a = float(input('Enter a postitive real number: '))
fractional_length = len(str(a).split('.')[1])
fractional_part = a - math.floor(a)
result = round(fractional_part, fractional_len... |
# https://snakify.org/en/lessons/print_input_numbers/problems/
# Write a program that reads an integer number and prints its previous and next numbers. See the examples below for the exact format your answers should take. There shouldn't be a space before the period.
# Remember that you can convert the numbers to stri... |
# Livro Ciência de Dados e Aprendizado de Máquina - https://www.amazon.com.br/dp/B07X1TVLKW
# Livro Inteligência Artificial com Python - Redes Neurais Intuitivas - https://www.amazon.com.br/dp/B087YSVVXW
# Livro Redes Neurais Artificiais - https://www.amazon.com.br/dp/B0881ZYYCJ
from rbm import RBM
import numpy a... |
def merge_sort(in_numbers):
if len(in_numbers) > 1:
left_part = in_numbers[:len(in_numbers)//2]
right_part = in_numbers[len(in_numbers)//2:]
merge_sort(left_part)
merge_sort(right_part)
i = 0 #index for left
j = 0 #index for right
k = 0 #ind... |
"""
file_read.py
文件读取演示
"""
# 打开文件
f = open('Install.txt','r')
# 读取文件
# data = f.read()
# print(data)
# 循环读取文件内容
# while True:
# # 如果读到文件结尾 read()会读到空字符串
# data = f.read(1024)
# # 读到结尾跳出循环
# if not data: # 当data为None的时候返回False,所以not data为True才会执行break
# break
# print(data)
# 读取文件一行内容
# ... |
i,j,tmp = 0,0,0
list = [5,3,1,9,8,2,4]
for i in range(7):
for j in range(i+1,7):
if(list[i]>list[j]):
tmp = list[i]
list[i] = list[j]
list[j] = tmp
print(list) |
def addItUP:
sum = 0
for num in range(n+1):
sum+=num
return num |
# krok 1. pozyskanie słownictwa występującego w naszych danych
import pandas as pd
import nltk
from nltk.corpus import words
vocabulary = {}
data = pd.read_csv('emails_data.csv')
nltk.download('words')
set_words = set(words.words())
def build_vocabulery(curr_email):
i = len(vocabulary)
for word in curr_emai... |
f = int(input())
t = int(input())
d = int(input())
m = f
if m < t:
m = t
if m < d:
m = d
print(m) |
class Rent:
"""
Object which contains data about a particular bill, including
the amount and period of the bill.
"""
def __init__(self, amount, period):
self.amount = amount
self.period = period
class Housemate:
"""
Person who lives in the home and pays a share of the rent... |
"""Define Franc Class."""
# for return Franc itself at method times()
from __future__ import annotations
from ch6.money import Money
class Franc(Money):
"""Define Franc Class."""
def times(self, multiplier: int) -> Franc:
"""multiplication."""
return Franc(self.amount * multiplier)
|
import pandas as pd
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
import os
def melt(df):
"""Melting the dataframe, returning a melted df, a list of species and a list of genes."""
species_columns = [x for x in df.columns if x != 'gene_name'] # getting the col... |
#Socket client example in python
import socket #for sockets
import sys #for exit
#create an INET, STREAMing socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print 'Failed to create socket'
sys.exit()
print 'Socket Created'
host = '127.0.0.1';
port = 2589;
... |
import turtle;
t=turtle.Turtle();
s=turtle.Screen();
s.bgcolor('black')
t.pencolor('blue')
a=0
b=0
#c=0
#d=0
t.speed(0)
t.penup()
t.goto(0,200)
t.pendown()
while True:
t.forward(a)
t.right(b)
#t.left(c)
#t.backward(d)
a+=3
b+=1
#c+=2
#d+=4
if b == 210:
break
t.hideturtle(... |
x_crazy_landlords = ['Cruella de Ville', 'Donald Duck', 'Popeye the Maltese']
counter = 1
print('loop started')
for landlord in x_crazy_landlords:
print(counter, '-', landlord)
counter += 1
print('loop ended')
spartans = [['shav', 'adam', 'julian', 'muji', 'ally'], ['pratheep', 'zaid', 'omid', 'payal', 'michea... |
# Group 4: Trinidad Ramirez, Jerridan Bonbright, Illia Sapryga, Christopher Flores
# Team Programming Assignment 3
# CST 311
# TCPClient.py
# Why is multithreading needed to solve this assignment?
# Incorporating multiple threads in the program creates parallel execution, which
# is significantly more efficient with r... |
from pystack.exc import EmptyStackError
class Stack(object):
"""A list-based stack implementation.
Attributes:
_data (list): Private list maintaining stack elements
"""
def __init__(self):
"""Initialises an empty stack."""
self._data = []
def is_empty(self):
"""C... |
def pagination(array, page, size):
if page is not None and size is not None:
if type(page) is str and page.isnumeric():
page = int(page)
if type(size) is str and size.isnumeric():
size = int(size)
p = page - 1
start = p * size
end = page * size
... |
# -*- encoding=utf-8 -*-
"""
proxy 模式
一个常见的用法就是延迟实际的求值操作
"""
class Rectangle(object):
def __init__(self, height, width):
print 'Create a Rectangle'
self._height = height
self._width = width
def draw(self):
print 'A rectangle of size: {height}x{width} = {size}'.format(height=s... |
# -*- encoding=utf-8 -*-
"""
FlyWeight 模式
用于处理大量重复的类的共享
"""
class DigitFactory(object):
def __init__(self):
self._digits = {}
def get_digit(self, key):
if key not in self._digits:
self._digits[key] = Digit(key)
return self._digits[key]
class Digit(object):
def __in... |
import random
for i in range(1,5):
random_num = random.uniform(0,1)
rounded = round(random_num)
total_heads = 0
total_tails = 0
if rounded == 1:
total_heads += 1
print "Attempt: #{} Throwing a coin.. Its a Head! got {} head(s) so far and {} tail(s) so far".format(i,total_head... |
'''
1.常用元字符
. 匹配任意除换行符"\n"外的字符
+ 匹配前一个字符1次或无限次
.+匹配多个除换行符"\n"外的字符
?匹配一个字符0次或1次,还有一个功能是可以防止贪婪匹配
^ 匹配字符串开头
$ 匹配字符串末尾
| 匹配该符号两边的一个
() 匹配括号内的表达式,也表示一个组
[] 匹配字符组中的字符
[^]匹配除了字符组中字符的所有字符
{n} 重复n次
{n,}重复n次或更多次
{n,m}重复n到m次
2.预定义字符集表
\d 匹配数字
\D 匹配非数字
\w 匹配字母或数字或下划线
\W 匹配非字母或数字或下划线
\s 匹配任意的空白符
\S 匹配非空白符
\n 匹配一个换行符
\t 匹配一个制... |
#-*- coding:utf-8 -*-
#startTimeStr : '2008-08-10'
#endTimeStr : '2008-09-10'
#Iteration Range : 'D' = day, 'H' = hour
#USAGE 1 : getTimeList('2008-08-01', '2008-08-10', 'H')
#USAGE 2 : getTimeList('2008-08-01', '2008-08-10', 'D')
#RESULT 1 : '2008-08-01 00:00:00', '2008-08-01 01:00:00' ...
# '20... |
#!/usr/bin/env python
"""
Usage
for vals in rand_graph(10, 4):
print vals
"""
import random
DB_RANGE = (-60, -50)
def rand_graph(num, conn):
"Creates a random graph with n elments"
for x in range(0, num):
for y in range(x+1, num):
if random.random() * conn > 1:
val = ... |
import random
from src import cell
RED = (255, 0, 0)
BLUE = (0, 0, 255)
WHITE = (255, 255, 255)
class Maze:
"""Object used to represent a maze and the information needed to specify the dimensions, cells contained, start and finish.
"""
def __init__(self, size, scale):
self.directions = {"above":(0... |
import numpy as np
class QLearningAgent():
def agent_init(self, agent_info):
"""Object instance of a Q-Learning agent that utilizes a model-free algorithm to learn a policy and identify an optimal action-selection policy.
num_actions {int} -- The number of actions the agent can take in th... |
#a) The password length should be in range 6-16 characters
#b) Should have atleast one number
#c) Should have atleast one special character in [$@!*]
#d) Should have atleast one lowercase and atleast one uppercase character
passwd = input("Enter password : ") #take password from user
#validate password
len... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 14 21:27:30 2018
@author: Ju-Un Park
"""
#Chapter 9 CLASSES
# Creating and using a class
# Creating the dog class
class Dog():
""" A simple attempt to model a dog."""
def __init__(self, name, age):
"""Initialize anme and age attributes."""
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 7 23:57:58 2018
@author: Ju-Un Park
"""
# User input and while loops
# how the input() function works
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
# Writing clear prompts
name = input("Please enter your name: ")
print("Hell... |
#!/usr/bin/env python3
# Created by: Wenda Zhao
# Created on: Dec 2020
# This program is check leap year
def main():
# this function is check leap year
# input
year = int(input("Enter the year: "))
print("")
# process & output
if year % 4 == 0:
if year % 100 == 0 and year % 400 != 0... |
''''创建列表'''
member = ["小甲鱼","小布丁","黑夜","迷途","怡静"]
print(member)
number = [1,2,3,4,5,6]
print(number)
mix = [1,"huahua",3.14,["大笨蛋","臭宝宝","小傻逼"]] #列表中可以添加不同类型的元素,甚至是另一个列表
print(mix)
#创建一个空列表
blank = []
print(type(blank))
'''向列表添加元素'''
member.append("The_zero")
print(member)
print(" 长度是"+str(len(member)))
member.extend(... |
#分片
str1 = "I love fishc.com "
print(str1[6:])
#获取单个字符
print(str1[3])
#修改字符串
str1 = str1[:4]+"插入的字符串"+str1[4:]
print(str1)
'''一些常用的方法'''
str2 = " fafa"
print(str2.capitalize()) #首字母大写
print(str2.center(40)) #填充空格至40长度 并使字符串居中
print(str2.count('a')) #计算a的次数
print(str2.endswith("fa")) #检查是... |
"""生成器 生成器是一种特殊的迭代器 生成器的出现使得协同程序的概念得以实现"""
"""协同程序就是可以运行的独立函数调用,函数可以展厅或者挂起,并在需要的时候从函数离开的地方继续或者重新开始"""
def myGen():
print("生成器被执行!")
yield 1
yield 2
myG = myGen()
print(next(myG))
next(myG)
myG = myGen()
for i in myG:
print(i)
"""用生成器写一个feb数列"""
def feb():
a = 0
b = 1
while True:
a... |
from datetime import datetime, timedelta
import sys
SCHOOL = "school"
NOT_SCHOOL = "not-school"
def calculate_day_type(date):
"""Return the type of a day for a student
Parameters:
date (datetime): A day to calculate the type of
There are 2 different day types returned:
school - When student ... |
# count the email from all the senders
with open("mbox-short.txt",'r')as file: #open file
emailList = {} #def as dict{}
for line in file:
if line.startswith("From ") == True: #take line starting with From
line = line.split()
email = line[1] #take out the email component
... |
#!/usr/bin/env python3
# Created by: Mr. Coxall
# Created on: Nov 2019
# This program prints five integers per line
def main():
# this function is the the famous Fizz-Buzz problem
for counter in range(1000, 2000 + 1):
if counter % 5 != 4:
print(counter, " ", end="")
else:
... |
import numpy as np
import copy
def print_shortest_records(record, start, destination):
if start == destination:
return 'You already there.'
path = []
previous_point = record[start][destination]
while previous_point != start:
path.append(previous_point)
previous_point = recor... |
#!/usr/bin/python3
# Standard imports
import cv2
import numpy as np;
import sys
import pprint
pprint.pprint(sys.argv)
filename = sys.argv[1]
print("Filename = " + filename)
# Read image
im = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
# Set up the detector with default parameters.
detector = cv2.SimpleBlobDetector(... |
n=4
def staircase(n):
# Write your code here
i=0
while i<=n-1:
column=((n-i-1)*" ")+"#"
print(column,end="")
row=i*"#"
print(row)
i +=1
staircase(n)
### |
age = input("What's you age ? \n")
if(int(age) >= 18):
print("Okay! you are old enough")
else:
print("No! you cannot buy it")
|
#Find the word that are not present in the book
f=open("20.txt","r")
print(f.read())
srch_word=input("enter any word:")
if(srch_word not in f):
print("word not found.")
else:
print("word found.")
|
# -*- coding: utf-8 -*-
import sys
class Agent(object):
def __init__(self, toys=[], LearnC=1, LearnR=1, DiscoverC=1, DiscoverR=1, ExploreProb=1, toynames=[0, 1]):
"""
toys[]: List of toy objects.
Learn (bool): Does the agent care about the learner's experience with the taught toy?
... |
# add value to unknown object dictionary or list
a = {} # dictionary
# a = [] # list
def add_element():
if isinstance(a, dict):
a.update({1: "one"})
print "dict updated"
if isinstance(a, type({})):
a.update({1: "one"})
print "dict updated"
if isinstance(a, list):
... |
"""""""""
We can predefine b in f(a,b) using f(a,b=3)
Operator "pass" do nothing
Function always returns None in case "return" is absent
It could be written as f(b=1, a=3, c =7)
Task: Write function of sum 3 numbers tranfering arguments not different orders
"""""
a = int(input("Input A"))
b = int(input("Input B"))
c ... |
from turtle import Turtle, Screen
import random
is_race_on = False
screen = Screen()
screen.setup(width=500, height= 400)
user_bet = screen.textinput(title="Who will win?", prompt="Choose a turtle:").lower()
colours = ["blue", "red", "purple", "orange"]
y_start = [45, 15, -15, -45]
all_turtles = []
for turtle_index ... |
import math
funlist = ['abs', 'acos', 'atan', 'asin', 'sin', 'tan', 'cos', 'log', 'ln']
def EquationSolver(eqstr, Xvalue, Yvalue=None):
"""(str, number [, number]) -> number
solves a raw equation string with given Xvalue. Returns number solution.
>>> EquationSolver('54log(x)', 1)
0
>>> EquationS... |
print('-----------------kaiyue---------------------')
temp = input("不妨猜一下kaiyue心里想的那个数字:")
guess = int(temp)
while guess !=8:
temp = input("不妨猜一下kaiyue心里想的那个数字:")
guess = int(temp)
if guess == 8:
print("卧槽,你是kaiyue心中的蛔虫吗?!")
print("哼,猜中了也没有奖励!")
else:
if guess >8:
pri... |
#Efetua a leitura da variável inteira
A = int(input())
#Efetua a leitura da variável inteira
B = int(input())
#Efetua o produto dos valores A e B
PROD = (A*B)
#Exibe o Valor do produto
print("PROD = %i" %PROD) |
#tic tac toe game
import random
#the game board
board = [0, 1, 2,
3, 4, 5,
6, 7, 8]
def show():
print(boarrd[0],"|",board[1],"|",board[2])
print("_______________________")
print(boarrd[3],"|",board[4],"|",board[5])
print("_______________________")
print(boarrd[6],"|",board[7],"|",board[8])
... |
#Joshua Atherton TCSS 142
napierNumber = ['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']
numberList = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192,
16384, 32768, 65536, 131... |
import adventofcode
def is_valid_password_1(password):
"""
>>> is_valid_password_1("111111")
True
>>> is_valid_password_1("223450")
False
>>> is_valid_password_1("123789")
False
"""
has_double = any(password[c] == password[c+1] for c in range(len(password)-1))
is_ascending = al... |
import math
def is_permutation(n, m) -> bool:
str1 = [x for x in str(n)]
str2 = [x for x in str(m)]
if len(str1) != len(str2):
return False
a = sorted(str1)
str1 = " ".join(a)
b = sorted(str2)
str2 = " ".join(b)
for i in range(0, len(str1)):
if str1[i] != str2[i]:
... |
import random
a = random.randrange(0,101)
if a >= 90:
print("A+")
elif a >= 80 and a <=90:
print("A")
elif a >= 70 and a <=80:
print("B")
elif a >= 60 and a <=70:
print("C")
else:
print("F")
print(a) |
a = 11
b = 4
c = 0
c = a + b
print("Line 1 - Value of c is ", c)
c = a - b
print("Line 2 - Value of c is ", c)
c = a * b
print("Line 3 - Value of c is ", c)
c = a / b
print("Line 4 - Value of c is ", c)
c = a % b
print("Line 5 - Value of c is ", c)
a = 3
b = 4
c = a**b
print("Line 6 - Value ... |
# Define a faster fibonacci procedure that will enable us to computer
# fibonacci(36).
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
old_fib, result_fib = 1, 1
while n > 2:
old_fib, result_fib = result_fib, result_fib + old_fib
n ... |
# Dictionaries of Dictionaries (of Dictionaries)
# The next several questions concern the data structure below for keeping
# track of Udacity's courses (where all of the values are strings):
# { <hexamester>, { <class>: { <property>: <value>, ... },
# ... },
# ... }
# For ... |
# Numbers in lists by SeanMc from forums
# define a procedure that takes in a string of numbers from 1-9 and
# outputs a list with the following parameters:
# Every number in the string should be inserted into the list.
# If a number x in the string is less than or equal
# to the preceding number y, the number x should... |
# Write a program that returns the number of edges
# in a star network that has `n` nodes
def star_network(n):
# return number of edges
if n < 2:
return 0
return n - 1
for x in range(5):
print(x, star_network(x))
|
#!/usr/bin/env python3
# encoding: utf-8
import numpy as np
'''
Numpy copy & deep copy
Ref: https://morvanzhou.github.io/tutorials/data-manipulation/np-pd/2-8-np-copy/
'''
# = 的赋值方式会带有关联性
a = np.arange(4)
b = a
c = a
d = b
a[0] = 11
print(a)
print(d[0])
print(b is a) # True
print(c is a) # True
print(d is a) # Tru... |
# 7. Write a Python program to accept
# filename from the user and print
# the extension of that.
# Sample filename : abc.java
# Output : java
x: str = input('input file name'
'aka abc.java: ')
arr_str = x.split('.')
print(f'extension is: {arr_str[-1]}')
|
# Question 2
# Level 1
#
# Question:
# Write a program which can compute the factorial of a given numbers.
# Suppose the following input is supplied to the program:
# 8
# Then, the output should be:
# 40320
#
# Hints:
# In case of input data being supplied to the question, it should be
# assumed to be a console input.
... |
# class : 내가 자료형을 만들어 쓰는 것(문자열 하나로도, 리스트 하나로도 표현할 수 없을 때)
class User:
pass
# 아예 비워놓으면 오류떠서 다른 내용 쓰지 않겠다는 명령어
user1 = User()
user2 = User()
print(type(user1))
# 출력결과 : <class '__main__.User'>
# __main__ : 실행 파일 이름
# .User : 클래스 이름
# 인스턴스
class User:
pass
user1 = User()
user2 = User()
print... |
Y = 2014
A = 7
B = 9
W = 'Wednesday'
def solution(Y, A, B, W):
# write your code in Python 3.6
month = [0,31,28,31,30,31,30,31,31,30,31,30,31]
days = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
]
first_m... |
def capitalize_all(t):
res = []
for item in t:
res.append(item.capitalize())
return res
def only_upper(t):
res = []
for item in t:
if item.isupper():
res.append(item)
return res
def nested_sum(t):
res = 0
for item in t:
if isinstance(item, list):
... |
# Dada una lista de nombres, ingresada por usuario
# que regresa la cantidad de nombres en la lista
# e imprima la lista alfabeticamente
ordenador = []
nombres = int(input("Numero de nombres:"))
for i in range (nombres):
n = (input("Ingresa un nombre:"))
ordenador.append(n)
print("Arreglo antes de ordenarl... |
# Crea una función que reciba un número y regrese un booleano indicando si es divisible entre 243
def isDivisible(num):
return num % 243 == 0
print(isDivisible(490))
print(isDivisible(486))
# Crea una función llamada multiplicarString que reciba un string y un número entero positivo.
# La función debe regresar... |
# IMPORT -----------------------------------------------------------------------
import random
import sys
import time
# ------------------------------------------------------------------------------
# BINARY -----------------------------------------------------------------------
def binary(valuelist, searchval):
... |
import pygame as pg
import sys
import random
#вывод текста
pg.font.init()
def draw_text(surf, text, size, x, y):
font = pg.font.SysFont('arial', size)
text = font.render(text, True, [200,200,200])
surf.blit(text, [x,y])
#проверка на смерть
def IsDead(head, body, poisonFruit):
for i in body:... |
import math
file = open('comm_words.txt', encoding="utf8")
s = file.read()
s = s.split("\n")
word_list = dict()
med_len = float(0)
let_freq = []
total_let_freq = 0
for i in range(31):
let_freq.append(0)
for word in s: # aici o sa fie cate cuvinte bagam, inputul l-am presupus a fi de forma cuvant f... |
# Uses python3
import sys
# Solution provided:
"""
def fibonacci_sum_naive(n):
if n <= 1:
return n
previous = 0
current = 1
sum = 1
for _ in range(n - 1):
previous, current = current, previous + current
sum += current
return sum % 10
"""
# Knowing that Pisano P... |
import sys
def knapsack(n, W):
"""Recursive solution"""
arr = [[None for _ in range(W+1)] for _ in range(n+1)]
if arr[n][W] != None: return arr[n][W]
if n == 0 or W == 0:
res = 0
elif weights[n-1] > W:
res = knapsack(n-1, W)
else:
tmp1 = knapsack(n-1, W)
tmp2 =... |
from enum import Enum, unique
@unique
class TokenType(Enum):
# Single-character tokens.
LEFT_PAREN = '('
RIGHT_PAREN = ')'
LEFT_BRACE = '{'
RIGHT_BRACE = '}'
LEFT_BRACKET = '['
RIGHT_BRACKET = ']'
COMMA = ','
DOT = '.'
MINUS = '-'
PLUS = '+'
SLASH = '/'
STAR = '*'... |
'''
In this lecture we cover how optimized is binary search
And how to use AVL tree concepts to balance the binary tree's height to atmost logn
'''
class Node:
def __init__(self, val: int or float , left=None, right=None):
self.val = val
self.left = left
self.right = right
self.heig... |
class First:
def __init__(self,a,b):
self.a = a
self.b = b
print("iam constructor")
def sum(self):
res=self.a+self.b
print(res)
'''def __str__(self):
print("a="+str(self.a)+"b="+str(self.b))'''
def __del__(self):
print("iam destructor")
... |
n=;arm=0;temp=n
while n!=0:
rem=n%10
arm=arm+(rem**3)
n=n//10
print(temp,'is reverse is',arm)
if temp==arm:
print(temp,'is armstong')
else:
print(temp,'is not armstrong')
|
import random
from time import sleep
##o random.randint gera numeros inteiros
pc = random.randint(1,6)
usuario = int(input('Descubra o numero numero escolido pelo computador: '))
print('PROCESSANDO...')
sleep(3)
if pc == usuario:
print('Parabens voce acertou')
else:
print('Infelizmente voce nao acertou, o compu... |
import math
num = int(input('Digite um numero: '))
raiz= math.sqrt(num)
print('Araiz do numero {} é igual a {}'.format(num, raiz))
#random gera numeros aleatoorios
import random
num = random.random()
print(num) |
nome = (input('Digite o seu nome: '))
print('Prazer em te conhecer {:=^20}!'.format(nome))
n1 = int(input('Digite um numero: '))
n2 = int(input('Digite um segundo numeror: '))
print('A soma vale {}'.format(n1+n2))
n3 = int(input('Entre com um valor: '))
n4 = int(input('Entre com um outro valor: '))
s = n3 + n4
m = n3... |
import math
num = float(input('Digite o valor do cateto oposto: '))
num2 = float(input('Digite o valor do cateto adjacente:'))
#hi = (num ** 2 + num2 **2) ** (1/2)
hi= math.hypot(num, num2)
print('A hipotenusa vai medir {:.1f}'.format(hi)) |
'''通过bp算法拟合y = 2x这个函数'''
import numpy as np
x = np.array([1,2,3]).T
y = (2 * x).T
w = 10
for i in range(1000):
p_y = x * w
dy = (p_y - y)/3
dw = x.T.dot(dy)
w += -0.01 * dw
print(w)
|
def FileReader(filename):
try:
with open(filename, "r") as reader:
inputsent = reader.read()
except:
inputsent = filename.lower()
return(inputsent)
def CheckCommComb(inputsent): #The program can take any list it wants to check for the combinations, and thu... |
def FileReader(filename):
try:
with open(filename, "r") as reader:
inputsent = reader.read()
except:
inputsent = filename.lower()
return(inputsent)
def CheckMedklink(filename):
inputsent = FileReader(filename) #Reads all the items from a file or s... |
def LangRecog(input):
def FileReader(filename):
try:
with open(filename, "r") as reader:
inputsent = reader.read()
except:
inputsent = filename.lower()
return(inputsent)
def RatioKlinkCheck(filename):
inputsent = FileReader(filename) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.