text stringlengths 37 1.41M |
|---|
"""This module defines a preprocess function to call to preprocess tweets before loading into a database."""
import re
import string
import pytest
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize, sent_tokenize
from xml.etree import ElementTree
import numpy ... |
import sys
from enum import Enum
class TICPCommand(Enum):
"""Enumeration for Command Opcodes of the TICP Protocol.
This Class is a specialization of the Enum class.
Use this Enumeration für decoding 8 bit Message Blocks to the corresponding Opcode
Example:
The easiest way to initialize an TIC... |
# rstrip, lstrip, strip: will not change the string itself.
str1 = " Test Test Test "
# rstrip
print(str1.rstrip())
# lstrip
print(str1.lstrip())
# strip
print(str1.strip())
|
# RUN = 32
#mengurutkan indeks dari kiri ke kanan dengan ukuran yang paling besar pada RUN
def insertionSort(arr, left, right):
for i in range(left + 1, right+1):
temp = arr[i]
j = i - 1
while arr[j] > temp and j >= left:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = temp
# menggabungkan nilai y... |
def functionselection(llist):
for i in range(len(llist)):
#mencari elemen terkecil
min_idx = i
for j in range(i+1, len(llist)):
if llist[min_idx] > llist[j]:
min_idx = j
#menukar elemen terkecil dengan elemen pertama ... |
"""CSC148 Assignment 2
=== CSC148 Winter 2020 ===
Department of Computer Science,
University of Toronto
This code is provided solely for the personal and private use of
students taking the CSC148 course at the University of Toronto.
Copying for purposes other than this use is expressly prohibited.
All forms ... |
s1=input("Enter comma-separated alphabets:")
lis=s1.split(",")
tup=tuple(lis)
print(tup)
print("SECOND METHOD")
lis1=[]
s2=input("Enter a string:")
for i in s2:
lis1.append(i)
tup1=tuple(lis1)
print(tup1)
print("THIRD METHOD")
l1=[]
while(True):
s2=input("Enter an alphabet:")
if(s2.isalpha()):
l1.ap... |
import random
import string
def generate_password(password_length):
random_source = string.ascii_letters + string.digits + string.punctuation
password = random.choice(string.ascii_lowercase)
password += random.choice(string.ascii_uppercase)
password += random.choice(string.digits)
password += rando... |
import sys
import timeit
# Tuples are orderd, immutable, allows duplicate elements
intelcpu = ("3.2Gz", 2019, "genuine")
print(intelcpu)
# mytuple = ("max",) <= string, end with , to make it tuple
# Create tuple from list with 'tuple' keyword
user = tuple(["Max", 28, "Boston", "BS Computer Science", "WSU"])
print(user... |
NAMES = ['arnold schwarzenegger', 'alec baldwin', 'bob belderbos',
'julian sequeira', 'sandra bullock', 'keanu reeves',
'julbob pybites', 'bob belderbos', 'julian sequeira',
'al pacino', 'brad pitt', 'matt damon', 'brad pitt']
NAMES = [name.title() for name in NAMES]
print(NAMES)
def reverse... |
# Booleans in Python
# Booleans only take two values True or False
Today_is_Friday = True
print(Today_is_Friday)
a = 3
b = 5
print( a == b)
print( a != b)
print( a < b)
print( a > b)
# All non-empty strings are default to True
# All empty strings are default to False
# bool(int) will be True if int is non-zero
#bool(i... |
def sort(arr):
for x in range (0,len(arr)):
lowest = arr[x]
lowestIndex = x
for y in range (x+1,len(arr)):
if(arr[y]<arr[lowestIndex]):
lowest = arr[y]
lowestIndex = y
arr[lowestIndex] = arr[x]
arr[x] = lowest
re... |
from typing import List
import re
def separate_with_dash(tokens: List[str], sep: chr = ' ') -> str:
tokens = [re.sub(r'་([^ །])', r'-\1', t) for t in tokens]
return sep.join(tokens)
|
"""
Simple rules
"""
def nil_rule(facts):
return None
def un_rule(facts):
return facts
def raise_rule(ex, mes):
def raise_warn(facts):
m = "%s -> %s" % (mes, str(facts))
raise ex(m)
return raise_warn
def is_instance_rule(t):
def is_instance(facts):
if isinstance(fac... |
# 1.4
# Palindrome Permutation
# Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is
# a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of
# letters. The palindrome does not need to be limited to just dictionary words.
# EXAMPLE
# ... |
import unittest
from student import Student
class StudentTest(unittest.TestCase):
def testDefaults(self):
student = Student()
self.assertEqual(student.name, Student.DEFAULT_NAME)
self.assertEqual(student.grade, Student.DEFAULT_GRADE)
self.assertEqual(student.fail, False)
... |
# coding=utf-8
def fibonacci():
a, b = 0, 1
while True:
yield b
a, b = b, a+b
fib = fibonacci()
elems = [next(fib) for _ in range(10)]
print(elems)
|
# 우리가 제공되는 API(Advanced Programming Interface)를 사용해야 하는 이유
class Person:
def __init__(self, age=0, name=''):
self._age = age
self._name = name
@property
def age(self):
return self._age
@age.setter
def age(self, age):
# 0을 포함한 양의 정수값만 입력이 가능하도록
try:
... |
from threading import Thread
import time
def countdown(n):
while n > 0:
n -= 1
c = 50000000
t1 = Thread(target=countdown, args=(c//2, ))
t2 = Thread(target=countdown, args=(c//2, ))
start = time.clock()
t1.start(); t2.start()
t1.join(); t2.join()
stop = time.clock()
print("elapsed time: {}".format(stop... |
from pandas import DataFrame, read_csv
import pandas as pd
import matplotlib.pyplot as plt
# The initial set of baby names and birth rates
names = ['Bob', 'Jessica', 'Mary', 'John', 'Mel']
births = [968, 155, 77, 578, 973]
# To merge these two lists together, use the zip function
BabyDataSet = zip(names, births)
df ... |
class Node():
def __init__(self,data):
self.data = data
self.prev=None
self.next=None
def get_prev(self):
return self.prev
def set_prev(self,prev):
self.prev = prev
def get_next(self):
return self.next
def set_next(self,next):
self.next = ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 13 15:45:07 2020
@author: sis
"""
import socket
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
print("Your Computer Name is:" + hostname)
print("Your Computer IP Address is:" + IPAddr) |
1
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 1 17:01:20 2020
@author: sis
"""
while True:
balance=10000
print("ATM")
print("""
1)balance
2)withdraw
3)deposit
4)Quit """)
try:
option=int(input("enter option:"))
except Exception as e:
print("... |
import math
import time
# Using decorators to see the time each function takes to complete the execution.
def timing(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"It took {(end - start) * 1000} mil seconds.")
... |
"""
DEFINITION
One partition:
One partition (ascending):
Choose the first element to be the sorted portion, and 2nd element for making comparison,
compare the next element to the sorted portion and insert it in the appropriate index of the sorted portion.
Sorted portion has increment by 1, unsorted has decremented by 1... |
# dict(key, value)
# Value can be repeated, but key cannot be repeated.
# This is the concept of HashTable and HashMap
student = dict([(101, 'Robert'), (102, 'William'), (103, 'Anderson')])
print(student)
print(student.keys())
print(student.values())
print(student[101])
# The default iterable is the keys, not values... |
from decimal import Decimal
"""This program implements the RSA algorithm"""
# from math import gcd can be used as well
def gcd(a, b):
if a==a:
return a, 0, 1
else:
return gcd(b, a%b)
def RSA(p, q, no):
n = p*q
t = (p-1)*(q-1)
for e in range(2, t):
if gcd(e, t) == 1:
... |
arr1 = [1, 232, 345, 345, 2346]
# This is because a list is iterable
for num in iter(arr1):
print(num)
# A tuple is also iterable
arr2 = {1, 2, 45, 56}
for num in iter(arr2):
print(num)
student = {101: "William", 102: "Henry", 103: "Joshua", 104: "George"}
# A dictionary is also iterable (specifically its k... |
import nltk
from nltk.stem import PorterStemmer
porter = PorterStemmer()
words = ['fish', 'fishing']
for word in words:
print(f"{word}: {porter.stem(word)}")
print("\n")
words = ['game', 'gaming', 'gamed', 'games']
for word in words:
print(f"{word}: {porter.stem(word)}")
|
import math
# Default Argument
def greeting(name='User'):
print(f"Welcome, {name}!")
greeting() # <= default case
greeting('Allie')
# Keyword Argument
def expon(a, b):
return math.pow(a, b)
print(expon(a=24, b=3)) # Both gives the same answers because a and b are now keywords
print(expon(b=3, a=24))
# Ar... |
"""
This program implements the Havel-Hakimi Algorithm, which finds if a degree sequence can form a a valid graph
"""
def graphExist(a):
# Keep performing the operations until one of the stopping condition is met
while True:
#Sort the list in a non-increasing order
a = sorted(a, reverse=True)
... |
from collections import namedtuple
colors = namedtuple('colors', 'r g b')
red = colors(r=250, g=0, b=0)
print(red.r)
print(red[0])
print(getattr(red, 'r'))
# All 3 gives the same output
# namedtuple is immutable
# Convertible into dict
print(red._asdict())
# Iterables into namedtuple
color1 = colors._make([24, 234... |
# reduce(function, sequence)
# Recursive implementation of a function to a sequence.
# First obtains a and b (the first 2 elems) and function is applied to them. result is stored
# To apply the function again, a = result and b = 3rd elem. result is stored.
# The process continues until it hits the last elem
from func... |
import re
def main():
# 'match' matches the entire string. 'search' look for specific words or character in the string
line = "I think I know it"
matchResult = re.match('think ', line, re.M | re.I)
if matchResult:
print("Match found" + matchResult.group())
else:
print("No match was... |
class Plateau:
"""
The plateau class keeps track of the bounds of the plateau and can check
whether a given coordinate is within those bounds.
"""
def __init__(self, x_limit, y_limit):
"""
Store the edges as a tuple. They don't need to be mutable.
Does that make sense? Or sh... |
#!/usr/bin/python3
import random
import simpy
import numpy
###########################################
#Author: Alan Fleming
#Email: alanfleming1998@gmail.com
#Description: This is a script to simulate a McDonalds Drivethru
#Asummuptions: The inter-arrival time is representable by a exponential distribution
# ... |
# course: DSC510
# assignment: 2.1
# date: 3/17/20
# name: Blaine Blasdell
# description: Customer Fiber Optic cable calculator
# Get Today's date for receipt
import datetime
today_date = datetime.datetime.today()
# welcome message
print('Welcome to Blasdell\'s IT Services')
print('\r')
print('Fiber Optic Cable Cost ... |
# Author: Justin Cappos
#
# This program takes files of the form: lat long count
# and produces a drawing of the resulting information. It is assumed that
# the lat goes from -90 to 90 and the long from -179 to 180.
import sys
import Image, ImageDraw
def georgbarep(origvalue):
r,b,g = georgbrep(origvalue)
retu... |
print("begin")
i = 1
while(i<=5):
print("Welcome",i)
i = i+1
else:
print("In while-else")
print("End")
|
import sys
import os
def clear_screen():
os.system('cls' if os.name=='nt' else 'clear')
def get_input(prompt, accept_blank=True):
try:
while True:
response = raw_input(prompt)
if response == "" and accept_blank==False:
print("A response is required here.\n")
... |
#! /usr/bin/env python
########
#
# Even Fibonacci numbers
#
########
def fib(n):
if n == 0:
return 0
if n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
def main():
final_sum = 0
max_sequence_value = 4000000
i = 1
while final_sum <= max_sequence_value:
... |
import random
f = open('word_rus.txt', 'r', encoding='utf-8')
words = f.readlines()
w = words[random.randint(1, 34010)]
answer = list('_' * (len(w) - 1))
flag = True
lives = 6
used = list()
print('Your word:')
print(''.join(answer))
while flag:
fl = False
print('Select a letter:')
letter = input()
used... |
file system:
windows:NTFS
Ubuntu: ext4
windows, MAC, linux:fat32: support all 3 system
Partition: the piece of a disk that you can manage
two main partition table schemes: MBR(Master boot record) #main on windows, only allow 2TB or less
GPT(GUID partition Table)# 2TB or more, n... |
# put your python code here
length = int(input())
width = int(input())
height = int(input())
edges = 4 * (length + width + height)
surface = 2 * (length * width + width * height + length * height)
volume = length * width * height
print(edges)
print(surface)
print(volume)
|
""" Card deck program.
"""
import collections
import itertools
deck = collections.namedtuple('deck', 'rank suit')
suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0)
class FrenchDeck(object):
""" Deck of cards.
"""
ranks = [str(rank) for rank in range(2, 11)] + list('JQKA')
suit = ['spades'... |
# 给定n个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为1 。
# 求在该柱状图中,能够勾勒出来的矩形的最大面积。
# 给定的高度为[2, 1, 5, 6, 2, 3]。
# 最大矩形面积为10个单位。
#
# 示例:
# 输入: [2, 1, 5, 6, 2, 3]
# 输出: 10
from typing import List
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
heights.append(0)
n = len(heights)
... |
# 编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
# 每行中的整数从左到右按升序排列。
# 每行的第一个整数大于前一行的最后一个整数。
#
# 示例 1:
# 输入:
# matrix = [
# [1, 3, 5, 7],
# [10, 11, 16, 20],
# [23, 30, 34, 50]
# ]
# target = 3
# 输出: true
#
# 示例 2:
# 输入:
# matrix = [
# [1, 3, 5, 7],
# [10, 11, 16, 20],
# [23, 30, 34, 50]
# ]
# target = ... |
# 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
#
# 示例:
# 给定一个链表: 1->2->3->4->5, 和 n = 2.
# 当删除了倒数第二个节点后,链表变为 1->2->3->5.
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
dummy_node = Li... |
# 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
# 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
# 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
#
# 示例:
# 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
# 输出:7 -> 0 -> 8
# 原因:342 + 465 = 807
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val =... |
# 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
from typing import List
class Solution:
def singleNumber(self, nums: List[int]) -> int:
res = 0
for i in nums:
res = res ^ i
return res
input = [4, 2, 1, 4, 1]
s = Solution()
print(s.singleNumber(input)) |
# 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
#
# 示例 1:
# 输入: 123
# 输出: 321
#
# 示例 2:
# 输入: -123
# 输出: -321
#
# 示例 3:
# 输入: 120
# 输出: 21
#
# 注意:
# 假设我们的环境只能存储得下 32 位的有符号整数,请根据这个假设,如果反转后整数溢出那么就返回 0。
class Solution:
def reverse(self, x):
is_positive = True
if x < 0:
is_positive = False
... |
# Description
#
# Given a square grid of size n, each cell of which contains integer cost which represents a cost to traverse through
# that cell, we need to find a path from top left cell to bottom right cell by which total cost incurred is minimum.
#
# Note : It is assumed that negative cost cycles do not exist in in... |
# 给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。
# 说明:每次只能向下或者向右移动一步。
#
# 示例:
# 输入:
# [
# [1,3,1],
# [1,5,1],
# [4,2,1]
# ]
# 输出: 7
# 解释: 因为路径 1→3→1→1→1 的总和最小
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m =... |
# 给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
#
# 示例:
#
# 输入: "25525511135"
# 输出: ["255.255.11.135", "255.255.111.35"]
from typing import List
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
def traceback(idx: int, segment: int, cur: str):
if segment == 4 and idx == n:
... |
# 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
# 你可以假设数组中无重复元素。
#
# 示例 1:
# 输入: [1,3,5,6], 5
# 输出: 2
#
# 示例 2:
# 输入: [1,3,5,6], 2
# 输出: 1
#
# 示例 3:
# 输入: [1,3,5,6], 7
# 输出: 4
#
# 示例 4:
# 输入: [1,3,5,6], 0
# 输出: 0
class Solution:
def searchInsert(self, nums, target):
if not nums:
... |
# 给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。
#
# 在杨辉三角中,每个数是它左上方和右上方的数的和。
#
# 示例:
#
# 输入: 3
# 输出: [1,3,3,1]
from typing import List
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
if rowIndex == 0:
return [1]
if rowIndex == 1:
return [1, 1]
pre, cur = [1, ... |
def insert_sort(arr):
n = len(arr)
for i in range(1, n):
cur = arr[i]
j = i - 1
while j >= 0 and cur < arr[j]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = cur
num = [5, 3, 2, 4, 1]
insert_sort(num)
print(num)
|
#!/bin/env python
# This script will validate and convert a custom formatted tab-delimited text file
# into an OBO file based on input parameters.
import sys, string
import argparse
import time
import collections
generatingTool = "BioGRID Tab2OBO 0.0.1a"
formatVersion = "1.2"
colCount = 8
# Process Co... |
def gcd(a,b):
if a<b:
return gcd(b,a)
if b == 0:
return a
return gcd(a%b,b)
def gcd2(a,b):
if a<b:
a,b=b,a
while b!=1:
if b == 0:
return a
else:
a,b=b,a%b
return 1
x=1
y=2
j=0
for i in range(1000):
j+=len(str(x+y))-len(str(y))... |
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_excel("preprocessed.xlsx")
# Drugi nacin
corr = df.corr()
print(corr)
def plot_corr(df,size=15):
'''Function plots a graphical correlation matrix for each pair of columns in the dataframe.
Input:
df: pandas DataFrame
... |
from socket import *
# TCP port we will listen for connections on
serverPort = 12000
# Create a listening socket
serverSocket = socket(AF_INET, SOCK_STREAM)
# Bind the socket to the local IP address ('') and port number
serverSocket.bind(('', serverPort))
# Start listening on the socket
serverSocket.listen(1)
prin... |
import mnist_reader
import numpy as np
import matplotlib.pyplot as plt
# train_images, train_labels ==> 60000, 60000
X_train, y_train = mnist_reader.load_mnist('train')
# test_images, test_labels ==> 10000, 10000
X_test, y_test = mnist_reader.load_mnist('t10k')
accuracy_test = [] # calculate the accuracy for text e... |
from random import *
class Cell(object):
""" Cell object with x,y position
"""
def __init__(self, x, y):
self.x = x
self.y = y
class Circuit:
def __init__(self, f):
[self.numCells, self.numNets, self.ny, self.nx] = [int(s) for s in f.readline().split()]
self.nets = []... |
# num=13
# print(type(num))
# n = int(input())
# sum = 2
# for i in range(n+1):
# sum+=i
# print(sum)
# sum = 0
# i =0
# while(i<=5):
# sum+=i
# i+=1
# print(sum)
# sum = 0
# for i in range(1,6):
# cube = i**3
# sum+= cube
# print(sum)
# sum = 0
# i = 0... |
# coding: utf-8
from inheritance import Person
obj2 = Person("Joana", 0)
obj1 = Person("João", 1)
print()
print("{name}:{sex}".format(name=obj1.name, sex=obj1.sex))
print("{name}:{sex}".format(name=obj2.name, sex=obj2.sex))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright © 2017 Manoel Vilela
#
# @project: Prática 9 - Python
# @author: Manoel Vilela
# @email: manoel_vilela@engineer.com
#
class Empregados(object):
def __init__(self, nome, sobrenome, salario):
self.nome = nome
self.sobrenome... |
#EX-5-lumbbharam
#Write a Python program to access dictionary key’s element by index.
num = {'stats': 80, 'math': 90, 'algorithm': 86}
print(list(num)[0])
|
#Cifrado Caesar, sistema de cifrado creado por Caesar para enviar sus
# mensajes mas importantes a sus generales sin que espias descubrieran
# la informacion que contenian sus cartas.
def cifrado_caesar(texto):
abc="abcdefghijklmnñopqrstuvwxyz"
cif = ""
for c in texto:
if c in abc:
if... |
# rpy2 library used to call r function
# more detailed documentation can be found at https://rpy2.github.io/doc/latest/html/robjects_robjects.html
import rpy2.robjects as ro
# used to exit program when user enters exit
import sys
def load_r_module(path_to_module):
"""[summary]
Args:
path_to_module (s... |
from display import *
from matrix import *
def draw_lines( matrix, screen, color ):
q = 0
while q < len(matrix) -1:
draw_line(matrix[q][0], matrix[q][1], matrix[q+1][0], matrix[q+1][1], screen, color)
q+=1
def add_edge( matrix, x0, y0, z0, x1, y1, z1 ):
matrix.append([x0, y0, z0])
matrix.append([x1, y1, z1]... |
import sys
#迭代器操作
def fun1():
list1=['1','a','b','c']
it1=iter(list1)
# print(next(it1))
# print(next(it1))
# 正常循环
# for i in it1:
# print(i,end="|")
# while循环方式
# while True:
# try:
# print(next(it1))
# except StopIteration:
# sys.exit... |
# 继承的方式,实现多线程
import threading
import time
exitFlag = 0
class myThread(threading.Thread):
def __init__(self, threadIdParam, nameParam, counterParam):
threading.Thread.__init__(self)
self.name = nameParam
self.threadID = threadIdParam
self.counter = counterParam
def print_te... |
from collections import deque
# 列表的操作
list1=[1,2,3,4]
list1.append(7)
list1.append(9)
print(list1)
# 列表当做堆栈使用
# print(list1)
# list1.pop()
# print(list1)
# list1.pop()
# print(list1)
# 列表当做队列使用
queue=deque(list1)
queue.popleft()
print(queue)
queue.popleft()
print(queue)
|
''' 7. Write program to convert prefix/net mask to IP
eg: input:16 output: 255.255.0.0 '''
def convert(n):
a = n//8
b = n%8
l =[]
for i in range(a):
l.append(str(255))
d,s=7,0
for i in range(b):
s+= 2**d
d-=1
l.append(str(s))
while len(l) < 4:
l.append(str(0))
return '.'.join(l)
inp = int(input("ent... |
import math
# Set of Joint Angles
# User Input
print("---Creating Player Profile---")
player_name = input('Name: ')
dominant_hand = input("Are you left (L) or right (R) handed? ")
if dominant_hand in ('R', 'r', 'right', 'Right'):
shooting_arm = 'right'
else:
shooting_arm = 'left'
print('What i... |
# -*- coding: utf-8 -*-
import sys
import itertools
import collections
def list2dict(l):
"""
Convert list to ordered dictionary, where adjacent elements become key and value
Example: [1, 2, 3, 4] --> {1: 2, 2: 4}
"""
return collections.OrderedDict(itertools.izip_longest(*[iter(l)] * 2))
def list2... |
"""
4. Написать функцию которая принимает на вход число от 1 до 100. Если число
равно 13, функция поднимает исключительную ситуации ValueError иначе
возвращает введенное число, возведенное в квадрат. Далее написать основной
код программы. Пользователь вводит число. Введенное число передаем параметром
в напи... |
import os
import shutil
import datetime
import random
def create_file(name, text=None):
with open(name, 'w', encoding='utf-8') as f:
if text:
f.write(text)
def create_folder(name):
try:
os.mkdir(name)
except FileExistsError:
print('already exist')
def get_list(folde... |
"""
3. Напишите функцию которая принимает на вход список. Функция создает из этого
списка новый список из квадратных корней чисел (если число положительное) и
самих чисел (если число отрицательное) и возвращает результат (желательно
применить генератор и тернарный оператор при необходимости). В результате
р... |
import unittest
from models.player import *
from models.game import Game
class TestPlayer(unittest.TestCase):
def setUp(self):
self.player1 = Player("Erin", "rock")
self.player2 = Player("Helen", "paper")
def test_player_has_name(self):
self.assertEqual("Erin", self.player1.name)
... |
"""Shaped bubble field implementation -- allows for creating a field
and placing (rectangular) bubbles in it and expanding them.
currently used for creating clusters of rooms
"""
import random
from rl.util import geometry
class BubbleField:
target_areas = [4, 6, 6, 10, 10, 12, 20, 20, 30, 30, 40]
target_rat... |
# Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
def dev(number_1, number_2):
try:
result = number_1 / number_2
return result
except ZeroDivisionError:
return "We can't divide by zero!"
print(dev(int(input(f"Введите целое число: ")), int(in... |
from itertools import combinations
main_tup = []
even = []
odd = []
rm_tuple = []
def rSubset(arr, r):
return list(combinations(arr, r))
def getData(num):
input_num = num[0]
check_num = num[1:]
arr = range(1,input_num + 1)
r = 2
main_tup.append(rSubset(arr, r))
for i in range(... |
from functools import wraps
import numpy as np
class _InvalidatingSetter(object):
"""Setter descriptor that sets target object's _parametrized_circuit to None.
The descriptor uses __get__ and __set__ methods. Both of them accept ansatz as the
first argument (in this case). We just forward the __get__, ... |
from math import sqrt, ceil
def get_primes(n):
"""Calculates a list of primes up to n (included. """
primelist = []
for candidate in range(2, n + 1):
is_prime = True
root = int(ceil(sqrt(candidate))) # division limit
for prime in primelist: # we try only primes
if prime ... |
"""
usage:using list demo
"""
shoplist = ['apple','mango','carrot','banana']
print("I hava",len(shoplist),'itmes to purchase')
print("thes itmes are:")
for item in shoplist :
print(item)
print("I also hava to buy rice.")
shoplist.append("rice")
print("My shopping list is now ",shoplist)
print("I will sort my Li... |
"""
usage: docString
"""
def printMax (x,y):
"""Prints the Maximum of two numbers
the two value must be integer."""
x = int(x) #强制转换成int型
y = int(y)
if x > y:
print (x,"is maximum")
else:
print(y,"is maximum")
printMax(3,5)
print (printMax.__doc__)#类似文档注释 |
"""
usage:while 循环demo
"""
number = 23
running = True #true大写
while running:
guess = int(input("please input a int number:"))
if guess == number:
print('Congradulations, you guessed it')
running = False #stop the loop
elif guess < number:
print('No, it is a little higher than you guess')
else:
print("No... |
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import math
def main_screen():
root=Tk()
rango_a_sexagesimal=StringVar()
rango_b_sexagesimal=StringVar()
numerador_rango_a=StringVar()
denominador_rango_a=StringVar()
numerador_rango_b=StringVar()
den... |
from sklearn import tree
'''
features - used to describe data (i.e. weight, color)
label - identify the kind data (i.e. name)
'''
#in example: 0 = apple, 1 = orange
features = [[140,1],[130,1],[150,0],[170,0]] #input to classifier
labels = [0,0,1,1] #output from classifier
#decision tree - box of rules
clf = tree.Dec... |
ch=input("Enter a character:")
if((ch>='a'and ch<='z')or(ch>='a'and ch<='z')):
print(ch,"Alphabet")
else:
print("Not alphabet")
|
class Meeting:
def __init__(self, start, end):
self.start = start
self.end = end
def __repr__(self):
return f"Meeting({self.start}, {self.end})"
def merge_meetings(meetings):
ordered = sorted(meetings, key=lambda x: x.start)
tmp = ordered[0]
condensed_meetings = [tmp]
for... |
import random
score = 0
def main():
print("Rolling Dice !")
print(" ")
doMoreRolls = True
while doMoreRolls == True:
playerChoice = input("Do you want to roll again ? Y/N : ")
if (playerChoice == "Y" or playerChoice == "y" or
playerChoice == "Yes" or playerChoice ==... |
string=raw_input("Enter a string:")
word=string.split()
str=""
for i in word[::-1]:
str+=" "+i
print(str)
|
n1=input("Enter no1:")
n2=input("Enter no2:")
n3=input("Enter no3:")
if(n1>n2):
if(n1>n3):
max=n1
else:
max=n3
elif(n2>n3):
max=n2
else:
max=n3
print (max)
|
def circle(r):
return 3.14*(r**2)
def rectangle(l,b):
return l*b
def triangle(b,h):
return 1.5*b*h
print ("1.Circle\n2.Rectangle\n3.Square")
ch=input("Enter your choice:")
if (ch==1):
r=input("Enter the radius:")
print("Area of circle:"+str(circle(r)))
if (ch==2):
l=input("Enter the breadth:")
... |
#funcao responsavel por ler o arquivo e gerar as matrizes a serem utilizadas pelo sistema
#ao achar a matriz de cada sistema, ele resolve o problema com outra função e mostra o resultado
#repetindo para todos os sistemas.
#Antes da repeticao, o resultado eh salvo no arquivo RESUL
def criaMatriz():
#esvazia o arquiv... |
'''
@Descripttion: 寻找最大数
@Author: daxiong
@Date: 2019-09-06 20:31:58
@LastEditors: daxiong
@LastEditTime: 2019-09-06 20:41:30
'''
s = input().strip().split()
strL = [int(x) for x in s[0]]
m = int(s[1])
newLength = len(strL) - m
newNum = ''
while newLength != 0: # 一个一个的找到最大的数字
maxNum = max(strL[: len(strL) - newLen... |
def QuickSort(list,low,high):
if high > low:
k = Partitions(list,low,high)
QuickSort(list,low,k-1)
QuickSort(list,k+1,high)
def Partitions(list,low,high):
left = low
right = high
k = list[low]
while left < right :
while list[left] <= k:
left += 1
... |
'''
@Descripttion:
@Author: daxiong
@Date: 2019-08-29 19:53:13
@LastEditors: daxiong
@LastEditTime: 2019-08-29 20:26:40
'''
size = int(input().strip())
nums = input().split()
nums = [int(x) for x in nums]
tail = [nums[0]]
for i in range(1, size):
left = 0
right = len(tail)
while left < right:
mid... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.