text stringlengths 37 1.41M |
|---|
outstanding_balance_ = float(raw_input('Balance: '))
interest_rate = float(raw_input('Rate: '))
count = 0
while 1:
payment = 10 * count
outstanding_balance = outstanding_balance_
for month in range(1, 13):
monthly_interest_rate = (interest_rate / 12.0)
monthly_unpaid_balance = outstanding_b... |
#This game is written by Siang and Nikko
import pygame
from pygame.locals import * #maybe get rid of later
class BrickBreaker:
def __init__(self, winWidth, winHeight):
"""Constructor of game
Inputs
1)Window width and height"""
#Set window width and height
... |
import random
num = []
def stuff(list):
i = 0
while i <=6:
list.append(random.randint(1,6)+random.randint(1,6)+random.randint(1,6))
i = i +1
print(list)
def avg(list):
t = 0
for i in range(len(list)):
t = t + list[i]
print(t//len(list))
def main():
stuff(num)
avg(num)
li = [7,10,9,15,12,12]
r... |
age = 31
if age < 18:
rate = 450
else:
if age > 100:
rate = 500
else:
if age < 25:
rate = 400
else:
rate = 300
print(rate) |
import turtle
import tictactoeai
# Configure these variables as you like (within reason).
radius = 100
padding = 10
user = "O"
# These variables are then automatically configured.
if user == "O":
ai = "X"
else:
ai = "O"
numMoves = 0
stillPlaying = True
board = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
de... |
# In this file, all plaintext strings are assumed to contain only spaces and upper-case Roman characters A, B, C, ..., Z. Each encryption system has an encryptor and a decryptor.
# Convert letters A, ..., Z to indices 0, ..., 25.
# Also handle a, ..., z, just because we can.
def indexFromLetter(char):
if "A" <= char ... |
def insert_sort(lists):
count = len(lists)
# 因为第一个元素自成有序序列,所以遍历从第二个元素开始
for i in range(1, count):
# 获取当前需要向前插入的元素
key = lists[i]
# 从i前面一个位置开始插入
j = i - 1
while j >= 0:
# 如果待插位置的原有元素比待插元素大(如果是降序也可以是小)
# 那么移动j元素到j+1位,j元素用待插元素替代
# 这个过程... |
'''
This script can convert a picture to character picture.
Usage:
python3 ascii.py filename [-o|--output] [--width] [--height]
'''
from PIL import Image
import argparse
class ImgToChar():
'''
Usage:
1.New a object
2.Call draw() method
'''
def __init__(self):
self.parser = argparse.Ar... |
'''
680. Valid Palindrome II
Easy
Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.
Example 1:
Input: "aba"
Output: True
Example 2:
Input: "abca"
Output: True
Explanation: You could delete the character 'c'.
Note:
The string will only contain lowercase chara... |
"""
Создайте класс RandSequence с методами, формирующими вложенную последовательность.
Определить атрибуты:
- sequence - последовательность
Определить методы:
- инициализатор __init__, который принимает длину последовательности n
- метод generate, который принимает длину последовательности n
- метод print_seq, кото... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by iFantastic on 2019/7/4
"""
1.6. 面试题目:1块钱1瓶水,2个瓶盖换一瓶水,
用程序实现输入钱数,得到水的个数
1 1
2 2+1
3 3+1+1 5
4 4+1+1+1 7
。。。。。。
"""
while True:
money = int(input("请输入钱数:\n"))
connt = 2 * money - 1
print("水的个数是 %d" % connt)
if __name__ == '__main__':
pass |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by iFantastic on 2019/7/4
'''
6.1. find
find 检测str是否包含在mystr中,如果是返回开始索引值,否则返回-1
6.2. rfind
rfind 类似于find,不过是从右边开始找。
'''
starts = "郭富城、刘德华、黎明、fzd、刘德华"
# 从左往右找第一个字符串的索引 下标 从0 开始
index = starts.find("郭富城") # 将返回值传给index
print(index)
index = starts.find("刘德华")
print(i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by iFantastic on 2019/7/9
"""
定义一个网络用户类 要处理的信息有用户ID、用户密码、email地址。
在建立类的实例时 把以上三个信息都作为参数输入
其中用户ID和用户密码是必须的 缺省的email地址,是用户ID加上字符串"@gameschool.com"
判断邮箱是否合法,判断id不能为空的方法
要求定义函数,能获取出用户的个人信息。
"""
class NetUser:
def __init__(self, id, pwd):
self.id = id
... |
try:
age=int(input("enter age :"))
if(age<18):
raise ValueError;
else:
print("Valid age")
except ValueError:
print("you are not eligible for voting")
|
import random
print(random.randrange(5))
def elementexist(lis,search):
for e in lis:
if e==search:
return True
return False
l=[1,2,3,4,5,6]
if elementexist(l,4):
print("Element Exist")
else:
print("Element doesn't exist")
L=[]
L.append(random.randrange(5))
print(L)
'''
import random
import math
def c... |
def InsertInList(x, p, q):
l.insert(p,q)
if __name__ == '__main__':
N = int(input())
l = []
for i in range(N):
x = input()
if(x.find("insert")>=0):
temp = x[7:]
a, b = temp.split()
p = int(a)
q = int(b)
InsertInList(l, p, q)
elif(x.find("print")>=0):
... |
# -*- coding: utf-8 -*-
# from collections.abc import Iterable
def a(b, *a, **data):
# print(11, b, a, type(a), data, type(data))
print(11, b, a, type(a), data, type(data))
c(data)
def c(cc=22, aa=44, bb=56, a=1, b=543, c=45):
print(22, cc, aa, bb, a, b, c)
b = {"a": 'b', 'b': 2, 'c': 3}
bb = [1... |
# sets - множества
# не можем получить элемент по индексу
# не можем удалить элемент
# множество контейнер уникальных и повторяющихся элементов
# st = set()
# st2 = {54, True, "get"}
# lst = [54, 54, True, True, 5, 3, 8, 3]
# umit = set(lst)
# #print(st2[0]) будет ошибка
# print(type(st2))
# st2.add(54)
# print(st2)... |
#list = маасив
# lst = list()
# lst.append("nurbek")
# lst.append(True)
# lst.append(34)
# lst.append(55.4)
# print(lst)
# 0 1 2 3 4
# lst2 = ["cat", False, 58, "kg", [544, "dog", False]]
# a = lst2[4]
# lst2.remove(lst2[4])
# a.remove(544)
# lst2.append(a)
# print(ls... |
#__str__
#ООП - наследование
# class Cat:
# def __init__(self, name2, age, tail, color, paws):
# self.name = name2
# self.age = age
# self.tale = tail
# self.color = color
# self.paws = paws
# def __str__(self):
# return self.name
# class Tiger(Cat):
# def... |
def go_vert(lines, idx, start_line):
# find direction up or down
if start_line != 0:
if lines[start_line - 1][idx] != ' ':
direction = 'u'
cur_line = start_line - 1
else:
direction = 'd'
cur_line = start_line + 1
else:
direction = 'd'
... |
import functools
def comment_lines_with_escaping(
text,
prefix="#",
escape_prefix="# EPY",
escape_format_string="# EPY: ESCAPE {}"):
"""
Build a Python comment line from input text.
Parameters
----------
text : str
Text to comment out.
prefix : str
... |
import sys
l = [n*2 for n in range(10000)] # List comprehension
g = (n for n in range(10000)) # Generator expression
print(type(l)) # <type 'list'>
print(type(g)) # <type 'generator'>
print(sys.getsizeof(l)) # 9032
print(sys.getsizeof(g)) # 80
print("new")
# firstn with list
def firstn(n):
num, nums = 0, []
... |
people_1 = {
'first_name': 'Xinhan',
'last_name': 'Niu',
'age': 21,
'city': 'Hefei',
}
people_2 = {
'first_name': 'Zhuang',
'last_name': 'Li',
'age': '21',
'city': 'Hefei',
}
people_3 = {
'first_name': 'Gangjun',
'last_name': 'Zhang',
'age': '21',
'city': 'Hefei',
}
peo... |
while True:
print('\nPlease enter two numbers\n(Enter "q" to exit.)')
numbers_1 = input('first number: ')
if numbers_1 == 'q':
break
numbers_2 = input('second number: ')
if numbers_2 == 'q':
break
try:
sum = int(numbers_1) + int(numbers_2)
except ValueError:
p... |
lists = ['mountain', 'river', 'country', 'city', 'language']
print(sorted(lists))
print(len(lists)) |
favorite_numbers = {
'alice': [1, 3, 4],
'bob': [5, 67, 2],
'david': [3, 78, 5],
'eric': [3, 5, 7],
'frank': [23],
}
for name, numbers in favorite_numbers.items():
print(name)
print(numbers) |
class Restaurant:
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print(
f'restaurant name:{self.restaurant_name}\ncuisine type:{self.cuisine_type}'
)
def o... |
def make_album(singer_name, album_name, number_of_songs=None):
if number_of_songs == None:
album = {'singer': singer_name, 'album_name': album_name}
else:
album = {
'singer': singer_name,
'album_name': album_name,
'number': number_of_songs
}
ret... |
# Задание 1 из домашней работы №8
class Date:
current_date: str = "00-00-0000"
def __init__(self, current_date):
self.current_date = current_date
def __str__(self):
return self.current_date
@classmethod
def get_date(cls, current_date):
c_day, c_month, c_year ... |
#Задание 1 из домашней работы №2
saved_list = [1, 2, 3, 4]
created_list = [11, "Number", 11.086, saved_list, None]
length_of_list = int(len(created_list))
i = 0
while i < length_of_list:
print(type(created_list[i]))
i += 1
|
# Задание 3 вторая часть
translate = {'One': 'Odin', 'Two': 'Dva', 'Three': 'Tri', 'Four': 'Chetire'}
result = []
with open("translate.txt") as file_obj:
for line in file_obj:
strings = line.split(" - ")
print(strings)
print(translate[strings[0]], "-", strings[1])
result.ap... |
ranges = [[53,57],[42,43],[58,63]]
result =['','']
outcomes = ["This diamond is bad","This is a good diamond"]
feedback = ["Inputs are all valid", "The number of properties must equal 3","At least one input is incorrect"]
properties = ['58','43','56']
def DiamondQuality (properties):
for i in range ... |
def duplicatereverse(text):
if len(text) == 0:
return text
else:
return text[-1] + duplicatereverse(text[0:-1]) + text[-1]
def main():
word = input ('Introduce text to duplicate and reverse: ', )
print("Input is: ", word)
print("Duplicated and Reversed text is: ", dupl... |
characters = [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,zip]
digits = [0,1,2,3,4,5,,6,7,8,9]
symbols = [¬,!,£,$,%,^,&,*,(,),_,+]
from random import randint:
def randomCharacter (characters):
n
def makePassword (lenght):
password = ''
for i in range (lenght - 2):
pa... |
#printing function
a=int(input("enter the value of a "))
b=int(input("enter the value of b"))
def add():
return a+b
def sub():
return a-b
def mulitiplication():
return a*b
def divion():
return a%b
print("addition of ",a,"and",b,"=",add())
print("subtraction of ",a,"and",b,"=",sub())
print("mulitiplication of ",... |
#printing values
print("the value of a=")
a=18
print(a)
print("the value of b=")
b=12
print(b)
c=a+b
print("the value of c=")
print(c)
|
import math
# Parameters - num is a positive integer
def prime_factorization(num):
curr = num
factors = {}
while curr % 2 == 0:
if not 2 in factors:
factors[2] = 1
else:
factors[2] = factors[2] + 1
curr = curr/2
divisor = 3
while curr > 1:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 18 23:51:59 2020
@author: ms
"""
n = 10**10-1
def isPrime(n):
# Corner cases
if (n <= 1):
return False
if (n <= 3):
return True
# This is checked so that we can skip
# middle five numbers in below loop
if (n... |
import pandas as pd
def prescribe(disease):
remedy = []
medicine = []
df = pd.read_csv('deseaseremedies.csv', engine='python')
for row in df.values:
if row[0].lower() == disease:
remedy.append(row[1])
medicine.append(row[2])
while '-' in medicine:
... |
# This class initially will create a bank object with a name you choose and
# then will print the following menu (it should print this menu, until user says exit)
from bank import Bank
from client import Client
import time
while True:
print('''
Welcome to International Bank!
Choose an option:
1. Open ... |
list = []
print("printing list",list)
if list==[] :
print("list is empty")
else :
print("list is not empty") |
# The reduce(fun,seq) function is used to apply a particular function
# passed in its argument to all of the list elements mentioned
# in the sequence passed along.This function is defined
# in “functools” module.
#
# Working :
# At first step, first two elements of sequence are picked and
# the result is obtain... |
try:
f=open('hi.txt')
print("from try")
print(f.read())
if f.name=='hi.txt':
print ("hi again")
raise FileNotFoundError #atemshi l exception lewla
# specific exception
except IOError as e:
print('First!')
except FileNotFoundError :
print("stooooop")
# general exception at th... |
def title_case(title, minor_words):
ignore_minor = True
r = ''
for t in title.lower().split(' '):
r += ' {}'.format(
t.capitalize()
if ignore_minor or t not in minor_words.lower().split(' ')
else t
)
ignore_minor = False
return r[1:]
def titl... |
class TheBlackJackDivTwo():
def score(self,cards):
count=0
for i in range(len(cards)):
print cards[i][0]
if cards[i][0]=='2' or cards[i][0]=='3' or cards[i][0]=='4' or cards[i][0]=='5' or cards[i][0]=='6' or cards[i][0]=='7' or cards[i][0]=='8' or cards[i][0]=='9':
... |
class InsideOut(object):
def unscramble(self,line):
#self.line=line
#line= list(line)
#x=len(line)/2
#print x,len(line)
r=s=""
#r+=line[:]
#r+=line[0,x]
#r+=line[len(line)/2:]
#r+=line[0:len(line)/2]
for i in range(len(line)/... |
class SoccerLeagues(object):
def points(self,matches):
r=[]
for i in range(len(matches)):
p=0
for j in range(len(matches[i])):
while(i!=j):
if matches[i][j]=='W':
p+=3
break
... |
class WhiteCells(object):
def countOccupied(self,board):
self.board=""
count=0
#board=list(board)
for i in range(len(board)):
c_1=board[i]
#c_1=list(c_1)
if i%2==0:
for j in range(0,len(c_1),2):
if c_1[... |
import WordSupply
# add classes for Player for multiplayer version
def main():
print("Starting a game of Hangman...\n")
welcome()
def startgame(attempts_int, wordLength_int):
attemptedChars_list = []
word_str = WordSupply.pickWord(wordLength_int)
gameWord_str = "*" * len(word_str)
print(f"G... |
class LinkedList:
"""
Linked list implementation
TODO: have a linked list class and use it to create single, double, and
circular linked list classes...
"""
def __init__(self):
"""
Initializes a Doubly Linked list
Example:
```python
list = Lin... |
import xml.etree.ElementTree as ET
import sys
def read_xml(xml_file):
tree = ET.parse(xml_file)
root = tree.getroot()
return root
def search(term, root):
words = term.lower().split()
output = []
i = 0
for word in words:
for child in root:
if word == root[i][0].text:
... |
#!/usr/bin/python3
import geopandas as gp
import pandas as pd
import argparse
'''Code takes latitude and longitude coordinates along with path to shapefile
and returns a neighborhood council identifier in response. Can be run as
executable from command line or imported into another codebase as the
classify_p... |
"""
Space Station Simulation
Using SimPy and Tkinter
"""
import numpy as np
import simpy
from tkinter import *
import tkinter.scrolledtext as tkscrolled
HOUR = 60 # 60 minutes in a hour
SIM_YEAR = 1 # How many years will continue to simulate
HUMAN_NUMB... |
#### Simple decorators
def my_decorator(func):
def wrapper():
print('something is happening before the function is called')
func()
print('something is happeing after the function is called')
return wrapper
def say_whee():
print('Whee!')
say_whee = my_decorator(say_whee)
say_whee(... |
#Inheritance: What common attributes and behaviors exist between real-world objects?
#Inheritance models an is a relationship (Cat is an animal; Apple is a fruit; Fish is a food and an animal)
#Composition: How are objects in the real world composed (made up) of one another?
#Composition models a has a relationship (A... |
from PyPDF2 import PdfFileReader, PdfFileWriter
def rotate_pages(pdf_path):
pdf_writer = PdfFileWriter()
pdf_reader = PdfFileReader(pdf_path)
#rotate page 90 degrees to the right
page_1 = pdf_reader.getPage(0).rotateClockwise(90)
pdf_writer.addPage(page_1)
#rotate page 90 degrees to the left
... |
class Color:
def __init__(self, rgb_value, name):
self.rgb_value = rgb_value
self._name = name
def _set_name(self, name):
if not name:
raise Exception("Invalid Name")
self._name = name
def _get_name(self):
return self._name
name = property(_set_n... |
def my_sum(a,b):
return a+b
#my_sum(a, b)
def my_sum2(integers):
res = 0
for x in integers:
res += x
return res
ints = [1,2,3]
print(my_sum2(ints))
def my_sum3(*args):
res = 0
#Iterating over the Python args tuple
for x in args:
res += x
return res
print(my_sum... |
# !/usr/bin/python
# Part 1 Step 1 : Hang Huynh
# pillomavirus_type_63_uid15486 This assume that the "virus genome files" is saved manually file by file
# grabbing files with common ".fas" files in the same directories
# input "common name" by user
import os, glob
from Bio import SeqIO
import fileinput
# Finding t... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 23 12:25:16 2018
@author: Jotun
"""
#Importing necessary stuff
import os
import datetime
import shutil
import tkinter, tkinter.filedialog
root = tkinter.Tk()
root.withdraw()
#Get the back up desitnation directory from user
backupPath= tkinter.filedialog.askdirectory (par... |
def isPalindrome(i):
return i == i[::-1]
i = input("Enter word: ")
answer = isPalindrome(i)
if answer:
print("Yes")
else:
print("No") |
"""Utilities for dealing with latches' actuators in the physical universe."""
import threading
import time
import RPi.GPIO as GPIO
class Latch(object):
"""Class to deal with latches."""
def __init__(self, lock_pin=12):
self.lock_pin = lock_pin
self.lock_lock = threading.RLock()
def __enter__(self):
... |
import datetime
def calculate_start_end_date(start_year=2008, start_month=2):
# From the beginning of a month
start_date = datetime.date(start_year, start_month, 1)
end_year, end_month = start_year, start_month + 1
if end_month > 12:
end_year += 1
end_month = 1
end_date = dateti... |
def year_leap(a):
if (a % 4 == 0,a % 100 != 0) or a % 400 == 0:
print("YES, you birth year is a leap-year")
else:
print("NO, you birth year is not a leap-year")
m = input("print your birth year:")
y = year_leap(int(m))
print(y)
|
import unittest
from OOP1 import ITEmpl
class EmplTest(unittest.TestCase):
def setUp(self):
self.emp = ITEmpl("Nata", "Pin")
def test_name(self):
self.assertEqual (self.emp.name, "Nata")
self.assertEqual (self.emp.surname, "Pin") |
import pygame
from random import randint
pygame.init()
window = pygame.display.set_mode((500,500))
pygame.display.caption('wordgame')
gamerunning = True
class character():
def __init__(self, name, hp, attack, profession, gold):
self.name = name
self.hp = hp
self.attack = attack
s... |
def main():
a=int(input("Enter a number"))
for i in range(a):
print("Hello")
if __name__ == '__main__':
main()
|
import os
from Donnee import *
from Fonction import *
print("---------------START--------------")
print("Bonjour,")
nom = input("Bienvenu quel est ton nom: ")
scores = down_save()
score_fin = 0
if nom in scores:
print("Tu as {} points.".format(scores[nom]))
else:
print("Tu est nouveau ici {}". ... |
#register
#username, password
#generation user id
#login
#username or email and password
#bank operation
#initializing the system
import random
import validation
import database
def init():
print('Welcome to bankPHP')
haveAccount = int(input('do you have an account with us: 1. (yes) 2 (no) \n'))
... |
def runningSum(nums):
for i in range(1, len(nums)):
nums[i] += nums[i-1]
print(nums)
runningSum([1,2,3,4]) |
for n in range(int(input())):
ans = 0
for i in input().split():
if int(i)%2 == 1:
ans += int(i)
print("#"+str(n+1)+" "+str(ans))
|
str = input()
tmp = ""
for i in range(0,len(str)):
tmp+=str[i]
if i%10==9:
print(tmp)
tmp=""
print(tmp)
|
def insertion_sort(data):
for index in range(len(data) - 1):
for index2 in range(index+1, 0, -1):
if data[index2] < data[index2 - 1]:
data[index2], data[index2 -1] = data[index2 - 1], data[index2]
else:
break
return data
def insertion_sort2(x):
for size in range(1, len(x)): #... |
def kangaroo(x1, v1, x2, v2):
if (x1 <= x2 and v1 <= v2) or (x1 > x2 and v1 > v2):
return 'NO'
if abs(x2 - x1) % abs(v2 - v1) != 0:
return 'NO'
return 'YES'
print(kangaroo(0, 2, 5, 3)) |
graph = {
'A': ['B', 'C'],
'B': ['A','D','E'],
'C': ['A','F'],
'D': ['B'],
'E': ['B'],
'F': ['C']
}
from queue import Queue
# BFS
def bfs(graph, start_node):
visited = {} # 방문했던 노드목록 (dic, set 형태로 구현해야 효율
q = Queue() # bfs는 queue, dfs는 stack : 유일한 차... |
import random
import Field
from Position import Direction, Position
class Particle:
"""Represents a particle in movement with a position
and a direction.
:author: Peter Sander
:author: ZHENG Yannan
"""
def __init__(self, position: Position, direction: Direction,
colour: str... |
from polynomials import *
def test_at_point():
assert Polynomial([1,2,3]).__call__(2)==3*2**2+2*2+1
assert Polynomial([1,2,3]).__call__(4)==3*4**2+2*4+1
assert Polynomial([1,2,3]).__call__(7)==3*7**2+2*7+1
def test_add_2_polynomials():
assert Polynomial([1,2,3])+Polynomial([1,2,3])==Polynomial([2,4,6])
assert Po... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
'''
pad2D(img,padlengths,padtype='constant',cval=0)
Pads the image with given padlengths and given type of padding.
parameters:
* img: image to be padded
* padlengths: a tuple (N,M) to pad the image with N rows and M colum... |
#
# Example file for working with date information
#
def main():
# DATE OBJECTS
from datetime import datetime
# Get today's date from the simple today() method from the date class
today = datetime.today()
print(today)
# print out the date's individual components
print(today.year)
print... |
#!/usr/bin/env python3
import os
def get_port():
while True:
try:
port = int(input('Puerto (1024 - 49151): '))
if port >= 1024 and port <= 49151:
break
except Exception:
pass
return port
def get_secure():
type = input('Establecer conexi... |
i = 0
numbers = []
while i < 6:
print ("At the top i is %d" % i)
numbers.append(i)
i = i + 1
print ("Numbers now:", numbers)
print ("At the bottom i is %d" % i)
print "The numbers: "
for num in numbers:
print num
# these are the study drills bellow:
def study_1(n):
... |
# To see wich version of Python it's used
import sys
print(sys.executable)
print(sys.version)
# Employees names class
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = (first + '.' + last + '@mail.co... |
# this will count the amount of words in a sentence
# this function will split the sentence into words
def break_words(sentence):
"""This function will break up words for us."""
words = sentence.split(' ')
return words
print "Please write something."
sentence = raw_input(">: ")
print "Th... |
# Program to Check Even No in List
def even(x):
if(x%2==0):
return x
a = int(input("Enter no : "))
list1 = []
for i in range(0,a):
v=int(input("Enter No to Add : "))
list1.append(v)
print(list1)
s =list(filter(even,list1))
print("Even No in the List are ",s) |
a = int(input("Enter a Number : "))
if(a%2==0):
{
print("The No is Even")
}
else:
{
print("The No is odd")
}
|
class delete:
def __init__(self):
self.stacks = []
def push(self, val):
self.stacks.append(val)
def pop(self):
val = self.stacks[-1]
del self.stacks[-1]
return val
stack_object = delete()
stack_object.push(4)
stack_object.push(3)
stack_object.push(2)
stack_object.p... |
import json
from src.input.raw import Raw
def read(filename, maximum):
"""
Get data from JSON files.
- filename: str with JSON file with a list of dictionaries.
- maximum: int with maximum length for output list.
- return: [Raw].
"""
raws = []
with open(filename, "r") as f:
for... |
from math import ceil
def threshold(scores, thresh):
"""
Filter sentences given their associated scores and
the threshold to filter them. Only get those above threshold.
- scores: [float].
- thresh: float.
- return: [int] with selected indices.
"""
return mask([thresh <= s for s in sco... |
import os
def arguments(files):
"""
Tidy files so that we get [(original, sum1, sum2)].
All files must be in the same directory.
All files must have the notation of the corpus, i.e.
- <ID>.txt
- SUM_<ID>_<NAME1>.sum
- SUM_<ID>_<NAME2>.sum
where <ID> is the id of the document and <NAME1... |
# бʽ
list1 = [x for x in range(10)]
iter(list1)
print(next(list1))
for l in list1:
print(l)
# Შкʽ
def fun(num):
a, b = 0, 1
count = 0
while count < num:
yield a
a, b = b, a + b
# print(count)
count += 1
print(next(fun(10)))
|
import time
def time_count(fun):
"""统计程序运行时间装饰器"""
def t():
start = time.time()
fun()
end = time.time()
print(fun.__name__, "消耗", end - start, "秒")
return end - start
return t
# 用time_count装饰器装饰函数,统计函数print_count()运行的时间
@time_count
def print_count():
"""
... |
# pop_calculate.py
# CS 1181
# D. Ivan Ochoa
# 16 February, 2021
# Jon Holmes
# Description: script of functions required for population_sim to run.
def as_rate(rate_percentage: str) -> float:
"""accepts desired rate string and returns it as a float"""
amount_in_percent = float(rate_percentage)/100
return... |
import random
class Dog:
def __init__(self, name):
self.name = name
self.age = 0
self.weight = 1
self.sex = random.choice(['m', 'f'])
def __str__(self):
return "{} is {} years old and is {} and weighs {} lbs".format(self.name, self.age, self.sex, self.weight)
def ... |
class Cat:
count = 3
def add():
Cat.count += 1
def __init__(self, name):
self.name = name
def meow(self):
return "{} says hello".format(self.name)
def lol(haz):
return haz.name
# ---------------
c = Cat('mews')
# ---------------
def sample(*args, **kwargs):
... |
import turtle
import random
import time
# drawing methods
def draw_board():
board_drawer = turtle.Turtle()
board_drawer.speed(20)
board_drawer.pensize(20)
board_drawer.color("white")
for i in range(2):
board_drawer.penup()
board_drawer.goto(turtle.window_width() / 8 - turtle.windo... |
#-------------------------------------------------------------------------------
# Name: ouncesgrams.py
#
# Purpose: A progam that converts ounces to grams from 1 to 15
#
# Author: A. Fazelipour
#
# Created: 03/26/2019
#-------------------------------------------------------------------------------
print("**** Ounces... |
def caught_speeding(speed, is_birthday):
if speed <= 60 and is_birthday == True or speed >= 61 and speed >= 65 and is_birthday == True:
return (0)
elif speed >= 61 and speed >= 80 and is_birthday == False or speed >= 81 and speed <= 85 and is_birthday == True:
return (1)
else:
retu... |
class Node(object):
def __init__(self, id):
self.id = id
self.adj_nodes = []
self.visited = False
class Graph(object):
def __init__(self):
self.nodes = {}
def Link(self, node_a, node_b):
for node in [node_a, node_b]:
if node not in self.nodes:
self.nodes[node] = Node(node)
... |
import copy
def BalancedPartition(xs):
_, left_bag = Knapsack(xs, sum(xs) / 2)
right_bag = ArrayMinus(xs, left_bag)
return left_bag, right_bag, abs(sum(left_bag) - sum(right_bag))
def Knapsack(xs, limit):
if limit <= 0:
return 0, []
max_sum = 0
max_bag = []
for i, x in enumerate(xs):
sub_sum,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.