text stringlengths 37 1.41M |
|---|
from __future__ import print_function
import numpy
from logistic_regression import LogisticRegression
from hidden_layer import HiddenLayer
import theano.tensor as T
class MLP(object):
"""Multi-Layer Perceptron Class
A multilayer perceptron is a feedforward artificial neural network model
that has one ... |
#Rajouter une situation où certains nodes ne peuvent plus bouger (drône en panne)
#-> définir une nouvelle liste où l'on met les nodes statiques
#-> ou un paramètre booléen dans la class node pour indiquer si le noeud peut bouger ou non.
#Source for mathematique: https://fr.wikibooks.org/wiki/Math%C3%A9matiques_avec_... |
#coding=utf-8
#遍历 字符串 ,列表,元组,字典等数据结构
#字符串遍历
mystr = "welcome to young world"
for char in mystr :
print char,' ',
print ''
#列表遍历
mylist = [1, 2, 3, 4, 5]
for num in mylist :
print num ,
print type(num)
print ''
#元组遍历
myturple = (1, 2, 3, 4, 5)
for num in myturple :
print num,
print ''
... |
#coding=utf-8
#
#
#创建对象后,python解释器默认调用__init__()方法;
#当删除一个对象时,python解释器也会默认调用一个方法,这个方法为__del__()方法
import time
print 'test1 析构'
class animals(object) :
#初始化方法,创建对象后会自动被调用
def __init__(self, name) :
print '__init__方法被调用'
self.__name = name
#析构方法,当对象被删除时候,会自动被调用
def __del__(self) :
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Question:
You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.
B... |
# Ezequiel Zapata PSID: 001863257
# part 1 a program that reads words in a list and outputs the word and its frequency. Caps sensitive.
words = input().split()
for word in words:
count = 0
for w in words:
if w == word:
count += 1
print(word, count) |
# Ezequiel Zapata PSID: 001863257
# We will take input from the user and return date if input is in correct format, else it will ignore string.
def extract_date(date):
correct_date = 0
n_date = ""
if date.find(",") != -1:
month_day, year = date.split(',')
if month_day.find(" ") ... |
# Global variable
num_calls = 0
# TODO: Write the partitioning algorithm - pick the middle element as the
# pivot, compare the values using two index variables l and h (low and high),
# initialized to the left and right sides of the current elements being sorted,
# and determine if a swap is ... |
# Online Python compiler to write code and run Python online
a = input("Enter a number ")
print("1",int(a)*1)
print("2",int(a)*2)
print("3",int(a)*3)
print("4",int(a)*4)
print("5",int(a)*5)
print("6",int(a)*6)
print("7",int(a)*7)
print("8",int(a)*8)
print("9",int(a)*9)
print("10",int(a)*10) |
# Defining and Visualizing Simple Networks (Python)
# prepare for Python version 3x features and functions
from __future__ import division, print_function
# load package into the workspace for this program
import networkx as nx
import matplotlib.pyplot as plt # 2D plotting
import numpy as np
# -----------... |
class Solution:
def climbStairs(self, n: int) -> int:
options = [0,1,2]
if n > 2:
for x in range(3, n+1):
options.append(options[x-1]+options[x-2])
return options[n]
|
# PARA IMPRIMIR CAPICUAS DE 5 DÍGITOS DE MANERA SIMPLE
# @samusisto - UNRN, Ingeniería en computación
# respondiendo al desafío del profe de prog I
def prueba():
for i in range(10):
for j in range(10):
for k in range(10):
print(f"{k}{j}{i}{j}{k}")
if __name__ == "... |
#encoding:utf-8
from sys import argv
script,input_file=argv#将argv赋值与script,input_file
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_a_line(line_count,f):
print line_count,f.readline()#readline()第一次接触
current_file=open(input_file)
print "First,let's print the whole fil... |
#encoding:utf-8
#总共有100辆车
cars =100
#每辆车可以坐四个人
space_in_a_car=4.0 #If there are 2.8 people average in each cars,we got 2,that's a waste.
#总共有30个司机
drivers=30
#目前有90个乘客待送
passengers=90
cars_not_driven=cars-drivers
cars_driven=drivers
carpool_capacity=cars_driven*space_in_a_car
average_passengers_per_car=passengers/cars... |
#encoding:utf-8
def add(a,b):
print "ADDING %d+%d"%(a,b)
return a+b
def subtract(a,b):
print "SUBTRACTING %d -%d"%(a,b)
return a-b
def multiply(a,b):
print "MULTIPLY %d *%d"%(a,b)
return a*b
def divide(a,b):
print "DIVDIDING %d / %d"%(a,b)
return a/b
print "Let's do ... |
#encoding:utf-8
print "Let's practise everything."
print 'You\' d need to know \'bout escape with \\ that do \n newlines and \t tabs.'
poem ="""
\t The lovely world
with magic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\twhere there is none.... |
Dict = {'Karthik':29, 'Karthik':'Good boy', 'Keyan':28, 'abc':0, 'Abc':'this is different key', 'xyz':11}
print(Dict)
print(Dict.items())
print(Dict['Keyan'])
copiedDict = Dict.copy();
print(copiedDict)
copiedDict.update({'a':111})
print(copiedDict)
#copiedDict.add({'b':111}, {'c':111}, {'d':111} )
#print(copiedDi... |
import time
from math import sqrt
def solution2(n):
answer = 0
for i in range(2, n+1):
flag = True
for j in range(2,i):
if i%j==0:
flag = False
break
if flag : answer = answer + 1
return answer
def solution(n):
#에레스토테네스의 체
list =... |
#Queue Implementation
class Queue:
def __init__(self):
self.item=[]
def enqueue(self,item):
self.item.insert(0,item) #O(N) and rest all methods are O(1) constant time
def dequeue(self):
if self.item:
return self.item.pop()
else:
ret... |
#Composition :-creating relationship between classes and its objects.
class Book:
def __init__(self, title,price,author=None):
self.title=title
self.price=price
self.author=author
self.chapter=[]
def addchapter(self,chapter):
self.chapter.append(chapter)
... |
#Instance method and attributes
class book:
def __init__(self,Title,Pages,Price):
self.Title=Title
self.Pages=Pages
self.Price=Price
self.__secret='This is secret'
def getprice(self):
if hasattr(self, "_discount"): #hasattr important function to ... |
#More into Self
class myclass():
schoolname="St. Xaviers"
Batch="A2"
#Basically self is an object which refers to this particular instance
def func1(self):
return self.schoolname
def main():
if False:
print(1)
elif True:
print(2)
elif True:
... |
# # #Revision
# # x=0
# # while(x<10):
# # print(x,end='')
# # x+=1
# # for i in range(5,10):
# # if i%2==0:
# # break
# # print(i,end='')
# # l1=['hi','hello','bye','goodbye']
# # for i in l1:
# # print(i)
# # for i,v in enumerate(l1):
# # print(f'index={i},value={v... |
def sentence_maker(phrases):
questions=("how","where","when","why","what")
capitalized = phrases.title()
if phrases.startswith(questions):
return "{}?".format(capitalized)
else:
return "{}.".format(capitalized)
print(sentence_maker("what are you"))
total=[]
final=''
while True:
mess... |
# 1. Write a program which accepts a string as input to print "Yes" if the string is "yes",
# "YES" or "Yes", otherwise print "No".
# Hint: Use input () to get the persons input
#string = input("enter a string")
# if string = "yes":
# print("YES")
# else:
# print("NO")
y3= input("please enter a string:")... |
# for i in range(10):
# print(i+2)
# for every in range(10):
# print(every)
# continue takes what is below it
# for every in range(10):
# print(every)
# if every == 5:
# continue
# print("Jacque")
# break
days= ["M","T","W","T", "F"]
for day in days:
print(day)
|
#calsswork example 4 , loops
from random import randrange #this is to be able to use randrange for the random number generator
print("Random number guessing name ")
print("Written by Franklin Araque")
print("\n you get 5 guessese to guess the number between 1 and 100")
#random number selector
rando... |
def dodivision(a,b);
return (a/b) # Return the quotient of a and b
a = int(input("Enter a"))
b = int(input("Enter b"))
res=dodivision(a,b)
print(res) |
import random
def insertion_sort(array:list, stop=0):
if stop== len(array)-3:
return array
print(f'{stop} Iteracion = {array}')
print('')
for i in range(1,len(array)):
if array[i]<array[i-1] :
array[i], array[i-1] = array[i-1], array[i]
... |
A = float(input())
if ( 400>=A and A>=0):
Reajuste1 = ((A/100)*15)+ A
ReajusteG1 = Reajuste1 - A
print ("Novo salario: %.2f" % Reajuste1)
print ("Reajuste ganho: %.2f" % ReajusteG1)
print ("Em percentual: 15 %")
elif ( 400>A and 800>=A):
Reajuste2 = ((A/100)*12)+ A
ReajusteG2 = Reajuste2 - A
print ("Novo sal... |
N = int(input())
resp = N**2
Zero = 0
for i in range (1,N+1):
if i%2==0 :
resp = i**2
print("%d^2 = %d" %(i,resp)) |
"""
ML lab 11-3
CNN using class
CNN using Layers
"""
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
class Model:
"""
img_x : 이미지의 가로 픽셀 사이즈
img_y : 이미지의 세로 픽셀 사이즈
label : 정답 label의 사이즈
"""
def __init__(self, session, img_x, img_y, label):
self.sess =... |
"""
Author: Chris Bruns
Title: HW3.py
Description:
"""
import itertools
def possibleMoves(boardList, changeItems, goalState):
"""
Takes in the original input board. The possible moves (changeItems) is iterated
through and all possible combinations are created. This is then used to compare
to the indexe... |
print("#하나만 출력1")
print()
print("#하나만 출력2","abce",sep="\n", end="\n\n")
print("결과" ,end="\n\n")
print(type("하나만"), type(12), type(12.5), sep='\n', end='\n\n')
print("안녕하세요\n"*5)
print("안녕하세요"[0])
print("안녕하세요"[1])
print("안녕하세요"[2])
print("안녕하세요"[3])
print("안녕하세요"[4])
print("안녕하세요"[-2])
print("안녕하세요"[-3])
print("안녕하... |
tuple_test1 = (10,20,30)
# tuple_test2 = tuple(10,20,30)
tuple_test2 = 10,20,30
list_test1=[1,2,3]
print("tuple_test1",tuple_test1, type(tuple_test1), end='\n\n')
print("tuple_test2",tuple_test2, type(tuple_test2), end='\n\n')
print("list_test1",list_test1,type(list_test1),end='\n\n')
# 튜플은 수정불가능, 리스트는 수정가능
list_test... |
example_list = ["요소A","요소B","요소C"]
i = 0
print("# 단순 출력")
print(example_list)
print()
print("#enumerate()함수 적용 출력")
print(enumerate(example_list))
print()
print("#list() 함수로 강제 변환 출력")
print(list(enumerate(example_list)))
print()
print("#반복분과 조합하기")
for i, value in enumerate(example_list):
print("{}번째 요소는 {}입니다... |
import json
data = '{"name1" : "Satya", "Age": 26}'
parse_data = json.loads(data)
print(parse_data)
print(parse_data['Age'])
'''
Difference Between json.load and json.load
json.loads = accepts data in string format
json.load = accepts the file path inside which json data is present
json.dumps = accepts data in st... |
class Car:
# class variables
# when a class variable is changed by an object, then system creates an instance variable for that object
wheels = 4
# any variable defined inside method or constructor, then it's called instance variable
# constructor of the pass
# Meaning of self is the object on... |
# Tuple is a collection of elements of any type
# But it can't be modified as it's immutable
# syntax names = (1,2,3)
# Tuple is order based i.e. stores data according to index
names = ("java","js","python")
# names[1] = ".net" --> not allowed to change
print(names)
#to delete the object from memory
del nam... |
#while
count = 0
while(count<=3):
print(count)
count+=1;
count1 = 0
while(count1<=3):
print(count1)
count1+=1;
else:
print("Reached the Number")
#For Loop
name = ["java","python","js"]
for i in name:
print(i)
str = "I am loving python"
for i in str:
print(i)
#Range --> excluding the ... |
# Global Variable
i = 10
def try_a_fun(n):
# if the below line is not used, then error will be thrown
global i
i += 1
k = 23
print(n)
print(i)
try_a_fun(22)
#######################################################
rr = 10
def test_local_global():
# the below rr is the local scope tp the fun... |
class Employee:
no_of_leaves = 8
def __init__(self, arg_name, arg_salary, arg_age):
self.name = arg_name
self.salary = arg_salary
self.age = arg_age
def print_name(self):
print(f'Employee name is {self.name}, salary is {self.salary}, and age is {self.age}')
# static m... |
def max(a, b):
if a > b:
return a
return b
def f(a, i, j, value, p):
value += a[i][j]
if (i == 0) and (j == 0):
if p[i][j].find('*') == -1:
p[i][j] += "*"
return value
if i == 0:
return f(a, i, j - 1, value, p)
elif j == 0:
return f(a, i - 1,... |
import random
BIN = [1, 2, 4, 8, 16, 32, 64, 124, 256, 512, 1024]
def find(ar):
result = []
for el in ar:
if el in BIN:
result.append(el)
return result
if __name__ == "__main__":
array = []
for i in range(int(input(''))):
array.append(random.randrange(1000))
prin... |
def sequences(lst : list, k, n):
"""
:param lst: підсписок перестановок
:param k: елемент для вставки
:param n: найбільший елемент послідовності
:return: None
"""
if k > n: # Якщо всі елементи вже вичерпано
return
# Вставляємо елемент k у всі можливі позиції списку
#... |
class Solution(object):
def shortestDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
i1, i2 = -1, -1
res = len(words)
for i, w in enumerate(words):
if w == word1:
... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
from heapq import *
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
h = []
... |
import unittest
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
count = 0
if n == 0:
return 0
while n != 0:
n &= (n-1)
count += 1
return count
class Test(unittest.TestCase):
... |
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
front = 0
back = len(nums)-1
i = 0
while i <= back:
if nums[i] == 0:
nums[i... |
import unittest
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
int_char = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ans_str = ""
while n != 0:
if n % 26 != 0:
ans_str = int_char[n % 26] + ans_str
... |
# 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 closestValue(self, root, target):
"""
:type root: TreeNode
:type target: float
:rtype... |
from collections import defaultdict
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
dict = defaultdict(list)
for str in strs:
dict[''.join(sorted(str))].append(str)
return [... |
from collections import OrderedDict
class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.dict = OrderedDict()
self.cap = capacity
def get(self, key):
"""
:rtype: int
"""
if key in self.dict:
... |
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[... |
# 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 binaryTreePathsHelper(self, root, s):
"""
:type root: TreeNode
:rtype: List[str]
"""
... |
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
results = []
resultsSet = set()
nums.sort()
for i in range(0, len(nums)-2):
num = nums[i]
l, r = i+1, len(nums)-1
... |
import unittest
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
s = str(x)
if s[0] == "-":
if int(s[0] + s[1:][::-1]) < -2147483648:
return 0
else:
return int(s[0] + s[1:][::-1])
... |
import unittest
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
def push(self, x):
"""
:type x: int
:rtype: nothing
"""
current_min = x if len(self.stack) == 0 or x < self.getMin()... |
class Solution(object):
def walk(self, dist, r, c, rooms):
row = len(rooms)
col = len(rooms[0])
if not (0 <= r < row and 0 <= c < col):
return
if rooms[r][c] < dist:
return
rooms[r][c] = dist
self.walk(dist+1... |
from random import *
from time import *
from copy import copy
def swap(A, i, j):
temp = A[i]
A[i] = A[j]
A[j] = temp
def lomutoPartition(A, lo, hi):
pivot = A[hi]
i = lo
for j in range(lo, hi):
if A[j] <= pivot:
swap(A, i, j)
i += 1
swap(A, i, hi)
return i
def hoarePartitio... |
from classes import lnAndDelay
import classes
from classes import Player
def world1lev1():
lnAndDelay("INTO THE TEXT", 3)
lnAndDelay("By: Caden Fischer", 3)
print()
lnAndDelay("A New Adventure awaits, {}!".format(Player.name), 4)
lnAndDelay("You awake from a deep sleep.", 1.5)
lnAndDelay("You f... |
num=0
while num<100:
print(num+1)
num=num+1
|
r=int(input("Enter no. of rows :"))
r=r-1
i=0
j=0
while i<r+1:
for col in range(0,2*r+1):
if col in range(r-j,r+j+1):
print("*",end="")
else :
print(" ",end="")
print("\n")
j=j+1
i=i+1
|
class Pow:
def __init__(self,n=2,m=0):
self.m=m
self.n=n
def __iter__(self):
self.c=1
return self
def __next__(self):
if self.c<=self.m:
self.c=self.c+1
r=self.n**self.c
return r
else:
raise StopIteration("you h... |
def hello():
print("first")
yield 1
print("second")
yield 2
print("third")
yield 3
print("fourth")
yield 4
print("fifth")
yield 5
hello()
p=hello()
next(p)
next(p)
next(p)
next(p)
next(p)
next(p)
next(p)
|
x=input().split(",")
l=[]
for var in x:
t=int(var)
l.append(t)
print(l)
|
username = input('Введите имя: ')
userlast = input('Введите фамилию: ')
userage = int(input('Введите год рождения: '))
userplace = input('Введите место рождения: ').capitalize()
userage1 = 2018 - userage
print('Hello', username, userlast, 'You are ', userage1 , 'years old. You are living in ', userplace) |
a = []
user = input('Введите число : ')
b = 'end'
while True:
if user == b:
break
uint = int(user)
a.append(uint)
markia = sum(a)
user = input('Введите число: ')
average = markia / len(a)
print('you entered: ', a)
print('Total: ', markia)
print('Average: ', average) |
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr)//2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i = 0
j = 0
k = 0
while i < len(left_half) and j < len(right_half):
if left_half[i]... |
#Coinflip game
import random
from time import sleep
import math
def coinflip():
heads = 0
tails = 0
flips = 0
for i in range(3):
result = random.randint(0,1)
flips += 1
sleep(1)
if result == 0:
heads += 1
print("Heads")
... |
#!/usr/bin/python
# Animal.py
class Animal:
############################
# Helping function
############################
def __pi(self,s):
return (s)
############################
# Manager function
############################
# Including a default contrutctor
def __init__(... |
import csv
#read the csv file
with open('file1.csv', 'r') as input_file:
file_read = csv.DictReader(input_file)
with open('file2.csv', 'wb') as file_write:
# column names to be included in file
columnNames = ['ParkName', 'State', 'partySize', 'RateType', 'BookingType', 'Equipment']
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Создайте списки:
# моя семья (минимум 3 элемента, есть еще дедушки и бабушки, если что)
my_family = ['father', 'mather', 'sister', 'brother']
# список списков приблизителного роста членов вашей семьи
my_family_height = [
['father', 180],
['mother', 165],
... |
#In this assignment you will write a Python program that expands on https://www.py4e.com/code3/urllinks.py. The program will use urllib to read the HTML from the data files below, extract the href= vaues from the anchor tags, scan for a tag that is in a particular position from the top and follow that link, repeat the ... |
def get_answer(question, answers):
return answers.get(question)
myanswers = {"привет": "И тебе привет!", "как дела": "Лучше всех", "пока": "Увидимся"}
#input(question)
# r = get_answer("привет", myanswers)
# print(r)
# r = get_answer("как дела", myanswers)
# print(r)
q = input("Что скажешь?\n")
r = get_answer(q, ... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if(head==None or head.next==None):
... |
import re
name_age_sentence : str = '''
Jack is of age 21 and Jill is of age 18
Tom is of age 8 and Jerry is of age 4
Groot is of age 1 and Rocket is of age 2
'''
ages :dict = re.findall(r'\d{1,3}', name_age_sentence)
names :dict = re.findall(r'[A-Z][a-z]*', name_age_sentence)
age_dict :dict = {}
x=0
for name in na... |
import sys
def str(n):
_str = ""
_toBeAppended = "0"
for x in range(1, n):
_str += _toBeAppended
return n
n = int( sys.argv[1] )
# print n
print str(n) |
from typing import List
class CollisionDetection:
"""
Parameters for how a Magnebot handles collision detection.
"""
def __init__(self, walls: bool = True, floor: bool = False, objects: bool = True, mass: float = 8,
include_objects: List[int] = None, exclude_objects: List[int] = None... |
def relative_strength_index(df, base, target, period=8):
"""
Function to compute Relative Strength Index (RSI)
df - the data frame
base - on which the indicator has to be calculated eg Close
target - column name to store output
period - period of the rsi
"""
delta = df[base].diff()
... |
def getRow(rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
row = [1]
for _ in range(rowIndex):
a = [0] + row
b = row + [0]
row = [sum(x) for x in zip(a, b)]
return row
print (getRow(3)) |
def hammingWeight(n):
"""
:type n: int
:rtype: int
"""
if not n:
return 0
count = 0
for _ in range(32):
a = n & 1
if a == 1:
count += 1
n = n >> 1
return count
print (hammingWeight(11))
|
def trailingZeroes(n):
"""
:type n: int
:rtype: int
"""
res = 0
x = 5
while n >= x:
res = res + n / x
x = x * 5
return res
print (trailingZeroes(10)) |
def lengthOfLastWord(s):
sn = s.split()
if sn:
s_last = sn[-1]
return len(s_last)
else:
return 0
s = ' '
print (lengthOfLastWord(s)) |
def wordPattern(pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
t = str.split()
a = map(pattern.find, pattern)
b = map(t.index, t)
return a == b
print (wordPattern("abba", "dog cat cat dog"))
|
def thirdMax(nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = list(set(nums))
nums.sort()
if len(nums) >= 3:
return nums[-3]
else:
return nums[-1]
print (thirdMax([1, 2]))
|
def power1(x, y):
if y == 0:
return 1
if y % 2 == 0:
return power1(x, y / 2) * power1(x, y / 2)
else:
return x * power1(x, y / 2) * power1(x, y / 2)
print (power1(2, 4)) |
import random
def strip_elem(elem):
elem = elem.strip()
elem = elem.strip('.,?!()')
return elem
def split_text():
f = open('словосочетания.csv', 'r')
b = {}
string = f.read()
string.lower()
temp = string.split()
if string:
for i in range(0,len(temp),2):
... |
def split_text(d):
f = open(d, 'r', encoding = 'utf-8')
b = []
string = f.read()
string.lower()
if string:
for word in string.split():
word = word.strip()
b.append(word.strip('.,?!()'))
f.close()
return b
def printing(d):
for elem... |
#codigo01
import sys
nome = input ("Digite seu nome:")
idade = input ("Digite sua Idade:")
print ("Digite seu sexo:")
sexo = sys.stdin.readline()
print("Nome:" +nome +"\n" + "Sexo: %s Idade: %s" %(sexo,idade))
#Codigo teste 02
# coding:utf-8
dedos = int(input("Voçê tem quantos Anos?"))
if dedos == ... |
from board.board import Board
class Game:
def __init__(self, upper_player, lower_player):
"""Instantiate a Mancala game."""
self.board = Board()
self._upper_player = upper_player
self._lower_player = lower_player
self._current_player = self._upper_player
def play(se... |
##count = 0
##
##while count < 10:
## if isinstance(count / 3.0, int)
## numThree += 3
##print int in range (1-10, 3)
##i = 0
f = -3
for i in range(0, 10, 3):
print i
f += 3
print f
|
# Google spreadsheet/map of hometowns and travel routes
# instructions on how to do this with Sheets instead of a CSV: https://www.twilio.com/blog/2017/02/an-easy-way-to-read-and-write-to-a-google-spreadsheet-in-python.html
# note: doing the mapping part with live Google API requires giving a credit card and being ch... |
import re
# Regular expressions used to tokenize.
_WORD_SPLIT = re.compile(b"([.,!?\"':;)(])\t")
_DIGIT_RE = re.compile(br"\d")
_PAD = b"_PAD"
_GO = b"_GO"
_EOS = b"_EOS"
_UNK = b"_UNK"
_START_VOCAB = [_PAD, _GO, _EOS, _UNK]
PAD_ID = 0
GO_ID = 1
EOS_ID = 2
UNK_ID = 3
def basic_tokenizer(sentence):
"""Very bas... |
import pandas as pd
import xlsxwriter
# --------------------- custom rows------------------#
def getrows(num):
row_sel=input('for sheet '+str(num+1)+' discrete, continuous or all rows please enter D/C/A?\n')
chk2 = row_sel.lower()== 'd'
chk1=row_sel.lower()=='c'
chk3 = row_sel.lower()=='a'
... |
import sys
# comment
'''
multi-line comment
num = raw_input('What is your fave float? ')
print float(num) + 1
with open('numbers.txt', 'rb') as file:
for line in file.readlines():
print line.rstrip()
print('automatically prints newline')
#print 'doesnt print newline because of comma',
# how to do no newline ... |
#!/usr/bin/python
__author__ = 'chukwuyem'
#source: https://www.hackerrank.com/contests/countercode/challenges/campers
#this worked!!!
def main():
n, k = raw_input('').split(' ')
m_team_id = [] #list with sniper ids and ids consecutive to sniper ids
for x in raw_input('').split(' '):
m_team_id.a... |
from collections import Counter, defaultdict, namedtuple
mylist = [1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,3]
a = Counter('aaabbccccccdddddddd')
# print(a['a'])
# print(Counter(mylist))
letters = 'aaaaaabbbbcccccdddd'
letter_class = Counter(letters)
#print(letter_class.most_common(1)) # most common letter
j = list(le... |
"""
判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-sudoku
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
from collections import defaultdict
class Solution:
def isValidSudoku(self, board: List[Lis... |
# 给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。
#
#
#
# 说明:
#
#
# 初始化 nums1 和 nums2 的元素数量分别为 m 和 n 。
# 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
#
#
#
#
# 示例:
#
# 输入:
# nums1 = [1,2,3,0,0,0], m = 3
# nums2 = [2,5,6], n = 3
#
# 输出: [1,2,2,3,5,6]
# Related Topics 数组 双指针
# leetcod... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.