text stringlengths 37 1.41M |
|---|
from lib import wallpapers_calc
width_room = float(input("Введите ширину комнаты > "))
lenght_room = float(input("Введите длину комнаты > "))
height_room = float(input("Введите высоту комнаты > "))
width_wallpapers = float(input("Введите ширину рулона обоев > "))
lenght_wallpapers = float(input("Введите длину рулона ... |
import quiz_tests
def csv_to_close(csv_filepath, field_names):
"""Reads in data from a csv file and produces a DataFrame with close data.
Parameters
----------
csv_filepath : str
The name of the csv file to read
field_names : list of str
The field names of the field in the csv... |
height = int(input('введите высоту в символах :'))
width = height * 2
count = 1
for i in range(height):
gap = int((width - count) / 2)
line = (" " * gap) + ("*" * count)
count += 2
print(line)
|
import pandas as pd
from matplotlib import pyplot as plt
data = pd.read_csv('ex.csv')
X= data.iloc[:,1:3].values
print('Graph for whole dataset')
plt.scatter(X[:,0], X[:,1], c='black', s=60)
plt.show()
from sklearn.cluster import KMeans
kmeans = KMeans(2, random_state=0)
kmeans.fit(X)
labels=kmeans.predict(X)
plt.s... |
import numpy as np
#Implementacion
T = np.random.randint(1, 5000) #Se asigna un valor aleatorio entre 1 y 5000 a T
N = []
M = []
Directions = []
#Se agregan T valores aleatorios a N y M
for i in range(T):
N.append(np.random.randint(1,1000000000))
M.append(np.random.randint(1,1000000000))
#La posici... |
def is_leap(year):
leap = False
if (year%4) != 0:
leap = False
elif (year%100 != 0):
leap = True
elif (year%400 != 0):
leap = False
else:
leap = True
return leap
# if (year is not divisible by 4) then (it is a common year)
# else if (year is not divis... |
from simple_spearmint import SimpleSpearmint
import numpy as np
# Define an objective function, must return a scalar value
def squared(x):
return x ** 2
def negative_squared(x):
return -1.0 * (x ** 2)
# test to see if the minimum of f(x) = x^2 is the same point that maximizes f(x) = -x^2
def test_maximize()... |
def is_even(x):
return x % 2 == 0
def is_odd(x):
return not is_even(x)
def only_evens(numbers):
only_evens = []
for number in numbers:
if is_even(number) == True:
only_evens.append(number)
return only_evens
input_list = []
while True:
command = input("Input a number or don... |
string_one = input("Input your first string.")
string_two = input("Input your second string.")
character_list = []
if string_one == string_two:
print("These strings are the same!")
else:
for value in string_two:
if value not in string_one:
character_list.append(value)
print(character_list... |
import sys
def has_alphanumerical(s):
for caractere in s:
if caractere.isalnum():
return True
return False
def has_alphabetical(s):
for caractere in s:
if caractere.isalpha():
return True
return False
def has_digit(s):
for caractere in s:
if caracte... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2021/2/14 11:34
# @Author : john
# @File : homework02.py
"""
自定义一个 python 函数,实现 map() 函数的功能。
"""
def my_map(func, args):
t = []
for i in args:
# print(i)
ret = func(i)
# print(ret)
t.append(ret)
return ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2021/2/18 20:50
# @Author : john
# @File : homework_demo.py
from abc import ABCMeta
class Zoo:
def __init__(self, name) -> None:
self.name = name
self.zoo = set()
def add_animal(self, animal):
if not isinstance(an... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2021/1/24 14:47
# @Author : john
# @File : c01.py
class Human(object):
# 静态字段
live = True
def __init__(self, name):
# 普通字段
self.name = name # self 表示示例化本身, 可以改成任意字符,但建议保持
print("object init", self.name)
man =... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2021/4/10 10:06
# @Author : john
# @File : c06.py
import pandas as pd
df = pd.DataFrame({"A": [5, 5, None, 4],
"B": [None, 2, 4, 3],
"C": [4, 3, 8, 5],
"D": [5, 4, 2, None]
... |
x = {}
x = {'a': 2, 'b': 3}
# print(type(x)) #<class 'dict'>
# 增加 KV
x['c'] = 4
# print(x)
id(x) # 内存地址 ,字典可以原地修改
# 元组构建字典
x = (['a', 1], ['b', 2])
d = dict(x)
# print(d) #{'a': 1, 'b': 2}
#
d = dict(a=2, b=4)
# print(d) #{'b': 4, 'a': 2}
#
d = {}.fromkeys(('a', 'b'), 22)
# print(d) #{'b': 22, 'a': 22}
"""
字典的key... |
#! C:\Users\yeshw\Desktop\Umass\Geology_497\Lab5
"""
This code calculates strike given dip direction
Yesh 3/2/2020
"""
import sys
try:
dipDirection = float(input('give me dip !!'))
except ValueError:
print('Error')
print('DipDirection must be an float between 0 and 360')
sys.exit()
if (dipDirection <... |
class Node:
def __init__(self, value):
self.data = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
#create new node to increment
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_nod... |
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
def asciiToScore(score):
temp = list(score)
return [ord(x) - 33 for x in score]
def writeMedianQualityScores(qaFile, outputFile):
# Writes a list of quality scores to a text file
with open(qaFile, 'r') as f1:
with open(outputFi... |
import urllib.request
from bs4 import BeautifulSoup
import pdfkit
import os
from fileinput import filename
from _codecs import decode
import codecs
import shutil
'''
It recives an url
Reads the source code of the page/s
Parses the pages
Outputs Temporal pages in temporal folder1
Gets all the pages, then fu... |
import random
from environment import Environment
cities = {'Barcelona' : 2011, 'Paris': 1441, 'Honolulu': 11860,
'Ottawa': 6489, 'PyeongChang': 7953, 'Sydney':15716,
'Egypt': 2955, 'Oslo': 1460, 'London': 1508}
random_city = random.choice(list(cities.keys()));
random_distance = cities[random_city]
... |
lista1=['a', 'b', 'c', 'd']
for x in frase:
print(lista1.index(x)+2)
cifra=input('Digite o número de elementos da cifra:')
for x in cifra:
print(lista(x))
alterando
ola joyce tudo bem
comigo esta tudo otimo
como está o clima ai? |
from dictreader import dict_func
baby_dict = dict_func('dictionary_names.csv')
search_string = str(input("Type in a name to search engine: "))
search_string = search_string.upper()
if search_string in baby_dict:
print(baby_dict[search_string])
else:
print( f"{search_string} doesn't exist in this ... |
"""
Here is a Pygame Sprite [1] animation using the approach presented by Joe Wreschnig [2] and Nicolas Crovatti [3].
1. http://www.pygame.org/docs/ref/sprite.html
2. http://www.sacredchao.net/~piman/writing/sprite-tutorial.shtml
3. http://blog.shinylittlething.com/2009/07/21/pygame-and-animated-sprites/
"""
# PEP 8: ... |
filas = int(10)
columnas = int(10)
tablero = []
for i in range(filas):
tablero.append([False]*columnas)
tablero[4][5] = True
tablero[5][5] = True
tablero[6][5] = True
# Representar el tablero
print("Estado inicial")
for y in range(filas):
for x in range(columnas):
if tablero[y][x]:
... |
edad = int(input("Dime tu edad: "))
print("Pues parece que tengas", edad - 2) |
import pygame
#Variables
WIDTH=1200
HEIGHT=600
BORDER=20
VELOCITY=15
FRAMERATE=35
#Define my classes
class Ball:
RADIUS = 15
def __init__(self,x,y,vx,vy):
self.x = x
self.y = y
self.vx = vx
self.vy = vy
def show(self, color):
global screen
... |
def main():
Fahrenheit = eval(input("Temperature in Fahrenheit"))
print ("The temperature is", (Fahrenheit - 32) * 5/9, "degree Celseius.")
main()
|
#!/usr/bin/env python
"""
A simple python script for reverse the bytes of a file.
Author: Lenin Alevski Huerta Arias
Year: 2018
"""
from __future__ import print_function
import os
import sys
import argparse
def main(arguments):
parser = argparse.ArgumentParser(
description=__doc__,
formatter_... |
"""
Predicts NBA scores by matrix factorization.
See readme for details.
"""
import urllib2
import pickle
import subprocess
import pandas as pd
from bs4 import BeautifulSoup
class NBAModel:
"""
NBA model for predicting final scores.
Seperate predictions are made for Offensive Rating and Pace, which
... |
# 1) Complete the function to return the result of the conversion
def convert_distance(miles):
km = miles * 1.6 # approximately 1.6 km in 1 mile
return km
my_trip_miles =convert_distance(55)
my_trip_km = convert_distance(55)
print("The distance in kilometers is " + str(my_trip_miles))
print("The round-trip in ki... |
import time
def square(numbers):
result = []
start_time = time.time()
for num in numbers:
result.append(num ** 2)
end_time = time.time()
print("This func1 takes" + str(end_time - start_time) +" seconds")
return result
def cube(numbers):
... |
def main_func(operation_name):
def addition(*args):
result1 = 0
for i in args:
result1 += i
return result1
def mult(*args):
result2 = 1
for i in args:
result2 *= i
return result2
if operation_name == "addition":
r... |
def _n_chars(x,y):
print(x*y)
x=int(input('enter integer:'))
y=input( 'enter char: ')
_n_chars(x,y);
|
def Char_Freq(string):
# Creating an empty dictionary
freq = {}
for i in string:
if (i in freq):
freq[i] += 1
else:
freq[i] = 1
for key, value in freq.items():
print ("%c : %d"%(key, value),end=' ')
Char_Freq("abbabcbdbabdbdbabab... |
str=input("Enter string:")
print(str.swapcase())
|
import torch
import matplotlib.pyplot as plt
import numpy as np
## generate M data points roughly forming a line (noise added)
M = 100
theta_true = torch.Tensor([[0.5], [2]])
X = 10 * torch.rand(M, 2) - 5
X[:, 1] = 1.0
y = torch.mm(X, theta_true) + 0.3 * torch.randn(M, 1)
# print (y)
# ## visualise the data by plot... |
#!/usr/bin/python
def selection_sort_asc(arr):
for i in range(0, len(arr) - 1):
min = arr[i]
index = i
for j in range(i+1, len(arr)):
if arr[j] < min:
min = arr[j]
index = j
arr[index] = arr[i]
arr[i] = min
return arr
if __nam... |
days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def determine_leap(year):
return (year % 4 == 0) and (year % 100 != 0 or year % 400== 0)
def calculate_days():
current_day = 1
sundays = 0
for i in range(2000-1900):
for day in days_in_month:
current_day += day
... |
import math
def solve():
return sum([i for i in range(3, 40586) if i == fac(i)])
def fac(x):
return sum([math.factorial(int(x)) for x in str(x)])
print(solve())
|
# Step 1 - Import required libraries
from __future__ import division # for python 2 only
import pandas as pd
import numpy as np
from sklearn import tree
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from itertools import product
from datetime import datetime
# Step 2 ... |
from func import *
cash = 15000
equity = 90000
bonds = 10000
RE = 0
otherA = 10000
stu_loans = 30000
mort = 0
credit = 2000
per_loans = 0
otherL = 0
salary = 100000
eq_returns = (equity * 0.07)/12
cash_int = (cash * 0.02)/12
otherI = 200
rent = 700
food = 200
utilities = 100
car = 300
otherE = 150
desired_retire... |
import tkinter as tk
win = tk.Tk()
win.title('layout')
win.geometry('480x320')
# ! 绝对布局
label1 = tk.Label(win, text='C', bg='red')
label2 = tk.Label(win, text='Java', bg='green')
label3 = tk.Label(win, text='Python', bg='blue')
label1.place(x=10, y=10)
label2.place(x=50, y=50)
label3.place(x=100, y=100)
win.mainloo... |
# 1.导入tkinter库
import tkinter as tk
import tkinter.messagebox
# 2.创建窗口window
window = tk.Tk()
window.title('Hello')
window.geometry('480x320')
var1 = tk.StringVar()
var2 = tk.StringVar()
var3 = tk.StringVar()
var4 = tk.StringVar()
def print_selection():
print(f"your selectin is A({var1.get()}) B({var2.get()}) C(... |
import math
def get_input() -> list:
with open(r'AOC2020/day03input.txt', 'r') as file:
file_list = file.read().splitlines()
return [[char for char in line] for line in file_list]
def tree_count(forest:list, x_traj:int, y_traj:int):
tree_count = 0
x_len = len(forest[0])
y_len = len(fore... |
# Creating variable
my_string = "This is string stored in the my_string variables"
my_num = 5 # an integer stored in a variable
my_tuple = (1, 2, 3, 4, 5) # a tuple store in a variable
my_dictionary = {'name': 'Michael Choi', 'fave_lang': 'Python', 'level': 'Sensei'} # a dictionary stored in a variable
#Data Types
# B... |
# Uma fruteira está vendendo frutas com a seguinte tabela de preços:
# Até 5 Kg Acima de 5 Kg
# Morango R$ 2,50 por Kg R$ 2,20 por Kg
# Maçã R$ 1,80 por Kg R$ 1,50 por Kg
# Se o cliente comprar mais de 8 Kg em frutas ou o valor total da compra ultrapa... |
# Faça um Programa que leia 2 números e em seguida pergunte ao usuário qual operação ele deseja
# realizar. O resultado da operação deve ser acompanhado de uma frase que diga se o número é:
# par ou ímpar;
# positivo ou negativo;
# inteiro ou decimal.
num1 = int(input('Informe um número: '))
num2 = float(input('Inform... |
# O Hipermercado Tabajara está com uma promoção de carnes que é imperdível. Confira:
# Até 5 Kg Acima de 5 Kg
# File Duplo R$ 4,90 por Kg R$ 5,80 por Kg
# Alcatra R$ 5,90 por Kg R$ 6,80 por Kg
# Picanha R$ 6,90 por Kg R$ 7,80 por Kg
# Para ... |
# Faça um Programa que leia um vetor de 10 caracteres, e diga quantas consoantes foram lidas.
# Imprima as consoantes.
caracteres = []
num_consoantes = 0
consoantes = []
for i in range(10):
caracteres.append(str(input('Informe o ' + str(i + 1) + 'º caractere: ')))
if caracteres[i] not in ('a', 'e', 'i', 'o', ... |
# Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro desta área para o usuário.
l = float(input('Informe o valor_latas do lado do quadrado: '))
a = l ** 2
a2 = a * 2
print('A área do quadrado é: ', a, ' e o dobro desta área é: ', a2)
|
# Faça um programa que calcule as raízes de uma equação do segundo grau, na forma ax2 + bx + c.
# O programa deverá pedir os valores de a, b e c e fazer as consistências, informando ao usuário nas
# seguintes situações:
# Se o usuário informar o valor de A igual a zero, a equação não é do segundo grau e o programa não ... |
# Faça um programa que receba dois números inteiros e gere os números inteiros que estão no
# intervalo compreendido por eles.
num1 = int(input('Informe o 1º número inteiro: '))
num2 = int(input('Informe o 2º número inteiro: '))
for i in range(num1 + 1, num2):
print(i)
for i in range(num2 + 1, num1):
print(i... |
#Tutorial on:- https://www.geeksforgeeks.org/given-an-array-a-and-a-number-x-check-for-pair-in-a-with-sum-as-x/
# Inputting a list of numbers
lst=[int(i) for i in input().split(" ")]
# Inputting the required number k
k=int(input())
#creating an empty hash set
s=set()
found=False
for i in range(len(lst)):
temp=... |
import random
score = 0
print("this is a mcq test; pick one answer")
answer = ''
question_ar = [["How to do while in pseudocode? ","a - WHILE ","b - while()","c - for i","d - WHILE()",'a'],['What data type is ("boofoo")?','a - Boolean', 'b - Date','c - String','d - Char','c'],["What sign(s) is used to indicate 'Not equ... |
#! /usr/bin/python3
# ./swap_content.py <encoded_file>
#
# Reads input from stdin and replaces the content (but not the hashes!) of the
# encoded file with the stdin bytes. If stdin is shorter than the content, the
# remaining content bytes are unmodified. If stdin is longer, only the input up
# to the length of the e... |
import sys
import csv
import numpy as np
from fractions import Fraction
def SpamCheck(emailInput,dataset):
Number_of_spam_emails=1500
Number_of_real_emails=3672
fraction_of_spam_emails=1500/5712
fraction_of_real_emails=3672/5712
spamProbabilities=[]
hamProbabilities=[]
my_file = open(emailIn... |
def pythag(a,b,c):
if(not (a<b and b<c)):
return False
else:
if((a**2 + b**2) == c**2):
return True
return False
def add(a,b,c):
return (a+b+c)==1000
def find():
for a in xrange(1,998):
for b in xrange(a,999):
for c in xrange(b,1000):
... |
import math
def isPrime(n):
for i in xrange(2,int(math.sqrt(n))+1):
if(n%i==0):
return False
return True
def find():
f = open("primes.txt","r+a+")
primes = f.read()
primes = primes.splitlines()
while(len(primes)<1000000):
p = len(primes)
i = int(primes[p-1])... |
"""
Practice using the Python interpreter as a calculator:
1. The volume of a sphere with radius r is 4/3 * π(r^3) . What is the volume of a sphere with radius 5?
"""
# Write your program below
radius=5
PI = 3.14
volume=4/3 * PI*(radius**3)
print("output",volume)
|
import random as r
import seaborn as sns
import pandas as pd
class Set():
math = {"Questions":[], "Answer": [], "Distance":[]}
def generate(self,runtime):
#Initailze local varibles
clock = r.randint(0,1)
que = 0
#Create questions
for i in range(1, runtime):
#p... |
n = int(input())
sum = 0
while n:
d=n%10
n//=10
sum+=d*d
print(sum,end='')
|
base=float(input())
height=float(input())
area=int(base*height/2)
print(area)
|
string="prithika"
string2=" "
for i in string:
string2=i+string2
print(string)
print(string2)
if(string==string2):
print("palindrome")
else:
print("not palindrome")
|
class mark:
def __init__(self,m1,m2,m3,m4,m5):
self.m1=m1
self.m2=m2
self.m3=m3
self.m4=m4
self.m5=m5
def display(self):
print(self.m1)
print(self.m2)
print(self.m3)
print(self.m4)
print(self.m5)
avg=(self.m1+self.m2+self.m3+self.m4+self.m5)/5... |
F=float(input('F='))
C=(F-32)/1.8
print('C=%.1f'%C)
print(f"C={C:.1f}") |
str1 = 'hello,world! '
print(len(str1)) # 计算长度
print(str1.capitalize()) # 首字母大写
print(str1.title()) # 每个单词首字母均大写
print(str1.upper()) # 所有字母均大写
print(str1.find('or')) # 从字符串中查找子串所在位置
print(str1.find('shit')) # 找不到返回-1
print(str1.index('or')) # 从字符串中查找子串所在位置
# print(str1.index('shit'))#找不到发生异常
print(str1.startswit... |
a=int(input("enter number"))
n=a
sum=0
while(n>0):
c=n%10
sum=sum*10+c
n//=10
if(sum==a):
print("palindrome")
else:
print("not palindrome")
|
num=int(input("enter the no. of rows :"))
A=[[0 for x in range(num)]for y in range (num)]
n=1
low=0
high=num-1
count=int((num+1)/2)
for i in range(count):
for j in range(low,high+1):
A[i][j]=n
n+=1
for j in range(low+1,high+1):
A[j][high]=n
n+=1
for j in range(high-1,low-1,-1... |
for i in range(3):
print("*",end="")
print(" "*7,end="")
print("*")
print("* "*5)
for i in range(3):
print("*",end="")
print(" "*7,end="")
print("*")
""""
* *
* *
* *
* * * * *
* *
* *
* *
"""
|
# binary search
n,A=int(input("enter total no. of elements in array")),[]
for j in range(n):
A+=[int(input())]
A=sorted(A) #for binary search list should be in sorted order
f=int(input("enter no. you want to search"))
beg=0
end=len(A)-1
k=0
while(beg<=end):
mid=(beg+end)/2
mid=int(mid)
if(A[(mid)]==f... |
for row in range(7):
for col in range(7):
if((row==0 and col not in [0,3,6])or(row in[1,2,3])or((row==4 and col not in[0,6])or(row==5 and col not in(0,1,5,6)or(row==6 and col not in[0,2,1,4,6,5])))):
print("*",end=" ")
else:
print(end=" ")
print()
"""
* *... |
#PLOTDATA Plots the data points X and y into a new figure
# PLOTDATA(x,y) plots the data points with + for the positive examples
# and o for the negative examples. X is assumed to be a Mx2 matrix.
import matplotlib.pyplot as plt
# Create New Figure
import numpy as np
# %%
def plotData(X,y):
# plt.plot(... |
# -*- coding: utf-8 -*-
"""
============================
Plotting simple sin function
============================
A simple example of the plot of a sin function
in order to test the autonomy of the gallery.
To illustrate how to insert maths in example descriptions,
it corresponds mathematically to the function:
.. ... |
import threading
import time
def square(num):
print("Inside square function")
time.sleep(5)
print(num * num)
def multiply(num1,num2):
print("Inside multiply function")
print(num1 * num2)
# square(10)
# multiply(10,20)
t1 = threading.Thread(target= square,args=(10,))
t2 = thr... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 27 23:22:40 2018
@author: yiqian
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def averageO... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 25 17:11:35 2018
@author: yiqian
"""
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or head.next == None:
return True
count... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 12 12:13:45 2018
@author: yiqian
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def inorderS... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon May 28 10:05:32 2018
@author: yiqian
"""
class Solution(object):
def minSteps(self, n):
"""
:type n: int
:rtype: int
"""
if n==1:
return 0
if n==2:
return n
if... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 12 17:24:39 2018
@author: yiqian
"""
class Solution(object):
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
s = [i*i for i in range(1,int(math.sqrt(n))+1)] # Square numbers <= n
l = 0 ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 15 14:29:28 2018
@author: yiqian
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 19 16:12:10 2018
@author: yiqian
"""
class Solution(object):
def poorPigs(self, buckets, minutesToDie, minutesToTest):
"""
:type buckets: int
:type minutesToDie: int
:type minutesToTest: int
:rtype: int
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 19 10:51:42 2018
@author: yiqian
"""
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
return str(x)==str(x)[::-1] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 27 09:41:59 2018
@author: yiqian
"""
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
return n>0 and 1162261467%n==0
"""
1162261467 is 3^19 and 3^20 is ... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat May 26 19:59:03 2018
@author: yiqian
"""
class Solution(object):
def find132pattern(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums) < 3:
return False
min_nums = [nums[... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 22 16:00:04 2018
@author: yiqian
"""
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n==1: return 1
if n==2: return 2
res = [1,2]
for i in xra... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 22 15:53:10 2018
@author: yiqian
"""
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
zero = 0 # record... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 26 15:34:49 2018
@author: yiqian
"""
import operator
class Solution:
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = list()
ops = { "+": operator.add, "-": operator... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 27 09:46:51 2018
@author: yiqian
"""
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
return matrix and list(matrix.pop(0)) + self.sp... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri May 25 10:55:34 2018
@author: yiqian
"""
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
resul... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 10 10:40:12 2018
@author: yiqian
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 10 22:17:50 2018
@author: yiqian
"""
class Solution(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
dic = {}
for ele in secret:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 25 10:16:06 2018
@author: yiqian
"""
class Solution:
# @param {integer[]} nums
# @return {integer[]}
def productExceptSelf(self, nums):
p = 1
n = len(nums)
output = []
for i in range(0,n):
out... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 19 16:30:54 2018
@author: yiqian
"""
class Solution(object):
def subreverse(self, x):
res = 0
if x==0:
return res
while (x!=0):
res = res*10 + (x%10)*10
x = x/10
return re... |
def traversal():
l = [(x, x**2) for x in range(5)]
d = dict(l)
for i in d:
print(i, d[i])
for k, v in d.items():
print("%d : %d" % (k, v))
for k, v in zip(d.iterkeys(), d.itervalues()):
print(k, v)
def set_value():
d1 = {}
d1['a'] = 1
d2={'bb':1, 'cc':2}
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 28 01:18:57 2017
@author: julie
"""
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 27 12:56:00 2017
@author: julie
"""
import matplotlib.pyplot as plt
def graph2():
#sliceSs are going to be the 9 industries
#percentages will either be the total wages or e... |
""" Here is the list data types in python and examples how to work with it"""
''' Lists
1. creating list
2. append()
3. concatenation of lists
4. len()
5. list indexing and slicing
6. change element at a position
7. clearing list by slicing
8. nested listed
'''
# 1.creating list
... |
#medianas = [19,16,16,15,17,14,13,14,11,13,15,14,12,12,1];
#medianas = [16,12,12,10,15,10,10,12,7,11,12,11,10,10,1];
medianas = [17,15,15,11,16,11,12,13,8,11,12,11,11,11,1];
locais = ['Casa Sherlock','Museu','Bar','Farmacia','Scotland Yard','Banco','Teatro','Penhores','Parque','Docas','Livraria','Chaveiro','Charutari... |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def found(lis):
x=ListNode(0)
h=x
for i in lis:
x.next=ListNode(i)
x=x.next
return h.next
def foundlis(lis):
res=[]
for i in lis:
res.append(found(i))
return res
def printlis(lis):
while lis!=None:
print lis... |
import listnode
class Solution(object):
def swapPairs(self, head):
list0=listnode.ListNode(0)
list0.next=head
lis0=list0
while list0.next!=None and list0.next.next!=None:
swap(list0)
list0=list0.next.next
return lis0.next
def swap(node):
a=node.next
b=node.next.next
node.next=b
a.next=b.next
b... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
p=head
q=head
if head== None:
return None
if n<1:
return None
p=head
for i in range(n):
if p.next!=Non... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.