text stringlengths 37 1.41M |
|---|
from collections import deque
N = int(input())
nums = deque([i + 1 for i in range(N)])
while len(nums) != 1:
nums.popleft()
nums.append(nums.popleft())
print(nums[0])
|
#Adding and Sorting in revered order to avoid insertion and moving 20ms
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/1/10 下午4:36
# Time Limit Exceeded
class Solution(object):
def first_uniq_char(self, s):
for i in range(len(s)):
for j in range(0, len(s)):
if i == j:
continue
data = ord(s[i]) ^ o... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/1/17 下午8:17
class ListNode(object):
def __init__(self, x):
self.val = x
self.next_ = None
class Solution(object):
def removeNthFromEnd(self, head, n):
list_node = ListNode(0)
list_node.next_ = head
before_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/5/3 下午5:30
"""
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
"""
class Solution(object):
def __init__(self):
self.stack = list()
self.result = list()
def postord... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/2/2 上午11:20
class Solution(object):
def count_primes(self, n):
if n < 3:
return 0
digits = [1] * n
digits[0] = digits[1] = 0
for i in range(2, int(n ** 0.5) + 1):
if digits[i] == 1:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
多继承方法调用解决方案1, without super
这里D继承了方法m的两个冲突定义, 并且发出错误信息。然后D可以通过覆盖m来解决冲突,但是D的定义是什么?, 它可以
调用B的m, 然后调用C的m, 但是由于两个定义都调用了从A继承的m的定义, 因此A的m最终被调用两次,老python简单的
通过只取第一个来解决。
这种困境的传统结局方案如下, 将m的每个派生定义分为两部分, 部分实现_m, 它只保存一个类唯一的数据。以及一个完整的实现m
"""
class A(object):
def m(self):
... |
"""
class TreeNode(object):
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution(object):
"""
@param root: the root of binary tree
@return an integer
"""
def maxsum(self, root):
if root == None: return 0
sum = root.val
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/25 下午9:33
class Solution(object):
def __init__(self):
self.digits_map = {'2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'],
... |
import curses
from random import randint
WINDOW_WIDTH = 60 # number of columns of window box
WINDOW_HEIGHT = 20 # number of rows of window box
#setupwindow
curses.initscr()
win=curses.newwin(WINDOW_HEIGHT,WINDOW_WIDTH,0,0)
win.keypad(1)
curses.noecho()
curses.curs_set(0)
win.border(0)
win.nodelay(1)
#snake and food... |
from abc import ABCMeta, abstractmethod
class Node:
def __init__(self,before,after,data):
self.before = before
self.after = after
self.data = data
def getAfter(self):
return self.after
def setAfter(self,after):
self.after = after
def setBefore(self,before):
self.before = before
def getData(self)... |
# 不适用type(元类)动态创建类对象
def chooseClass(class_name):
if class_name == 'Demo1':
class Demo1(object):
pass
return Demo1
else:
class Demo2(object):
pass
return Demo2
demo = chooseClass('Demo2')
print(demo)
# 使用type(元类)动态创建类对象
class MyClass(object):
class_... |
# coding=utf-8
# python一切皆对象,数字、字符串、列表、字典、元组等
# 任何对象都有三个关键属性:标识,值,类型
i = 10
i2 = '10'
print(i)
print(i2)
nums = []
for num in range(100):
nums.append(num)
print(nums)
dicts = {'name':'zhang','age':23,}
print(dicts)
# 等号右边是对象,左边是给对象取的名字。
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 小明的成绩从去年的72分提升到了今年的85分,请计算小明成绩提升的百分点,并用字符串格式化显示出'xx.x%',只保留小数点后1位:
def practice0():
s1 = 72
s2 = 85
r = (s2 - s1) / s1
print("小明成绩提升百分点r = %.2f" % r)
pass
def encode_use():
print("ord('A')获取字符串整数表示 = ",ord('A'))
print("chr(66)获取编码对应字符 = ",ch... |
"""
Provides Linked List implementation for clients
"""
class Node(object):
"""
Holder for linked list data and next pointer
"""
def __init__(self, d):
self.next = None
self.data = d
def __repr__(self):
return "Node({0.data!r})".format(self)
def __str__(self):
... |
#! /usr/bin/env python
def merge_array(arr, tarr, ls, le, rs, re):
"""
arr: Original array to be modified
tarr: temporary array to store result of merge
ls: left start index
le: left end index
rs: right start index
re: right end index
"""
if ls > le: return
... |
# Breaking a big task into multiple tasks (simliar to multitasking )
from time import sleep # to get sleep timer
from threading import * # importing threading function
class Hello(Thread): # passing thread as sub class to the main class Hello - splits into multiple threads
def run(self):
for i i... |
def macthingWords (sentence1,sentence2):
score = 0
word1 = sentence1.strip().split(" ")
word2 = sentence2.strip().split(" ")
for words1 in word1:
for words2 in word2:
if words1.lower() == words2.lower():
score+=1
return score
if __name__ == '__main__':
... |
import math
# 시작하기
str = "Hello World"
print(str)
# 간단한 프로그램 작성
a = 1
b = 2
c = a+b
print(c)
# 코딩의 기초
n = math.sqrt(9.0)
print(n)
# 기본 데이타 타입
i = int(3.5)
exp = 2e3
f1 = float("1.6")
f2 = float("inf")
f3 = float("-inf")
b1 = bool(0)
b2 = bool(-1)
b3 = bool("False")
n1 = None
n2 = n1 is None
print(i, exp, f1, f2,... |
import tweepy
import time
def get_api(cfg):
auth = tweepy.OAuthHandler(cfg['consumer_key'], cfg['consumer_secret'])
auth.set_access_token(cfg['access_token'], cfg['access_token_secret'])
return tweepy.API(auth)
def tweetIt(_text):
# Fill in the values noted in previous step here
cfg = {
"consumer_key" ... |
try:
a=int(input("Enter decimal value : "))
print("The respective octal value is : ",oct(a))
print("The respective binary value is : ",bin(a))
print("The respective hexadecimal value is : ",hex(a))
except:
print("Exception occurs")
|
'''A python program that prompts the user for a file name containing directions for a turtle,
and then uses turtle graphics to execute the directions.
Created Spring 2018
homework09
@author: Nana Osei Asiedu Yirenkyi (na29) '''
import turtle #gains access to the turtle code
bob = turtle.Turtle() #names the turtle ... |
'''
Unit test the temperature class
Spring 2018
@author: Nana Osei Asiedu Yirenkyi (na29)
'''
import unittest
from temperature import Temperature
class Test(unittest.TestCase):
def setUp(self):
'''
Set up the temperature converter for each of the unit tests
This function is run onc... |
first_name =input("What is your first name ")
last_name=input("what is your last name?")
print("Your full name is " , first_name + last_name)
x=137
a= 0 or x
print( a and x==a)
print("Choose any 3 numbers")
first_number = input("First number ")
second_number = input("Second number")
third_number = input("Third numb... |
import pandas as pd
import numpy as np
t1 = pd.DataFrame(np.arange(12).reshape((3,4)))
print(t1)
"""
0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
0 1 2 3代表列索引,0 1 2代表行索引
行索引,表明不同行,横向索引,叫index,0轴,axis=0
列索引,表名不同列,纵向索引,叫columns,1轴,axis=1
"""
t2 = pd.DataFrame(np.arange(12).reshape(3,4),index=list(... |
class Person:
# scope = ["people", "something"]
def __init__(self, name="", surname="", age=None, position=None):
self.name = name
self.surname = surname
self.age = age
self.position = position
def __str__(self):
return f"<Person with name {self.name}>"
def full... |
class student:
def __init__(self,a,b,c,d,e):
self.name=str(a)
self.age=int(b)
self.num_ch=int(b)
self.num_math=int(c)
self.num_en=int(e)
def getname(self):
return self.name
def getmaxscore(self):
ma1=max(self.num_ch,self.num_en,self.num_math)
r... |
def prime(innum):
for i in range(2,innum):
i+=1
if innum % i == 0:
return False
if i == innum-1:
return True
num=0
print(prime(5))
for j in range(20,71):
if prime(j):num+=1;print(j,end=' ')
print(' ')
print(num) |
def f():pass
print(type(f))
pass
print(4.5/2)
print(4.5//2)
print(4.5%2)
a=10
a %=a-a%4
print(a)
print(12/4-2+5*8/4%5/2)
x=y=z=10
print(x)
print(y)
print(z)
massege='hello'
print(massege)
massege+='world'
massege_two='fuck'
massege_three=massege+massege_two+' '
print(massege_three)
print(massege_two)
massege_three=... |
class Atest:
def __init__(self,a,b,*c):
self.__num1=float(a)
self.__num2=float(b)
self.__list_1=list(c)
def sum(self):
sum=0
for num_to_sum in self.__list_1:
sum+=num_to_sum
sum+=self.__num1+self.__num2
return sum
def gai(self,v1,v2):
... |
nove = ''
idve = 0
contm = 0
somaidade = 0
for cont in range(1, 6):
print('------------ {}° Pessoa ------------'.format(cont))
nome = str(input('Qual é seu nome: ')).upper().strip()
idade = int(input('Qual a sua idade: '))
sexo = str(input('Masculino [M] Feminino [F]: ')).strip().upper()
somaidade +... |
print('=-='*20)
casa = float(input('Qual valor da casa? R$:'))
sala = float(input('Qual valor do seu salario? R$:'))
time = int(input('Quantos anos deseja pagar? '))
prest = casa / (time * 12)
porc = 30 * sala / 100
if porc >= prest:
print('Emprestimo aprovado!')
print('Seu valor disponível para uso é de {}'... |
from random import randint
from time import sleep
itens = ('Pedra', 'Papel', 'Tesoura')
computador = randint(0, 2)
print('''ESCOLHA UM NUMERO:
[ 0 ] Pedra
[ 1 ] Papel
[ 2 ] Tesoura''')
jogador = int(input('Qual sua jogada? '))
while jogador < 0 or jogador > 2:
jogador = int(input("Digite novamente: "))
print('... |
print('='*30)
from datetime import date
atual = date.today().year
maior = 0
menor = 0
for idade in range(1, 8):
num = int(input('Em que ano a {}°pessoa nasceu? '.format(idade)))
idade = atual - num
if idade > 21:
maior += 1
else:
menor += 1
print('O total de maiores de idade são {}'.form... |
print ('Qual São Os Valores?')
v1 = int(input ('Valor 1: '))
v2 = int(input ('Valor 2: '))
s = v1 + v2
print('A soma de {} mais {} gera {}'.format(v1, v2, s))
|
n1 = float(input('Quanto foi a Quilometragem rodada?: '))
n2 = int(input('Quantos dias o carro foi utilizado?: '))
print('O total pagar é: R${:.2f}'.format(n1*0.15+n2*60))
|
#Extracting Data from XML
import urllib.request, urllib.parse, urllib.error
import xml.etree.ElementTree as ET
# sample input url:
# http://py4e-data.dr-chuck.net/comments_42.xml
# http://py4e-data.dr-chuck.net/comments_117409.xml
url = input('Enter location: ')
print('Retrieving ', url)
uh = urllib.request.urlopen... |
s = input()
uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
lowercase = 'abcdefghijklmnopqrstuvwxyz'
upper_count = 0
lower_count = 0
for i in s:
if i in uppercase:
upper_count += 1
else:
lower_count += 1
if upper_count > lower_count:
print(s.upper())
else:
print(s.lower()) |
import time
while True:
start_time = time.time()
n = print("Введите число n ")
if (n == "exit"):
break
else :
n = int(input())
factorial = 1
for i in range(2, n+1):
factorial *= i
print("Факториал = ", factorial)
print("--- %s seconds ---" % (time.tim... |
a = input ("input a: ")
f = 0.0
a= float(a)
if(a<0):
f = a * (-1)
elif(a<1):
f = a
elif(a<2):
f = 1.0
else:
f = (5-(2*a))
print ("f = %.2f" % f)
|
a = input ("input a: ")
f = 0.0
a = float(a)
if (a <= 0):
f = abs(a+1)
else:
f = abs(a-1)
print ("f = %.2f" % f)
|
import math
print("Задание 88(b) ")
n = input("Введите число n ")
n = int(n)
print("n = ", n)
x=1
y=1
i = 2
s = x /(1+(abs(y)))
for i in range(n):
y = x+y
x = 0.3*x
s=(s+(x*(1+(abs(y)))))
print("Sum = ",s)
|
def task(n,m):
for i in range(n):
s=0
j=i
while(j>0):
s+=(j%10)**2
j=j//10
if s==m:
print(i)
task(1000,10)
|
print("Задание 144")
n = int(input("n = : "))
print("n = ",n)
print("Последовательность un: ")
u0 = 0
u1=1
print("u0 = ",u0,"u1 = ",u1)
i = 1
for i in range(n-1):
buf = u1
u1 = u0+u1
u0 = buf
print("u1 = ",u1)
print("Последовательность fn: ")
f0 = 0
f1 = 1
u0 = 0
u1 = 1
print("f0 = ",f0,"f1 = ",f1)
for ... |
class Human:
name = 'a'
surname = 'b'
patronimic = 's'
age = 0
gender = 'm'
counter = 0
def setName(self, n):
self.name = n
def setSurname(self, s):
self.surname = s
def setPatron(self, p):
self.patronimic = p
def setAge(self, a):
self.age = a
... |
import math
x = input ("Введіть x: ")
x = int(x)
y = input ("Введіть y: ")
y = int(y)
z = input ("Введіть z: ")
z = int(z)
if (x>y) and (x>z):
print("Макимальное число = ", x)
elif (y>x) and (y>z):
print("Макимальное число = ", y)
elif (z>y) and (z>x):
print("Макимальное число = ", z)
x = input ("Введіть x:... |
import math
a = float(input('A = '))
b = float(input('B = '))
c = math.sqrt(b * b - a * a);
r = (a + c - b) / 2;
print(c)
print(r)
|
print ("Задание 17: Найти площадь кольца, внутренний радиус которого равен 20, а внешний - заданому числу r (r > 20)")
import math
R2 = 20
pi = 3.14
R1 = input ("Введите внешний радиус кольца (>20)")
R1 = int(R1)
S = (pi*abs(R1*R1+R2*R2))
print ("Площадь кольца: %.2f" % S)
input ("Нажмите ENTER для выхода")
|
import math
print ("Задание 23")
a = input("Введите число а ")
a = float(a)
b = input ("Введите число b ")
b = float (b)
c = input ("Введите число c ")
c = float (c)
p = (a+b+c)/2
print ("Полупериметр = ", p)
H = (2*a)* math.sqrt(p*(p-a)*(p-b)*(p-c))
print ("Висота = ", H)
M = (1/2)* math.sqrt(2*a*a+2*b*b-c*c)
print (... |
import math
print("Задание 84 a")
n = input("Введите число n ")
n = int(n)
x = input("Введите число x ")
x = int(x)
print("n=",n)
print("x=",x)
s = 0
i = 1
for i in range(n):
s = s + (math.exp(i*(math.log(math.sin(x)))))
print("Suma = ",s )
print("Задание 84 б")
n = input("Введите число n ")
n = int(n)
x = input("... |
print("Задание 151")
a = [i for i in range(1,101)]
n = (int(input("Введите количество конденсаторов = ")))
print("Количество конденаторов = ",n)
i = 1
for i in range(n):
if i == 3:print('Введите емкость',i,'его конденсатора')
else:print('Введите емкость',i,'его конденсатора')
print(a[i])
cpar = 0
for i in r... |
import random
Numbers = ["0","1","2","3","4","5","6","7","8","9",]
Big_Letters = ["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"]
Small_Letters = ["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"]
print("Ск... |
n = input('N: ')
print(f'В числе {len(n)} цифр')
print(f'Сумма цифр: {sum(map(int, [_ for _ in n]))}')
print(f'Последняя цифра: {n[-1:]}')
print(f'Первая цифра: {n[:1]}')
if len(n) >= 2:
print(f'Предпоследняя цифра: {n[-2:-1]}')
|
import math
x = input("Введите x: ")
y = input("Введите y: ")
x = float(x)
y = float(y)
if (x >= y): z = x-y
else:
z = y - (x+1)
print ("Z = ", z)
|
print("Задание")
n = (int(input("Введите n ")))
i = 1
for i in range(1,n):
if n%i ==0 :
print("Результат",i,)
|
print ("Задание 4 Даны два действительных положительных числа.Найти среднее арифметическое и среднее геометрическое этих чисел.")
a = input("Введите число а ")
a = float(a)
b = input ("Введите число b ")
b = float (b)
c = (a + b) / 2
d = (a * b) / 2
print ("Среднее арифметическое = %.2f" %c)
print ("Среднее геометрич... |
import math
print ("Задание 80")
x = input("Введите число ")
x = int(x)
print("x=",x)
summa= 0
kvadrat = 1
fact = 1
i =1
for i in range (1, 13):
kvadrat = kvadrat*x
fact = fact*i
if i%2 == 1:
if i%4 == 3:
summa = summa-kvadrat/fact
print("Ответ = ", summa)
|
import math
s = input("Enter s: ")
t = input("Enter t: ")
s = float(s)
t = float(t)
r = 0.0
def F(a, b, c):
return (2 * a - b - math.sin(c)) / (5 + abs(c))
r = F(t, -2*s, 1.17)+F(2.2, t, s-t)
print("Result: %.2f" % r)
|
import math
print ("Задание 11")
x = input("Введите число x ")
x = float(x)
y = input ("Введите число y ")
y = float (y)
z = input("Введите число z ")
z = float (z)
abs(x)
abs(y)
abs(z)
a = (math.sqrt(abs(x-1))-(pow(abs(y),1/3)) / (1+(pow(x,2)/2)+(pow(y,2)/4) ))
b = x*(math.atan(z)) + (math.exp(-(x+3)))
c = 3+(math.ex... |
def getCipher(s,k):
'''
K can be any large number but whatever may be its value it keeps cycling
as we are dealing with only the lowercase alphabets ( 26 )
SO we can modify K to be K%26 ( if k > 26 then the remainder ensures the result is between 1 and 25)
in Python ord() function ... |
def interleavingStrings(one,two,three):
# length of the third string must be the sum of the first and second strings.
# if not the interleaving is not possible
if len(three)!=len(two)+len(one):
print("Yes")
return False
# 0,0 indicate the current positions of the pointer in the firs... |
def display(board):
print()
print("Solved:")
for i in range(9):
for j in range(9):
print(board[i][j],end=" ")
print()
def solveSudoku(board,i,j):
if i==len(board):
display(board)
return
next_i = 0
next_j = 0
if j==(len(board[0])-1):... |
import matplotlib.pyplot as plt
import math
import random
import time
import numpy as np
###PLOTTING###
def plot(position,order,pop):
plt.figure(figsize=(5,5))
x,y=[],[]
for i in range(0,len(position)):
x.append(position[order[i]][0])
y.append(position[... |
"""Smallest multiple
2520 is the smallest number that can be divided by each of the numbers from
1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible (divisible with no
remainder) by all of the numbers from 1 to 20?
"""
def smallest_multiple(limit):
"""Find the smallest po... |
"""Counting Sundays
You are given the following information, but you may prefer to do some research for yourself.
- 1 Jan 1900 was a Monday.
- Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, t... |
import sys
sys.setrecursionlimit(10**6)
dic = {}
def fibo(num):
global dic
if num == 0:
dic[num] = 0
elif num == 1:
dic[num] = 1
else:
if num not in dic: #verifico se o calculo da fibo ja foi feito
dic[num] = fibo(num-1) + fibo(num-2)
return dic[num]
def mai... |
rows = eval(input('Enter number of rows : '))
columns = eval(input('Enter number of columns : '))
print('*'*columns)
for i in range(rows-2):
print('*',' '*(columns-2),'*',sep='')
print('*'*columns)
|
temperature = eval(input('Enter A Temperature : '))
if temperature < -273.15:
print('Temperature is invalid.')
elif temperature==-273.15:
print('Temperature is absolute zero.')
elif temperature <0:
print('Temperature is below freezing point.')
elif temperature ==0:
print('Temperature is at freezing poi... |
fromTemperature = eval(input('Enter temperature : '))
usedUnits = input('Enter \'F\' For Fahrenheit and \'C\' Celsius : ')
toTemperature = fromTemperature
if usedUnits=='F' or usedUnits=='f':
toTemperature = (9/5)*(fromTemperature-32)
print(fromTemperature,'Fahrenheit is',toTemperature,'Degrees Celsius.')
elif... |
value1 = eval(input('Enter Value1 : '))
value2 = eval(input('Enter Value2 : '))
value3 = eval(input('Enter Value3 : '))
total = value1
total = total + value2
total = total + value3
average = total
average = average/3
print('Total =',total)
print('Average =', average)
|
angle = eval(input('Enter an angle : '))
convertedAngle = (360+angle)%360
print('User Angle = ',angle,'\tConverted Angle = ',convertedAngle,sep='')
|
from math import sin, radians
print(sin(radians(eval(input('Enter an angle : ')))))
|
numOfItems = eval(input('Enter number of items : '))
if numOfItems <=0:
print('Invalid Input')
elif numOfItems <10:
print('Total Cost =',numOfItems*12)
elif numOfItems <100:
print('Total Cost =',numOfItems*10)
else:
print('Total Cost =',numOfItems*7)
|
from itertools import chain, combinations
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
def get_ranking(d):
# https://stackoverflow.com/questions/2299696/positional-... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from random import randint
print("This is an interactive guessing game!")
print("You have to enter a number between 1 and 99 to find out the secret number.")
print("Type 'exit' to end the game.")
print("Good luck!\n")
myst = randint(1, 99)
atp = 1
while True:
print("Wh... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
i = 2
str = sys.argv[1]
while i < len(sys.argv):
str = ''.join([str, ' '])
str = ''.join([str, sys.argv[i]])
i += 1
newstr = ''
for a in str:
if (a.isupper()) == True:
newstr += a.lower()
elif (a.islower()) == True:
newstr += a.upper()
else:
newstr ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from math import sqrt
class TinyStatistician():
def mean(self, x):
if x == []:
return None
i = 0
res = 0
for a in x:
res += a
i += 1
res = res / i
return (float(res))
def median(self, x):
if x == []:
return None
x.sort()
i = 0
for a in x... |
import Russell_2000_CSV as R2
import csv
#To read in data
def reader(address, x):
with open(address,"r") as data:
read_in = csv.reader(data,delimiter=',')
#for skip in range(2): #skips the first two rows
# next(read_in)
names = next(read_in)
#print(type(names))... |
import pygame
from math import cos, sin, radians, inf
class Sensor:
factor = 8
def __init__(self, start_x, start_y, angle, radius, color, bounds_color):
self.color = color
# maze bounds color.
self.bounds_color = bounds_color
self.x_pos_start = start_x
self.y_pos_start... |
#!/usr/bin/python
import sys
def is_binary_from_filename(file_name):
if (file_name.find("hnco") <> -1 or file_name.find("hncoca") <> -1):
return True
else:
return False
def split_label(label):
return label.split("-")
# Given string "A107H" -> ["A", "107", "H"]
def split_res_num(res_num):... |
#Import mysql connector
import mysql.connector
#Create Database instance and credentials including URL of database
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
passwd = "p@ssw0rd",
#Add database, like mysql USE command
database = "bookdb")
#Create instance of cursor
my_cursor = ... |
#!/usr/bin/env python3
"""
Snake Renderer
Author: dowusu
This will open a PyQt window and draw rectangles
to the screen representing the snake game.
"""
import sys
import main
from PyQt5 import QtGui,QtCore,QtWidgets
class App(QtWidgets.QWidget):
"""
This is the main widget class
"""
def __init_... |
#script 4
payment =.01
total = 0
days = int(input("Enter number of days would you like to calculate the salary: "))
for x in range(1,days+1):
payment *= 2
total += payment
print ("On day"+str(x)+"the salary is $",payment/2)
print("The total salary is $",total/2)
|
def lineNumbers(filename):
infile = open(filename, 'r')
count = 0
for line in infile:
count += 1
print (count ,':'line)
infile.close()
main()
# Exercise 5, chapter 6
def sumNumbers(filename):
def main():
total = 0.0
infile = open('numbers.txt','r')
for line in ... |
grade = int(input('PLZ input Grade:'))
if grade >=90 and grade <=100 :
Level = 'A'
elif grade >= 80 :
Level = 'B'
elif grade >= 70 :
Level = 'C'
elif grade >= 60 :
Level = 'D'
elif grade <= 60 and grade >=0 :
Level = 'D'
else :
Level = 'Not a grade'
print(Level) |
from math import sqrt
a = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))
if c < a+b and c > abs(a-b):
Perimeter = a + b + c
p = Perimeter / 2
Area = sqrt(p * (p-a) * (p-b) * (p-c))
print('Perimeter = %.2f , Area = %.2f' % (Perimeter, Area))
else:
print('Not a triangle!') |
#99. recover Binary tree:
class Solution:
def recoverTree(self, root: TreeNode):
#return the inorder traversal of the current binary searching tree.
def inorder(r: TreeNode):
return inorder(r.left) + [r.val] + inorder(r.right) if r else []
def findSwapping(nums: List[int]):
... |
#246. Strobogrammatic Number:
#Here first, the digits should only include 0, 1, 6, 8, 9
#where in the reversed order 6 would become 9 and 9 would become 6.
class Solution:
def isStrobogrammatic(self, num: str) -> bool:
reversedNumber = ""
for i in reversed(range(num)):
if num[i] == "1" o... |
#AUC calculation
def auc(actualPred, labelPred):
numPositive = len([0 for x in actualPred if x == 1])
numNegative = len(actual) - numPositive
sumPositive = sum([r[i] for i in range(len(r)) if actualPred[i] == 1])
auc = ((sumPositive - numPositive * (numPositive + 1)/ 2.0)/ (numNegative * numPositive))
... |
#topK problems: sort/heap/quickselect:
#O(N*logN)
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return sorted(nums, reverse = True)[k - 1]
#O(N* logK): heap -> start with empty heap, push items into it
#quick-select:
#Why lstm works better than the RNN: utilize the forget ... |
#344. Reverse String
class Solution(object):
def reverseString(self, strs):
i1, i2 = 0, len(strs) - 1
while i1 < i2:
strs[i2], strs[i1] = strs[i1], strs[i2]
i2 -= 1
i1 += 1
return strs |
#121. Best time to buy and sell stock
class Solution:
def maxProfit(self, prices: List[int]) -> int:
curmax = 0
curmin = 10000
curresult = 0
for i in range(len(prices)):
if curmin > prices[i]:
curmin = prices[i]
elif prices[i] - curmin > curresult:
curresult = prices[i] - curmin
#you need to buy... |
#112. Path Sum:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
def search(node: TreeN... |
#
import urllib2
from bs4 import BeautifulSoup
response = urllib2.urlopen("http://tutorialspoint.com/python/python_overview.htm")
html_doc = response.read()
soup = BeautifulSoup(html_doc, 'html.parser')
for x in soup.find_all('b'):
print(x.string)
import urllib.request
with urllib.request.urlopen("http://python-d... |
#topological sort:
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.graph = defaultdict(list)
self.V = vertices
def addEdge(self, u, v):
self.graph[u].append(v)
def topologicalSortUtil(self, v, visited, stack):
visited[v] = True
for... |
#695. Max area of island::
#Island category questions: requiring an indicator of
#whether we have seen it.
class Solution:
def maxAreaofIsland(self, grid: List[List[int]]) -> int:
n_r = len(grid)
n_c = len(grid)
seen_indicator = set()
def area(i, j):
if(i < 0 or i >= n_r or j < 0 or j >= n_c
or
... |
#valid parenthesis: a typical first in first out structure.
class Solution:
def isValid(strings: str) -> bool:
stacks = []
leftParenthesis = ["(", "[", "{"]
mapList = {"(": ")", "[": "]", "{": "}"}
for num in strings:
if num in leftParenthesis:
stacks.append(num)
elif stacks and m... |
#1331. Rank Transform of an array:
class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
hashSet = {}
rank = 1
for num in sorted(arr):
if num not in hashSet:
hashSet[num] = rank
rank += 1
for idx, val in enumerate(arr):
arr[idx] = hashSet[val]
... |
from eulertools import EulerProblem
import numpy as np
def problem(args:int) -> int:
"""Sum of number divisible by 3 and 5. Numbers divisible by both are counted in both, so remove the sum of them..
"""
n = np.arange(args)
n = np.add(1, n)
x = n[n % 3 == 0]
y = n[n % 5 == 0]
z = n[n % (5*3) == 0]
re... |
from eulertools import EulerProblem
from requests import get
from typing import List
def read_data(s:str) -> List[str]:
"""Read the list of names into a list, return it sorted.
"""
r = []
d = [i for i in s.strip().split('\n') if len(i) > 0]
for line in d:
split_line = line.split(',')
for line2 in s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.