text stringlengths 37 1.41M |
|---|
for x in range(5):
print(x)
for x in range(3,5):
print(x)
for x in range(3,8,3):
print(x) |
def square_definer(width: int, length: int) -> int:
"""Returns the size of the smallest square side possible in area"""
while width != length:
if width > length:
width -= length
return square_definer(width, length)
elif length > width:
length -= width
... |
set_1 = set()
for number in range(5):
set_1.add(input('Put int or float number: '))
set_1 = list(set_1)
min_num = set_1[0]
max_num = set_1[0]
for i in set_1:
if min_num > i:
min_num = i
if max_num < i:
max_num = i
print('Min num = ', min_num)
print('Max num = ', max_num)
|
def calculator() -> print:
"""Calculates input formula"""
print('Welcome to Calculator!'
'\nProceed with formula input (with spaces), use only "+, -, *, /" as operators, example: "2 * 2"'
'\nTo exit enter "exit"')
user_input = str(input('Please enter formula: '))
if user_input == 'e... |
"""
A module to perform SVD decompostion on a given training dataset.
"""
from __future__ import division
import numpy as np
from scipy.sparse import csr_matrix
import scipy.linalg as linalg
import csv
import os
from math import sqrt
import time
total_users = 943
total_movies = 1682
def get_data():
"""
A fu... |
############# GENERAL TREE ########
class TreeNode:
def __init__(self,data):
self.data=data
self.children=[]
self.parent=None
def add_child(self,child):
child.parent=self
self.children.append(child)
def get_level(self):
level=0
iterator=self.parent
... |
import math
def solution(n, m):
answer = []
answer.append(math.gcd(n, m))
answer.append(int((n * m) / answer[0]))
return answer
n = 3
m = 12
print(solution(n, m)) |
def solution(nums):
answer = 0
tmp = len(nums) / 2
nums = list(set(nums))
nums = len(nums)
if(tmp < nums) :
answer = int(tmp)
else :
answer = nums
return answer
num = [3, 1, 2, 3]
print(solution(num)) |
import random
import sys
import time
def setze_zeitstempel():
return time.time() * 1000
def stelle_aufgabe():
i = 0
while True:
i += 1
print(" --- Aufgabe %d --- " % (i))
rechne(0)
def rechne(mode = 0):
answer_correct = False
try:
a... |
# def choice_to_number(choice):
# """Convert choice to number."""
# if choice == 'Usain':
# return 1
# elif choice == 'Me':
# return 2
# elif choice == 'Aybek':
# return 3
# else:
# return choice
def choice_to_number(choice):
return {'Usain': 1, 'Me': 2, 'Qazi': 3}... |
def fib(n):
if (n is 0 or n is 1):
return 1
return fib(n - 1) + fib(n - 2)
if __name__ == "__main__":
print("Im here")
print(fib(50))
|
#!/usr/bin/env python
# coding: utf-8
# # Linear Regression
# In[1]:
import matplotlib.pyplot as plt
import pandas as pd
import plotly.express as px
from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
# In[2]:
# load th... |
"""
使用生成器函数实现可迭代类
"""
import math
class PrimeNumbers(object):
"""
实现正向迭代
实现 __iter__ 或 __getitem__ 方法
实现反向迭代
实现 __reversed__ 方法
"""
def __init__(self, start, end):
self.start = start
self.end = end
def isParimeNum(self, k):
if k < 2:
... |
"""
对迭代器进行切片操作
"""
# 使用itertools.islice,返回一个迭代对象切片的生成器
from itertools import islice
def file_slice():
f = open('aaa')
# islice(f, 1, 100)
# islice(f, 500)
for i in islice(f, 1, None):
print(i)
def list_slice():
l = [i for i in range(0, 20)]
i = iter(l)
# start=4表示列表中取索引4开始... |
b=16
for mani in range(int(pow(b,1/2)),1,-1):
if(b%mani==0):
print(mani)
print(int(b/mani)) |
import random
from abc import ABC
class Listas_Frutas(ABC):
_frutas_lista = ['banana',
'jabuticaba',
'pitanga',
'mirtilo',
'morango',
'abacaxi',
'cereja'
]
def escolher_f... |
"""This script makes the search to wikipedia by passing the search keyword as the only argument."""
import sys
from elasticsearch import Elasticsearch
import config
def title_to_url(title):
"""Takes the article title and turns it into a wikipedia URL"""
title = title.replace(' ', '_')
return config.WIKI... |
'''
Given a sorted list of disjoint intervals, each interval intervals[i] = [a, b]
represents the set of real numbers x such that a <= x < b.
We remove the intersections between any interval in intervals and the interval toBeRemoved.
Return a sorted list of intervals after all such removals.
Example 1:
Input= 3
... |
import operator
from datetime import datetime
class Person():
def __init__(self, last_name='', first_name='', gender='', fav_color='', dob=''):
self.last_name = last_name
self.first_name = first_name
gender = gender
if gender == 'M' or gender == 'Male':
self.gender =... |
import sys
sys.stdin = open('sample_input.txt')
T = int(input())
for tc in range(1,T+1):
card = input()
card_list = [card[idx:idx+3] for idx in range(0,len(card),3)]
card_type = ['S','D','H','C']
card_cnt = {key:[] for key in card_type}
for card in card_list:
key, value = card[0], card[1:... |
N = int(input("Please write a count of students: ")) #студенти
K = int(input("Please write a count of apples: ")) #яблуки
count_apples = K//N
apples_left = K%N
print("every student receiped", count_apples,"apples") #виводимо результат
print("apples left:",apples_left) #виводимо результат
input()
|
#!/usr/bin/env python3
class Employee(object):
def __init__(self, name, title):
self.name = name
self.title = title
self.salary_table = {
'manager': 50000,
'director': 20000,
'staff': 10000
}
def salary(self):
return self.salary_table... |
import csv
file_to_load = "C:/Users/David/Desktop/GTATL201908DATA3/02 - Homework/03-Python/Instructions/PyPoll/Resources/election_data.csv"
file_to_output= "Resources/election_data.txt"
#variables
vote_total = 0
candidates = []
candidate_votes = {}
winner = " "
winner_votes = {}
#csv format from class activities
wit... |
#!/usr/bin/env python
#Set python environment in the first line as written above
''' This script is written to do the following:
a) Read a .rnt file and save the Location, Strand and Product columns
to another file called filename_LocStrPro.txt
b) Split the Location into two parts and save the Strand and Location
int... |
#!/usr/bin/env python3
import random
arr = list(range(20))
random.shuffle(arr)
print('Original Array: ' + str(arr))
# QUICKSORT
def partition(A, low, high):
pivot = low
for j in range(low, high):
if A[j] <= A[high]:
A[pivot], A[j] = A[j], A[pivot]
pivot+=1
A[pivot], A[high] ... |
import csv
def create_record(number_of_rec):
while number_of_rec:
install_date = raw_input("Enter the Install Date: ")
device_number = raw_input("Enter the Device Number: ")
serv_address = raw_input("Enter the Service Address: ")
serv_city = raw_input("Enter Service City : ")
... |
"""
This script will try to convert pdfs to text files using pdftotext
"""
import pdftotext
import glob
import os
import csv
def convert(path, outfolder, pattern="*.pdf"):
"""convert files in path with pattern and save to outfolder
"""
filelist = glob.glob(os.path.join(path, pattern))
meta = []
if n... |
"""
If else, elseif are supported, space delimited like the rest of python
Brutespray examples
https://github.com/x90skysn3k/brutespray/blob/master/brutespray.py#L161
"""
protocols = {"postgressql":"sql",
"pop3": "email"}
# Trying a get a protocol that does exist
print(protocols["pop3"])
# Trying to ge... |
"""
If else, elseif are supported, space delimited like the rest of python
Brutespray examples
Not in Brutespray but really needs to be
"""
protocols = {"postgressql":"sql",
"pop3": "email"}
people_protocol = [["Steve", "postgressql"],
["Alice", "pop3"],
["Alice", ... |
#bring in file types
import os
import csv
# import the file i'm working on
budgetData_csv = os.path.join('PyBank','Resources', 'budget_data.csv')
# what am I looking for - Total (months)
totalMonths = []
#print(totalMonths)
# net total of profit/losses -
totalAmount = []
# past Amount -
amountVariance = 0
# amount v... |
def isAmbiguous(inputDateString):
dateStringArray = inputDateString.split('/')
first = int(dateStringArray[0])
second = int(dateStringArray[1])
if first <= 12 and second <= 12:
return True
else:
return False
inputDateString = input()
if isAmbiguous(inputDateString):
print("D... |
DIR = {"N" :(0, 1),"S" :(0, -1) ,"E" :(1, 0) ,"W":(-1,0) ,"NE" :(1,1) ,"NW" :(-1, 1) ,"SE" :(1,-1) ,"SW" :(-1,-1)}
def termino(coordinate, directions) :
x = coordinate[0]
y = coordinate[1]
for i in directions :
dir = ""
digit = 0
for j in range(len(i)) :
if ord(i[j]) >=... |
class ArrayStack:
""" LIFO Stack implementation using a Python list as underlying storage. """
def __init__(self):
"""Create an empty stack"""
self._data = []
def __len__(self):
""" Return the number of elements in the stack. """
return len(self._data)
def is_empty... |
class Calculator():
def dodaj(self, a, b):
wynik = a + b
print("Twój wynik dodawania to {}".format(wynik))
def odejmij(self, a, b):
wynik = a - b
print("Twój wynik odejmowania to {}".format(wynik))
def mnozenie(self, a, b):
wynik = a * b
print("Twój wynik m... |
import Clases as c
def convertir_texto_numero(mensaje, min, max):
num = int(mensaje)
if num < min:
raise c.ValorMenorMin()
if num > max:
raise c.ValorMayorMax()
return num
def ingresa_numero(mensaje, min, max):
numero = 0
while True:
try:
texto = input(mensa... |
from dataclasses import dataclass
from typing import List
@dataclass
class Fecha:
dia : int
mes : int
anio : int
@dataclass
class Direccion:
calle : str
altura : int
localidad : str
@dataclass
class Persona:
nombre : str
apellido : str
direcciones : List[Direccion]
fecha_naci... |
from PIL import Image
import os
import sys
# directory = "B:\mozakra\\fourth year\\semester1\\machine learning\\project\\sawery"
directory = raw_input("What is your name? ")
for file_name in os.listdir(directory):
print("Processing %s" % file_name)
image = Image.open(os.path.join(directory, file_name))
x,y = i... |
slides=[]
slides.append("Hello. Press Enter.")
slides.append("How are you?")
slides.append("This is slide number 3")
slides.append("Yes, this is indeed a cli slideshow presentation")
slides.append(r"""
______________________________________
< This is how you do multi-line slides >
-----------------------------------... |
print (63832+750)
print ((20+50+80+120+160+200)*2-20+822)
'''
1,进入各种老虎机,显示账号是吃肉的小花
2,点击hud的齿轮,就回到了大厅
3,水果机进不去
4,没有任务
'''
for i in range(1,10,2):
print (i)
if i%5==4:
print ('bbbb')
break
else:
print (i)
def myaddstr(x):
'str+str'
return(x+x)
print (myaddstr.__doc__)#用来查看函数说明文字的
print (myaddstr(1)) |
def get_number():
numberlist=[]
numbers=open("a.txt",'r').readlines()
for number in numbers:
number.strip('\n')
numberlist.append(number)
list=[]
i=0
for i in xrange(len(numberlist)):
w={'phone':numberlist[i].strip('\n')}
list.append(w)
i+=1
return lis... |
import csv
import re
class Navigate:
# away to get the line number of something we want
@staticmethod
def get_line(word='Why', filename="sample.txt"):
with open(filename) as file:
for num, line in enumerate(file, 1):
if word in line:
return ... |
def function_quarter(x,y):
# x,y = input(), input()
if x > 0:
if y > 0:
print("I quarter")
else:
print("IV quarter")
else:
if y > 0:
print("II quarter")
else:
print("III quarter")
function_quarter(3, 4)
function_quarter(-3.5, 8... |
num = raw_input("Enter a number:")
num = int(num)
if num%2 == 0:
print("Even number.")
else:
print("Odd number.") |
"""Manipulates path."""
import os
import typing as t # NOQA
def get_path_seperator():
# type: () -> str
"""Returns character that seperates directories in the PATH env variable"""
if 'nt' == os.name:
return ';'
else:
return ':'
class PathUpdater(object):
def __init__(self, pat... |
# 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 averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ... |
# 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):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
... |
# how to use argparse?
# https://docs.python.org/3/library/argparse.html
import argparse
# I - The first step in using the argparse is creating an ArgumentParser object:
parser = argparse.ArgumentParser(description='Process some integers.')
# II - Filling an ArgumentParser with information about program arguments i... |
# Non Abundant Sum
# A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the
# proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
# A number n is called deficient if the sum of its proper divisors ... |
"""
Brainfuck to python compiler. Example:
$ cat mul.bf
read a and b
,>,<
| a | b | c | d |
compute c = a*b using d as temp (pointer starts and ends and a)
[
sum b to c and copy in d (ends in b)
>[->+>+<<]
move d in b (ends in d)
>>[-<<+>>]
back on a
<<<-
]
print c
>>.
$ python bpc.py --... |
"""
Blackbody temperature calculations
"""
import numpy as np
import ChiantiPy.tools.constants as const
class blackStar:
"""
Calculate blackbody radiation
Parameters
----------
temperature : `~numpy.ndarray`
Temperature in Kelvin
radius : `~numpy.ndarray`
Stellar radius in cm... |
#Numpy 2-D array
import numpy as np
np_2d=np.array([[1.73,1.68,1.93,1.44],
[65.2,59.7,63.0,66.9]])
print(np_2d)
print(np_2d.shape)
print(np_2d[0][2])
print(np_2d[0,2])
print(np_2d[:,1:3])
print(np_2d[1:])
|
"""Functions to handle currency exchange."""
import requests
from django.conf import settings
class CurrencyRates:
"""Fetch current exchange rates for USD conversion."""
ENDPOINT = "http://api.exchangeratesapi.io/v1/latest"
def __init__(self):
"""Create request and fetch."""
url = (
... |
import turtle
n = 1
a = 30
x = -100
y = 0
turtle.shape('turtle')
turtle.left(90)
for i in range(8):
turtle.penup()
turtle.goto(x,y)
turtle.pendown()
for i in range(360):
turtle.left(1)
turtle.forward(n/4)
for i in range(360):
turtle.right(1)
turtle.forward(n / 4)
... |
# Explanation
# Bubble sort, sorts the array elements by repeatedly moving the largest element to the highest index position.
# In bubble sorting, consecutive adjacent pairs of elements in the array are compared with each other.
# If the element at the lower index is greater than the element at the higher index then th... |
# Video Reference : https://www.youtube.com/watch?v=QN9hnmAgmOc&t=376s
# Quick Sort is based on the concept of Divide and Conquer, just like merge sort
# 1. Select an element pivot from the array element
# 2. Rearrange the element in the array in such a way that all elements that
# are less than the pivot appear bef... |
# Problem Statement Link : https://leetcode.com/problems/power-of-two/
def powerOfTwo(n):
if n < 0: return False
ans = 0
while n:
ans += 1
n = n & (n - 1)
if ans == 1:
return True
else:
return False
n = int(input())
print(powerOfTwo(n))
|
"""
Python has the following data types built-in by default, in these categories:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
"""
x = 5
print(type(x))
|
### imports ###
import face_recognition as fr
import os
import cv2
import face_recognition
import numpy as np
### encode all the face images ###
def encoded_faces():
#looks through the facee_iamges folder and encodes all the faces ###
# returns a dict of (name, image encoded)
encoded = {}
for dirp... |
import sys
import warnings
import matplotlib.pyplot as plt
import numpy as np
from bokeh.plotting import figure, show
from scipy import integrate
class PressureMatrix:
r"""This class calculates the pressure matrix of the object with the given parameters.
It is supposed to be an attribute of a bearing element... |
import ctypes
class Array :
"""Implements the Array ADT using array capabilities of the ctypes module."""
def __init__( self, size ):
"""Creates an array with size elements."""
assert size > 0, "Array size must be > 0"
self._size = size
# Create the array structure using the ct... |
max = 0
num = 0
for i in range(1, 10):
a = int(input())
if a > max:
max = a
num = i
print('%d\n%d' %(max, num)) |
T=int(input())
for _ in range(T):
stack=0
ps=input()
flag=True#for x in ps를 하면 stack이 음수되면 False
for x in ps:
if x =='(':stack+=1
elif x ==')':stack-=1
if stack<0:flag=False
if flag and stack==0:print('YES')
else:print('NO')
'''
1
(()())((()))
''' |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 24 09:33:52 2019
@author: owner
"""
'''
def name(a):
print(a)
name("yasmin")
def my_function(x):
for x in x:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
def y(*num):
sum=0
for n in num:
... |
secret = "1"
guess = input("Guess the secret number...")
match = secret == guess
if match:
print ("Congratulations, you guessed the right number!")
else:
print("I'm sorry. This was not the correct number :(") |
# I hate trying to figure out 2D space in my brain.
import os
# Easy function to parse direction and distance and return a point
def drawWire(Wire):
Points = list()
X = 0
Y = 0
for line in Wire:
direction = line[0:1]
distance = int(line[1:len(line)])
if (direction == "U"):
Y += ... |
import os
from anytree import Node
from anytree.search import findall
def getOrbits(node):
if (node.parent != None):
return 1 + getOrbits(node.parent)
else:
return 0
def findCommonParent(a,b):
commonParent = a
while True:
res = findall(commonParent, filter_=lambda node: node.name == b.nam... |
import sys
import math
import pandas as pd
from collections import Counter
from sklearn.tree import DecisionTreeClassifier
class DecisionNode:
# A DecisionNode contains an attribute and a dictionary of children.
# The attribute is either the attribute being split on, or the predicted label if the ... |
import asyncio
def square_distance(n1=2, n2=4):
"""
distancia cuadrada entre dos números
"""
x_square = (n1.x - n2.x) ** 2
y_square = (n1.y - n2.y) ** 2
return x_square + y_square
def even_odd(n1=0):
"""
calcula par o impar de un número
devuelve True si es par y False si es impa... |
from random import SystemRandom
sr = SystemRandom()
def generate_password(length, valid_chars = None):
if valid_chars == None:
valid_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
valid_chars += valid_chars.lower() + "0123456789"
password = ""
counter = 0
while counter < length:
rnum = s... |
from bulls_and_cows.combinatorics import all_colors
def inconsistent(p, guesses):
"""
The function checks, if a permutation p is consistent with the previous
colors. Each previous color permutation guess[0] compared with p has to
return the same amount of blacks and whites as the corresponding
eva... |
'''
Calculate the runtime of the following recursive binary search function.
HINT:
The function contains a subtle runtime bug due to memory management.
This bug causes the runtime to not be O(log n).
'''
def binary_search(xs, x):
'''
Returns whether x is contained in xs.
>>> binary_search([0,1,3,4],1)
... |
#To make game of hangman
def HangManOyy(question,answer):
import random
from os import system
ra=answer.upper() if answer.upper()==answer else answer.lower()
take=""
turn=3#The tries
while(turn>=0):
fail=0
print('\nYour question is : ',question)
for char in ra:
... |
lst=[1, 2 ,3, 4, 3, 3, 2, 1]
new_lst=list()
_min=0
while(lst!=[]):
new_lst.append(len(lst))
_min=min(lst)
lst=[i for i in lst if i != min(lst)]
for i in range(len(lst)):
lst[i]= lst[i]-_min
print(new_lst) |
def to_fahrenheit (temperature):
fahrenheit = (temperature * (9 / 5)) + 32
return fahrenheit
def to_celsius (temperature):
celsius = (temperature - 32) * (5 / 9)
return celsius
def to_kelvin (temperature):
#print("tc")
#print(to_celsius(212))
kelvin = temperature + 273.15
return kelvin
f = to_f... |
#do slice to trip the space(method 1)
def trim(s):
item1 = 0
item2 = -1
while item1 < len(s):
if s[item1] == ' ':
item1 += 1
else:
break
while item2 > -len(s):
if s[item2] == ' ':
item2 -= 1
else:
break
return s[item1 : len(s) + item2 + 1]
if trim('hello ') != 'hello':
print('测试失败!'... |
#判断回数(121,1331,1221等)
'''
from functools import reduce
digits = {'0' : 0, '1' : 1, '2' : 2, '3' : 3, '4' : 4, '5' : 5, \
'6' : 6, '7' : 7, '8' : 8, '9' : 9}
def str2num(s):
return digits[s]
def fn(x, y):
return 10 * x + y
def is_palindrome(n):
if n < 10:
return True
else:
s = str(n)
L = list(map(str2nu... |
from functools import reduce
digits = {'0' : 0, '1' : 1, '2' : 2, '3' : 3, '4' : 4, '5' : 5, \
'6' : 6, '7' : 7, '8' : 8, '9' : 9}
def str2int(s):
def chr2num(s):
return digits[s]
return reduce(lambda x, y: 10 * x + y, map(chr2num, s))
S = input("Input your string:")
print(str2int(S))
print(type(str2... |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 13 00:46:30 2020
@author: nnath
"""
#DATA VISUALIZATION FOR DATAT SCIENCE
'''
Popular plotting libaries
MATPLOTLIB : to create 2D graphs ; uses numpy internally
PANDAS VISUALISATION : built on Matplotlib
SEABORN : High level interface for attractive an... |
import math
# Returns the lcm of first n numbers
def lcm(n):
ans = 1
for i in range(1, n + 1):
ans = int((ans * i)/math.gcd(ans, i))
return ans
# main
n = 20
print (lcm(n))
|
import json
def are_equal_lists(list1, list2):
"""Check if two lists contain same items regardless of their orders."""
return len(list1) == len(list2) and all(list1.count(i) == list2.count(i) for i in list1)
def load_json_data(json_file_path):
with open(json_file_path, 'r') as json_file:
return ... |
from tkinter import *
cal= Tk()
cal.title("Calculator")
expression = ""
cal.iconbitmap('E:\calculator.ico')
cal.config(bg="gray25")
def add(value):
global expression
expression += value
label_display.config(text=expression)
def clear():
global expression
expression = ""
label_display.config... |
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
Node = pHead
ppre = None
pnext = None # 设置了三个指针
re = None
while (N... |
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
row_N = len(array)
col = len(array[0]) - 1
if (row_N > 0 and col > 0): # 至少要有一行和一列,才能进行循环
row = 0
while (row < row_N and col >= 0): # 遍历完所有行和列的时候终止循环
... |
# -*- coding:utf-8 -*-
class Solution:
min_stack = []
data = []
def push(self, node):
# write code here
self.data.append(node)
if len(self.min_stack)==0 or node < self.min_stack[-1]: #倒数第一个元素
self.min_stack.append(node)
else:
self.min_stack.append... |
# -*- coding:utf-8 -*-
class Solution:
def reOrderArray(self, array):
# write code here
odd = []
even = []
for num in array:
if num&(2-1) == 1: #用位与计算代替求余,判断奇
odd.append(num)
if num&(2-1) == 0: #用位与计算代替求余,判断偶
even.append(num)
... |
# -*- coding:utf-8 -*-
class Solution:
def rectCover(self, number):
# write code here
r1 = 1
r2 = 2
if number < 3:
return number
else:
for i in range(3,number+1):
fn = r1+r2 # 横着放时,必须同时横放两个才不会出现覆盖
r1,r2 = r2,fn
... |
# 13. Escreva um programa que substitua ‘,’ por ‘.’ e ‘.’ por ‘,’ em uma string. Exemplo: 1,000.54
# por 1.000,54.
myname = input('Qual é o seu nome? ====>>>: ')
print()
numantigo = input(myname + ', digite um número com vírgulas para as partes inteiras e ponto para as partes decimais: ')
print()
numnovo = numantig... |
a=int(input("Digite o Primeiro Número")) #Converte em inteiro, aplicado aos demais tipos da linguagem
b=int(input("Digite o Segundo Número"))
for x in range(a,b):
if (x%4)==0:
print(x) |
#!/usr/bin/python
m_palidromes = []
def isPalindrome(m_num, m_palidromes):
if ( str(m_num) == str(m_num)[::-1] ):
m_palidromes.append(m_num)
return m_palidromes
for m_left in xrange(999, 100, -1):
for m_right in xrange(999, 100, -1):
m_palidromes = isPalindrome(m_left * m_right, m_palidromes)
m_palidr... |
class Token():
def __init__(self,Tipo,caracter): #Constructor de la clase animal
self.Tipo=Tipo #usamos la notacion __ por que lo estamos encapsulando, ninguna subclase puede acceder a el, es un atributo privado
self.caracter=caracter
def setTipo(self,Tipo):
self.__Tipo=Tipo ... |
#!/usr/bin/env python
import sys,os,argparse
def main():
it = get_args()
try:
file = open(it.thefile,'r')
except:
print "cant open file: ",it.thefile,"."
print "we will replace ",it.searcher," with ",it.replacer, \
" in the file ",it.thefile," and output that to the screen"
for lines ... |
# -*- coding: UTF-8 -*-
import time
from copy import deepcopy
board_size = 0
def read_data(filename):
"""根据文件名读取board
:param filename:
:return:
"""
board = []
# 限制分为大于,小于两部分存,为了后面检查限制的时候更方便
comparison_constraint = []
with open(filename) as f:
global board_size
board_si... |
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
pd.set_option('max_columns', 15)
#loading the datasets
train = pd.read_csv('train_Df64byy.csv')
test = pd.read_csv('test_YCcRUnU.csv')
target = 'Response'
ID = test['ID']
#First look to the data
train.head()
#Some basic sta... |
# Process the word list
# Remove the words that has numbers/special characters
f = open("words.txt","r")
print f
myList = []
for line in f:
if line.strip().isalpha():
myList.append(line)
print len(myList)
f = open("english_words.txt",'w')
for i in myList:
f.write(i) |
"""Custom topology example
author: Brandon Heller (brandonh@stanford.edu)
Two directly connected switches plus a host for each switch:
host --- switch --- switch --- host
Adding the 'topos' dict with a key/value pair to generate our newly defined
topology enables one to pass in '--topo=mytopo' from the command l... |
#pragma once
#include "Tile.h"
class Tile:
# char ,char ,Piece*
""" The function creates the class variable of the Bishop
Input- bishop's x, bishop's y, piece to set on tile
Output- none """
def __init__(self, x, y, piece = None):
self._x = x
self._y = y
self._piece = piece
""" The function returns the... |
__author__ = 'longqi'
'''
import time
run = raw_input("Start? > ")
mins = 0
# Only run if the user types in "start"
if run == "start":
# This is saying "while we have not reached 20 minutes running"
while mins != 20:
print ">>>>>>>>>>>>>>>>>>>>>", mins
# Sleep for a minute
time.sleep(60)... |
dezena = input("Digite um número inteiro:")
dezena = int(dezena)
valor = dezena // 10
valor = valor % 10
print("O dígito das dezenas é",valor) |
def fatorial(k):
'''(int) -> int
Recebe um inteiro k e retorna o valor de k!
Pre-condicao: supoe que k eh um numero inteiro nao negativo.
'''
if k == 0:
k_fat = 1
else:
k_fat = k * fatorial(k - 1)
return k_fat
# testes
print("0! =", fatorial(0))
print("1! =", fatorial(1)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.