text stringlengths 37 1.41M |
|---|
print("Привет, я Анфиса!")
friends = ['Серёга', 'Соня', 'Дима', 'Алина', 'Егор']
friends_string = ', '.join(friends)
print("Твои друзья: " + friends_string)
stations = ['Москва', 'Серп и Молот', 'Карачарово', 'Чухлинка', 'Кусково', 'Новогиреево', 'Реутово', 'Никольское',
'Салтыковская', 'Кучино', 'Железнод... |
def func(square):
return square ** 2
iterator_list = [1,2,3,4,5]
print(list(map(func, iterator_list))) |
#Write a function that checks whether a number is in a given range (inclusive of high and low)
def ran(num,high,low):
if num > low and num < high:
print(f"the middle number is {num} and low is {low} and high is {high}")
# if num in range(low,high) |
from utils import read_file
def calc_fuel(mass):
return mass // 3 - 2
def calc_fuel_recursive(mass):
total = 0
res = calc_fuel(mass)
while res > 0:
total += res
res = calc_fuel(res)
return total
print("#--- part1 ---#")
assert(calc_fuel(12) == 2)
assert(calc_fuel(14) == 2)
ass... |
# Rearrange an array with alternate high and low elements
def solve(arr):
for i in range(1, len(arr), 2):
if arr[i-1] > arr[i]:
arr[i], arr[i-1] = arr[i-1], arr[i]
if i + 1 < len(arr) and arr[i+1] > arr[i]:
arr[i+1], arr[i] = arr[i], arr[i + 1]
return arr
arr = list(map... |
# Merge two arrays by satisfying given constraints
def solve(x, y):
# move non empty elements of x to the begining
j = 0
for i in range(len(x)):
if x[i]:
x[j] = x[i]
j += 1
x_pos = len(x) - len(y) - 1
y_pos = len(y) - 1
k = len(x) - 1
while x_pos > -1 and y_p... |
numb = int(input("Enter a number: "))
if numb > 1:
# check for factors
for i in range(2,numb):
if (numb % i) == 0:
print(numb,"is not a prime number")
print(i,"times",numb//i,"is",numb)
break
else:
print(numb,"is a prime number")
else:
print(numb,"is not a pri... |
import sqlite3
try:
sqliteConnection = sqlite3.connect("SQLite_Python.db")
cursor = sqliteConnection.cursor()
print("Succesfully connected to SQLite")
sqlite_insert_query = """INSERT INTO SQLiteDb_developers
(id, name, email, joining_date, salary)
... |
import random
def random_color():
number = "#"
for n in range(6):
number += str(random.randint(0, 9))
return number
if __name__ == "__main__":
print(type(random_color()))
|
"""This module contain functions to calculate option pricing
using different finite difference methods.
This will work for 1 factor(asset) and
2 factors(asset and interest rate) models.
-*- coding: utf-8 -*-
Author: Agam Shah(shahagam4@gmail.com)
Reference "Paul-Wilmott-on-Quantitative-Finance"
"""
import math
imp... |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
if __name__ == '__main__':
file = "F:/Data/MNIST"
mnist = input_data.read_data_sets(file, one_hot=True)
x = tf.placeholder(tf.float32, shape=[None, 784])
output = tf.placeholder(tf.float32, shape=[None, 10])... |
import pygame
#importa funciones especificas de la libreria pygame
class Tablero():
# Funcion constrcutra (se ejecuta al crear el objeto)
def __init__(self,window,color=(255,255,255)):
self._window = window
self._window
self
self._color = color
self._recuadros = []... |
name_1 = 'karim'
name_2 = 'karim'
name_3 = 'KARim'
name_4 = 'karim'
name_5 = 'karim'
# find upper letter
def find_upper_litter(name):
for i in range(len(name)):
if name[i].isupper():
return name[i]
return 'no upper letters found !'
x = find_upper_litter(name_1)
x1 = find_upp... |
data = []
for i in range(1,100):
data.append(i)
target = 22
# linear search
def linear_search(data,target):
for j in range(len(data)):
if data[j]==target:
return True
return False
x = linear_search(data,target)
print(x) |
import random
class Entity(object):
def __init__(self, node, max_moves):
self.node = node
self.alive = True
self.max_moves = max_moves
def action(self):
"""What to do after movement"""
pass
def can_move(self):
"""Whether there's anything interesting enough ... |
"""
This module contains an interface for the distance measures that are used to compute the distance between two
data points in the 'SeqClu' algorithm.
"""
from abc import ABC, abstractmethod
from typing import Union
from numpy import ndarray
class IDistanceMeasure(ABC):
@abstractmethod
def calculateDistance(s... |
def computepay(h, r):
if h <= 40:
return h*r
else:
return (r*1.5)*(h-40) + (r*40)
hrs = float(input("Enter Hours:"))
rate = float(input("Enter Rate:"))
p = computepay(hrs, rate)
print("Pay", p)
|
# Use the file name mbox-short.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
count = 0
num = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:"):
continue
# line = line.find("0")
line = float(line[20:])
count += line
num += 1
# print(line)
# pri... |
from string import Template
first = int(input("What's the first number? "))
second = int(input("What's the second number? "))
total = first + second
diff = first - second
product = first * second
quotient = first / second
output = Template("$first + $second = $sum\n$first - $second = $diff\n"
"$fir... |
# Program takes a sequence of DNA, searches for and counts STR repetitions, then cross-references the
# results with a table in a CSV file to identify who the DNA sequence belongs to.
import csv
from sys import argv, exit
def main():
# User must provide at least one command line argument, otherwise terminate prog... |
#!/usr/bin/python
import sys
import os
import math
#####################################################################
# Helper functions
#####################################################################
# function getNGrams(text, n)
# returns all phrases of length n words in text
def getNGrams(text, n):
n... |
from decimal import *
''' Initialize the variables '''
darlehen = Decimal(0)
zinssatz = Decimal(0)
laufzeit = Decimal(0)
while Decimal(darlehen)<=0:
darlehen = input("Geben Sie bitte die Darlehen ein: (€) ")
while Decimal(zinssatz)<=0:
zinssatz = input("Geben Sie bitte die Zinssatz ein: (%) ")
while Decimal(l... |
from move import Move
class InputReader(object):
def read_move(self):
print "Place your move:row,column,number or quit"
print "sudoku> ",
raw_move = raw_input() # input (he reads what you type)
if raw_move == "quit":
return Move(0,0,0,True) # returns the instantiation of the class Move
else:
row_in... |
def factorial(number):
if number == 1:
print('Base case reached!')
return 1
else:
print('Finding ', number, ' * ', number - 1, '!', sep='')
result = number * factorial(number - 1)
print(number, ' * ', number -1, '! = ', result, sep='')
return result
print('5! is'... |
#Write a function called add_to_dictionary. add_to_dictionary
#should have three parameters: a dictionary, a potential new
#key, and a potential new value.
#
#add_to_dictionary should add the given key and value to the
#dictionary if the key is of a legal type to be used as a
#dictionary key.
#
#If the key is a legal t... |
#Write a function called check_value. check_value should
#take as input two parameters: a dictionary and a string.
#Both the keys and the values in the dictionary will be
#strings. The string parameter will be the key to look up in
#the dictionary.
#
#check_value should look up the string in the dictionary and
#get its... |
#Imagine you're writing a program to check attendance on a
#classroom roster. The list of students in attendance comes
#in the form of a list of instances of the Student class.
#
#You don't have access to the code for the Student class.
#However, you know that it has at least two attributes:
#first_name and last_name.
... |
#Write a function called to_upper_copy. This function should
#take two parameters, both strings. The first string is the
#filename of a file to which to write (output_file), and the
#second string is the filename of a file from which to read
#(input_file).
#
#to_upper_copy should copy the contents of input_file into
#o... |
#Copy your Burrito class from the last exercise. Now, add
#a method called "get_cost" to the Burrito class. It should
#accept zero arguments (except for "self", of course) and
#it will return a float. Here's how the cost should be
#computed:
#
# - The base cost of a burrito is $5.00
# - If the burrito's meat is "chicke... |
#Write a function called not_list. not_list should have two
#parameters: a list of booleans and a list of integers.
#
#The list of integers will represent indices for the list of
#booleans. not_list should switch the values of all the
#booleans located at those indices.
#
#For example:
#
# bool_list = [True, False, Fal... |
#Last problem, you wrote a function that generated the all-
#time win-loss-tie record for Georgia Tech against any other
#team.
#
#That dataset had a lot of other information in it. Let's
#use it to answer some more questions. As a reminder, the
#data will be a CSV file, meaning that each line will be a
#comma-separate... |
# CMPS 101
# HW7
# Andres Segundo
# Tarum Fraz
import copy
import collections
import heapq
import time
import os
class Graph(object):
# Initializing empty graph
def __init__(self):
self.adj_list = dict() # Initial adjacency list is empty dictionary
self.vertices = set() # Vertices are s... |
def reverse(S):
if S=='':
return ''
else:
return S[-1] + reverse(S[:-1])
print reverse('Ryan') |
f = open("goodStuff.txt")
linesList = f.readlines()
f.close()
print linesList
newList=[] # A new list!
for line in linesList: # for each line in our linesList...
newList.append(line[:-1]) # ... slice off the last character and append the truncated string to the newList
print newList |
#coding:utf-8
radius = input("请输入半径: ")
area = radius * radius * 3.14159
#Display results
print "结果:"
#正常情况
print "半径为",radius,"的圆面积为", area
#去处之间空格
print "半径为"+str(radius)+"的圆面积为"+str(area) |
"""programa que crea el resumen de una contrasenya"""
from Crypto.Hash import SHA256
CLAU = input("ingrese una contraseña: ")
CLAU = CLAU.encode("UTF-8")
OBJH = SHA256.new(CLAU)
RESUM = OBJH.digest()
IV = b"1234567887654321"
print(OBJH.hexdigest())
|
#!/usr/bin/python3
import csv
def readData(fileName):
"""Reads existing data file and returns contents.
Args:
fileName: string; name of file to read.
Returns:
List of lists of strings; with all data previously recorded."""
history = []
with open(fileName, newline='') as csvfile:
... |
from dataclasses import dataclass
from math import sqrt
from typing import Optional
@dataclass
class Point:
x: float
y: float
previous_point: Point = Point(0, 0)
length = 0
number = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'nineth', 'tenth']
def find_distance(distance, f... |
# -*- coding:utf-8 -*-
"""
作者:lby
日期:2020年11月08日
"""
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
# 暴力破解法(超出时间限制)
# if len(s) < 2:
# return s
# max = s[0]
# for i in range(len(s)):
# ... |
# -*- coding:utf-8 -*-
"""
作者:lby
日期:2020年12月24日
"""
class Solution(object):
def xorOperation(self, n, start):
"""
:type n: int
:type start: int
:rtype: int
"""
result = 0
for i in [start + 2 * i for i in range(n)]:
result ^= i
return res... |
##The following code is based on Fig.12.2. in John Guttag's book. Class Item defines name, value and weight attribute for each item.##
class Item(object):
def __init__(self,n,v,w):
self.name=n
self.value=v
self.weight=w
def getName(self):
return self.name
def getVa... |
#Sum of all items in a list
list=[1,2,5,6,8,7,9,11]
print(list)
sum=0
for i in list:
sum=sum+i
print("Sum of the list is",sum) |
#Work with built-in packages
import math
num = int(input("Enter a number: "))
p = int(input("Enter the power: "))
print(num,"to the power of", p, " is: ", math.pow(num, p))
print("Square root of ", p, " is: ", math.sqrt(num)) |
import random
MINIMUM = 1
MAXIMUM = 45
NUMBERS_PER_LINE = 6
def main():
number_of_quick_picks = int(input("How many quick picks? "))
for i in range(number_of_quick_picks):
row_numbers_generated = calculate_row_numbers()
row_numbers_generated.sort()
print(" ".join("{:2}".format(number)... |
'''
*************
* *
* *
* *
*************
'''
def boxPrint(symbol, width, height):
if len(symbol) != 1:
raise Exception('"symbol" needs to a string of length 1.')
if (width < 2) or (height < 2):
raise Exception('"width" and "height" must be greater than or equal to 2.')
print(symbol * width... |
## Assignment 1 ##
# Importing the data #
import pandas as pd
king = pd.read_csv('https://raw.githubusercontent.com/mcanela-iese/' +
'DataSci_Course/master/Data/king.csv')
# Linear regression model (class) #
from sklearn import linear_model
lm = linear_model.LinearRegression()
y = king['price']
X = king[['bedroom... |
# -*- coding: utf-8 -*-
"""
***** STUDENT MANAGEMENT SYSTEM *****
"""
import sys
lessons = ["A", "B", "C", "D", "E"]
list0 = []
student = "Serkan Toraman"
i = 0
while i<3:
name = input("Name Surname: ")
if name == student:
print(f'\n Welcome {name}\n')
break
... |
def bubble_sort(l):
for i in range(len(l)):
for j in range(len(l)-1):
if l[i] < l[j]:
l[i], l[j] = l[j] , l[i]
return l
|
# ***Notes from class***
# CAT
# 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 Z
# 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
# Shift = 3
# C = F
# A = D
# T = W
# set a message
# get a message
# set shift
# encrypt message
# decrypt message!
# print me... |
from tkinter import *
root = Tk(className = "button_click_label")
root.geometry("200x200")
message = StringVar()
message.set('hi')
l1 = Label(root, text="hi")
def press():
l1.config(text="hello")
b1 = Button(root, text = "clickhere", command = press).pack()
l1.pack()
root.mainloop() |
"""
Binary search algorithm, iterative implementation.
A binary search is a method to quickly find a given item in a sorted
list. It's important the input list is sorted, or the binary search
algorithm won't be useful at all. Sorted lists are things like
alphabets (because "A" is always before "B," and so on), or numb... |
getal1 = int(input("Geef getal 1 in: "))
getal2 = int(input("Geef getal 2 in: "))
code = int(input("Geef een code in: "))
if code == 1:
print(getal1 + getal2)
elif code == 2:
print(getal1 - getal2)
elif code == 3:
print(getal1 * getal2)
elif code == 4:
print(getal1 ** 2)
elif code == 5:
print(geta... |
def print_gelijkenissen():
tekst1 = "Georgiouszen"
tekst2 = "Giogriiuzzin"
for i in range(len(tekst1)): # van 0 tot lengte van "Georgi"
if tekst1[i] in tekst2: # als er een letter van "Georgi" terugkomt in "Giogri"
for j in range(len(tekst2)): # van 0 tot lengte van "Giogri"
... |
import math
diameter_wiel = int(input("Geef de diameter van een wiel in: "))
afgelegde_weg_omwenteling = diameter_wiel * math.pi * 0.0254
print("De omwenteling van het wiel is: " + str(int((afgelegde_weg_omwenteling * 100) + 0.5) / 100))
|
som = 0
for i in range(28):
leeftijd = int(input("Geef leeftijd van student " + str(i+1) + " in: "))
som += leeftijd
gemiddelde = som / (i + 1)
print("Gemiddelde leeftijd " + str(gemiddelde) + ".")
|
def teken_rand_rechthoek(aantal_tekens, aantal_rijen):
for i in range(aantal_rijen):
if i == 0:
print("* " * aantal_tekens, end="")
print()
elif i == aantal_rijen - 1:
print("* " * aantal_tekens, end="")
else:
print("* " + " " * (aantal_tekens... |
def print_driehoek(grootte, begin_letter):
tekst = ""
for i in range(0, grootte + 1):
for j in range(0, i):
tekst += chr(ord(begin_letter))
begin_letter = chr(ord(begin_letter) + 1)
if ord(begin_letter) > 90:
begin_letter = "A"
print(tekst)
... |
hoogte = int(input("Geef de grootte van de driehoek in: "))
for i in range(hoogte, 0, -1):
print("@" * i)
|
from typing import Any, Dict, List, Iterable, Optional, Tuple
ProductDict = Dict[str, Any]
# Initialise an empty list to store product records in
product_records: List[ProductDict] = []
def get_product_by_id(product_id: str) -> Optional[ProductDict]:
product = next(
(
prod for prod in produc... |
'''
Este script grafica la superficie de un toro con ecuacion
z^2 + (sqrt(x^2+y^2)-3)^2 = 1 y la superficie de un cilindro con
ecuacion (x-2)^2 + z^2 = 1.
'''
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
# primer plot, toro
angulo = ... |
# Python3
# -*- coding: utf-8 -*-
# FIFO即First in First Out,先进先出。
# Queue提供了一个基本的FIFO容器,使用方法很简单,maxsize是个整数,
# 指明了队列中能存放的数据个数的上限。一旦达到上限,插入会导致阻塞,
# 直到队列中的数据被消费掉。如果maxsize小于或者等于0,队列大小没有限制。
import queue
q = queue.Queue()
for i in range(10):
q.put(i)
while not q.empty():
print(q.get()) |
#!/usr/bin/python3
# 出现锁嵌套时,要用threading.RLock建立锁,否则程序会出问题
import time
import logging
import threading
import random
import sys
from threading import Thread
logging.basicConfig(
level=logging.DEBUG,
format='%(threadName)-10s: %(message)s',
) # format 中的 threadName 可以捕获到线程的名字,所以下边logging.debug()中不需要传入线程名
def ... |
from modules.binary_tree import BinaryTree
class Node:
"""Class for storing a node."""
__slots__ = '_element', '_parent', '_left', '_right', 'mark'
def __init__(self, element, parent=None, left=None, right=None,
mark='unknown'):
self.mark = mark
self._element = element
... |
from helpers.helper import input_data, print_table, pregunta
from helpers.menu import Menu
from controller.categoria_controller import Categoria_controller
from classes.producto import Productos
class Productos_controller:
def __init__(self):
self.categoria_controller = Categoria_controller()
self.... |
# python function def
print '************** Function arguments Test Programs **************'
print 'keyword arguments'
def person(name, age, **kw):
print 'name:', name, 'age:', age
for name, value in kw.items():
print '{0}: {1}'.format(name, value)
person('Remind',6)
person('Remind',6,city='shanghai... |
# python function def
print '************** Function arguments Test Programs **************'
print 'changeable arguments'
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
print calc(2,7,0)
nums = [1,2,3]
print calc(*nums)
raw_input()
|
# python function def
print '************** Function arguments Test Programs **************'
# Type check
def power_001(x):
if not isinstance(x,(int,float)):
raise TypeError('Bad Operand Type')
else:
return x*x;
print power_001(2)
# Default arguments
def power_002(x,n=2):
if not isinstance(x,(int,float)):
r... |
# Set foundation
print '************** Set Test Programs **************'
s1 = set([1,2])
print 's1:',s1
#duplicate elements will not be stored
s2 = set([1,1,1,1,4,5])
print 's2:',s2
s2.add(3)
print 'add 3 to s2:',s2
s2.add(3)
print 'add 3 to s2:',s2
s2.remove(3)
print 'remove 3 from s2:',s2
#remove non-exist eleme... |
# -*- coding: utf-8 -*-
"""Calculations (re-scaling, etc.)"""
from math import ceil
def rescale(data, maximum):
"""
Crude and simple rescaling of the numeric values
of `data` to the maximum number `maximum`.
:param data: <dict> in the form of {key: val <float> or <int>}
:return: <dict> if the ... |
# The energy in joules released for a particular Richter scale measurement is given by:
# Energy = 10 ^ (1.5 x richter + 4.8)
# ------------------------------------------
# One ton of exploded TNT yields 4.184x10^9
# joules. Thus, you can relate the energy released in
# joules to tons of exploded TNT.
richter_scale_... |
def ask_numbers ():
while True:
try:
wall_length = float(input("Type a length of wall:"))
break
except:
print("Data is not a number. Try again!")
continue
while True:
try:
flower_distance = float(input("Distance bet... |
def detect_anagrams(string, array):
lst = []
for word in array:
if word == string:
continue
if len(string) != len(word):
continue
for letter in word:
if letter not in string:
continue
s = set(string)
w = set(word)
... |
"""
Purpose:
A program to implement a guessing game.
Game rules
1. A game co-ordinator inputs the number of players to a game
2. At the start of the game, all players are asked for their names
3. At the start of each round, a new magic number between 1 and 10 (not visible to the players) is generated
4. Each player i... |
"""
Selenium Test Automation:
Scope:
1.To count the number of items listed in the cart.
2.To calculate the total cost of the items in the cart.
Author: Preedhi Vivek
Date: 14/08/2019
"""
import time
from selenium import webdriver
import weather_shopper_module as m1
# Start of program execution
if (__name__ == '__m... |
__author__ = "Joselito Junior"
print("Programa que calcula do valor consumido pelo cliente no restaurante")
print("")
hamburger = input("Digite a quantidade de Hambúrger: ")
batataFritas = input("Digite a quantidade de Batata Fritas: ")
milkshake = input("Digite a quantidade de Milkshake: ")
print("")
print(" O valor ... |
i = 0
palavra = "palavra"
while i < len(palavra):
print(palavra[i])
i += 1 |
__author__ = "Joselito Junior"
#Inicio da função media
def media(nota1, nota2, nota3):
return ((float(nota1) + float(nota2) + float(nota3)) / 3)
#Fim da função media
print("Este programa faz o cálculo da média de 3 valores")
notas = input("Digite os três valores na oredem: nota1, nota2, nota3 (separados por vígu... |
__author__ = "Joselito Junior"
#valor = input("Digite dois números inteiros separados por virgula:\n")
#valor1, valor2 = valor.split(',')
valor1 = int(input("Digite o valor 1: "))
valor2 = int(input("Digite o valor 2: "))
print(sum(range(valor1 + 1, valor2, 1)))
|
__author__ = "Joselito Junior"
ano = float(input("Digite um ano: "))
if((ano % 4) == 0):
if((ano % 100) != 0): #Verifica se o ano termina em 00
print("Esse ano é bissexto")
elif((ano % 400) == 0):
print("Esse ano é bissexto")
else:
print("Esse ano não é bissexto")
else... |
#Write a function called sum_lists. sum_lists should take
#one parameter, which will be a list of lists of integers.
#sum_lists should return the sum of adding every number from
#every list.
#
#For example:
#
# list_of_lists = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
# sum_list(list_of_lists) -> 67
#Add your cod... |
#Write a function called "write_file" that accepts two
#parameters: a filename and some data that will either
#be an integer or a string to write. The function
#should open the file and write the data to the file.
#
#Hints:
#
# - Don't forget to close the file when you're done!
# - If the data isn't a string already... |
"""This class provides the necessary classes for agents (general), predators and prey."""
import numpy as np
import random as rd
from collections import namedtuple, deque
from typing import Callable, NamedTuple, Union
memory = namedtuple('Memory', ('States', 'Rewards', 'Actions'))
class Agent:
"""
This clas... |
x=input("enter the first no: ")
y=input("enter the second no: ")
f=str(input("which operation? +,-,/,* : "))
if f=="+":
addition=float(x)+float(y)
print(addition)
elif f=="-":
subraction=float(x)-float(y)
print(subraction)
elif f=="*":
multiplication=float(x)*float(y)
print(multiplica... |
"""
Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
"""
from typing import List
class Solution... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 5 21:08:42 2020
@author: Mike
"""
#Data Science Capstone
#Michael Bassett
#This is the first set of code used for the "business.json" yelp dataset
import json
import pandas as pd
#Creating one large dataset with all 8 cities we need
#Opening up the a... |
#!/usr/bin/python
print("content-type: text/html\n\n")
# Import the library with the CGI components and functionality
import cgi
import random
# Use the CGI library to gain access to the information entered in the HTML format
form = cgi.FieldStorage()
html = ""
def roll(num_of_dice):
number = [1, 2, 3, 4, 5, ... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 12 04:02:50 2018
@author: bjwil
Assignment #7 - Test Drive
"""
# Test Drive 1 - Chapter 3 - Page 113
# instantiating vowel list to search if letters in string match vowels
vowels = ['a', 'e', 'i', 'o', 'u']
# create an input prompt for the user to enter a string
word = i... |
from collections import deque
def wallCount(walls, filled, x, y, cellWidth):
'''
func: gives the number of walls/ untraversible cells around given cell
inp: list of walls, list of cells which are filled, x coord of current cell, y coord of current cell, cellWidth
out: count of neighbouring cells which are untr... |
#!/usr/bin/python3
if __name__ == "__main__":
import sys
args = sys.argv[1:]
count = len(args)
sum = 0
for i in range(count):
sum = sum + int(args[i])
print(sum)
|
#!/usr/bin/python3
"""Unittest for Base class"""
import unittest
from models.base import Base
from models.rectangle import Rectangle
from models.square import Square
class TestBase(unittest.TestCase):
""" test class"""
def setUp(self):
"""setup for tests"""
self.b1 = Base()
self.b2 ... |
#!/usr/bin/python3
"""THis is a rectangle class"""
class Rectangle:
"""rectangle"""
@property
def width(self):
return self.width
@width.setter
def width(self, value):
if not isinstance(
|
#!/usr/bin/python3
for i in range(8):
for j in range(10):
if j > i:
print("{:d}{:d}, " .format(i, j), end='')
print("{:d}".format(89))
|
#!/usr/bin/python3
class Square:
__size = None
def __init__(self, new_size=None):
self.is_new = True
if new_size is not None:
self.size = new_size
|
#!/usr/bin/python3
""" rectangle class """
from models.base import Base
class Rectangle(Base):
""" rectangle class"""
@property
def width(self):
""" widh getter"""
return self.__width
@width.setter
def width(self, width):
""" width setter"""
if type(width) != in... |
liquor=int(input('请输入一个数字:'))
if 100>=liquor>=90:
print('A')
elif 90>liquor>=80:
print('B')
elif 80>liquor>=60:
print('C')
elif 60>liquor>=0:
print('D')
else:
print("输入错误!")
|
import random
x = random.randrange(100,201) #产生一个[100,200]之间的随机数x
maxn = x
print(x,end="")
for i in range(2,11):
x = random.randrange(100,201) #再产生一个[100,201]之间的随机数x
print(x,end="")
if x>maxn:
maxn = x;
print("最大数:",maxn)
|
import time
### Source: https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&cad=rja&uact=8&ved=0ahUKEwjZk5fmg6DXAhUCPhQKHVdBDBcQjRwIBw&url=http%3A%2F%2Fwww.woojr.com%2Fsummer-mad-libs%2Ffunny-mad-libs%2F&psig=AOvVaw0Mq2_JCsyidLCX4f6V7TT-&ust=1509716868331291
print("Write an adjective")
adjective1 = i... |
class Solution:
def longestCommonPrefix(self, m) -> str:
if not m:
return ""
shortest=min(m,key=len)
for i, letter in enumerate(shortest):
for j in m:
if j[i] != letter:
return shortest[:i]
return shortest
func=Solution()
s... |
# count 1s in list and ignore 0s
# i.e. [1,0,1,1,0,0,0,0,1,1,1,1,1] = 1, 2, 5
a = [0,0,0,0,0]
b = [1,1,1,1,1]
c = [0,1,1,1,1,1,0,1,1,1,1]
d = [1,1,0,1,0,0,1,1,1,0,0]
e = [0,0,0,0,1,1,0,0,1,0,1,1,1]
f = [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1]
def nonogram(binary_array):
nonogram_list = []
one_count = 0
for element... |
class hashTable:
def __init__(self, length):
self.len = length *2
self.buckets = [None] * self.len
def getIndex(self, key):
index = hash(key) % self.len
return index
def set(self, key, value):
index = self.getIndex(key)
if self.buckets[index] is None:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.