text
stringlengths
37
1.41M
// https://www.hackerrank.com/challenges/jim-and-the-orders/problem def jimOrders(orders): if len(orders) == 1: return [1] queue = [] for i in range(len(orders)): queue.append([sum(orders[i]),i+1]) queue.sort() return [i[1] for i in queue]
import csv import os.path class ContactBox: def __init__(self, contacts=[]): self.contacts = contacts def read_contact(self): with open('contacts.csv', 'r') as file: for con in file: print(con) #This reads from the file def create_csv(self, contact): fi...
class Marker: def __init__(self, color='Red'): self.color = color class MarkerBox: def __init__(self, markers=[]): self.markers = markers def add_marker(self, marker): self.markers.append(marker) def remove_marker(self, color): for marker in self.markers: i...
import numpy as np from math import sqrt from matplotlib import pyplot as plt from matplotlib import style from collections import Counter import warnings import pandas as pd import random def k_nearest_neighbors(data,predict,k=3): # Each label should have at least one chance for a vote if len(dat...
########################################## # Program Name: mapReduce.py # Description: Map Reduce program # Date: 09/18/2012 # Written By: Milind Zodge ########################################## print('Map Reduce Program') dlist = {} infile=open('first.txt', 'r') line=infile.readline() #print('line: ' + lin...
import itertools primes = set(int(p.strip()) for p in open("primes.txt")) def getf(a, b): return lambda n: n**2 + a*n + b def how_many(a, b): f = getf(a, b) count = 0 for i in itertools.count(0): if f(i) not in primes: break count += 1 return count a = 0 b = 0 max = 0 for i in xrange(-999, 1000): ...
# -*- coding: utf-8; -*- import collections def duplicates(xs): """ >>> sorted(duplicates([1, 2, 3, 1, 4, 5, 2, 6, 4, 7, 8])) [1, 2, 4] """ counter = collections.Counter(xs) return [x for (x, count) in counter.items() if count > 1]
#! /usr/bin/env python # -*- coding: utf-8 -*- ''' Created on 2017-11-02 09:58:50; @author: joinpython.com ''' list1 = ['physics', 'chemistry', 1997, 2000]; print list1 list2 = [1, 2, 3, 4, 5 ]; l2=list2 list2.remove(3) list2=[11,12] print l2 list2.append(7) print l2 list3 = ["a", "b", "c", "d"]; list1.append("joinpyt...
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def reverseList(self, head: ListNode) -> ListNode: ans = head nop = head if not ans: return ans while ans.next: ...
# mistake 很妙 wonderful class Solution: def isPowerOfTwo(self, n: int) -> bool: #print(list(bin(n))) #return True return (n > 0) and (n & -n) == n return (n>0) and (1<<30) % n == 0 # 神仙题。。没见过就不会,见过就会了。 # 重点在于对位运算符的理解 # 解法1:&运算,同1则1。 return (n > 0) && (n & -n) == n; # 解释:2的幂次方在二进制下,...
#! /usr/bin/env python def vowel_check(text): vowel = 'a', 'e', 'i', 'o', 'u' check = False vowel_count = 0 for i in text: for j in vowel: if i == j: check = True vowel_count += 1 if vowel_count < 3: check = False return check def...
# # Example file for working with classes # class myClass(): def method1(self): print("myClass has method1") def method2(self, someString): print("myClass has method2",someString) class anotherClass(myClass): def method1(self): myClass.method1(self) print("anotherClass has method1") def method2...
import random import string keys = [] def shuffle_hints(hints): return random.sample(hints, len(hints)) def reset_keys(): global keys keys = [] def get_key(N=3): key = ''.join(random.choices(string.ascii_uppercase + string.digits, k=N)) print(f'key: {key}') if(key not in keys): ...
# -*- coding: utf-8 -*- """ Created on Tue Oct 6 21:34:04 2020 @author: schei """ import random N = 4 turns = 10000000 # dice=[2,3,3,4,4,4,5,5,5,5,6,6,6,6,6,7,7,7,7,7,7,8,8,8,8,8,9,9,9,9,10,10,10,11,11,12] dice=[2,3,3,4,4,4,5,5,5,5,6,6,6,7,7,8] landed = [0 for i in range(40)] current = 0 turn = 0 doubles = 0 while...
# -*- coding: utf-8 -*- """ Created on Sat Sep 19 22:20:31 2020 @author: schei """ def calc_primes(below_num): primes = [2] # first prime (and only even prime) for num in range(3, below_num, 2): # skip even numbers if (num+1) % 1000000 == 0: # prog report for big prime calculations pri...
# -*- coding: utf-8 -*- """ Created on Fri Sep 25 09:41:11 2020 @author: schei """ # Can pass in np.array(primes) to speed things up if needed def get_prime_factorization(num, primes): factored = [] factor = num for prime in primes: first = True while factor % prime == 0: fact...
# -*- coding: utf-8 -*- """ Created on Thu Sep 17 14:28:30 2020 @author: schei """ num = str(2 ** 1000) the_sum = 0 for digit in num: the_sum += int(digit) print(the_sum)
# -*- coding: utf-8 -*- """ Created on Mon Sep 21 22:20:29 2020 @author: schei """ max_sum = 0 for a in range(100): for b in range(100): num = str(a**b) the_sum = 0 for digit in num: the_sum += int(digit) if the_sum > max_sum: max_sum = the_sum print(max_su...
def check(content): with open("extractedTextFromURL.txt") as f: datafile = f.readlines() for line in datafile: if content in line: # print("A Plag Found!!!...\n") print("Comparison DONE!!!...True\n") return True print("Comparison DONE!!!...False\n")...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') class CorpusReader: """ CorpusReader class. It reads the corpus and return it. """ def __init__(self, filename): self.filename = filename def read_corpus(self): """ R...
from automata.fa.dfa import DFA Machine = DFA( states = {"0","1","2","3"}, input_symbols = {'a','b'}, transitions = { "0": { "a":"1" , "b":"3" }, "1": { "a":"0" , "b":"2" }, "2": { "a":"3" , "b":"1" }, "3": { "a":"2" , "b":"0" } }, initial_state="0", final_states={"0"} ) string = input("Ent...
def sec_to_time(sec): min = sec // 60 sec %= 60 hr = min // 60 min %= 60 day = hr // 24 hr %= 24 if day > 0: return f"{day}d {hr}h {min}m {sec}s" elif hr > 0: return f"{hr}h {min}m {sec}s" elif min > 0: return f"{min}m {sec}s" else: return f"{se...
import numpy as np def gradient_descent(x,y): m_current = b_current = 0 iteration = 1000 n = len(x) learning_rate = 0.001 for i in range(iteration): y_prdicted = m_current * x + b_current cost = (1/n) * sum([val**2 for val in (y-y_prdicted)]) md = -(2/n)*sum(x*(y...
#!./bin/python from swampy.TurtleWorld import * import math world = TurtleWorld() def square(t , length): for i in range(4): fd(t , length) lt(t) # lt(t , degree) def polygon(t , n , length , polyg = 0): """Draws n line segments with the given length and angle (in degrees) between them. t ...
import concurrent.futures import logging # Call recursively, with dynamic programming def howManyArrangementsWork(curVoltage,listNumbers,solutions): key = "curVoltage: "+str(curVoltage)+" "+str(listNumbers) if key in solutions: return solutions[key] # How many arrangements worked if len(listNum...
import re filename = "..\inputs\day_six_input.txt" #filename = "temp_input.txt" with open(filename) as f: lines = f.readlines() lights = [[0 for x in range(1000)] for x in range(1000)] for line in lines: searchObj = re.search(r'(turn on|turn off|toggle) ([0-9]+),([0-9]+) through ([0-9]+),([0-9]+)',line) if se...
def findPositions(numSpoken, numsSpoken): mostRecent = -1 mostRecentFound = False for index in range(len(numsSpoken)-1,-1,-1): if numsSpoken[index] == numSpoken and not mostRecentFound: mostRecentFound = True mostRecent = index elif numsSpoken[index] == numSpoken and ...
class PresentDeliverer: present_locations = {} def __init__(self, name): self.name = name self.x = 0 self.y = 0 self.present_locations[self.get_key()]=1 def get_key(self): return str(self.x)+"-"+str(self.y) def status(self): print(self.name + " x: "+str(self.x)+" y: "+str(self.y)) def move(self...
from tkinter import * import wikipedia from googlesearch import search def wiki(): entry_value=entry.get() answer.delete(1.0,END) try: answer_value=wikipedia.summary(entry_value) answer.insert(INSERT,answer_value) except: answer.insert(INSERT,"Please check your input or your inte...
import cs50 import sys import csv if len(sys.argv) != 2: print("Usage: python import.py data.csv") sys.exit(1) csv_file = sys.argv[1] open("students.db", "w").close() db = cs50.SQL("sqlite:///students.db") db.execute("CREATE TABLE students (first TEXT, middle TEXT, last TEXT, house TEXT, birth NUMERIC);") wi...
# -*- coding: utf-8 -*- """ Created on Tue Oct 13 21:34:28 2015 @author: Skyeyes """ class Person(object): def __init__(self, name, age): self.name = name self.age = age def introduce(self): return "My name is %s. I am %d years old." % (self.name, self.age) class Student...
def fib(term): if term > 2: return fib(term - 1) + fib(term - 2) else: return 1 k = int(input("Enter up to which term you want to know:")) for i in range(1, k + 1): print(fib(i))
def affine(msg, key): result = "" for i in range(len(msg)): if i == 0: result += chr(((ord(msg[i]) - 64) + key) % 26 + 64) else: result += chr(((ord(msg[i]) - 64) + (ord(msg[i - 1]) - 64)) % 26 + 64) return result key = int(input("Enter ke...
print("Pattern 1:") patt1 = [] for i in range(1, 6): temp = [] for j in range(0, i): temp.append("*") patt1.append(temp) for i in range(4, 0, -1): temp = [] for j in range(0, i): temp.append("*") patt1.append(temp) for i in patt1: print(*i, sep='') print("Pattern 2:") patt2 ...
print('Welcome to the loan estimator tool or "LET" for short. You can use this tool to calculate your estimated monthly paymemts for your desired loan amount. ') loan = input('What is the loan amount you would like to take out? ') loan = float(loan) interest = input('How much would you like to pay in interest?/n I.E.,...
#! /usr/bin/python # change calculator from decimal import * def menuChoice0(): getcontext().prec = 2 valid = [1,2] choice = ['Would you like to start over?', 'Sorry, I didn\'t catch that. Try again.', '1: Yes', '2: No', 'How much did the item cost?', 'How much money did you hand over?', ...
def del_double(a): """ Функция удаляет дублирующиеся(накладывабщиеся друг на друга) интервалы. :param a: list :return: list """ if len(a) == 2: return a intervals = [] i = 2 while i < len(a): if len(intervals) != 0: a_start, a_end = intervals...
class Father: def activity(self): print("Playing Tennis") class Mother: def art(self): print("Playing Piano") class Daughter(Father,Mother): def hobby(self): print("Dancing") ob=Daughter() ob.hobby(),ob.activity(),ob.art() """ Output: Dancing Playing Tennis Playing Piano """
""" Scenario 2: 1. Open any browser. 2. Navigate to https://www.amazon.in/ 3. Hover on Shop by category drop down 4. Move to Women's Fashion 5. Click on Western wear 6. Select a category from left navigation menu, say Winterwear 7. Click on Jacket under Shop by category 8. Print the total count of the result of that pa...
def listOfTuple(): a=[(i,i**2) for i in range(1,5)] print(a) b = [(i,i**2) for i in range(1,5) if i!=1] print(b) listOfTuple()
class EvenAndOddList: def evenAndOdd(self,l): even=[] odd=[] for i in l: if i%2==0: even.append(i) else: odd.append(i) print("Even element: ",even) print("Odd element: ",odd) ob=EvenAndOddList() l=[4,7,9,6,2,3,5] ob.even...
import random class RandomNumbersinList: def randomNo(self,n): l=[] for i in range(n): l.append(input("Enter the numbers: "))
count=0 lines=open('read.txt','r') for line in lines: words=line.split() count += len(words) print(count) fname = input("Enter file name: ") num_words = 0 f= open(fname, 'r') for line in f: words = line.split() num_words += len(words) print("Number of words:") print(num_words)
num_words = 0 with open("readdata.txt", 'r') as f: for line in f: words = line.split() num_words += len(words) print("Number of words: ", num_words)
""" Scenario 3: 1. Open any browser. 2. Navigate to https://www.amazon.in/ 3. Hover on Shop by category drop down 4. Move to Women's Fashion 5. Click on Western wear 6. Select a category from left navigation menu, say Winterwear 7. Click on Jacket under Shop by category 8. Filter by size, color 9. Sort the result based...
def avgOfNo(li): total = 0 for i in li: total += i avg = total / len(li) print(avg) # another way print(sum(li)/len(li)) li=[2,6,8,4] avgOfNo(li) limit = int(input("Please enter the range of numbers in list: ")) li=[] for i in range(limit): li.append(int(input("Please enter the numb...
dict1={'a': '50', 'c': '78'} print(dict1.get('c')) if dict1.get('c')!= None: print("Key is exist")
def myGenerator(): n=1 yield n n+=1 yield n ob = myGenerator() print(next(ob)) print(next(ob)) for item in myGenerator(): print(item)
file=open("write.txt","w") for lines in range(2): file.write(input("Please enter the content:")) file.write("\n") file.close() lines=open("write.txt","r") data = lines.read() print(data)
def fact(n): f=1 for i in range(1,n+1): f=f*i yield f ob=fact(3) i=iter(ob) print(i) print(next(i)) print(next(i)) print(next(i)) print(next(i)) print(next(i)) print(next(i)) print(next(i))
''' SIMILAR ------------------------------------------------------------------------- https://leetcode.com/problems/prison-cells-after-n-days/ PROMPT ------------------------------------------------------------------------- Write a function that takes two values, an array (arr) and an int (days). The array will have o...
# Решение для одног ослова def int_func(word): lst = list(word) lst[0] = chr(ord(lst[0]) - 32) return ''.join(lst) #word = input('Введите слово: ') w = 'world' print(int_func(w)) # Решение для предложения #string = input('Type your text, please: ') string = 'hello world it is a great day' lst = string.s...
name = input("What is your name: ") leader = input("What is the name of your mentor: ") event = input("What is your favourite festival? ") print(name+" is too cool") # it will dispay the users name and the string that is in red print("for attending " +leader+"'s class, ") print("instead she/he will beattending the " + ...
import math #used math iport the math library a = float(input("Enter the length of the first side: ")) b = float(input("Enter the length of the second side: ")) c = float(input("Enter the length of the third side: ")) s=(a+b+c)/2 area=math.sqrt(s*(s-a)*(s-b)*(s-c))# math.sqrt is the function to find a squar root in th...
secret_number = 42 guess = 0 while guess != secret_number: guess = eval(input("Guess the secret number? ")) if guess < secret_number: print("The number is much too low try again ") elif guess > secret_number: print("The number is much too high try again ") elif guess == secret_number: ...
#Love in the Time of COVID-19 #simDating.py #a pandemic dating sim game #douglas mckenney from simPlayer import * from simNPC import * from simVirus import * from simItem import * from textwrap import * import random def main(): #display title print(("***Love in the Time of COVID-19***").center(...
class _ObjectDict(dict): pass class ObjectTree(object): """A class to facilitate the creation of tree structures.""" def __init__(self): self.root = _ObjectDict() def _split(self, path): if '/' not in path: return "", path else: return path.rsplit('...
a = int(input("enter a number")) b = int(input("enter b number")) c = a+b; print("sum of two number is ",c); #if we don't take a number as a int .by deafult number pass a string see the below example
def volumeOfCube(lengthOfEdge): if (isinstance(lengthOfEdge, int) == False): return "Error! Value should be a number." elif (lengthOfEdge <= 0): return "Error! Value should be greater than 0." else: return(lengthOfEdge * lengthOfEdge * lengthOfEdge)
import time import os import sys import csv def read_file(filename): with open(filename, 'r') as f: return f.read() def write_file(content, filename): with open(filename, 'w') as f: return f.write(content) def append_line_file(content, filename): with open(filename, 'a') as f: ret...
d={} num=int(input("Enter number: ")) for i in range(1,num+1): d[i]=i*i print(d)
tc = input("Enter the number of test cases: ") sort=[] def valid(number): n=int(number) if n>=1 and n<=126: return 'Class A' elif n>=128 and n<=191: return 'Class B' elif n>=192 and n<=223: return 'Class C' ...
tc = input("Enter the number of test cases: ") mass=[] force=[] for i in range(tc): mass.append(input("Enter the mass of "+str(i+1)+ " test case: ")) force.append(input("Enter the force of "+str(i+1)+ " test case: ")) for i,m in enumerate(mass): print str(i+1)+' Acceleration: '+str(force[i]/m)
ip=input("enter the ip address ").split('.') a=[] for i in ip: a.append(int(i)) print(a)
list1=input('Enter the space separated elements for list 1 : ').split(' ') list2=input('Enter the space separated elements for list 2 : ').split(' ') print(list(set(list1).intersection(list2)))
# svm-banknote.py # parsons/5-mar-2017 # # The input data is the banknote authenticaton dataset at the UCI # Machine Learning repository: # https://archive.ics.uci.edu/ml/datasets/banknote+authentication # # The code to load a csv file is based on code written by Elizabeth Sklar for Lab 1. # # The code to plot the deci...
#!/usr/bin/env python # coding: utf-8 # In[5]: # CREATE A SET set1={"a","b","c"} set1 # In[6]: # add an element set1={"a","b","c"} set1.add("1") set1 # In[9]: set1={"a","b","c"} set1.add("1") set1.add("$") set1.add("100") set1.add("apple") set1.add("@") set1.add("bat") set1.add("1000") set1 # In[10]: ...
nodes = ['A', 'B','C','F','O','P','R','S'] weightedEdges = [ ['A','C',494], ['A','S',140], ['A','O',146], ['O','S',151], ['C','R',146], ['C','P',138], ['S','F',99], ['S','R',80], ['R','P',97], ['F','B',211], ['P','B',101] ] initialState = 'A' goalState = 'B' goalPath = [ini...
# -*- coding: utf-8 -*- """ Created on Thu Sep 14 22:32:01 2017 @author: mywow 1、 买帽子 【题目描述】度度熊想去商场买一顶帽子,商场里有N顶帽子,有些帽子的价格可能相同。度度熊想买一顶价格第三便宜的帽子,问第三便宜的帽子价格是多少? 输入描述: 首先输入一个正整数N(N <= 50),接下来输入N个数表示每顶帽子的价格(价格均是正整数,且小于等于 1000) 输出描述: 如果存在第三便宜的帽子,请输出这个价格是多少,否则输出-1 输入例子: 10 10 10 10 10 20 20 30 30 40 40 输出例子: 30 分析:因为Python可...
"""Generate Markov text from text files.""" from random import choice import sys def open_and_read_file(files): """Take file path as string; return text as string. Takes a string that is a file path, opens the file, and turns the file's contents as one string of text. """ full_document = [] ...
# Enter your code here. Read input from STDIN. Print output to STDOUT import re import email.utils class Regex(): def __init__(self, string): self.string = string def varify_email_address(self): email = string.split('<') if re.match('^[a-z][a-z0-9-._]+@[a-z]+[.][a-z]{1,3}[>]$', email[1]...
import numpy as np import gym def single_relu(x): if x < 0: return 0 else: return x relu = np.vectorize(single_relu) class Agent: def __init__(self, std=0.5, verbose=False): self.verbose = verbose self.std = std self.reward = 0 self.weights1 = np.ra...
def digital_root(n): """ function to return digital root of a number args: int n return: recursive addition of number's digits """ new_num = 0 for num in str(n): new_num += int(num) return (new_num if new_num < 10 else digital_root(new_num))
a = int(input('Enter the deposit: \n')) year = int(input('Enter years: \n')) x = 0 while x in range(year): x = x + 1 a += a * 0.1 print(round(a, 2))
#account test goes here import unittest from bank.account import Account class TestAccountClass(unittest.TestCase): """Test Account Class""" def test_account_object_returns_current_balance(self): """Test if account object returns current balance.""" account = Account('001', 50) self.a...
#!/bin/python3 import sys def fairRations(B): loaves = 0 # If we want all of the elements in the set to be even # and our only tool is to add +2 to the set each time # the set must have an even sum or we will always have # at least 1 odd element left if sum(B) % 2 == 1: return "NO"...
import random from random import randint import time percentg = randint(90, 100) percentg = str(percentg) randassign = input("Enter assignment example: The map quiz >>>") time.sleep(1) finished = False while finished == False: goals = ["I will complete most of my homework in class", "I will be focused in class " +...
''' Created: 1st June, 2017 @author aguimaraesduarte@usfca.edu ''' class sound(object): ''' This class creates an object that allows for transformation of a word into its corresponding soundex. ''' def __init__(self): ''' Constructor ''' self.soundex_dict = { ...
#Load the libraries import pandas as pd import numpy as np #Read the data data = pd.read_csv("sample/sample_0.011.csv") numeric = ["lotarea", "bldgarea","numbldgs","numfloors","unitsres","unitstotal","lotfront", "lotdepth","bldgfront","bldgdepth","yearbuilt", "residfar","commfar","facilfar"...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Nov 9 13:05:38 2019 @author: sapronov """ import math import time import numpy as np from matplotlib import pyplot as plt from matplotlib.animation import FuncAnimation plt.style.use('seaborn-pastel') fig = plt.figure() ax = plt.axe...
# -*- coding: utf-8 -*- """ Spyder Editor """ import os import csv csv_path = os.path.join("Resources","budget_data.csv") month = [] pl = [] totalmonth = 0 with open (csv_path) as budgetdata: csv_reader = csv.reader(budgetdata,delimiter = ",") csv_header = next(csv_reader) # print(csv_header) ...
group1 = int(input("Введіть кількість учнів 1 групи: ")) group2 = int(input("Введіть кількість учнів 1 групи: ")) group3 = int(input("Введіть кількість учнів 1 групи: ")) desk1 = group1//2 + group1%2 desk2 = group2//2 + group2%2 desk3 = group3//2 + group3%2 amount = desk1 + desk2 + desk3 print("Мінімальна кількість сто...
x1 = int(input("Enter 1 coordinate of 1 cell")) y1 = int(input("Enter 2 coordinate of 1 cell")) x2 = int(input("Enter 1 coordinate of 2 cell")) y2 = int(input("Enter 2 coordinate of 2 cell")) if (x1 == x2) or (y1 == y2): print("YES") else: print("NO")
def add(a,b): """add function""" c=a+b print c def sub(a,b): """sub function""" c=a-b print c def div(a,b): """division function""" if(b==0): print "not defined" else: c=a/b print c def mul(a,b): """mulitply function""" c=a*b print c def mod(a,b): """modulus function""" if(b==0): print "not d...
#q4 print "Enter a number" n=raw_input() b=list(n) i=0 sum=0 while(i<len(b)): sum=sum+int(b[i]) i=i+1 print sum
import re print "Enter passwords separated by comma" p=raw_input() b=p.split(",") i=0 while(i<len(b)): x = True while x: if (len(b[i])<6 or len(b[i])>12): break elif not re.search("[a-z]",b[i]): break elif not re.search("[0-9]",b[i]): break elif not re.search("[A-Z]",b[i]): break elif not re.s...
mes = int(input("Ingresa el número de mes [1-12]: ")) if mes == 1: mesTexto = "Enero" elif mes == 2: mesTexto = "Febrero" elif mes == 3: mesTexto = "Marzo" elif mes == 4: mesTexto = "Abril" elif mes == 5: mesTexto = "Mayo" elif mes == 6: mesTexto = "Junio" elif mes == 7: mesTexto = "Julio" ...
# ¿Cuál es la utilidad del Break? for letra in "UNIVERSIDAD ESTATAL DE SONORA": if letra == "A": print(letra) break # ¿Cuál es la utilidad del Continue? # Enviar a impresión por pantalla los números pares # contenidos dentro de un rango de valores for i in range(50): if i%2 == 0: pr...
auswahl = input('Bitte Wähle ein rezept aus 1=Pfankuchen, 2=Waffeln, 3=Käsekuchen ') auswahl1 = '1' auswahl2 = '2' auswahl3 = '3' if auswahl == '1' : print('400g Mehl', '750ml Mich', '1 Prise Salz', '3 Eier', 'Etwas Butter zum backen') print('') print('Ja, ich weiß was nun viele denken. Das hat d...
import re import json CARD_REGEX = re.compile(r"(\d+|[jqkar])([hdcs])") RANKS = { "2": "two", "3": "three", "4": "four", "5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine", "10": "ten", "j": "jack", "q": "queen", "k": "king", "a": "ace", "r": "joke...
import math def gen_primes(n): """ Generate an infinite sequence of prime numbers. """ # Maps composites to primes witnessing their compositeness. # This is memory efficient, as the sieve is not "run forward" # indefinitely, but only as long as required by the current # number being tested. ...
x=input('name') y='hello' z=y+x print(z)
# Course: CS261 - Data Structures # Author: Brandon Hong # Date: 6/10/21 # Description: A directed graph that utilizes DFS, BFS, and Dijkstra's algorithm to compute graph inputs # and desired outputs. Can be used to find shortest paths to certain problems. import heapq class DirectedGraph: """ Clas...
X = int(input()) if X>=0: ans =X else: ans = 0 print(ans)
# input # N # d1,d2 ... dn # # output # 作ることのできる鏡餅の最大の段数を出力せよ。 n = int(input()) diameters = set() for i in range(n): diameters.add(input()) print(len(diameters))
from networkx import Graph from networkx.algorithms.traversal.breadth_first_search import bfs_predecessors G = Graph() N,M = map(int,input().split()) rows = [list(map(int,input().split())) for _ in range(M)] G.add_edges_from(rows) preds = dict(bfs_predecessors(G,source=1)) if len(preds)+1 != N: print("No") ...
n = int(input()) s = input() len = n//2 if s == s[:len]*2: ans = "Yes" else: ans = "No" print(ans)
N = int(input()) ans = 0 def dfs(n,use3,use5,use7): global ans if n>N: return if use3 and use5 and use7: ans += 1 dfs(n*10+3,True,use5,use7) dfs(n*10+5,use3,True,use7) dfs(n*10+7,use3,use5,True) dfs(0,False,False,False) print(ans)
# from math import factorial,sqrt # from itertools import permutations as permus # from fractions import gcd # from collections import deque,Counter # import numpy as np # import scipy as scp # 入力の受け取り n = int(input()) strlist = "abcdefghij" def dfs(s,num): if len(s) >= n: print(s) return el...
class Operation: def __init__(self, name, function, function_on_equal, neutral_value=0): self.name = name self.f = function self.f_on_equal = function_on_equal def add_multiple(x, count): return x * count def min_multiple(x, count): return x def max_multiple(x, count): retu...