text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python
# encoding: utf-8
"""
https://leetcode.com/discuss/22898/the-bottom-up-o-n-solution-would-be-better
method is based on DFS. Instead of calling depth() explicitly for each child node, we return the height of the current node in DFS recursion. When the sub tree of the current node (inclusive) is ba... |
class Employee:
company_name="tata ltd"
def __init__(self,ename,exp):
self.ename=ename
self.exp=exp
def printdet(self,):
print("emp name",self.ename)
print("experience",self.exp)
print("company",Employee.company_name)
def __str__(self):
return str(self.exp... |
class Employ:
def setval(self, name, id, salary, age):
self.name = name
self.id = id
self.salary = salary
self.age = age
def printval(self):
print("name::", self.name)
print("id::", self.id)
print("salary::", self.salary)
print("age::", self.age)
... |
age=int(input("enter age"))
if age<70:
raise Exception("Age is under")
else:
print("vaccine available")
|
class Person:
def __init__(self,name,age,address):
self.name = name
self.age=age
self.address=address
def printval(self):
print(self.name,self.age,self.address)
pe=Person("anu",24,"qpf")
pe.printval() |
no1=int(input("enter num1"))
no2=int(input("enter num2"))
if no1==no2:
raise Exception("two num is same")
else:
print("no1+no2") |
x = 1
def f():
#global x # important to remember: when you want to use a global variable you need to state it in the function
y = x
#x = 2
return x + y
print(x)
print(f())
print(x)
|
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
dict1 = {}
nums1.sort()
nums2.sort()
for i in nums1:
if i not in dict1:
dict1[i] = ... |
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
for i in range(len(nums)):
#SOLUTION
test_list = [0, 1, 3]
my_solution = Solution()
print(my_solution.missingNumber(test_list))
|
#Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
... |
#1
def getUserInputTitle(message):
x = input(message)
return x.title()
#2
def getUserInputData():
print('Whats your date of birth?')
a = input('Day: ')
while int(a) < 1 or int(a) > 31:
a = input('Day: ')
b = input('Month: ')
c = input('Year: ')
return a + '/' + b + '... |
"""
lec 9
"""
#class car: #define a class
# maker= 'toyota' #dont HAVE to define an attribute
# def report_maker(self): #method
# return(self.maker)
#my_car = car() #create an instance/ object
#print(my_car.report_maker())
#cl... |
"""
lab 9
classes
"""
# 3.1
class my_stat():
def cal_sigma(self,m,n):
self.result = 0
for i in range(n,m+1):
self.result = self.result +i
return self.result
def cal_pi(self,m,n):
self.result = 1
for i in range(n,m+1):
self.result = self.r... |
#tihs little project maked by Anas Sabir
#This is a simple database for our application that includes the foldername ==> file formats it should contain
data = {'pdfs':['pdf'],
'images':['jpg','png','jpeg','PNG'],
'exels':['xlsx'],
'words':['docx'],
'rars':['rar'],
'videos'... |
l = [1, '2', 3, 'hello', 5, 6, 'world']
Sum = 0
for i in range(0, len(l)):
if type(l[i]) == int or type(l[i]) == float:
Sum = Sum + l[i]
print("Sum of {} is {}".format(l, Sum))
|
rad=float(input("Enter radius of circle: "))
area=3.142*(rad**2)
print('Area of circle is: ', area)
|
l = [14,1,5,56,4,87,9,65]
gr_num = 0
for i in range(0,len(l)):
if i != len(l)-1:
if l[i] >= l[i+1]:
gr_num = l[i]
else:
gr_num = l[i+1]
print("Greater number in list {} is {}".format(l,gr_num))
|
user_list = []
a = input('Print the value--')
if len(a) <= 50:
user_list.append(a)
print(user_list)
else :
print (' put the value again--')
|
'''
Append in file
'''
user_email = input('Type your email--')
b = open('eamil_task.txt' , 'a')
if '@' in user_email and user_email.endswith('.com'):
print(user_email)
b.write(user_email + '\n' )
else:
print('Try again')
b.close()
'''keijser@yahoo.ca
mgreen@att.net
shubhansh@gmail.com... |
import turtle
import random
#import colorgram
from turtle import Turtle, Screen
turtle.colormode(255)
franklin = Turtle()
screen = Screen()
screen.setup(width=800, height=800)
franklin.shape("turtle")
franklin.color("forest green")
franklin.speed(9)
franklin.penup()
### Uncomment following code and "import colorg... |
#!/usr/bin/env python
#coiding=utf-8
a = raw_input("What is the input string? ")
print '%s has %d characters' % (a,len(a))
|
#!/usr/bin/env python
#coding=utf-8
a = raw_input("What's your name? ")
print "Hello, %s, nice to meet you." % a
|
'''
Kody Alan Kantor
Weather Research
Creating a program to parse a data file and create a comma separated value file.
Mod History:
4-24-13: Original compilation.
Converts one line of the file into an array.
4-25-13: Parsed the relevant information from the file.
Created a text file of the relevant informatio... |
# geometry.py
# ---------------
# Licensing Information: You are free to use or extend this projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to the University of Illinois at Urbana-Champaign
#
# Creat... |
import MapReduce
import sys
"""
Word Count Example in the Simple Python MapReduce Framework
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
def mapper(record):
# relation table name (order or line item)
# order number
relation = record[0]
order_num = re... |
from datetime import datetime
from dataclasses import dataclass
import os
import json
from optparse import OptionParser
@dataclass
class AbstractParams:
"""
Abstract parameters class.
If we want to run an experiment with some params,
we just inherit this class and add our params to it.
2 requ... |
text = "this this is the text and this is the text"
word_list = text.split()
# d = {'a':3, 'b':4}
# if 'a' in d:
# print("True")
word_dict = {i : word_list.count(i) for i in word_list}
# for i in word_list:
# if i not in word_dict:
# word_dict[i] = word_list.count(i)
print(word_dict)
|
# -*- coding:UTF-8 -*-
def cadastrar(nomes):
print 'Digite o nome:'
nome = raw_input()
nomes.append(nome)
def alterar(nomes):
print 'Qual nome deseja alterar?'
nome = raw_input()
if (nome in nomes):
indice = nomes.index(nome)
print 'Informe o novo nome:'
nome_alterado = raw_input()
nomes[indice] = nome... |
# Python program to print the even numbers from a given list.
def even(list1):
a = []
for x in list1:
if x % 2 == 0:
a.append(x)
return a
result = even([2, 3, 4])
print(result) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('/Users/amourlee/Desktop/digits.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Now we splite the image to 5000 cells, each 20x20 size
cells = [np.hsplit(row, 100) for row in np.vsplit(gr... |
# Tuples are used to store multiple items in a single variable.
# Tuple is one of 4 built-in data types in Python used to store collections of data,
# the other 3 are List, Set, and Dictionary,
# all with different qualities and usage. A tuple is a collection which is ordered and unchangeable.
# you declare tuples in ... |
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('TestData.csv')
print(dataset)
X = dataset.iloc[:, 1:8].values
y = dataset.iloc[:, 8].values
print(X)
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
# Splitting the dataset... |
word = input("Enter word: ")
def isPalindrome(input_string):
return input_string == input_string[::-1]
print(isPalindrome(word)) |
# initializing string
str = input("Input: ")
def simple_hash1(s):
r = 7
for c in s:
r = (r * 31 + ord(c)) % 2**16
return r
print(simple_hash1(str))
def simple_hash2(s):
result = 0
for c in s:
result = (result + ord(c) * 3 + 17) % 791
return result
print(simple_hash2(str)) |
def add(x, y):
"""
Returns x + y
:params x: int
:params y: int
:return: int sum of x and y
"""
return x + y |
# Austin Nowlen 50132880
class GameState:
def __init__(self, row_count: int, column_count: int, starting_top_left: str, starting_player: str, how_to_win: str):
self.new_gameboard(row_count, column_count)
self.create_starting_layout(starting_top_left)
self.turn = starting_player
self... |
#Write a program that prints the numbers
#from 1 to 100. You can use Python's range()
#to quickly make a list of numbers.
#For multiples of five (5, 10, 15, etc.)
#print "Chicken" instead of the number.
#For the multiples of seven (7, 14, 21, etc.)
# print "Monkey".
#For numbers which are multiples of both five
#a... |
# 십진법 -> 이진법
def DFS(x):
if x == 0 :
# 함수 종료
return
else :
DFS(x // 2)
print(x % 2, end = ' ')
if __name__ = "__main__" :
n = int(input())
DFS(n) |
# 재귀함수와 스택
# 재귀함수 : 반복문의 대체재
def DFS(x) :
if x > 0 :
DFS(x-1)
print(x, end= ' ')
# print(x) 다음 DFS(x-1) 실행 : 3 2 1
# DFS(x-1) 다음 print(x) 실행 : 1 2 3
# main 함수와 재귀함수 구분 : 여기부터 실행 됨
if __name__ == "__main__" :
n = int(input())
DFS(n) |
class Call(object):
def __init__ (self, unique_id, name, phone_number, time_call, reason_call):
self.call = [unique_id, name, phone_number, time_call, reason_call]
def display(self):
print self.call
class CallCenter(Call):
def __init__(self):
self.calls = []
self.queue = 0
... |
import pandas as pd
import requests
from bs4 import BeautifulSoup
def scrape_stats(base_url, year_start, year_end):
years = range(year_start,year_end+1,1)
final_df = pd.DataFrame()
for year in years:
print('Extraindo ano {}'.format(year))
req_url = base_url.format(year)
req = requ... |
# #FOR LOOP MAPS
"""
The first mapping creates a list of all the permutations of n length,
then joins all elements of that list into a single string.
This allocates a new key in the dictionary, entitled with
the name of the string being generated.
"""
"""
The second mapping does the same, except it accesses the value... |
import tensorflow as tf //tensorFlow
import numpy as np
# 例子1,拟合y_data的函数,权重和偏置分别趋近0.1和0.3
# np.random.rand(100)生成100个[0,1]之间的随机数,构成1维数组
# np.random.rand(2,3)生成2行3列的二维数组
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data * 0.1 + 0.3 # 权重偏置这些不断更新的值用tf变量存储,
# tf.random_uniform()的参数意义:(shape,min,max) #... |
count = 0
for i in range(0,5):
for j in range(0,7):
for k in range(0,4):
print("count = {} [{} {} {}]".format(count,i,j,k))
count = count + 1
|
while True:
try:
char = int(input('input a number:'))
print(char)
except:
print('a int number!')
|
list_num = [0,1,2,3]
sum = 0
list_sum =[]
count_0 = 0
count_1 = 0
count_2 = 0
count_3 = 0
count_4 = 0
for num_01 in list_num:
for num_02 in list_num:
for num_03 in list_num:
for num_04 in list_num:
for num_05 in list_num:
sum = num_01 + num_02 + num_03 + num_0... |
#GlobalAIHub Final Project
"""
Managers: Vahap Onur YILDIRIM 23 Turkish English German
Alaattin Ahmet DİRİ 25 Turkish
İrem Eylül GÖBEL 22 Turkish Spanish
Employees: Ayşe İÇÖZ 25 Turkish Spanish
John DUGGAN 30 English
Hideo KOJIMA 45 Engl... |
def generator(num, prefix, __open=0, __close=0):
if __open == num and __close == num:
return print(prefix)
else:
if __open < num:
generator(num, prefix + '(', __open + 1, __close)
if __close < __open:
generator(num, prefix + ')', __open, __close + 1)
if __name__... |
def two_sum(arg_list, arg_number):
if arg_list is None:
raise TypeError
elif arg_list == []:
raise ValueError
else:
pass
for x,y in enumerate(arg_list):
for k,l in enumerate(arg_list):
if y + l == arg_number:
return [x, k]
return None
|
#!/usr/bin/env python
# coding: utf-8
# **Here is the demo for the imitation model of the scikit-learn's LinearRegression**
# **This notebook presents you single-variable linear regression**
# In[1]:
from LinearReg import LinReg
# In[2]:
help(LinReg)
# In[3]:
import matplotlib.pyplot as plt
import numpy as... |
e_s=0
o_s=0
for i in range(101):
if i%2 ==0:
e_s += i
else:
o_s += i
print("홀수의 합 :",o_s)
print("짝수의 합 :",e_s)
|
# file name : if03.py
# if (조건문)에서 조건문이 True이면 if 아래에 있는 명령들이 실행
# 그렇지 않고 elif 조건문이 True이면 elif 아래에 있는 명령들이 실행
# 그렇지 않고 elif 조건문이 True이면 elif 아래에 있는 명령들이 실행
# ...
# 그렇지 않으면 (위의 조건들이 True가 아니면 ) else 아래에 있는 명령들이 실행
a = int(input('정수 입력 :'))
if a >= 90:
print('당신의 학점은 A 입니다.')
elif a >= 80:
print('당... |
# 파이썬 산술 연산자 종류
a=int(input("첫 번째 수 입력 : "))
b=int(input('두 번쨰 수 입력 : '))
print(a,'+',b,'=',(a+b)) #더하기
print(a,'-',b,'=',(a-b)) #뺴기
print(a,'*',b,'=',(a*b)) #곱하기
print(a,'/',b,'=',(a/b)) #나누기
print(a,'//',b,'=',(a//b)) #몫
print(a,'%',b,'=',(a%b)) #나머지
print(a,'**',b... |
import sys
import os
Users_file = open("Users.txt", 'a+')
Domains_file = open("Domains.txt", 'a+')
Types_file = open("Types.txt", 'a+')
Access_file = open("Accesses.txt", 'a+')
def Search(target, file):
for line in file:
if target == (line.split(' ')[0]):
return True
return False
def Sea... |
print("learning tuple")
#similar to lists but they are immutable
#sometimes few things should be immutable
credit_card1=(123123212212221,"joe rogan","11/20",123)
credit_card2=(122332233444444,"subbu","11/21",133)
#you can have list of tuples
#you can have more number of tuples in a list but you cannot change an... |
import calendar
print ("learning calendar module")
#weekheader fumction returns the days in the week
#weekheader(numofletters) here numofletter=no of characters of a name of a day you print
#suppose numofletters=3 then O/p will "Mon" if it is 2 o/p will be Mo
print(calendar.weekheader(9))
#skips a line
pri... |
# How many n-digit positive integers exist which are also an nth power?
def solve():
c = 1
for b in range(2, 10):
e = 1
while e <= len(str(b ** e)):
if e == len(str(b ** e)):
c += 1
e += 1
return c
|
#!/usr/bin/python3
print ('BIENVENID@')
SEXO = int(input('Ingrese su sexo,en caso que sea Mujer ingrese 1,si es hombre ingrese 2: '))
HEMOGLOBINA = int(input('Ingrese su nivel de hemoglobina: '))
EDAD = int(input('Hola por favor ingrese su edad,en caso que tenga menos de un año ingrese 0: '))
if EDAD == 0:
... |
print ('BIENVENID@ A TIENDA COMPUCHRIS')
COMPRA = int(input('Ingrese su compra: '))
if COMPRA > 2000:
PC_YNOS = str(input('Usted compro una YNOS?'))
if PC_YNOS == 'si':
PRECIO_FINAL = (COMPRA - (COMPRA * 0.15))
else:
PRECIO_FINAL = (COMPRA - (COMPRA * 0.10))
else:
PRECIO_FINAL = (COMP... |
#!/usr/bin/python3
print ('BIENVENID@')
OBREROS = int(input('Ingrese la cantidad de obreros que hay: '))
HORAS = int(input('Cuantas horas trabajo?'))
EXTRAS = int(input('Cuantas horas extras trabajo?'))
VALOR_EXTRAS = EXTRAS * 25
if HORAS < 40:
SUELDO = HORAS * 20
print (SUELDO)
else:
SUELDO = HORAS * ... |
TOTAL_DE_MUJERES = int(input('Cantidad de mujeres en curso son: '))
TOTAL_DE_HOMBRES = int(input('Cantidad de hombres en curso son: '))
TOTAL_DE_ALUMNOS = (TOTAL_DE_MUJERES + TOTAL_DE_HOMBRES)
PORCENTAJE_DE_MUJERES = ((TOTAL_DE_MUJERES /TOTAL_DE_ALUMNOS) * 100)
print ('PORCENTAJE DE MUJERES CURSANDO: ')
print (PORCENT... |
Valor_compra = int(input('Ingresar valor'))
Numero_al_azar = int(input('Elija numero'))
if Numero_al_azar > 74:
Descuento = Valor_compra * 0.20
else:
Descuento = Valor_compra * 0.15
print (str(Descuento))
|
lista = [3,5,6,7,8]
maxx = 0
for i in lista:
if (i > maxx):
maxx = i
print (maxx)
|
#!/usr/bin/python3
def Sueldo(x,y):
Comision_total = (x / 100 ) * y
print ('VALOR DE COMISIONES')
print (Comision_total)
Sueldo_mensual = x + Comision_total
print ('SUELDO MENSUAL')
print (Sueldo_mensual)
Sueldo_base = int(input('Ingrese su sueldo base: '))
Ventas_realizadas_en_el_mes = int(i... |
Sueldo_base = int(input('Ingrese su sueldo base: '))
Ventas_realizadas_en_el_mes = int(input('Ingrese cuantas ventas realizo: '))
Comision_total = (Sueldo_base / 100 ) * Ventas_realizadas_en_el_mes
print ('VALOR DE COMISIONES')
print (Comision_total)
Sueldo_total = Sueldo_base + Comision_total
print ('SUELDO MENSUAL')
... |
print ('BIENVENID@,por favor ingrese 20 numeros')
NUMERO_UNO = int(input(': '))
NUMERO_DOS = int(input(': '))
NUMERO_TRES = int(input(': '))
NUMERO_CUATRO = int(input(': '))
NUMERO_CINCO = int(input(': '))
NUMERO_SEIS = int(input(': '))
NUMERO_SIETE = int(input(': '))
NUMERO_OCHO = int(input(': '))
NUM... |
print ('BIENVENID@ CONDUCTOR')
def auto():
Patente = input('Por favor ingrese patente del auto: ')
global Resultado
global Amarilla
global Roja
global Rosa
global Verde
global Azul
Resultado = Patente[4]
if Resultado == "1" or Resultado == "2":
print ('Es Amarilla')
... |
#!/usr/bin/env python3
import sys
current_year = None
current_max_temp = None
for line in sys.stdin:
line_year, line_temp_str = line.strip().split("\t")
line_temp = int(line_temp_str)
if current_year == line_year:
if line_temp > current_max_temp:
current_max_temp = line_temp
else:... |
dictionary = {
"hc": "học",
"any": "anh người iu",
"hk": "không",
}
while True:
for key in dictionary:
print(key, end="\t")
print()
input_key = input("your code?")
if input_key in dictionary:
print("it means:", dictionary[input_key])
else:
choice = input("Not foun... |
from copy import deepcopy
from typing import List, Tuple
import numpy as np
# from ..tour import Tour
Tour = List[int]
Candidate = Tuple[int, int]
class SteepestOnEdges:
"""Local search tour improvement algorithm.
It consider every possible 2-edges swap,
swapping 2 edges when it results in an improved to... |
# address book
# - store a name and a corresponding phone number (can be in plain 10 digits)
# and an email address (lastname.firstname@email.com)
# - functions to build
# list -- list all entries in the address book
# add -- add an entry
# delete -- delete an entry
# search -- find a... |
str1 = input("Please input a string: ")
str2 = input("Please input another string: ")
if str1.isdigit() and str2.isdigit():
average = (int(str1) + int(str2)) / 2
print("The average of teh two numvers is", average)
elif not str1.isdigit() and not str2.isdigit():
if str2 in str1:
count = str1.count(s... |
import math
# David Daugela - Student #: 250938255
# Declaring Input Variables - Part 1.
custName = str(input("Please type in the customer's first and last name: "))
custAge = int(input("Please type in the customer's age: "))
custClassification = str(input("Please type in the customer's classification code: ").upper(... |
word = input('введите что ли слово ')
string = ""
for letter in word:
string += letter
print(string)
|
#Программа должна открывать файл с русским текстом в utf-8 и сообщать про него следующую информацию (по вариантам):
#2. во сколько раз самая короткая строка короче самой длинной
f = open('one.txt', 'r', encoding = 'utf-8')
maks = 1;
mini = 999999;
for line in f:
words = line.split()
if len(words) != 0:
... |
from random import randint
def if_a_needed_num_or_not_that_much(x):
tr = False
for num in range (1, 101):
if x == str(num):
tr = True
return tr
t = False
while 4 < 5:
if t == False:
a = randint(0, 100) + 1
t = True
print('\n\n\nI\'ve chosen a number fro... |
import pandas as pd
import numpy as np
data = pd.DataFrame([[2.3, 3.3, np.nan],
[7.5, np.nan, 9.8], [np.nan, 2.2, 6.8],
[5.6, 9.2, 7.4], [np.nan, np.nan, np.nan]])
# 1. filtering missing data
# delete rows with null values
print(data.dropna())
# delete row with all null val... |
#Дана непорожня послідовність слів з малих українських літер; між сусідніми
#словами - кома, за останнім словом - крапка. Вивести на екран в алфавітному порядку всі
#глухі приголосні букви, що входять в кожне непарне слово і не входять хоча б в одне
#парне слово.
while True:
while True:
try:
a =... |
#### Quick TKinter fileselector ####
from tkinter.filedialog import askopenfilename
def askfilename():
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
return filename # ret... |
#!/usr/bin/python3
class MyInt(int):
""" class to invert operations"""
def __eq__(int, other):
return False
def __ne__(int, other):
return True
|
#!/usr/bin/python3
def matrix_divided(matrix, div):
""" function to divide elements of a matrix """
size = 0
if div == 0:
raise ZeroDivisionError('division by zero')
if type(matrix) is not list:
raise TypeError('matrix must be a matrix (list of lists) '
'of intege... |
#!/usr/bin/python3
if __name__ == "__main__":
import calculator_1 as calc
import sys
if len(sys.argv) != 4:
print("Usage: ./100-my_calculator.py <a> <operator> <b>")
sys.exit(1)
else:
var1 = int(sys.argv[1])
var2 = int(sys.argv[3])
oper = sys.argv[2]
if op... |
#!/usr/bin/python3
def update_dictionary(a_dictionary, key, value):
for keys in a_dictionary.keys():
if key == keys:
a_dictionary[keys] = value
a_dictionary[key] = value
return a_dictionary
|
#!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
for mat in matrix:
for elem in mat:
print("{:d}".format(elem), end=" " if mat[-1] != elem else "")
print()
|
x= input("Enter a number : ")
y= input("Enter another number : ")
print("Value of x = {} and Value of y = {}".format(x,y))
x,y=y,x
print("Swapped Value of x = {} and Value of y = {}".format(x,y))
|
num = int(input('Insira um numero: '))
if num % 2 == 0:
print('{} é par'.format(num))
else:
print('{} é impar'.format(num)) |
import math
an = float(input('digite o angulo q deseja?'))
r = math.radians(an)
s = math.sin(r)
c = math.cos(r)
t = math.tan(r)
print('se o angulo for {} \n o seno sera {:.3f} \n o coseno sera{:.3f} \n e a trangente sera {:.3f}'.format(an, s, c, t)) |
# Sistema Antecessor e Sucessor
num = int(input('Digite um numero:'))
proc = num + 1
proc2 = num - 1
print('O numero é', num, 'sucessor é', proc, 'e antecessor', proc2) |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 14 17:45:35 2017
@author: xuefei.yang
"""
# import the library used to query a website
import urllib.request as urllib2
# specify the url
wiki = "https://en.wikipedia.org/wiki/List_of_Olympic_Games_host_cities"
# Query the website and return the html to ... |
class NPC():
"""The base class for all NPCs"""
def __init__(self, id, name, description, dialogue):
self.id = id
self.name = name
self.description = description
self.dialogue = dialogue
#THESE EXAMPLES ARE ONLY HERE TO GIVE YOU AN IDEA ON HOW THIS CLASS WORKS, DELETE THEM WHEN YOU DON'T NEED THEM ANYMORE
... |
import sud2sat as sud
import sat2sud as sat
import sys
import os
def main():
if len(sys.argv)==1:
sys.exit("please input the puzzle file you want to solve")
if len(sys.argv)>2:
sys.exit("Argument Error: Program requires 1 arguement (%s given)"%(len(sys.argv)-1))
print("\n===================... |
from turtle import fd, rt, lt, bk
def tree(minl, length):
if length < minl:
fd(length)
bk(length)
return
fd(length)
lt(25)
tree(minl, length * .8)
rt(75)
tree(minl, length * .5)
lt(50)
bk(length)
def spi(minl, ang, length):
if length < minl:
return
... |
#!/usr/bin/env python
"""
Assumption
Element in ordered set in redis will allways be "element_name"|"time_stamp" - based on this fact we will asume that it is unique
add(r_server, worker_set_name, int(time.time()),"element_name|%s" % int(time.time()))
This implementation will store Your tasks as a todo list:
Work lis... |
import numpy as np
import pandas as pd
def dataloader(multiIndex=False):
"""
Utility function to facilitate loading CHACK data. Returns two separate dataframes
Parameters:
----------
multIndex (bool) - flag to set whether function returns species abundance data as multi-index dataframe or sing... |
'''Trains a denoising autoencoder on MNIST dataset.
Denoising is one of the classic applications of autoencoders.
The denoising process removes unwanted noise that corrupted the
true signal.
Noise + Data ---> Denoising Autoencoder ---> Data
Given a training dataset of corrupted data as input and
true signal as outpu... |
import turtle as t
def fractale(n, l=400):
if n == 0:
t.fd(l)
return
fractale(n-1, l/3)
t.left(60)
fractale(n-1, l/3)
t.right(120)
fractale(n-1, l/3)
t.left(60)
fractale(n-1, l/3)
t.speed(0)
fractale(3)
t.done() |
import math
def vowel(words):
v ="aeiou"
length = len(v)
count = 0
resultflage = 1
for char in words:
if char in v:
if count >= length or char != v[count]:
resultflage= 0
return resultflage
count = count+1
if(count == length):
... |
import heapq
# Method Definitions --------------------------------
def max_product(arr):
'''
heap = []
for i in range(len(arr)):
heapq.heappush(heap, arr[i])
'''
a = heapq.nlargest(3, arr)
b = heapq.nsmallest(2, arr)
return max((a[0]*a[1]*a[2]),(b[0]*b[1]*a[0]))
# Dr... |
variavel = 2
print('variavel')
type(variavel)
#Variáveis com valor real
preco_do_produto = 2.5
print(preco_do_produto)
type (preco_do_produto)
#Variável String
variavel = 'texto'
print(variavel)
#Variável Boolean
verdadeiro = True
falso = False
print (verdadeiro)
print(falso)
#Listas
lista = [1,2,3,4,5,6,7,8,9... |
# Задача-1:
# Напишите скрипт, создающий директории dir_1 - dir_9 в папке,
# из которой запущен данный скрипт.
# И второй скрипт, удаляющий эти папки.
import os
try:
for i in range(1, 10):
os.mkdir("dir_" + str(i))
except:
print("Already exist")
a = input("enter something ")
print(a)
try:
for i ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.