text
stringlengths
37
1.41M
#!/usr/bin/python import sys def pair(a, b): pair_set = set() for n in range(a, b+1): s = str(n) for i in range(1,len(s)): s1 = s[i:] s1 = s1 + s[:i] v = int(s1) if v >= a and v <= b and v != n: pair_set.add((n, v)) ...
m = input() for test in range(m): n = input() if n == 0: print "Case #" + str(test + 1) + ": " + "INSOMNIA" continue x = n d = set() for i in str(x): d.add(i) while len(d) < 10: x += n for i in str(x): d.add(i) print "Case #" + str(test ...
def baseconverter(raw_number, base): digits = "0123456789" result = "" while 1: remains = raw_number % base result = digits[remains] + result raw_number = raw_number / base if raw_number == 0: break return result def check_prime_and_factor(raw_number): fo...
def getLast(n): t = n digits = [0]*10 digits = updateDigits(t,digits) while(sum(digits)<10): t += n digits = updateDigits(t,digits) return t def updateDigits(t,digits): for i in range(len(str(t))): ind = int(str(t)[i]) digits[ind] = max(digits[ind...
import StringIO import sys from collections import defaultdict def check(m): root = None for a in m: cs = len(m[a]) if cs == 2 and not root: # print 'root', a root = True elif cs not in (0, 1, 3): return False return True def remove_node(m, node...
def add_row(board, mines): empty = len(board[0]) - mines board += ["." * empty + "*" * mines] def add_col(board, mines): for i in xrange(len(board) - 1, -1, -1): if mines > 0: board[i] += "*" mines -= 1 else: board[i] += "." def display(board): if board == "Impossible": print boa...
import os import sys import re import math import random from itertools import product, permutations, combinations, combinations_with_replacement # Itertools Functions: # product('ABCD', repeat=2) AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD # permutations('ABCD', 2) AB AC AD B...
from math import sqrt def case(case_no): a, b = input().split() count = 0 for i in range(int(a), int(b)+1): root = sqrt(i) if root != round(root): continue root = round(root) if str(i) == str(i)[::-1] and str(root) == str(root)[::-1]: count += 1 print('Case #%i: %i' % (case_no, count)) for i in ...
def round1a_a(path): with open(path, mode='r') as file: lines = file.readlines() test_case_number = 0 line_number = 1 n_line_per_problem = 1 while test_case_number < int(lines[0]): test_case_number += 1 # variables for this problem ...
#!/usr/bin/python ''' Created on 14.04.2012 @author: Jens Grabarske ''' import sys # A number is only valid (i.e.: comes into consideration as a partner) iff, # after all the string manipulations, it doesn't start with a 0 and it is # within A and B (the lower and upper bound) def valid_str_number(candidate, lowerb,...
# Hezekiah's Code Jam Solution # Usage: python3 codejam.py < file.in > file.out def more(line): return int(line.split()[0]) def solve(lines): split = lines[0].split() height = int(split[0]) width = int(split[1]) lawn = [] lengths = [] for row in range(0, height): lawn.append([]) line = lines[row + 1].split...
def solve_fractal(base_length, complexity, students): permutations = [] current_permutation = [] for i in range(1, base_length + 1): current_permutation.append(i) if len(current_permutation) == complexity: permutations.append(current_permutation) current_permut...
def explore(topics, real, fake, pos): if pos == len(topics): for fake_topic in fake: found = [ False, False ] for real_topic in real: for i in range(2): if fake_topic[i] == real_topic[i]: found[i] = True if False in found: return 0 return len(fake) re...
#-*- coding: utf-8 -*- import math def lcm(x, y): """This function takes two integers and returns the L.C.M.""" # choose the greater number if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greate...
#!/usr/bin/env python import sys case_num = 1 def printres(result): global case_num print "Case #%s: %s" % (case_num, result) case_num += 1 def readline(): return sys.stdin.readline().rstrip('\n') def splitline(f): return map(f, readline().split()) def can_be_served(time, btimes, N): count =...
#!/usr/bin/python def readint (): return int(input()) def readarray ( f ): return map(f, input().split()) def solve(N, M, K): if M < 3 or N < 3: return K ret = K for i in range(3, N+1): for j in range(3, M+1): req = 2*(i-2) + 2*(j-2) enclosed = (i-2)*(j-2)+req #print("Considering", i, j, "with enc",...
import itertools def flatten(l): flattened = list() if isinstance(l, list) or isinstance(l, tuple): for node in l: flattened += flatten(node) else: return [l] return flattened with open("input3.txt", "r") as f: linenr = 0 lines = f.read().split("\n")[1:] casenr = 0 while linenr < len(l...
import itertools N = 32 J = 500 # # def isprime(n): # if n == 2: # return -1 # # if not n & 1: # return 2 # # for x in range(3, int(n**0.5) + 1, 2): # if n % x == 0: # return x # # return -1 def unique_permutations(seq): """ Yield only ...
#!/usr/bin/env python3 ################################################################################ def read_int(): return int(input()) def read_words(): return input().split() def read_ints(): return list(map(int,read_words())) def read_floats(): return list(map(float,read_words())) #########...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys from string import * def main(): n = input() googlerese = {'a': 'y', 'b': 'h', 'c': 'e', 'd': 's', 'e': 'o', 'f': 'c', 'g': 'v', 'h': 'x', 'i': 'd', 'j': 'u', 'k': 'i', 'l': 'g', 'm': 'l', 'n': 'b', 'o': 'k', 'p': 'r', 'q': 'z', 'r': 't', 's': 'n', 't': 'w'...
import random input() N,J = [int(x) for x in input().split()] found = 0 random.seed(555) fermatTest = [2,3,4,5,6,7,8,9,10] def isComposite(x) : for a in fermatTest : if pow(a,x-1,x) != 1 : return True return False def findDiv(x) : for i in range(3,1000,2) : if x%i == 0 : return i return None f...
import sys import math import bisect case_nums=0 num_of_lines=1 def print_ans(case_num,solution): print("Case #"+str(case_num)+":"), print_solution(solution) def print_solution(solution): """TO DO""" print solution def input_processor(filename): f=open(filename) data=f.read().split("\n") case_nums=int...
from fractions import Fraction T = int(raw_input()) def is_power2(num): return num != 0 and ((num & (num - 1)) == 0) for t in xrange(T): print "Case #%d:" % (t + 1), inp = raw_input().split("/") fr = Fraction(int(inp[0]), int(inp[1])) if is_power2(fr._denominator): frac ...
def slide(B, M): if M > 2**(B-2): return "IMPOSSIBLE" el = ['POSSIBLE'] if M == 2**(B-2): el.append('0' + (B-1)*'1') else: x = bin(M)[2:] el.append('0'*(B-len(x)-1) + x + '0') for line in range(2, B+1): el.append('0'*line + '1'*(B-line)) return '\n'.join(el) def ...
import itertools def checkPrime(jamcoin): ans = [] for i in xrange(2, 11): temp = int(jamcoin, i) found = 0 j = 3 if temp % 2 == 0: found = 2 while j < int(temp ** .5) + 1 and j < 100000 and not found: if temp % j == 0: ...
from sys import stdin def addToTree(items, tree): treeItem0 = tree.get(items[0], []) treeItem1 = tree.get(items[1], []) treeItem0.append(items[1]) treeItem1.append(items[0]) tree[items[0]] = treeItem0 tree[items[1]] = treeItem1 return tree def countChildren(tree, node, visited=None): ...
def read_line(): return raw_input().strip() def read_words(): return read_line().split() def read_integer(): return int( read_line() ) def read_integers(): return [ int( x ) for x in read_words() ] def fork( A, index = 0 ): if ( A, index ) in cache: return cache[ ( A, index...
#import re #regex #import math #math # math.sqrt(x) -> squre root of x # math.pow(x, y) -> x ^ y # math.ceil(math.sqrt(a)) inFile = "C-small-attempt1" verbose = False def main(): if not verbose: f = open("C:\Users\Peter\Downloads\\" + inFile + ".in", "r") o = open("C:...
# -*- coding: utf-8 -*- """ Created on Sat Apr 9 10:39:32 2016 @author: chenchen """ #test stdin class RevengePancake(): def __init__(self, input_cakes): self.__cakes = input_cakes def get_patterns(self): return self.__cakes #return the time to revenge def revenge_t...
def get_all_coins(number, divisor, coins): if number not in coins: coins[number] = divisor elif divisor == coins[number]: return # already looked at this tree bn = to_bin(number) dn = to_bin(divisor) search_str = "0" * len(dn) start = 0 bn = bn[::-1] while...
def top(n): return (n+2)/3 # n - total score # returns (max, larger?) # where larger is true iff can use a surprise to make it bigger def max_val(n): v = top(n) l = (n+2>3*v) and v>=1 return (v,l) # l - line of input def process(l): ln = [int(s) for s in l.split()] N = ln[0] ...
from sys import * from math import * def check_tiles(n, depth, check): i = 0 tiles = [] while i < n: tile = 0 p = 0 while i < n and p < depth: tile = tile + i * int(pow(n, p)) i = i + 1 p = p + 1 tiles.append(tile+1) if check < len(tiles): return "IMPOSSIBLE" else: return " ".join(str(tile) f...
from decimal import Decimal import math from fractions import Fraction def isEven(number): return number % 2 == 0 twotofourty = math.pow(2,40) def check(number): return Decimal(twotofourty*number)% 1 == 0 r = open("input","r") lines = r.readlines() w = open("output","w") T = int(lines[0]) for f in rang...
def intput(): return int(input()) def insplit(): return input().split() def intsplit(): a = input().split() for i in range(len(a)): a[i] = int(a[i]) return a def strtolist(a): list = [] for c in a: list.append(c) return list def s(a): return str(a) T...
#!/usr/bin/env python import re test = 'small' input = open('%s.in'%test) output = open('%s.out'%test, 'w') not_letters = re.compile(r'[^a-z]') sample_in = not_letters.sub('', """ ejp mysljylc kd kxveddknmc re jsicpdrysi rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd de kr kd eoya kw aej tysr re ujdr lkgc jv """) sam...
import sys def main(input_file): number_of_cases = int(input_file.readline().strip("\n")) for case_number in xrange(1, number_of_cases + 1): print "Case #%d: %s" % (case_number, case(input_file, case_number)) def case(input_file, case_number): next_line = input_file.readline().strip("\n").split() s_max = int(ne...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import sys class Line(object): def __init__(self, line): self.line = line def get_winner(self): x_won = all(char in ('X', 'T') for char in self.line) o_won = all(char in ('O', 'T') for char in self.line) result = [None, 'X', 'O'][o_...
import sys, random from math import sqrt def any_factor(n): i = 2 while i <= 100: if n % i == 0: return i i += 1 return None def make_jam_coin(s): factors = [] for base in range(2, 10+1): fact = any_factor(int(s, base)) if fact is not None: f...
#!/usr/bin/python3.4 import os import sys class Grid: def __init__(self, r, c, m): self.r = r self.c = c self.m = m self.left_to_place = m self.grid = [['.' for i in range(c)] for j in range(r)] self.verification_grid = [['.' for i in range(c)] for j in range(r)] ...
import re def calc(i, r): i = i-1 return (i+1)*(i)*2 + (2*r+1)*(i+1) def process_case() : r, t = map(int, raw_input().split()) lower = 0 upper = 10**18 + 99 # upper = 10 while lower<upper: mid = (lower+1+upper)/2 req = calc(mid, r) # print [lower, upper, mid, req, t] ...
import argparse import numpy as np VOWELS =['a','e','i','o','u'] def ss_count(name,n): lname = list(name) count = 0 for start in range(len(lname)): for stop in range(start,len(lname)): #print "Start %d, Stop %d, word %s" %(start,stop,name) test = [a not in VOWELS for a in lname[start:stop+1]] inR...
import sys def solve(case, k, c, s): # TODO Solve the problem targets = list() if c == 1 and s < k: return "IMPOSSIBLE" elif c > 1 and s < (k + 1) / 2: return "IMPOSSIBLE" off = k / 2 spot = 1 + off if c == 1: targets = range(1, k + 1) else: ...
def possible(lawn): # Get the maximum heights in each row or column row_max = [max(row) for row in lawn] col_max = [max([row[col_num] for row in lawn]) for col_num in range(len(lawn[0]))] # For each square, check if it could have been reached for row_num in range(len(lawn)): for col_nu...
def has3(i, j, name, n): # print "Does", name[i:j+1], "have", n, "?", z = 0 for c in name[i:j+1]: if z == n: return True if c in "aeiou": z = 0 else: z += 1 return z == n t = int(raw_input()) for c in range(t): name, n = raw_input().split() n = int...
# Problem C: Fair and Square # See how many square and palindromic numbers on an interval [a,b] # Fair and square: both it and its square root are palindromes from math import floor, ceil, sqrt inputFile = open('C-large-1.in','rU') outputFile = open('C-large-1.out','w') # do stuff here # METHOD 1: just bru...
#!/usr/bin/env python3 # coding=utf-8 """ Problem 1 for Google CodeJam 2014, Round 1B Author: A. Ayala killerrex@gmail.com """ import sys import re class FeglaString(object): """ String from Fegla """ def __init__(self, txt): """ Reduce to a set of letters and multiplicity ...
#Best friends visited = [] def GetMaxCircle(l, index): global visited count = 0 firstIndex = index lastVisited = -1 while True: count += 1 visited.append(index) lastVisited = index index = l[index] if l[index] == lastVisited: newLi...
from fractions import Fraction def partelf(frac,gen): if frac == Fraction(0,1): return 0 while gen<41: gen=gen+1 frac=frac*Fraction(2,1) if frac >= Fraction(1,1) and frac < Fraction(2,1): if partelf(frac-Fraction(1,1),gen) != 'impossible': ...
def read_case(): return map(int, input().split()) def make_solution(n, N): h = N//2 s = format(n, '0' + str(h-1)+'b') s = '1' + s s = s + "".join('1' if c == '0' else '0' for c in s) return [s] + list(range(3, 12)) def solve(case): N, J = case return [make_solution(i, N) fo...
import sys import math from decimal import Decimal def concat_str(args): s = "" for arg in args: s += str(arg) return s def debug(*args): sys.stderr.write(concat_str(args) + "\n") def printf(*args): debug(*args) print concat_str(args) def int_input(): return map(int, raw_input()....
def flip_stack(stack, top_n): # Left represents the top of the stack """ :rtype : str """ new_top = ''.join('-' if pancake == '+' else '+' for pancake in stack[top_n-1::-1]) old_bottom = stack[top_n:] assert len(stack) == len(new_top + old_bottom) return new_top + old_bottom ...
def get_operations(A,sizes): if A<2: #we cant make A bigger.. return len(sizes) enlargements_needed = [0] enlargements = 0 for size in sizes: while A<=size: A += A-1 enlargements += 1 enlargements_needed.append(enlargements) A += size removals_needed = range(len(sizes),...
#!/usr/bin/python """ template.py input-file > output-file""" import sys from numpy import * def input_words(): line = IN.readline() return line.strip().split() def input_ints(): return map(int, input_words()) def input_floats(): return map(float, input_words()) def fill_until(a): x = sum(a) ...
#!/usr/bin/env python def get_input(func): raw = raw_input().split(' ') return map(func, raw) def compute(i): typed = get_input(int) n = typed[0] x = typed[1:] r = {} rl = [] t = x.pop() r[t] = (t,) rl.append((t,)) while x: a = x.pop() t = [(a,)] f...
divisor = -1 def isprime(n): global divisor """Returns True if n is prime.""" if n == 2: return True if n == 3: return True if n % 2 == 0: divisor = 2 return False if n % 3 == 0: divisor = 3 return False i = 5 w = 2 while i * i <= n: ...
import re from math import ceil def n_ary(f): """Given binary function f(x, y), return an n_ary function such that f(x, y, z) = f(x, f(y,z)), etc. Also allow f(x) = x.""" def n_ary_f(x, *args): if len(args) == 0: return x else: return f(x, n_ary_f(args[0], *a...
cases = int(raw_input()) for case in range(cases): N = int(raw_input()) answer = 0 done = {'1','2','3','4','5','6','7','8','9','0'} if N == 0: answer = "INSOMNIA" else: val = N multiplier = 1 while 1: for c in str(val*multiplier): if c in done: done.remove(c) answer = val*multiplier ...
import sys from itertools import groupby def squash(pancakes): return [group[0] for group in groupby(pancakes)] def flip(pancake): if(pancake == '+'): return '-' elif (pancake == '-'): return '+' else: raise Exception('Pancake was neither blank nor flipped happly') def apply_best_step(pank...
import itertools import math def getNonPrimeDivisor(integerVal): n = integerVal if n % 2 == 0 and n > 2: return(2) for i in range(3, int(math.sqrt(n)) + 1, 2): if n % i == 0: return(i) return(-1) outputList = [] primeNumberList = set() strLen = 1 nuberOfCombReqd = 1 #get the data with open ('C:/Users/...
def read(n, m): board = [] for i in xrange(0,n): line = raw_input().split(" ") board+=[[ int(x) for x in line ]] return board def max_v(board): maxv = list(board[0]) for row in board: for i in xrange(0,len(row)): if row[i]>maxv[i]: maxv[i...
'''The Goal: Like the title suggests, this project involves writing a program that simulates rolling dice. When the program runs, it will randomly choose a number between 1 and 6. (Or whatever other integer you prefer — the number of sides on the die is up to you.) The program will print what that number is. It shoul...
# 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。 import collections import string text=open('D:\I\'M\\usedbypython\\1.txt').read() row=len(open('D:\I\'M\\usedbypython\\1.txt').readlines()) letter=0 digit=0 punc=0 space=0 zh=0 for i in range (len(text)): c=text[i] if c in string.ascii_letters: letter+=1 elif c.is...
""" 需要备份的文件和目录由一个列表指定。 备份应该保存在主备份目录中。 文件备份成一个zip文件。 zip存档的名称是当前的日期和时间。 我们使用标准的zip命令,它通常默认地随Linux/Unix发行版提供。Windows用户可以使用Info-Zip程序。注意你可以使用任何地存档命令, 只要它有命令行界面就可以了,那样的话我们可以从我们的脚本中传递参数给它。 """ import zipfile def zip_files(files, zip_name): zip = zipfile.ZipFile( zip_name, 'w') for file in files: print (...
# 求1+2!+3!+...+20!的和。 # Sum=[] # for i in range (1,21): # j=1 # for k in range(1,i+1): # j*=k # Sum.append(j) # print(sum(Sum)) # TODO 使用map l = range(1,21) def single(n): r = 1 for i in range(1,n+1): r *= i return r print(sum(map(single, l)))
# 按逗号分隔列表。 lista = ['one', 'two', 'three','four','five'] print(','.join(lista)) print(lista)
# 题目:利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。 score = int(input('Enter your score')) def classify(score,): global grade # 将局部作用域转换为全局作用域 if score<60: grade='C' elif score>=90: grade='A' else: grade='B' classify(score) print('%d is belong to %s level.'%(sco...
plain_chars =["a","b","c","d","e","f","g","h","i","l","m","n","o","p","q","r","s","t","u","v","z"] crypto_chars = list(range(0,21)) #returns a list with number between 0 and 20 crypto_chars.reverse() #reverse ##### CHIEDERE 3 FRASI O PAROLE CON IL WHILE N = 0 while N <3: text = input("Sentence: ") tex...
## https://leetcode.com/problems/design-linked-list/ ''' 建立一個Linked List, 包含 get, addAtHead, addAtTail, addAtIndex, deleteAtIndex等方法 ''' class Node: def __init__(self, val): self.val = val self.next = None class MyLinkedList: def __init__(self): self.head = None self.size =...
## https://leetcode.com/problems/search-insert-position/ ''' 將target數字插入到已排序好的序列中, 返回可插入的index 若序列中含有target, 則返回target的index ex: nums = [1,3,5,6], target = 5, return 2 (找到) nums = [1,3,5,6], target = 2, return 1 (沒找到, 插入在1的位置) nums = [1,3,5,6], target = 7, return 4 (沒找到, 大於最後一個值, 插入最後一個位置) nums = [1,3,5,6], target = 0...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Dec 2 17:47:11 2020 @author: dopiwoo Given two strings containing backspaces (identified by the character '#'), check if the two strings are equal. Example 1: Input: str1="xy#z", str2="xzz#" Output: True Explanation: After applying backspaces the str...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 26 16:19:21 2021 @author: dopiwoo We are given an unsorted array containing 'n' numbers taken from the range 1 to 'n'. The array originally contained all the numbers from 1 to 'n', but due to a data error, one of the numbers got duplicated which al...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Dec 30 09:43:53 2020 @author: dopiwoo Given two lists of intervals, find the intersection of these two lists. Each list consists of disjoint intervals sorted on their start time. Example 1: Input: arr1 = [[1, 3], [5, 6], [7, 9]], arr2 = [[2, 3], [5, 7...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Feb 5 17:25:28 2021 @author: dopiwoo Given a binary tree, populate an array to represent its level-by-level traversal. You should populate the values of all nodes of each level from left to right in separate sub-arrays. """ from collections import de...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Dec 1 15:24:13 2020 @author: dopiwoo Given an array containing 0s, 1s and 2s, sort the array in-place. You should treat numbers of the array os objects, hence, we can't count 0s, 1s and 2s to recreate the array. Example 1: Input: [1, 0, 2, 1, 0] Outp...
# -*- coding: utf-8 -*- """ Created on Tue Nov 24 14:45:54 2020 @author: dopiwoo Given an array of sorted numbers, remove all duplicates from it. You should not use any extra space; after removing the duplicates in-place return the length of the subarray that has no duplicate in it. Example 1: Input: [2, 3, 3, 3, 6,...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 30 17:20:06 2020 @author: dopiwoo Given an array arr of unsorted numbers and a target sum, count all triplets in it such that arr[i] + arr[j] + arr[k] < target where i, j, and k are three different indices. Write a function to return the count of s...
# -*- coding: utf-8 -*- """ Created on Sun Nov 15 13:59:35 2020 @author: dopiwoo Given an array containing 0s and 1s, if you are allowed to replace no more than ‘k’ 0s with 1s, find the length of the longest contiguous subarray having all 1s. Example 1: Input: Array=[0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1], k=2 Output: 6 E...
from turtle import * from random import randint # speed of drawing speed(20) # taking the starting point to top-left without drawing penup() goto(-140,140) # drawing race track with 16 vertical lines for step in range(16): # line no write(step, align='center') # turn right and forward with space ...
# Copyright 2015 Rooshil Patel # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
def getbalancepoint(array): num = len(array) if num >= 3: for i in range(num): if i == 0: pass else: list1 = array[:i] # 将传入的列表切片,将一个列表分成2个列表 list2 = array[i + 1:] sum1 = sum(list1) # 对切片后的列表分别求和 su...
"""MULTITHREADED MERGE SORT """ import math import multiprocessing import random import sys import time def merge_it(list_1, list_2): """ Iterative version of 2 lists merging (for the merge sort) """ list_1len, list_2len = len(list_1), len(list_2) list_1index, list_2index = 0, 0 res = []...
""" The GUI of the game. """ import pygame as pg from .square import Square from .animations import Animation class GUI: def __init__(self, location, square_size, gap_size, board): self.board = board self.move_distance = square_size + gap_size self.image = self.make_image(square_size, gap...
## Ejercicio 8 # Crea una clase NIF. Los atributos serán el número de DNI y la letra. # La clase contendrá un método que calcule la letra del NIF a partir del número de DNI. class Nif(): def __init__(self, NIF_number, NIF_letter = None): self.NIF_number = NIF_number self.NIF_letter = NIF_letter ...
# -*- coding: utf-8 -*- def fibonacci_generator(n): a,b = 1, 1 for i in range(n): yield a a,b = b,a+b def main(): while True: try: number = int(input('Please enter number: ')) except: print('You don\'t enter a number') else: ...
# 给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。 # 提醒一下,二叉搜索树满足下列约束条件: # 节点的左子树仅包含键 小于 节点键的节点。 # 节点的右子树仅包含键 大于 节点键的节点。 # 左右子树也必须是二叉搜索树。 # 示例 1: # 输入:[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] # 输出:[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8] # 示例 2:...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ carr...
# 实现获取 下一个排列 的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。 # 如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。 # 必须 原地 修改,只允许使用额外常数空间。 # 示例 1: # 输入:nums = [1,2,3] # 输出:[1,3,2] # 示例 2: # 输入:nums = [3,2,1] # 输出:[1,2,3] # 示例 3: # 输入:nums = [1,1,5] # 输出:[1,5,1] # 示例 4: # 输入:nums = [1] # 输出:[1] # Solution: # Step 1: find non-increasing fr...
""" George Dunnery CS 5001 Homework #7 - Othello (8x8 version) - Module 11/28/2018 Self-Citation: Reviewed code from module spaceship.py (HW5) to help write the flat file processing functions. """ # MODULES & CONSTANTS ---------------------------------------------------------- import turtle import math import os imp...
#SwollenNolon #1/24/18 #slope2.py x1 = float(input('x1 =')) y1 = float(input('y1 =')) x2 = float(input('x2 =')) y2 = float(input('y2 =')) if x1 != x2: slope = (y2-y1)/(x2-x1) print ('The slope is', slope) print ('The equation of the line is Y=', slope, 'X +', y1 - (slope*x1)) else: print ('The slope i...
import re, glob, os def renamer(files, pattern, replacement): print pattern, replacement for pathname in glob.glob(files): basename = os.path.basename(pathname) new_filename = re.sub(pattern, replacement, basename) if new_filename != basename: print "mv %s %s" % (basena...
def palindrome(s): s = str(s) rev = s[::-1] if s == rev: return True else: return False print("Dec\t\tBin") for i in range(100000): if palindrome(i) and palindrome(bin(i)[2:]): print("{:5} \t {} são palindromos".format(i, str(bin(i)[2:])))
import random def start_game(): print("Welcome to the Rando-Numbo!") print("In this game, I will pick a number between 1 and 10, and you will try to guess the number in the least amount of guesses possible.") guess_amount = 0 play_game = True high_score = [] player_guess = None while p...
def main(): infile = open('file.txt','r') outfile = open('newfile1.txt', 'w') for line in infile: print(line,file = outfile, end='') print('Completed wiriting to newfile txt') main()
''''Demo reading lines from text from a File ''''' print('\n***************Iterating over lines**********') '''Reading text from a file with default encoding'''' with open('hello.txt') as text_file: for line in text_file: print (line, end='') print("\n****************Using read() method ***********"...
#!/usr/bin/env python # Simple two DC motor robot class usage example. # Author: Tony DiCola # License: MIT License https://opensource.org/licenses/MIT import time import subprocess import os # Import the Robot.py file (must be in the same directory as this file!). import Robot import cwiid # Set the trim offset for ...
print("welcome to SBI bank ATM") restart=('y') chances = 3 balance = 1000 while chances>0: restart=('y') pin = int(input("please enter your secret number")) if pin == 1234: print('you entered your pin correctly\n') while restart not in ('n','N','no','NO'): print('press ...
from collections import Counter def palindrome_reconstruction(a_word): # To count chars and their occurrences a_w_counter = Counter(a_word) # sorts dictionary to satisfy "lexicographically smallest one" requirement sorted_dict = {k: v for k, v in sorted(a_w_counter.items(), ...
from collections import Counter def countCharacters(words, chars: str) -> int: out = 0 for word in words: # cat for char in word: # c,a,t if word.count(char) > chars.count(char): break else: out += len(word) return out def countCharacters_my_vers...
def print_tree(n): space = (n - 1) // 2 star = 1 while star <= n: print("{}{}{}".format(" " * space, "*" * star, " " * space)) space -= 1 star += 2 print_tree(7)
from collections import Counter from itertools import groupby from itertools import permutations def group_by(data, group_col, value_col, agg_function): """ Group by Inputs: - data: list of tuples e.g.: [('A', 2, 3), ('A', 3, 4)] - group_col: int, column to group by e.g.: 0 - ...