text
stringlengths
37
1.41M
''' Created on 26 May 2016 @author: Sam ''' # Python 2.7 import sys if __name__ == '__main__': #store board and check rows board, queens = [], [] try: for i in xrange(8): row = raw_input() queens.append((row.index('*'), i)) board.append(...
''' Created on 13 May 2016 @author: Sam ''' # Python 3.5 if __name__ == '__main__': n = int(input()) while n > -1: oldelapsed, miles = 0, 0 for i in range(n): line = input().split() elapsed = int(line[1]) miles += int(line[0]) * (elapsed - o...
''' Created on 13 May 2016 @author: Sam ''' # Python 3.5 if __name__ == '__main__': X, Y = set([]), set([]) for _ in range(3): line = input().split() newX, newY = int(line[0]), int(line[1]) if newX not in X: X.add(newX) else: X.remove(newX) ...
import os import ast def menu(): os.system('cls') print('account/password mgnt system') print('='*50) print(''' 1. input account and password 2. display account and password 3. change account and password 4. remove account and password 0. End''') print("="*50) def read_data()...
#! python # # http://adventofcode.com/2019/day/15 # import Intcode import click class Input: def __init__(self): self.calibrate() def SetOutput( self, mapOutput ): self.mapOutput = mapOutput def calibrate(self): print('Calibrate by pressing left arrow:') self.west = click...
import random class card: def __init__(self, suit=None, rank=None, faceUp=None): self.suits = { 0 : 'Diamonds', 1 : 'Clubs', 2 : 'Hearts', 3 : 'Spades' } self.ranks = { 1 : 'Ace', 2 : 'Two', 3 : 'Thre...
def writeFile(): try: f = open('NewFile', 'w') f.write("Text to be written in NewFile") except: print "There was an error writing into the file" else: print "File has been written succesfully" def writeFile2(): try: f = open('NewFile', 'w') f.write("Text to bee written in NewFile from 2nd function!") ...
file1 = open("Test.txt", "w") try: file1.read() except: print "You can't read, cause you are using the write parameter!!" file1.write("This is the ttest line to be written into the text file") #we need to close the file aafter writing in it file1.close() file2 = open("Test.txt", "r") print file2.read() #If the ...
def exception(): try: print 2 + "Arjun" except: print "Cannot Add an integer and a string!! \n" def exception2(): try: print 2 + "Arjun" except: print "Cannot Add an integer and a string!!" finally: print "I am from finally block\n" def exception3(): try: x = 2+2 print "Try block x is %s"%(x) p...
from Tkinter import * root = Tk() equalTo = "" def btnPress(num): global equalTo equalTo = equalTo + str(num) equation.set(equalTo) def equalPress(): global equalTo total = str(eval(equalTo)) equation.set(total) equalTo = "" def clear(): global equalTo equalTo = "" equation.set("Let's Calculate!") zero ...
def up_low(s): d = {"upper":0, "lower":0} for c in s: if c.isupper(): d["upper"]+=1 elif c.islower(): d["lower"]+=1 else: pass print "Original String : ", s print "No. of Upper case Characters : ", d["upper"] print "No. of Lower case Characters : ", d["lower"] s = "Hello, My name is Arjun Dass" up_...
import Tkinter import tkMessageBox root = Tkinter.Tk() tkMessageBox.showinfo("Title ", "Something went wrong!! ") answer = tkMessageBox.askquestion("Question 1:", "Are you a human?") if answer == "yes": tkMessageBox.showinfo("Congrats!!", "Well Duh!!") if answer == "no": tkMessageBox.showinfo("Nope!!", "You are a...
counties_dict = {"Arapahoe": 422829, "Denver": 463353, "Jefferson": 432438} for county, voters in counties_dict.items(): print(str(county) + " county has " + str(voters) + " registered voters.") voting_data = [{"county":"Arapahoe", "registered_voters": 422829}, {"county":"Denver", "registered_voters": 463353}, {"c...
t=int(input()) while t: n = int(input()) S = input() if "Y" in S: if S.count("Y") > S.count("I"): print("NOT INDIAN") elif "I" in S: print("INDIAN") else: print("NOT SURE") t = t-1
t = int(input()) while t: str1 = input() str2 = input() A = 0 B = 0 for i in range(len(str1)): if str1[i]=="?" or str2[i]=="?": B += 1 elif str1[i]!=str2[i]: A += 1 B += 1 print(A,B) t = t-1
import math t = int(input()) while t: A, B=list(map(int,input().split())) area = A*B hcf = math.gcd(A,B) print(int(area/(hcf*hcf))) t = t-1
""" -------------------------------------------------------------------------------------- Programa que implementa o client da comunicacao TCP/IP com Diffie-Hellman Objetivo: Comunicacao de cliente-servidor fazendo o estabelecimento de Chave Secreta com Diffie-Hellman Restricoes: o programa necessita que um...
import simplegui import random num = 100 # helper function to start and restart the game def new_game(): # initialize global variables used in your code here global tries, secret_number secret_number = random.randrange(0,num+1) if num == 100: tries = 7 else: tries = 10 print "R...
''' 利用python的max()和min(), 在Python里字符串是可以比较的,按照ascII值排,举例abb, aba,abac,最大为abb,最小为aba。 所以只需要比较最大最小的公共前缀就是整个数组的公共前缀。 法一法二不相上下。 ''' class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: if not strs: return "" strs_max = max(strs) strs_min = min(strs) if str...
''' External LED was connected to Pin 15 of the Raspberry Pi Pico''' ''' A resistor of 100 ohms was used''' from machine import Pin, Timer led = Pin(15, Pin.OUT) timer = Timer() #function def blink(timer): led.toggle() timer.init(freq=2.5, mode=Timer.PERIODIC, callback=blink)
total=0 print "how many are you adding" userinput= raw_input() for x in range(userinput): print "what is the number" total = total + userinput print total total2 =[] for x in range(3): print "input a number" userinput = int(raw_input()) total2.append(userinput) print sum(total2) total3=1...
#Justin Moroz 1/27/2017 import random #create list called gumballs gumballs=[] #append appropriate amount into list for each color yellow=random.randint(10,15) count=0 while count<yellow: gumballs.append("yellow") count+=1 blue=random.randint(1,10) count=0 while count<blue: gumballs....
import sys def get_colour_map(colour_input): colour_map = {} for l in colour_input: primary_colour, contained_colour_string = [x.strip() for x in l.replace('.','').split('bags contain')] colour_map[primary_colour] = {} if 'no other bag' in contained_colour_string: continue contained_colours =...
import re def numberOfCharacters(inputString): mainString = inputString[1:-1] i = 0 numberOfQuotedCharacters = 0 numberOfBackSlashes = 0 numberOfHexCharacters = 0 while i < len(mainString): if mainString[i] == '\\': if mainString[i+1] == '"': numberOfQuotedCh...
import unittest from . import day03 class TestDay3(unittest.TestCase): def test_manhattan_distance_is_calculated_correctly(self): self.assertTrue(True) def test_list_of_points_can_be_obtained_from_an_instruction(self): instruction = 'R2' starting_coordinates = (0,0) expected_re...
def get_input(): instruction_list_A, instruction_list_B = [instruction_line.split(',') for instruction_line in open('./python/inputday03.txt', 'r').read().split('\n')[:2]] return instruction_list_A, instruction_list_B def get_points_from_current_position_to_next(instruction='R0', starting_coordinates=(0,0)): ...
import unittest from . import day02 class TestDay2(unittest.TestCase): def test_input_can_be_broken_correctly(self): test_input = '1-3 a: abcde' output = day02.break_input_into_rules(test_input) expected_output = { 'min_times': 1, 'max_times': 3, 'test_letter': 'a', 'password': 'a...
import argparse def find_common_character_in_column(column_index, input, least=False): character_count = {} for row in input: if row[column_index] not in character_count: character_count[row[column_index]] = 1 else: character_count[row[column_index]] += 1 if not leas...
#wijziging # datatypes #----------- # int = integer = getal = nummer # string = tekst # boolean = (true or false) (1 of 0) #functies (built in functies van python zelf) #---------------------------------------------- # herkenning van een functie (ronde haakjes) # int() = functie zonder parameter # int(parameter) =...
getal1 = input("Geef getal 1 in:") getal2 = int(input("Geef getal 2 in:")) if(int(getal1) > getal2): product = int(getal1) * getal2 print("Product:", product) som = int(getal1) + getal2 print("Som:", som) verschil = int(getal1) - getal2 print("Verschil:", verschil) quotient = int(getal1) / getal2 print("Qu...
from collections import deque def check(d): while d: big = d.popleft() if d[0]>d[-1] else d.pop() if not d: return "Yes" if d[-1]>big or d[0]>big: return "No" for i in range(int(input())): int(input()) d = deque(map(int,input().split())) print(check(d...
""" functions around vectors """ def normalize(position): """ Accepts `position` of arbitrary precision and returns the block containing that position. Parameters ---------- position : tuple of len 3 Returns ------- block_position : tuple of ints of len 3 """ x, y, z = posit...
def benchmark_finder(corporate_bond, bond_dict): """ Finds government bond benchmark (government bond with closest term to corporate_bond) for a single corporate bond. @type bond_dict: dictionary @rtype: Bond """ min_diff = None benchmark = None for key, value in bond_dict.items...
# -*- coding: utf-8 -*- # !/usr/bin/env python # @Time : 2021/7/8 11:58 上午 # @Author : lidong@test.com # @Site : # @File : myself.py """ 930. 和相同的二元子数组 给你一个二元数组 nums ,和一个整数 goal ,请你统计并返回有多少个和为 goal 的 非空 子数组。子数组 是数组的一段连续部分 示例 1: 输入:nums = [1,0,1,0,1], goal = 2 输出:4 解释: 有 4 个满足题目要求的子数组:[1,0,1]...
from Node import Node class LinkedList(object): def __init__(self): self.head = None self.counter = 0 # O(N) def traverseList(self): currentNode = self.head while currentNode is not None: print("%d" % currentNode.data) currentNode = currentNo...
def quick_sort(A): if len(A) <= 1: return left, right, middle = [], [], [] pivot = A[0] for i in range(len(A)): if A[i] < pivot: left.append(A[i]) elif A[i] > pivot: right.append(A[i]) else: middle.append(A[i]) quick_sort(left) ...
def brackets(sequence): ''' Возвращает True, если переданная последовательность скобок правильная. Иначе False. ''' open_brackets = ('(', '[', '{') close_brackets = (')', ']', '}') stack = [] for bracket in sequence: if bracket in open_brackets: stack.append(bracket)...
#!/usr/bin/env python """ evaluators.py: Collection of functions that are used to evaluate individuals in the population. """ def optimize_depot_nodes(vrp, **kwargs): """ Attempts to optimize depot nodes by selecting them for each vehicle in such a manner that travel costs are as low as possible on ...
from algorithms.gradient_descent import * from algorithms.logistic_regression import * def iterations_to_achieve_minimum_error(min_value, initial_u=1, initial_v=1, learning_rate=0.1): n_iterations = 1 u = initial_u v = initial_v actual_value = error_surface_result(u, v) while actual_value > min_value: actual_v...
import requests import sys from bs4 import BeautifulSoup from PIL import Image from io import BytesIO base_url = "http://xkcd.com/" n = raw_input("Enter the comic number\n> ") if n.isdigit() == False: print "Input is not a number" sys.exit() url = base_url + str(n) page = requests.get(url).content soup = Beauti...
#Given a non-overlapping interval list which is sorted by start point. #Insert a new interval into it, make sure the list is still in order and non-overlapping (merge intervals if necessary). #Insert (2, 5) into [(1,2), (5,9)], we get [(1,9)]. #Insert (3, 4) into [(1,2), (5,9)], we get [(1,2), (3,4), (5,9)]. #Soluti...
#!/bin/python3 import math import os import random import re import sys # # Complete the 'nonDivisibleSubset' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER k # 2. INTEGER_ARRAY s # def nonDivisibleSubset(k, s): # Write your code he...
# Enter your code here. Read input from STDIN. Print output to STDOUT import re for i in range(0, int(input())): matches = re.findall( r"(#(?:[\da-f]{3}){1,2})(?!\w)(?=.*;)", input(), re.IGNORECASE) for m in matches: print(m)
# Enter your code here. Read input from STDIN. Print output to STDOUT K = int(input()) room_numbers = list(map(int, input().split())) first = set() existing = set() for room in room_numbers: if room in first: existing.add(room) else: first.add(room) print(first.difference(existing).pop())
# Enter your code here. Read input from STDIN. Print output to STDOUT from itertools import groupby if __name__ == "__main__": S = input() print(*[(len(list(g)), int(k)) for k, g in groupby(S)])
#!/bin/python3 import math import os import random import re import sys # # Complete the 'breakingRecords' function below. # # The function is expected to return an INTEGER_ARRAY. # The function accepts INTEGER_ARRAY scores as parameter. # def breakingRecords(scores): # Write your code here current_min = sc...
#!/bin/python3 import math import os import random import re import sys # # Complete the 'minimumDistances' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER_ARRAY a as parameter. # def minimumDistances(a): # Write your code here min_ = len(a) idx = {} ...
# Enter your code here. Read input from STDIN. Print output to STDOUT import re def convert(line): return re.sub(r"(?<= )(&&|\|\|)(?= )", lambda x: "and" if x.group() == "&&" else "or", line) if __name__ == "__main__": N = int(input()) for i in range(N): print(convert(input()))
#!/bin/python3 import math import os import random import re import sys # # Complete the 'cavityMap' function below. # # The function is expected to return a STRING_ARRAY. # The function accepts STRING_ARRAY grid as parameter. # def cavityMap(grid): # Write your code here idx_change = [] for i in range(1...
#!/bin/python3 import math import os import random import re import sys # # Complete the 'appendAndDelete' function below. # # The function is expected to return a STRING. # The function accepts following parameters: # 1. STRING s # 2. STRING t # 3. INTEGER k # def appendAndDelete(s, t, k): # Write your code...
# Enter your code here. Read input from STDIN. Print output to STDOUT def print_mode(a, b, m): print(pow(a, b)) print(pow(a, b, m)) if __name__ == "__main__": print_mode(int(input()), int(input()), int(input()))
#!/bin/python3 import math import os import random import re import sys # # Complete the 'viralAdvertising' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER n as parameter. # def viralAdvertising(n): # Write your code here shared = 5 cum = 0 for _ in ...
def char_counter(string): for char in string[::]: if char != ' ': if char not in unique: unique.append(char) charctr.append(string.count(char)) print(char + '---' + str(string.count(char))) unique = [] charctr = [] char_counter('Hello World') c...
import os, sys def digitNum(num): result = 0 while num > 0: result += 1 num /= 10 return result dict = { 0: 1, 1: 1, 2: 2 } index = 3 tmp = 2 while digitNum(dict[tmp]) < 1000: prePre = (tmp - 1 + 3) % 3 pre = tmp tmp = (tmp + 1) % 3 dict[tmp] = dict[pre] + di...
import os, sys Tri = 2 Pen = 2 Hex = 2 def Triangle(num): return num * (num + 1) / 2 def Pentagonal(num): return num * (3 * num - 1) / 2 def Hexagonal(num): return num * (2 * num - 1) start = 2 number = 0 while 1: while Triangle(Tri) < start: Tri += 1 while Pentagonal(Pen) < start: ...
import random def get_prime_dic_and_list(maxNumber) -> (dict, list): primeDic = {} primeList = [] for index in range(2, maxNumber): if index not in primeDic: primeList.append(index) facter = 2 while facter * index < maxNumber: primeDic[facter*inde...
''' ''' #target = 10 target = pow(10,25) #target = pow(10,18) #target = 4 unit = [1] while unit[len(unit)-1] * 2 <= target: nt = unit[len(unit)-1] * 2 unit.append(nt) hashDic=dict() def GetAnsFor(n, mx): if n == 0: return 1 #print(n) ret = 0 for i in range(mx-1, -1, -1): ...
# Assignment 2 - Puzzle Game # # CSC148 Fall 2015, University of Toronto # Instructor: David Liu # --------------------------------------------- """This module contains functions responsible for solving a puzzle. This module can be used to take a puzzle and generate one or all possible solutions. It can also generate ...
volt="radar" n=2 k=len(volt) uj=volt[k-1] while n<=k: uj=uj+volt[k-n] n=n+1 print (uj) if uj==volt: print ("palindrom") else: print ("nem palindrom")
""" Simple tools to make lists """ from collections import abc from typing import Any import numpy as np __all__ = [ "is_list_like", "listify", "ndfy", ] def is_list_like( *objs, allow_sets: bool = True, func: object = all ) -> bool: """ Check if inputs are list-like Parameters ...
# -*- coding: utf-8 -*- """ @Software:spyder @File:NumberToHanzi.py @Created on Thu Jun 4 16:08:47 2020 @author: betty @description:数字转文本表达 """ class NumberToHanzi(): def __init__(self): self.han_list = ["零" , "一" , "二" , "三" , "四" , "五" , "六" , "七" , "八" , "九"] self.unit_list = ["十" , "百" , "千"]...
#O(2N) runtime (simplifies to O(N) runtime.) from collections import deque def main(): d = deque('abcdefgghh') print d dupes = listDupes(d) newD = removeDupes(d, dupes) print newD def listDupes(d): values = {} take_out = [] for item in d: if item in values: take...
''' Wall Class ''' import pygame from physical_object import PhysObj class Wall(PhysObj): # Inherits functions from superclass PhysObj def __init__(self, orientation, x, y): super(Wall, self).__init__(x, y) # Sets the attributes of wall self.orientation = orientation self.pos_x = x self.pos_y = ...
''' Created on Feb 14, 2016 @author: fzhang ''' import sys x = 1234 res = 'integers:...%d...%-6d...%06d' % (x, x, x) print(res) x = 1.23456789 res = '%e | %f |%g' % (x, x, x) print(res) res = '%-6.2f | %05.2f | %+06.1f' % (x, x, x) print(res) ''' When sizes are not known until runtime, you can...
""" Uma rainha requisitou os serviços de um monge e disse-lhe que pagaria qualquer preço. O monge, necessitando de alimentos, indagou à rainha sobre o pagamento, se poderia ser feito com grãos de trigo dispostos em um tabuleiro de xadrez, de tal forma que o primeiro quadro deveria conter apenas um grão e os quadro...
import random nbr_secret = random.randint(1,100) invite = 'Propose un nombre : ' while True: nbr_joueur = input(invite) if nbr_secret == int(nbr_joueur): print('Correct!') break elif nbr_secret > int(nbr_joueur): print('Trop bas') else: print('Trop haut')
class Node : def __init__(self, item, n=None): self.item = item self.next = n def enQueue(item): global front, rear newNode = Node(item) # 새로운 노드 생성 if front == None : # 큐가 비었다면 front = newNode else: rear.next = newNode rear = newNode def isEmpty(): return f...
import time def insertion_sort(data,drawData,speed): for i in range(1,len(data)): key = data[i] drawData(data,['black' if x==i else 'red' for x in range(len(data))]) time.sleep(speed) j=i-1 while j>=0 and key < data[j]: data[j+1]=data[j] drawData(data...
# -*- coding: utf-8 -*- """ Created on Sat Sep 26 14:43:19 2015 @author: stoimenoff """ class KIntersect: def count(self, lists, n): nums = {} for i in range(n - 1): for item in lists[i]: if item in nums: nums[item] += 1 else: ...
# -*- coding: utf-8 -*- """ Created on Tue Jun 30 13:08:49 2015 @author: stoimenoff """ class Node: def __init__(self, value, next_node=None): self.value = value self.next_node = next_node def value(self): return self.value def get_next(self): return self.next_node def s...
class Vector: def __init__(self, capacity): self.items = [None] * capacity self.capacity = capacity self.size = 0 # Adds value at a specific index in the Vector. # Complexity: O(n) def insert(self, index, value): if self.size == self.capacity: self.items += se...
# -*- coding: utf-8 -*- """ Created on Thu Jun 11 13:39:00 2015 @author: stoimenoff """ class Sorting: # Sorts a sequence of integers. def sort(self, sequence): for index in range(0, len(sequence)): minEl = sequence[index] minElIndex = index for second_index in rang...
class Library: def __init__(self, listOfBooks): self.books = listOfBooks def displayAvailBooks(self): print("Books present in this libray are:") for book in self.books: print("\t*", book) def borrowBook(self,bookName): if bookName in self.books: print...
from tkinter import * from tkinter import font window = Tk() def from_kg(): gram = float(e2_value.get())*1000 pound = float(e2_value.get())*2.20462 ounce = float(e2_value.get())*35.274 t1.delete("1.0",END) t1.insert(END, gram) t2.delete("1.0", END) t2.insert(END, pound) t3.d...
import socket import select HEADER_LENGTH = 10 IP = "127.0.0.1" PORT = 1234 # Create a socket # socket.AF_INET - address family, IPv4, some otehr possible are AF_INET6, AF_BLUETOOTH, AF_UNIX # socket.SOCK_STREAM - TCP, conection-based, socket.SOCK_DGRAM - UDP, connectionless, datagrams, socket.SOCK_RAW - raw IP packe...
#Menor e Maior valor a = int(input('Digite o 1º número. ')) b = int(input('Digite o 2º número. ')) c = int(input('Digite o 3º número. ')) d = int(input('Digite o 4º número. ')) e = int(input('Digite o 5º número. ')) menor = a if b <= a and b <= c and b <= d and b <= e: menor = b if c <= a and c <= b and c ...
import pandas as pd import numpy as np import math from evaluation import evaluation filename = "datasets/" + input("Enter the dataset name : ") dataset = pd.read_csv(filename) y = dataset.iloc[:,0].to_numpy() x = dataset.iloc[:,1:].to_numpy() k = 1 baco = True lambda_ = 10 ** (-1*(len(str(len(x[0]))))) f,acc = evalu...
import os def Menu(): os.system("clear") print "---NetSend---" print "[1] Send message to a single computer" print "[2] Send message to multiple computers" print "[3] Send spam to a single computer" print "[4] Send spam to multiple computers" print "[5] view computers on network" try: option = int(raw_inpu...
from sys import argv script, username = argv prompt ='>' print ("Hi %s, I am the %r script." % (username, script)) print ("I'd like to ask you a few questions") print ("Do you like me %s?" % username) likes = input(prompt) print ("Where do you live?") lives = input(prompt) print ("What kind of computer do you have?...
container = ['a','b','c'] string_build = "" for data in container: string_build += str(data) # inefficient because it is done with immuatable object (string) print(string_build) builder_list = [] for data in container: builder_list.append(str(data)) # efficient because it is done with mutable object (list)...
def func(x, y, z): return x + y + z print(func(2, 3, 4)) f = lambda x, y, z: x + y + z print(f(2, 3, 4)) a = lambda x = 'fee', y = 'fie', z = 'foe': x + y + z print(a('wee')) def knights(): title = 'Sir' action = (lambda x: title+' '+x) return action act = knights() msg = act('Muthu') print(msg) L ...
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus'] print (animals[0], animals[-1], animals[:2], animals[2:], animals[1:1], animals[1:2])
# write your code here import random def get_task(): global a, b, opr, base_n if level == 2: base_n = random.randint(11, 29) print(base_n) elif level == 1: opr_list = ['+', '-', '*'] operands = [random.randrange(2, 10) for _ in range(2)] a = operands[0] b = ...
import copy class TreeNode: ''' This is a tree Node class ''' def __init__(self, key): self.left = None self.right = None self.key = key class BinaryTree(): ''' This is a Binary Tree Class ''' def __init__(self, root): self.root = root def preorderR(...
import math class Vector2: def __init__(self, x=0, y=0): self.x = x self.y = y def __add__(self, b): if isinstance(b, Vector2): return Vector2(self.x + b.x, self.y + b.y) else: raise TypeError('do no go') def __truediv__(self, b): if isins...
list_tuple=[] sorted_list=[] n=int(input("Enter the no of tuples : ")) for i in range(0,n): ele=input("Enter the tuple : ") list_tuple.append(tuple(ele.split())) l1=[] def convert(list): for i in list: l1.append (i[-1]) return (l1) def sort(sorted_list): sorted_list.sort() ...
import math OPERATORLAENGE = 1 OPERATORADDITION = "+" OPERATORSUBTRAKTION = "-" OPERATORDIVISION = ":" OPERATORMULTIPLIKATION = "*" ZEILENABSTAND = "\n\n" def output(string): # Erstellt, um zu einem spaeteren Zeitpunkt die Ausgabe in eine Textdatei zu schreiben print (string) def multiplikationMitEingabe(): ...
def maximum(*arguments): """ returns the maximum number *arguments: integer arguments e.g. 1,22,3,2 """ maximum_number = 0 *create_list, = arguments duplicate_list = [i for i in create_list] list_of_small_numbers = [i for i in create_list for j in duplicate_list if i < j] for i in d...
import sqlite3 import Student import Methods methods = Methods.Methods() while True: print("""Press (a) to display all students Press (b) to create a new student Press (c) to update an existing student Press (d) to delete a student Press (e) to query students Press (q) to quit""") command = raw_input...
from typing import List from copy import deepcopy class Phrase(object): def __init__(self, words: List[str], occ: int): """ 表示一个词组 :param words: 词组 :paran occ: 词组出现的次数,若为临时使用,请设为0 """ self.__words = deepcopy(words) self.__occ = occ def words(self): ...
import unittest from unittest.mock import * from car import * class TestCar(unittest.TestCase): def test_needsFuel_true(self): # prepare mock self.car.needsFuel = Mock(name='needsFuel') self.car.needsFuel.return_value = True # testing self.assertEqual(self.car.needsFuel()...
import unittest from app.models.game import * from app.models.player import Player class TestGame(unittest.TestCase): def test_play_game(self): play_game(player1, player3) self.assertEqual("Harry wins by playing rock", play_game(player1, player3)) def test_play_game_draw(self): ...
from prob004func import is_palindrome def revNum(num): numstr = str(num) length = len(numstr) pos = length - 1 #Position in the number, start at end newstr = '' while pos >= 0: newstr += numstr[pos] pos -= 1 newnum = int(newstr) return newnum def isLychrel(num, maxi...
size = 0 i1 = 1 i2 = 1 i3 = 0 count = 2 # Start at 2 because we've already set i1 and i2 while size < 1000: i3 = i1 + i2 size = len(str(i3)) i1 = i2 i2 = i3 count += 1 print(count)
def is_palindrome(test): teststr = str(test) length = len(teststr) count = 0 ending = length - 1 first = int(teststr[count]) last = int(teststr[ending]) if length == 1: return True while count <= ending: if first != last: return False count += 1 ...
from math import factorial i = 3 sum = 0 while i < 100000: i_str = str(i) sub_sum = 0 for j in i_str: j = int(j) sub_sum += factorial(j) if sub_sum == i: sum += i print(i) i += 1 print("Sum: ", sum)
def to_word(num): if num > 9999: exit("Error! Too big to convert") thousands = int(num / 1000) hundreds = int((num % 1000) / 100) tens = int((num % 100) / 10) ones = int(num % 10) word = "" if thousands > 0: word += word_ones(thousands) + " thousand " if hundreds > 0: ...
import random def read_sudoku(filename): """ Прочитать Судоку из указанного файла """ digits = [c for c in open(filename).read() if c in '123456789.'] grid = group(digits, 9) return grid def display(values): """Вывод Судоку """ width = 2 line = '+'.join(['-' * (width * 3)] * 3) for ro...
# First we need to import Lock and then we can re-write our functions to use the lock from multiprocessing import Process, Lock, Value import time def add_5000_lock(total, lock): '''This function adds 5000 to the shared value total. Even with the time.sleep functions the race condition should not occur because...
import random str_list=['самовар','весна','лето'] word=random.choice(str_list) letter=random.choice(word) print(word.replace(letter,"?")) input_letter=input('Введите букву: ') if input_letter==letter: print('Победа!\nСлово: {str}'.format(str=word)) else: print('Увы! Попробуй в другой раз.\nСлово: {str}'.form...