Added more python scripts
+5967 · 108 files changed
-
Pyton_stuff/AdventOfCode/25.LetItSnow.py+31 −0 -
Pyton_stuff/AdventOfCode/7.SomeAssemblyRequired.py+52 −0 -
Pyton_stuff/AdventOfCode/get_words.py+30 −0 -
Pyton_stuff/AdventOfCode/input_str.txt+339 −0 -
Pyton_stuff/AdventOfCode/test_str.txt+8 −0 -
Pyton_stuff/Algoritmica_USH_An1/pag_12.py+26 −0 -
Pyton_stuff/Algoritmica_USH_An1/pag_17.py+20 −0 -
Pyton_stuff/Algoritmica_USH_An1/pag_20.py+23 −0 -
Pyton_stuff/Algoritmica_USH_An1/pag_21.py+27 −0 -
Pyton_stuff/CC_number_regenator.py+33 −0 -
Pyton_stuff/Chapter_6_Strings/LICENSE.txt+113 −0 -
Pyton_stuff/Chapter_6_Strings/Strings.py+34 −0 -
Pyton_stuff/Chapter_6_Strings/out.txt+726 −0 -
Pyton_stuff/Chapter_6_Strings/out2.txt+53 −0 -
Pyton_stuff/Chapter_6_Strings/out3.txt+53 −0 -
Pyton_stuff/Codegame/2point_dist.py+10 −0 -
Pyton_stuff/Codegame/Modul_math.py+15 −0 -
Pyton_stuff/Codegame/list_min_index.py+4 −0 -
Pyton_stuff/Codegame/zombie_codegame.py+66 −0 -
Pyton_stuff/Codegame/zombie_codegame2.py+21 −0 -
Pyton_stuff/Codegame/zombie_codegame3.py+61 −0 -
Pyton_stuff/HarveyMuddX/4is4.py+11 −0 -
Pyton_stuff/HarveyMuddX/Chai_Tree.py+43 −0 -
Pyton_stuff/HarveyMuddX/Flakeside.py+31 −0 -
Pyton_stuff/HarveyMuddX/L10Hw1.py+19 −0 -
Pyton_stuff/HarveyMuddX/L10Hw2.py+38 −0 -
Pyton_stuff/HarveyMuddX/L1hw1.py+26 −0 -
Pyton_stuff/HarveyMuddX/L2E3.py+14 −0 -
Pyton_stuff/HarveyMuddX/L2Ex2.py+7 −0 -
Pyton_stuff/HarveyMuddX/L2HW2.py+26 −0 -
Pyton_stuff/HarveyMuddX/L2Hw22.py+86 −0 -
Pyton_stuff/HarveyMuddX/L2hw3.6.py+25 −0 -
Pyton_stuff/HarveyMuddX/L3HW2.py+42 −0 -
Pyton_stuff/HarveyMuddX/L3HW3.py+26 −0 -
Pyton_stuff/HarveyMuddX/L3Hw3.2.py+20 −0 -
Pyton_stuff/HarveyMuddX/L3Hw3.3.py+22 −0 -
Pyton_stuff/HarveyMuddX/L3Hw3.4.py+19 −0 -
Pyton_stuff/HarveyMuddX/L3Hw3.5.py+36 −0 -
Pyton_stuff/HarveyMuddX/L3hw4.py+41 −0 -
Pyton_stuff/HarveyMuddX/L3hw5.py+63 −0 -
Pyton_stuff/HarveyMuddX/L4Hw1.py+50 −0 -
Pyton_stuff/HarveyMuddX/L4Hw10.py+41 −0 -
Pyton_stuff/HarveyMuddX/L4Hw2.py+22 −0 -
Pyton_stuff/HarveyMuddX/L4Hw3.py+31 −0 -
Pyton_stuff/HarveyMuddX/L4Hw4.py+26 −0 -
Pyton_stuff/HarveyMuddX/L4Hw5.py+66 −0 -
Pyton_stuff/HarveyMuddX/L4Hw6.py+21 −0 -
Pyton_stuff/HarveyMuddX/L4Hw7.1.py+29 −0 -
Pyton_stuff/HarveyMuddX/L4Hw7.py+37 −0 -
Pyton_stuff/HarveyMuddX/L4Hw9.1.py+46 −0 -
Pyton_stuff/HarveyMuddX/L4Hw9.3.py+26 −0 -
Pyton_stuff/HarveyMuddX/L4Hw9.4.py+42 −0 -
Pyton_stuff/HarveyMuddX/L4Hw9.py+25 −0 -
Pyton_stuff/HarveyMuddX/L4hw9.2.py+48 −0 -
Pyton_stuff/HarveyMuddX/L5Hw2.1.py+45 −0 -
Pyton_stuff/HarveyMuddX/L5Hw8.1.py+41 −0 -
Pyton_stuff/HarveyMuddX/L5Hw8.py+27 −0 -
Pyton_stuff/HarveyMuddX/L8Hw1.py+71 −0 -
Pyton_stuff/HarveyMuddX/L8Hw2.py+31 −0 -
Pyton_stuff/HarveyMuddX/L9Hw1.1.py+40 −0 -
Pyton_stuff/HarveyMuddX/L9Hw1.py+67 −0 -
Pyton_stuff/HarveyMuddX/PerfTest1.py+19 −0 -
Pyton_stuff/HarveyMuddX/PerfTest2.py+20 −0 -
Pyton_stuff/HarveyMuddX/Picobot_square.txt+15 −0 -
Pyton_stuff/HarveyMuddX/Test_rand_range.py+6 −0 -
Pyton_stuff/HarveyMuddX/regex_sum_175685.txt+594 −0 -
Pyton_stuff/HarveyMuddX/regex_sum_42.txt+594 −0 -
Pyton_stuff/HarveyMuddX/sample_text.txt+8 −0 -
Pyton_stuff/Palindrom_bool.py+23 −0 -
Pyton_stuff/Teme_BD/IP_and_Hostname_out.txt+26 −0 -
Pyton_stuff/Teme_BD/PyAppReadCons.7z.fakebinary -
Pyton_stuff/Teme_BD/Tema2.py+36 −0 -
Pyton_stuff/Teme_BD/Tema3.py+17 −0 -
Pyton_stuff/Teme_BD/Tema3_Test2.py+11 −0 -
Pyton_stuff/Teme_BD/Tema3_Test6.py+18 −0 -
Pyton_stuff/Teme_BD/Tema3_test3.py+6 −0 -
Pyton_stuff/Teme_BD/Tema3_test4.py+21 −0 -
Pyton_stuff/Teme_BD/Tema3_test5.py+38 −0 -
Pyton_stuff/Teme_BD/Tema3_test7_5.py+33 −0 -
Pyton_stuff/Teme_BD/Tema3_test8.py+9 −0 -
Pyton_stuff/Teme_BD/Test1_Multithread.py+21 −0 -
Pyton_stuff/Teme_BD/Test3_Multithread.py+11 −0 -
Pyton_stuff/Teme_BD/Test4_Multithread.py+15 −0 -
Pyton_stuff/Teme_BD/in.txt+7 −0 -
Pyton_stuff/Teme_BD/out.txt+2 −0 -
Pyton_stuff/Teme_BD/tema1.py+11 −0 -
Pyton_stuff/Teme_BD/test2_Multithread.py+23 −0 -
Pyton_stuff/Teme_BD/test5_Multithread.py+24 −0 -
Pyton_stuff/Work/List_dlls.py+13 −0 -
Pyton_stuff/Work/Parse_LOG_files_ERROR_WARNING.py+56 −0 -
Pyton_stuff/Work/Parse_Log_files.py+83 −0 -
Pyton_stuff/Work/Parse_log_files2.py+82 −0 -
Pyton_stuff/Work/Test_ProcList.py+18 −0 -
Pyton_stuff/Work/Test_injection.py+47 −0 -
Pyton_stuff/Work/Teste_Volatility/pslist_test.py+113 −0 -
Pyton_stuff/Work/Teste_Volatility/vol.py_test.py+96 −0 -
Pyton_stuff/Work/exploit_simulator.py+49 −0 -
Pyton_stuff/bulk_rename.py+33 −0 -
Pyton_stuff/caesar_and_tools/List_movies.py+41 −0 -
Pyton_stuff/caesar_and_tools/auto_Caesar.py+79 −0 -
Pyton_stuff/caesar_and_tools/check_valid_mp3.py+23 −0 -
Pyton_stuff/caesar_and_tools/extended_caesar.py+114 −0 -
Pyton_stuff/caesar_and_tools/find_files.py+43 −0 -
Pyton_stuff/caesar_and_tools/leter_tool.py+64 −0 -
Pyton_stuff/caesar_and_tools/simple_substitution.py+76 −0 -
Pyton_stuff/fake_big_factorization.py+86 −0 -
Pyton_stuff/pr4e.py+12 −0 -
Pyton_stuff/real_name_gen.py+59 −0
@@ -0,0 +1,31 @@ +import sys +path = r"D:\StarWarsProj\BD_chalange_04.2017\tst.jpg" +f = open(path, "rb") +chars = f.read() +total_chars = len(chars) +new_char = "" +print(total_chars) +print(chars[0]) +#sys.exit() +last = "" +new_chr = "" +updated_chr = "" +for a in range(total_chars): + if chars[a] in range(32,127): + new_char += chr(chars[a]) + last = chr(chars[a]) + new_chr += last + elif last != "\n": + new_char += "\n" + last = "\n" + if len(new_chr) > 4 and last == "\n" and new_chr not in updated_chr: + updated_chr += new_chr + last + new_chr = "" +f.close() +g = open(r"D:\StarWarsProj\BD_chalange_04.2017\out.log", "w") +g.write(new_char) +g.close() +g = open(r"D:\StarWarsProj\BD_chalange_04.2017\new_out.log", "w") +g.write(updated_chr) +g.close() +print(new_char) @@ -0,0 +1,52 @@ +import string +#import sys +#sys.setrecursionlimit(1000000) # 10000 is an example, try with different values + +#filehandler = open('test_str.txt', 'r') +filehandler = open('input_str.txt', 'r') +text=filehandler.read() +text = text.split("\n") +#print(text) + +#for e in text: +# print (e, e.count(" ")) + +def isn(strg): + try: + a = int(strg) + return True + except: + return False + +def calc(text, value): + print ("Jump in for", value) + if isn(value) is True: + return int(value) + for e in text: + f = e.split(" ") + if e.endswith(" -> " + value): + + if e.count(" ") == 2: + return calc(text,(f[0])) + elif "AND" in e: + return calc(text, f[0]) & calc(text, f[2]) + elif "NOT" in e: + return 65536 + ~calc(text, f[1]) + elif "OR" in e: + return calc(text, f[0]) | calc(text, f[2]) + elif "LSHIFT" in e: + return calc(text, f[0]) << int(f[2]) + elif "RSHIFT" in e: + return calc(text, f[0]) >> int(f[2]) + else: + print("- = - = -") + return 0 +print(calc(text, "a")) +#print(calc(text, "d"),": 72") +#print(calc(text, "e"),": 507") +#print(calc(text, "f"),": 492") +#print(calc(text, "g"),": 114") +#print(calc(text, "h"),": 65412") +#print(calc(text, "i"),": 65079") +#print(calc(text, "x"),": 123") +#print(calc(text, "y"),": 456") @@ -0,0 +1,30 @@ +import string + +filehandler = open('input_str.txt', 'r') +text=filehandler.read() +new_text = [] +for a in text: + if a in "\n": + new_text.append(a) + elif a in string.ascii_uppercase: + new_text.append(a) +new_text = "".join(new_text) + +new_text = new_text.split("\n") + +cmdlist = [] +for command in new_text: + if command not in cmdlist: + cmdlist.append(command) + +print(cmdlist) + +take2 = text.split("\n") +for cmds in take2: + if "LSHIFT" in cmds: + print(cmds) + + +#print (string.ascii_uppercase) +#for i in range(ord('A'), ord('Z')+1): +# print (chr(i)) \ No newline at end of file @@ -0,0 +1,339 @@ +bn RSHIFT 2 -> bo +lf RSHIFT 1 -> ly +fo RSHIFT 3 -> fq +cj OR cp -> cq +fo OR fz -> ga +t OR s -> u +lx -> a +NOT ax -> ay +he RSHIFT 2 -> hf +lf OR lq -> lr +lr AND lt -> lu +dy OR ej -> ek +1 AND cx -> cy +hb LSHIFT 1 -> hv +1 AND bh -> bi +ih AND ij -> ik +c LSHIFT 1 -> t +ea AND eb -> ed +km OR kn -> ko +NOT bw -> bx +ci OR ct -> cu +NOT p -> q +lw OR lv -> lx +NOT lo -> lp +fp OR fv -> fw +o AND q -> r +dh AND dj -> dk +ap LSHIFT 1 -> bj +bk LSHIFT 1 -> ce +NOT ii -> ij +gh OR gi -> gj +kk RSHIFT 1 -> ld +lc LSHIFT 1 -> lw +lb OR la -> lc +1 AND am -> an +gn AND gp -> gq +lf RSHIFT 3 -> lh +e OR f -> g +lg AND lm -> lo +ci RSHIFT 1 -> db +cf LSHIFT 1 -> cz +bn RSHIFT 1 -> cg +et AND fe -> fg +is OR it -> iu +kw AND ky -> kz +ck AND cl -> cn +bj OR bi -> bk +gj RSHIFT 1 -> hc +iu AND jf -> jh +NOT bs -> bt +kk OR kv -> kw +ks AND ku -> kv +hz OR ik -> il +b RSHIFT 1 -> v +iu RSHIFT 1 -> jn +fo RSHIFT 5 -> fr +be AND bg -> bh +ga AND gc -> gd +hf OR hl -> hm +ld OR le -> lf +as RSHIFT 5 -> av +fm OR fn -> fo +hm AND ho -> hp +lg OR lm -> ln +NOT kx -> ky +kk RSHIFT 3 -> km +ek AND em -> en +NOT ft -> fu +NOT jh -> ji +jn OR jo -> jp +gj AND gu -> gw +d AND j -> l +et RSHIFT 1 -> fm +jq OR jw -> jx +ep OR eo -> eq +lv LSHIFT 15 -> lz +NOT ey -> ez +jp RSHIFT 2 -> jq +eg AND ei -> ej +NOT dm -> dn +jp AND ka -> kc +as AND bd -> bf +fk OR fj -> fl +dw OR dx -> dy +lj AND ll -> lm +ec AND ee -> ef +fq AND fr -> ft +NOT kp -> kq +ki OR kj -> kk +cz OR cy -> da +as RSHIFT 3 -> au +an LSHIFT 15 -> ar +fj LSHIFT 15 -> fn +1 AND fi -> fj +he RSHIFT 1 -> hx +lf RSHIFT 2 -> lg +kf LSHIFT 15 -> kj +dz AND ef -> eh +ib OR ic -> id +lf RSHIFT 5 -> li +bp OR bq -> br +NOT gs -> gt +fo RSHIFT 1 -> gh +bz AND cb -> cc +ea OR eb -> ec +lf AND lq -> ls +NOT l -> m +hz RSHIFT 3 -> ib +NOT di -> dj +NOT lk -> ll +jp RSHIFT 3 -> jr +jp RSHIFT 5 -> js +NOT bf -> bg +s LSHIFT 15 -> w +eq LSHIFT 1 -> fk +jl OR jk -> jm +hz AND ik -> im +dz OR ef -> eg +1 AND gy -> gz +la LSHIFT 15 -> le +br AND bt -> bu +NOT cn -> co +v OR w -> x +d OR j -> k +1 AND gd -> ge +ia OR ig -> ih +NOT go -> gp +NOT ed -> ee +jq AND jw -> jy +et OR fe -> ff +aw AND ay -> az +ff AND fh -> fi +ir LSHIFT 1 -> jl +gg LSHIFT 1 -> ha +x RSHIFT 2 -> y +db OR dc -> dd +bl OR bm -> bn +ib AND ic -> ie +x RSHIFT 3 -> z +lh AND li -> lk +ce OR cd -> cf +NOT bb -> bc +hi AND hk -> hl +NOT gb -> gc +1 AND r -> s +fw AND fy -> fz +fb AND fd -> fe +1 AND en -> eo +z OR aa -> ab +bi LSHIFT 15 -> bm +hg OR hh -> hi +kh LSHIFT 1 -> lb +cg OR ch -> ci +1 AND kz -> la +gf OR ge -> gg +gj RSHIFT 2 -> gk +dd RSHIFT 2 -> de +NOT ls -> lt +lh OR li -> lj +jr OR js -> jt +au AND av -> ax +0 -> c +he AND hp -> hr +id AND if -> ig +et RSHIFT 5 -> ew +bp AND bq -> bs +e AND f -> h +ly OR lz -> ma +1 AND lu -> lv +NOT jd -> je +ha OR gz -> hb +dy RSHIFT 1 -> er +iu RSHIFT 2 -> iv +NOT hr -> hs +as RSHIFT 1 -> bl +kk RSHIFT 2 -> kl +b AND n -> p +ln AND lp -> lq +cj AND cp -> cr +dl AND dn -> do +ci RSHIFT 2 -> cj +as OR bd -> be +ge LSHIFT 15 -> gi +hz RSHIFT 5 -> ic +dv LSHIFT 1 -> ep +kl OR kr -> ks +gj OR gu -> gv +he RSHIFT 5 -> hh +NOT fg -> fh +hg AND hh -> hj +b OR n -> o +jk LSHIFT 15 -> jo +gz LSHIFT 15 -> hd +cy LSHIFT 15 -> dc +kk RSHIFT 5 -> kn +ci RSHIFT 3 -> ck +at OR az -> ba +iu RSHIFT 3 -> iw +ko AND kq -> kr +NOT eh -> ei +aq OR ar -> as +iy AND ja -> jb +dd RSHIFT 3 -> df +bn RSHIFT 3 -> bp +1 AND cc -> cd +at AND az -> bb +x OR ai -> aj +kk AND kv -> kx +ao OR an -> ap +dy RSHIFT 3 -> ea +x RSHIFT 1 -> aq +eu AND fa -> fc +kl AND kr -> kt +ia AND ig -> ii +df AND dg -> di +NOT fx -> fy +k AND m -> n +bn RSHIFT 5 -> bq +km AND kn -> kp +dt LSHIFT 15 -> dx +hz RSHIFT 2 -> ia +aj AND al -> am +cd LSHIFT 15 -> ch +hc OR hd -> he +he RSHIFT 3 -> hg +bn OR by -> bz +NOT kt -> ku +z AND aa -> ac +NOT ak -> al +cu AND cw -> cx +NOT ie -> if +dy RSHIFT 2 -> dz +ip LSHIFT 15 -> it +de OR dk -> dl +au OR av -> aw +jg AND ji -> jj +ci AND ct -> cv +dy RSHIFT 5 -> eb +hx OR hy -> hz +eu OR fa -> fb +gj RSHIFT 3 -> gl +fo AND fz -> gb +1 AND jj -> jk +jp OR ka -> kb +de AND dk -> dm +ex AND ez -> fa +df OR dg -> dh +iv OR jb -> jc +x RSHIFT 5 -> aa +NOT hj -> hk +NOT im -> in +fl LSHIFT 1 -> gf +hu LSHIFT 15 -> hy +iq OR ip -> ir +iu RSHIFT 5 -> ix +NOT fc -> fd +NOT el -> em +ck OR cl -> cm +et RSHIFT 3 -> ev +hw LSHIFT 1 -> iq +ci RSHIFT 5 -> cl +iv AND jb -> jd +dd RSHIFT 5 -> dg +as RSHIFT 2 -> at +NOT jy -> jz +af AND ah -> ai +1 AND ds -> dt +jx AND jz -> ka +da LSHIFT 1 -> du +fs AND fu -> fv +jp RSHIFT 1 -> ki +iw AND ix -> iz +iw OR ix -> iy +eo LSHIFT 15 -> es +ev AND ew -> ey +ba AND bc -> bd +fp AND fv -> fx +jc AND je -> jf +et RSHIFT 2 -> eu +kg OR kf -> kh +iu OR jf -> jg +er OR es -> et +fo RSHIFT 2 -> fp +NOT ca -> cb +bv AND bx -> by +u LSHIFT 1 -> ao +cm AND co -> cp +y OR ae -> af +bn AND by -> ca +1 AND ke -> kf +jt AND jv -> jw +fq OR fr -> fs +dy AND ej -> el +NOT kc -> kd +ev OR ew -> ex +dd OR do -> dp +NOT cv -> cw +gr AND gt -> gu +dd RSHIFT 1 -> dw +NOT gw -> gx +NOT iz -> ja +1 AND io -> ip +NOT ag -> ah +b RSHIFT 5 -> f +NOT cr -> cs +kb AND kd -> ke +jr AND js -> ju +cq AND cs -> ct +il AND in -> io +NOT ju -> jv +du OR dt -> dv +dd AND do -> dq +b RSHIFT 2 -> d +jm LSHIFT 1 -> kg +NOT dq -> dr +bo OR bu -> bv +gk OR gq -> gr +he OR hp -> hq +NOT h -> i +hf AND hl -> hn +gv AND gx -> gy +x AND ai -> ak +bo AND bu -> bw +hq AND hs -> ht +hz RSHIFT 1 -> is +gj RSHIFT 5 -> gm +g AND i -> j +gk AND gq -> gs +dp AND dr -> ds +b RSHIFT 3 -> e +gl AND gm -> go +gl OR gm -> gn +y AND ae -> ag +hv OR hu -> hw +1674 -> b +ab AND ad -> ae +NOT ac -> ad +1 AND ht -> hu +NOT hn -> ho \ No newline at end of file @@ -0,0 +1,8 @@ +123 -> x +456 -> y +x AND y -> d +x OR y -> e +x LSHIFT 2 -> f +y RSHIFT 2 -> g +NOT x -> h +NOT y -> i \ No newline at end of file @@ -0,0 +1,26 @@ +def read_a_number(): + nb = input('Choose a number: ') + try: + mode = int(nb) + except ValueError: + print("Not a number") + mode = read_a_number() + return mode +def pag12_prog(): + n = read_a_number() + x = [] + for a in range(n): + x.append(read_a_number()) + print(x) + s=0 + i=0 + while(i<n): + if x[i] > 0: + s = s+x[i] + + else: + s = s-x[i] + i += 1 + s = s / n + print(s) +#pag12_prog() \ No newline at end of file @@ -0,0 +1,20 @@ +from pag_12 import * +def pag17_prog(): + n = read_a_number() + x = [] + for a in range(n): + x.append(read_a_number()) + s1 = 0 + s2 = 0 + i = 0 + while(i<n): + if x[i] != 0: + s1 +=x[i] + else: + s2 -= x[i] + if s1 != -s2: + i += 1 + else: + print(i) + break +#pag17_prog() \ No newline at end of file @@ -0,0 +1,23 @@ +from pag_12 import read_a_number +def pag20_prog(x = None): + n = len(x) + if n == 0: + n = read_a_number() + for a in range(n): + x.append(read_a_number()) + i=0 + print(x) + while i < n: + if x[i] != 0: + pass + else: + print("Sirul contine zerouri") + break + i += 1 + if i == n: + print("Sirul nu contine zerouri") +#pag20_prog([1,2,3]) +#pag20_prog([0,2,3]) +#pag20_prog([1,2,0]) +#pag20_prog([0]) +#pag20_prog([0,0]) @@ -0,0 +1,27 @@ +from pag_12 import read_a_number +def pag21_prog(m = None, n = None): + if m == None and n == None: + m = read_a_number() + n = read_a_number() + a,b = m, n + if m < n: m,n = n,m + r = 0 + if m == n: + n = 0 + r = m + while n: + r = n + n = m % n + m = r + if r == 0: + print(a, b," Numere prime", r) + else: + print(a, b," Cmmdc este ", r) + +pag21_prog(6, 3) +pag21_prog(4, 3) +pag21_prog(16, 240) +pag21_prog(0, 1) +pag21_prog(1, 0) +pag21_prog(0, 0) +pag21_prog(110, 110) \ No newline at end of file @@ -0,0 +1,33 @@ +part_number = "42560353245833ab" + + +def cardLuhnChecksumIsValid(card_number): + """ checks to make sure that the card passes a luhn mod-10 checksum """ + + sum = 0 + num_digits = len(card_number) + oddeven = num_digits & 1 + + for count in range(0, num_digits): + digit = int(card_number[count]) + + if not (( count & 1 ) ^ oddeven ): + digit = digit * 2 + if digit > 9: + digit = digit - 9 + + sum = sum + digit + + return ( (sum % 10) == 0 ) + + + +def get_numbs(): + for a in range(0,9): + for b in range (0,9): + s1 = part_number.replace("a", str(a)) + s2 = s1.replace("b", str(b)) + result = cardLuhnChecksumIsValid(s2) + if result: + print(s2) +get_numbs() \ No newline at end of file @@ -0,0 +1,113 @@ +COPYING -- Describes the terms under which Notepad++ is distributed. +A copy of the GNU GPL is appended to this file. + +IMPORTANT NOTEPAD++ LICENSE TERMS + +Copyright (C)2003 Don HO <don.h@free.fr>. This program is free software; you may redistribute and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; Version 2 with the clarifications and exceptions described below. This guarantees your right to use, modify, and redistribute this software under certain conditions. + +Note that the GPL places important restrictions on "derived works", yet it does not provide a detailed definition of that term. To avoid misunderstandings, we consider an application to constitute a "derivative work" for the purpose of this license if it does any of the following: +1. Integrates source code from Notepad++. +2. Integrates/includes/aggregates Notepad++ into a proprietary executable installer, such as those produced by InstallShield. +3. Links to a library or executes a program that does any of the above. + +Our interpretation applies only to Notepad++ - we don't speak for other people's GPL works. + +This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + +****************************************************************** + + +GNU GENERAL PUBLIC LICENSE +Version 2, June 1991 + +Copyright (C) 1989, 1991 Free Software Foundation, Inc. +59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. + +Preamble +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. + +To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. + +Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. + +Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION +0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. + +1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + +a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. + +b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. + +c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: + +a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, + +b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, + +c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) +The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. +If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. +An application to constitute a "derivative work" for the purpose of this license if it does any of the following: +// 1. Integrates source code from Notepad++. +// 2. Integrates/includes/aggregates Notepad++ into a proprietary executable installer, such as those produced by InstallShield. +// 3. Links to a library or executes a program that does any of the above. + + +4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. + +6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. + +7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. + +10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + + +NO WARRANTY + +11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + + +END OF TERMS AND CONDITIONS @@ -0,0 +1,34 @@ +__author__ = 'vpaun' +r_file=open("LICENSE.txt",'r') +w_file=open("out.txt",'w') +w_file2=open("out2.txt",'w') +w_file3=open("out3.txt",'w') +inp=r_file.read() +norm="" +wild="" +for litera in inp: + if not (ord(litera) > 64 and ord(litera) < 91 or ord(litera)>96 and ord(litera) < 123 or ord(litera) == 32 or ord(litera) == 10): + wild=wild+litera + else: + norm=norm+litera +norm_list = norm.split() +norm_char= norm.strip() +norm_char2= norm_char.strip(" ") +norm_char3= norm_char2.strip("\n") +norm_dictionar= dict() +norm_dictionar2= dict() +for element in norm_list: + norm_dictionar[element] = norm_dictionar.get(element, 0)+1 +for element in norm_char3: + norm_dictionar2[element] = norm_dictionar2.get(element, 0)+1 +table_hour = sorted(norm_dictionar.items()) +table_hour2 = sorted(norm_dictionar2.items()) +table_reversed=sorted([(h, a) for a,h in table_hour],reverse=True) +table_reversed2=sorted([(h, a) for a,h in table_hour2],reverse=True) +#print(sorted([(h, a) for a,h in table_hour],reverse=True), file=w_file) +for h, a in table_reversed: + print(a, " "*(40-len(a)),h, file=w_file) +for h, a in table_reversed2: + print(a, " "*(40-len(a)),h, file=w_file2) +for h, a in table_hour2: + print(h, " "*(40-len(h)),a, file=w_file3) \ No newline at end of file @@ -0,0 +1,726 @@ +the 159 +of 88 +to 85 +or 58 +a 54 +and 52 +you 50 +is 43 +this 40 +Program 40 +that 39 +any 33 +License 33 +it 32 +not 31 +for 30 +on 26 +work 25 +by 24 +software 23 +in 22 +under 19 +distribute 19 +as 19 +copy 18 +code 18 +source 17 +THE 16 +terms 15 +may 15 +distribution 15 +your 14 +program 14 +other 14 +if 14 +free 14 +with 13 +from 12 +be 12 +based 12 +are 12 +all 12 +You 12 +such 11 +rights 11 +conditions 11 +OR 11 +OF 11 +If 11 +which 9 +we 9 +version 9 +must 9 +modify 9 +have 9 +executable 9 +does 9 +an 9 +Software 9 +Free 9 +distributed 8 +copies 8 +TO 8 +Public 8 +PROGRAM 8 +General 8 +Foundation 8 +works 7 +will 7 +whole 7 +warranty 7 +so 7 +section 7 +make 7 +license 7 +its 7 +above 7 +This 7 +these 6 +only 6 +do 6 +copyright 6 +can 6 +The 6 +Notepad 6 +GNU 6 +ANY 6 +use 5 +those 5 +they 5 +system 5 +patent 5 +parties 5 +offer 5 +either 5 +derivative 5 +at 5 +apply 5 +andor 5 +FOR 5 +AND 5 +who 4 +when 4 +third 4 +then 4 +restrictions 4 +redistribute 4 +recipients 4 +receive 4 +purpose 4 +provided 4 +part 4 +original 4 +object 4 +notice 4 +no 4 +new 4 +modified 4 +medium 4 +made 4 +into 4 +intended 4 +freedom 4 +form 4 +following 4 +charge 4 +change 4 +certain 4 +but 4 +applies 4 +YOU 4 +WARRANTY 4 +OTHER 4 +IS 4 +For 4 +A 4 +written 3 +wish 3 +whose 3 +what 3 +want 3 +verbatim 3 +used 3 +time 3 +thus 3 +through 3 +sure 3 +sections 3 +running 3 +right 3 +received 3 +published 3 +publish 3 +proprietary 3 +programs 3 +print 3 +portion 3 +permission 3 +patents 3 +number 3 +normally 3 +most 3 +modifications 3 +modification 3 +means 3 +limitation 3 +licenses 3 +licensed 3 +know 3 +give 3 +files 3 +fee 3 +else 3 +each 3 +derived 3 +covered 3 +countries 3 +corresponding 3 +copying 3 +contains 3 +constitute 3 +consequence 3 +complete 3 +cause 3 +b 3 +authors 3 +application 3 +announcement 3 +To 3 +These 3 +TERMS 3 +Sections 3 +Our 3 +NO 3 +INCLUDING 3 +IN 3 +However 3 +GPL 3 +Each 3 +DAMAGES 3 +BY 3 +Accompany 3 +AS 3 +write 2 +would 2 +without 2 +whether 2 +way 2 +versions 2 +users 2 +two 2 +too 2 +there 2 +them 2 +their 2 +than 2 +term 2 +sublicense 2 +speak 2 +share 2 +separate 2 +scope 2 +saying 2 +satisfy 2 +same 2 +restricted 2 +required 2 +provide 2 +protection 2 +protect 2 +produced 2 +problems 2 +plus 2 +places 2 +place 2 +permitted 2 +otherwise 2 +option 2 +offering 2 +obligations 2 +notices 2 +need 2 +more 2 +modifying 2 +making 2 +machinereadable 2 +licensee 2 +library 2 +law 2 +later 2 +itself 2 +interchange 2 +interactive 2 +intent 2 +installer 2 +independent 2 +impose 2 +holder 2 +get 2 +exercise 2 +executes 2 +exceptions 2 +example 2 +even 2 +entirely 2 +distributing 2 +designed 2 +definition 2 +customarily 2 +court 2 +copyrighted 2 +control 2 +contest 2 +compliance 2 +clear 2 +claims 2 +cannot 2 +c 2 +below 2 +avoid 2 +automatically 2 +ask 2 +appropriate 2 +another 2 +also 2 +along 2 +allowed 2 +act 2 +access 2 +accept 2 +We 2 +WRITING 2 +WITHOUT 2 +WITH 2 +Version 2 +USE 2 +Section 2 +SUCH 2 +PURPOSE 2 +PERMITTED 2 +PARTY 2 +PARTIES 2 +PARTICULAR 2 +NOT 2 +MERCHANTABILITY 2 +Links 2 +LIMITED 2 +LICENSE 2 +LAW 2 +Integratesincludesaggregates 2 +Integrates 2 +InstallShield 2 +In 2 +IMPLIED 2 +HOLDER 2 +GENERAL 2 +FITNESS 2 +DATA 2 +Copyright 2 +COPYRIGHT 2 +COPYING 2 +CONDITIONS 2 +C 2 +BUT 2 +APPLICABLE 2 +ANDOR 2 +yet 1 +years 1 +wrote 1 +willing 1 +wide 1 +volume 1 +void 1 +view 1 +validity 1 +valid 1 +using 1 +user 1 +useful 1 +up 1 +unless 1 +unenforceable 1 +understands 1 +true 1 +translation 1 +translated 1 +translate 1 +transferring 1 +three 1 +threatened 1 +though 1 +thoroughly 1 +things 1 +thereof 1 +themselves 1 +terminated 1 +terminate 1 +telling 1 +take 1 +surrender 1 +subject 1 +storage 1 +steps 1 +status 1 +stating 1 +started 1 +spirit 1 +specify 1 +specifies 1 +special 1 +sometimes 1 +someone 1 +sole 1 +softwareto 1 +since 1 +simultaneously 1 +similar 1 +signed 1 +show 1 +she 1 +sharing 1 +service 1 +scripts 1 +say 1 +runs 1 +run 1 +royaltyfree 1 +revised 1 +reuse 1 +rest 1 +responsible 1 +responsibilities 1 +requirements 1 +reputations 1 +remain 1 +reliance 1 +regardless 1 +refrain 1 +reflect 1 +refers 1 +referring 1 +refer 1 +redistributors 1 +redistribution 1 +recipient 1 +receives 1 +reasonably 1 +reason 1 +reads 1 +rather 1 +range 1 +public 1 +protecting 1 +property 1 +promoting 1 +prominent 1 +prohibited 1 +price 1 +prevent 1 +preserving 1 +present 1 +preferred 1 +precise 1 +practices 1 +placed 1 +pieces 1 +physically 1 +physical 1 +pertinent 1 +permit 1 +permissions 1 +performing 1 +peoples 1 +people 1 +passed 1 +party 1 +parts 1 +particular 1 +outside 1 +output 1 +ours 1 +our 1 +others 1 +ordinary 1 +order 1 +operating 1 +one 1 +obtain 1 +nothing 1 +noncommercial 1 +modules 1 +misunderstandings 1 +mere 1 +meet 1 +major 1 +long 1 +limited 1 +licensor 1 +licensees 1 +legal 1 +least 1 +language 1 +kernel 1 +keep 1 +judgment 1 +issues 1 +invalid 1 +introduced 1 +interpretation 1 +interfaces 1 +interface 1 +interactively 1 +integrity 1 +intact 1 +instead 1 +installation 1 +infringement 1 +infringe 1 +information 1 +induce 1 +individually 1 +indirectly 1 +indicate 1 +incorporates 1 +incorporate 1 +including 1 +included 1 +include 1 +imposed 1 +important 1 +implied 1 +implemented 1 +identifiable 1 +how 1 +hope 1 +herein 1 +held 1 +he 1 +having 1 +has 1 +guided 1 +guarantees 1 +guarantee 1 +gratis 1 +grants 1 +granted 1 +goals 1 +gives 1 +given 1 +geographical 1 +generous 1 +generally 1 +further 1 +full 1 +forming 1 +forbid 1 +follow 1 +file 1 +extend 1 +expressly 1 +explicit 1 +excuse 1 +excluding 1 +excluded 1 +exchange 1 +exception 1 +except 1 +everyones 1 +everyone 1 +every 1 +ever 1 +equivalent 1 +entire 1 +enforcing 1 +effect 1 +dont 1 +donhfreefr 1 +document 1 +distinguishing 1 +display 1 +disclaimer 1 +directly 1 +different 1 +differ 1 +details 1 +detailed 1 +detail 1 +designated 1 +described 1 +derivatives 1 +depends 1 +deny 1 +decision 1 +decide 1 +date 1 +danger 1 +counts 1 +could 1 +cost 1 +contributions 1 +contrast 1 +contradict 1 +contents 1 +containing 1 +constantly 1 +conspicuously 1 +consistent 1 +considered 1 +consider 1 +concerns 1 +components 1 +component 1 +compiler 1 +compilation 1 +compelled 1 +commit 1 +commands 1 +collective 1 +clarifications 1 +claim 1 +circumstances 1 +circumstance 1 +choose 1 +choice 1 +changing 1 +changed 1 +case 1 +carry 1 +bring 1 +both 1 +body 1 +binary 1 +believed 1 +been 1 +balance 1 +away 1 +authordonor 1 +author 1 +attempt 1 +associated 1 +appropriately 1 +appended 1 +anything 1 +anyone 1 +among 1 +alternative 1 +allegation 1 +agreement 1 +aggregation 1 +addressed 1 +address 1 +addition 1 +add 1 +actions 1 +accord 1 +accompanies 1 +acceptance 1 +absence 1 +Whether 1 +When 1 +WILL 1 +WHO 1 +WHEN 1 +WARRANTIES 1 +USA 1 +UNLESS 1 +Thus 1 +Therefore 1 +Temple 1 +THIRD 1 +THERE 1 +Suite 1 +Such 1 +Subsection 1 +Some 1 +See 1 +SUSTAINED 1 +STATED 1 +SPECIAL 1 +SHOULD 1 +SERVICING 1 +RISK 1 +REQUIRED 1 +REPAIR 1 +RENDERED 1 +REDISTRIBUTE 1 +QUALITY 1 +Programs 1 +Preamble 1 +Place 1 +PUBLIC 1 +PROVIDE 1 +PROVE 1 +PROGRAMS 1 +POSSIBILITY 1 +PERFORMANCE 1 +OUT 1 +OTHERWISE 1 +OPERATE 1 +Note 1 +NOTEPAD 1 +NECESSARY 1 +Many 1 +MODIFY 1 +MODIFICATION 1 +MAY 1 +MA 1 +Licenses 1 +Library 1 +LOSSES 1 +LOSS 1 +LICENSED 1 +LIABLE 1 +KIND 1 +June 1 +It 1 +Inc 1 +INCIDENTAL 1 +INACCURATE 1 +INABILITY 1 +IMPORTANT 1 +IF 1 +Hereinafter 1 +HOLDERS 1 +HO 1 +HAS 1 +Foundations 1 +Finally 1 +FREE 1 +FAILURE 1 +Exception 1 +Everyone 1 +EXTENT 1 +EXPRESSED 1 +EXCEPT 1 +EVENT 1 +EVEN 1 +ENTIRE 1 +END 1 +EITHER 1 +Don 1 +Describes 1 +DISTRIBUTION 1 +DEFECTIVE 1 +COST 1 +CORRECTION 1 +CONSEQUENTIAL 1 +CHARGE 1 +By 1 +But 1 +Boston 1 +BEING 1 +BEEN 1 +BECAUSE 1 +BE 1 +Any 1 +And 1 +An 1 +Also 1 +Activities 1 +ASSUME 1 +ARISING 1 +ALL 1 +AGREED 1 +ADVISED 1 +ABOVE 1 @@ -0,0 +1,53 @@ + 2748 +e 1428 +t 1167 +o 1133 +i 952 +r 921 +n 788 +a 783 +s 749 +h 500 +c 456 +d 435 +u 361 +l 308 +f 299 +m 277 +y 272 +p 268 +g 207 +w 182 +b 181 +E 133 +T 125 +I 121 + + 112 +R 108 +A 107 +v 100 +O 100 +P 97 +N 89 +S 86 +L 83 +k 53 +D 50 +F 48 +H 47 +G 45 +Y 43 +C 41 +U 40 +M 31 +x 27 +B 23 +W 21 +V 10 +q 7 +j 7 +X 3 +Q 3 +K 2 +J 1 @@ -0,0 +1,53 @@ + + 112 + 2748 +A 107 +B 23 +C 41 +D 50 +E 133 +F 48 +G 45 +H 47 +I 121 +J 1 +K 2 +L 83 +M 31 +N 89 +O 100 +P 97 +Q 3 +R 108 +S 86 +T 125 +U 40 +V 10 +W 21 +X 3 +Y 43 +a 783 +b 181 +c 456 +d 435 +e 1428 +f 299 +g 207 +h 500 +i 952 +j 7 +k 53 +l 308 +m 277 +n 788 +o 1133 +p 268 +q 7 +r 921 +s 749 +t 1167 +u 361 +v 100 +w 182 +x 27 +y 272 @@ -0,0 +1,10 @@ +def distance(x1,y1,x2,y2): + return "%.2f" % (((x1-x2)**2)+((y1-y2)**2))**(1/2) +def sqrt(nmbr): + return nmbr**(1/2) +print(sqrt(4)) +print(sqrt(5)) +print(distance(9,7,3,2)) +print(distance(-3,5,7,-1)) +print(distance(1,0,4,4)) +print(distance(0,0,16000,9000)) \ No newline at end of file @@ -0,0 +1,15 @@ +def modul (nbr): + if nbr >= 0: + return nbr + else: + return -1*nbr +listnum = [] +listnum.append([1,modul(1)]) +listnum.append([-5,modul(-5)]) +listnum.append([0,modul(0)]) +listnum.append([-0,modul(-0)]) +print(listnum) +#print (modul(1)) +#print (modul(-5)) +#print(modul(0)) +#print (modul(-0)) \ No newline at end of file @@ -0,0 +1,4 @@ +a = [2,4,1,5,1,7] +print(a.index(min(a))) + +print(7//2) \ No newline at end of file @@ -0,0 +1,66 @@ +import sys +import math +#0 < x < 16000 +#0 < y < 9000 +# Save humans, destroy zombies! +def modul(nbr): + if nbr >= 0: + return nbr + else: + return -1*nbr +def distance(x1,y1,x2,y2): + return float("%.2f" % (((x1-x2)**2)+((y1-y2)**2))**(1/2)) +def dest_point(x1,x2,dist): + if x1<x2: return int(x1+(modul(x1-x2)*modul(dist-(dist%400)))/dist) + else: return int(x1-(modul(x1-x2)*modul(dist-(dist%400)))/dist) +# game loop +while 1: + zombies = [] + humans = [] + x, y = [int(i) for i in input().split()] + human_count = int(input()) + for i in range(human_count): + human_id, human_x, human_y = [int(j) for j in input().split()] + humans.append([human_id,human_x,human_y]) + zombie_count = int(input()) + for i in range(zombie_count): + zombie_id, zombie_x, zombie_y, zombie_xnext, zombie_ynext = [int(j) for j in input().split()] + zombies.append([zombie_id, zombie_x, zombie_y, zombie_xnext, zombie_ynext]) + min_dist=distance(0,0,16000,9000) + closest_zmb = 1 + zmb_dist = [] + for j in humans: + zmb_hum_dist = [] + for i in zombies: + zmb_hum_dist.append(distance(j[1],j[2],i[1],i[2])) + zmb_dist.append(zmb_hum_dist) + zmb_hmn_pair = [] + for zmb in zmb_dist: + zmb_hmn_pair.append([zmb.index(min(zmb)),min(zmb)]) + for zmb in zmb_hmn_pair: + if min_dist>zmb[1]: + closest_zmb = zmb[0] + min_dist = zmb[1] + #print(closest_zmb) + #print(zmb_hmn_pair) + #print(zmb_hmn_pair[closest_zmb]) + #print(humans) + #print(humans[zmb_hmn_pair[closest_zmb][0]]) + #print(humans[zmb_hmn_pair[closest_zmb][0]][1]) + #print(zmb_hmn_pair[closest_zmb][1]) + print(dest_point(zombies[closest_zmb][1],humans[zmb_hmn_pair[closest_zmb][0]][1],zmb_hmn_pair[closest_zmb][1]),dest_point(zombies[closest_zmb][2],humans[zmb_hmn_pair[closest_zmb][0]][2],zmb_hmn_pair[closest_zmb][1])) + + + + #print(zmb_dist,zmb_hmn_pair) + + + + #zmb_dist.append([i[0],distance(x,y,i[1],i[2]),distance(x,y,i[3],i[4])]) + + + # Write an action using print + # To debug: print("Debug messages...", file=sys.stderr) + + # Your destination coordinates + #print("0 0") \ No newline at end of file @@ -0,0 +1,21 @@ +import sys +import math + +# Save humans, destroy zombies! + + +# game loop +while 1: + x, y = [int(i) for i in input().split()] + human_count = int(input()) + for i in range(human_count): + human_id, human_x, human_y = [int(j) for j in input().split()] + zombie_count = int(input()) + for i in range(zombie_count): + zombie_id, zombie_x, zombie_y, zombie_xnext, zombie_ynext = [int(j) for j in input().split()] + + # Write an action using print + # To debug: print("Debug messages...", file=sys.stderr) + + # Your destination coordinates + print("0 0") @@ -0,0 +1,61 @@ +import sys +import math + +def modul(nbr): + if nbr >= 0: + return nbr + else: + return -1*nbr +def distance(x1,y1,x2,y2): + return float("%.2f" % (((x1-x2)**2)+((y1-y2)**2))**(1/2)) +def dest_point(x1,x2,dist): + if x1<x2: return int(x1+(modul(x1-x2)*modul(dist-(dist%400)))/dist) + else: return int(x1-(modul(x1-x2)*modul(dist-(dist%400)))/dist) + +# game loop +while 1: + + zombies = [] + humans = [] + x, y = [int(i) for i in input().split()] + human_count = int(input()) + for i in range(human_count): + human_id, human_x, human_y = [int(j) for j in input().split()] + humans.append([human_id,human_x,human_y]) + zombie_count = int(input()) + for i in range(zombie_count): + zombie_id, zombie_x, zombie_y, zombie_xnext, zombie_ynext = [int(j) for j in input().split()] + zombies.append([zombie_id, zombie_x, zombie_y, zombie_xnext, zombie_ynext]) + min_dist=distance(0,0,16000,9000) + winner_human = 0 + winer_zombie = 0 + for human in humans: + for zombie in zombies: + if distance(human[1],human[2],zombie[1],zombie[2]) < min_dist: + min_dist=distance(human[1],human[2],zombie[1],zombie[2]) + winner_human = humans.index(human) + winner_zombie = zombies.index(zombie) + if distance(x,y, + dest_point(zombies[winner_zombie][1],humans[winner_human][1], + distance(zombies[winner_zombie][1],zombies[winner_zombie][2],humans[winner_human][1],humans[winner_human][2])), + dest_point(zombies[winner_zombie][2],humans[winner_human][2], + distance(zombies[winner_zombie][1],zombies[winner_zombie][2],humans[winner_human][1],humans[winner_human][2])) + )>1599: + + try: + print (dest_point(zombies[winner_zombie][3],humans[winner_human][1], + distance(zombies[winner_zombie][3],zombies[winner_zombie][4],humans[winner_human][1],humans[winner_human][2])), + dest_point(zombies[winner_zombie][4],humans[winner_human][2], + distance(zombies[winner_zombie][3],zombies[winner_zombie][4],humans[winner_human][1],humans[winner_human][2]))) + except: + print (dest_point(zombies[winner_zombie][1],humans[winner_human][1], + distance(zombies[winner_zombie][1],zombies[winner_zombie][2],humans[winner_human][1],humans[winner_human][2])), + dest_point(zombies[winner_zombie][2],humans[winner_human][2], + distance(zombies[winner_zombie][1],zombies[winner_zombie][2],humans[winner_human][1],humans[winner_human][2]))) + else: + print (zombies[winner_zombie][1],zombies[winner_zombie][2]) + + # Write an action using print + # To debug: print("Debug messages...", file=sys.stderr) + + # Your destination coordinates @@ -0,0 +1,11 @@ +__author__ = 'darakna' +print("Zero is", 4+4-4-4) +print("One is", 4/4) +print("Two is", (4+4) / 4) +print("Three is", int((4*4-4)/4)) +print("Four is", 4) +print("Five is", 4+4/4) +print("Six is", 4 + (4+4) / 4) +print("Seven is", 4+4 - 4/4) +print("Eight is", 4+4) +print("Nine is", 4+4 + 4/4) \ No newline at end of file @@ -0,0 +1,43 @@ +__author__ = 'darakna' +from turtle import * +def chai(size): + """ our chai function! """ + if (size<9): + return 0 + else: + forward(size) + left(90) + forward(size/2.0) + right(90) + chai( size/2) + right(90) + forward(size) + left(90) + chai( size/2) + left(90) + forward(size/2.0) + right(90) + backward(size) + return #chai(size+5) +chai(100) +left(90) +speed(0) +width(0) +def svtree( trunklength, levels ): + if levels==1: + return 0 + else: + forward(trunklength) + left(60) + forward(trunklength*0.8) + svtree(trunklength*0.8,levels-1) + backward(trunklength*0.8) + right(120) + forward(trunklength*0.8) + svtree(trunklength*0.8,levels-1) + backward(trunklength*0.8) + left(60) + backward(trunklength) + return +hideturtle() +svtree(77,2) @@ -0,0 +1,31 @@ +__author__ = 'darakna' +from turtle import * +from time import * +def flakeside(sidelength, levels): + if levels==0: + forward (sidelength) + return 0 + else: + flakeside (sidelength/3,levels-1) + right(60) + flakeside(sidelength/3,levels-1) + left(120) + flakeside(sidelength/3,levels-1) + right(60) + flakeside (sidelength/3,levels-1) + + +def snowflake(sidelength, levels): + """ fractal snowflake function + sidelength: pixels in the largest-scale triangle side + levels: the number of recursive levels in each side + """ + flakeside( sidelength, levels ) + left(120) + flakeside( sidelength, levels ) + left(120) + flakeside( sidelength, levels ) + left(120) +snowflake(100,3) + +sleep(2) \ No newline at end of file @@ -0,0 +1,19 @@ +__author__ = 'darakna' +import re +def readfile(filename): + readfile = open(filename) + return readfile.read() +def num_list(text): + return re.findall("[0-9]+",text) +def list_sum(list): + testsum = 0 + for num in list: + testsum+=int(num) + return testsum +sample="sample_text.txt" +testfile = "regex_sum_42.txt" +hwfile = "regex_sum_175685.txt" + +print(list_sum(num_list(readfile(sample)))) +print(list_sum(num_list(readfile(testfile)))) +print(list_sum(num_list(readfile(hwfile)))) @@ -0,0 +1,38 @@ +__author__ = 'darakna' +import socket + +server1 = 'www.py4inf.com' +server2 = "www.k.ro" +server4 = "www.google.ro" +server3 = "www.pythonlearn.com" +server5 = "capitalplaza.ro" +server6 = "darakna.go.ro" + + +command1 = "GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n" +command2 = "GET http://www.k.ro HTTP/1.1\n host: www.k.ro \n User-Agent: Mozilla/5.0 (Macintosh; U; PPC; en-US; rv:1.3.1)\n Connection: Keep-Alive\n" +command3 = "GET http://www.pythonlearn.com/code/intro-short.txt HTTP/1.0\n\n" +command4 = "GET / HTTP/1.1\n\n" +command5 = "GET / HTTP/1.1\n" \ + "Host: capitalplaza.ro\n" \ + "Connection: keep-alive\n" \ + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\n"\ + "Upgrade-Insecure-Requests: 1\n"\ + "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7\n"\ + "Accept-Encoding: gzip, deflate, sdch\n"\ + "Accept-Language: en-US,en;q=0.8,ro;q=0.6,fr;q=0.4,de;q=0.2\n\n"\ + #"Cookie: trafic_h=a7b80b9al658558c1c0cd5e733899514*1442412248*k.ro*1446047192*1446216904*4\n" + + +mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +mysock.connect((server5, 80)) +mysock.send(command5.encode('utf-16')) + +while True: + data = mysock.recv(512) + if ( len(data) < 1 ) : + #print (data.decode()) + break + print (data.decode()) + #print(command5) +mysock.close() \ No newline at end of file @@ -0,0 +1,26 @@ +__author__ = 'darakna' +comp = 'elefant' +user = 'indian' # this line is changed during the video + +if comp == 'paper' : + if user == 'paper' : + print ("Tie") + elif user == "rock": + print ("You win") + elif user == "scissors": + print ("I win") + +elif comp == "rock": + if user == 'paper': + print ('I win') + elif user == "scissors": + print ('I win!') + else: + print ("Tie") +else: + if user == 'paper' : + print ("You win") + elif user == "rock": + print ("I win") + else: + print ("Tie") @@ -0,0 +1,14 @@ +__author__ = 'darakna' +pi = [3,1,4,1,5,9] +L = [ 'pi', "isn't", [4,2] ] +M = 'You need parentheses for chemistry !' +print(pi[0],pi[2],pi[4]) +print(pi[0:6:2]) + + +print(M[31:34]) + +print(M[-6:-20:-4]) + + +print(M[17],M[15],M[1],M[6]) \ No newline at end of file @@ -0,0 +1,7 @@ +__author__ = 'darakna' +string_r="1H2e3l4l5o6 7w8o9r0l1d2!" +list_string=list(string_r) +print(list_string) +for element in list_string: + if not element.isdigit(): + print (element,end="") \ No newline at end of file @@ -0,0 +1,26 @@ +__author__ = 'darakna' +# Homework 2, Problem 1 slicing and indexing challenges + +pi = [3,1,4,1,5,9] +e = [2,7,1] +# Example problem (problem 0): Creating the list [2,5,9] from pi and e +answer0 = [ e[0] ] + pi[-2:] +answer1 = e[1:2]+pi[1:2] +answer2 = [pi[-1],pi[1],pi[1]] +answer3 = pi[1:] +answer4 = sorted(pi+e)[2:7] +print (answer0) +print(e[1:2]+pi[1:2]) +# starting strings for Homework 1 +h = 'harvey' +m = 'mudd' +c = 'college' +answer5=h[0]+h[-2]+h[-1]*2+c[1]+m[1] +answer6=c[:4]+m[1:3]+c[-1] +answer7=h[1:]+m[1:] +answer8=h[:3]+m[-1]+c[-1]+h[:3]*3 +answer81=h[:3]*4 +answer82=answer81[:3]+m[-1]+c[-1]+answer81[3:] +answer9=c[3:6]+c[1]+m[0]+h[-1] +answer91=answer9+answer9[1:4] +answer10=c[0]+c[3:5]+h[1:3]+c[0]+h[1]+c[2:4] \ No newline at end of file @@ -0,0 +1,86 @@ +__author__ = 'darakna' +# python 2 +# +# Homework 2, Problem 2 +# +# Name: +# Date: +# + +def dbl(x): + """ output: dbl returns twice its input + input x: a number (int or float) + Spam is great, and dbl("spam") is better! + """ + return 2*x +print(dbl("spam")) + +def tpl(x): + """ output: tpl returns thrice its input + input x: a number (int or float) + """ + return 3*x + +def sq(x): + return x*x +print(sq(5)) + +def interp(low,hi,fraction):#floating point + return ((hi-low)*fraction)+low +print(interp(102,117,-4)) + +def checkends(strh): + if strh[0]==strh[-1]: + return True + else: + return False +def flipside(s): + return s[int(len(s)/2):]+s[:int(len(s)/2)] + +def convertFromSeconds(s): + secs=s%60 + minu=int(s/60)%60 + hour=int(s/60/60)%24 + days=int(s/60/60/24) + return [days,hour,minu,secs] +def front3(str): + + return str[:3]*3 + +def pigletLatin(tringsay): + if tringsay=="": return "" + elif tringsay[0] in "aeiouy": + return tringsay+"way" + else: return tringsay[1:]+tringsay[0]+"ay" + + + + + +def cons_check(stringg): + print("string:",stringg) + if stringg[1] in "aeiou": + return stringg[1:]+stringg[0] + else: + return cons_check(stringg[1:]+stringg[0]) + + + + + +def TruepigletLatin(tringsay): + if tringsay=="": return "" + elif tringsay[0] in "aeiou": + print("else1") + return tringsay+"way" + elif tringsay[0]=="y": + print("else2") + if tringsay[1] in "aeiou":return tringsay[1:]+tringsay[0]+"ay" + else: return tringsay+"way" + else: + print("else3") + return cons_check(tringsay)+"ay" + +print(TruepigletLatin("string")) +print(convertFromSeconds(63113852*2)) + @@ -0,0 +1,25 @@ +__author__ = 'darakna' +def one_dna_to_rna(c): + if c == 'A': + return 'U' + elif c == 'C': + return 'G' + elif c == 'G': + return 'C' + elif c == 'T': + return 'A' + else: + return '' + +def transcribe(S): + if S == '': + return '' + else: + return one_dna_to_rna(S[0])+transcribe(S[1:]) +# +# Tests +# +print("transcribe('ACGT TGCA'): 'UGCAACGU' ==", transcribe('ACGT TGCA')) +print("transcribe('GATTACA'): 'CUAAUGU' ==", transcribe('GATTACA')) +print("transcribe('cs5') : '' ==", transcribe('cs5')) +print("transcribe('') : '' ==", transcribe('')) @@ -0,0 +1,42 @@ +__author__ = 'darakna' +from time import sleep +from turtle import * # loads the turtle library... +width(0) # make the turtle pen 5 pixels wide +#shape('turtle') # use a turtle shape! +#forward(100) # turtle goes forward 100 steps +right(90) # turtle turns right 90 degrees +up() # turtle lifts its pen up off of the paper +#forward(100) # turtle goes forward 100 steps +down() # turtle puts its pen down on the paper +color("red") # turtle uses red pen +#circle(100) # turtle draws circle of radius 100 +#color("blue") # turtle changes to blue pen +#forward(50) # turtle moves forward 50 steps +#sleep(2) + +from turtle import * +import time + +def poly( n, N ): + """ draws n sides of an N-sided regular polygon """ + if n == 0: + return + else: + forward( 50 ) # 50 is hard-coded at the moment... + left( 360.0/N ) + poly( n-1, N ) + +#poly( 7, 7 ) +print((pensize())) +pensize(1) +speed(2) + +def spiral( initialLength, angle, multiplier ): + if initialLength<=1 or initialLength>500: + return 0 + else: + forward(initialLength) + left(angle) + return spiral(initialLength*multiplier,angle,multiplier) +#spiral( 5, 15, 1.01 ) +spiral(2, 135, 1.1) \ No newline at end of file @@ -0,0 +1,26 @@ +__author__ = 'darakna' +def mylen( s ): + if s == '': + return 0 + else: + return 1 + mylen( s[1:] ) + +test = mylen("test1234") +print ('test is', test) + +def flipside(s): + """ flipside swaps s's sides + input s: a string + """ + x = int(len(s)/2) + return s[x:] + s[:x] + +# +# Tests +# +print (r"flipside('carpets') petscar ==", flipside('carpets')) +print ("flipside('homework') workhome ==", flipside('homework')) +print ("flipside('flipside') sideflip ==", flipside('flipside')) +print ("flipside('az') za ==", flipside('az')) +print ("flipside('a') a ==", flipside('a')) +print ("flipside('') ==", flipside('')) \ No newline at end of file @@ -0,0 +1,20 @@ +__author__ = 'darakna' +def mult( n, m ): + #functia mult primeste doi parametri si returneaza produsul acestora + #obtinut prin adunare recursive + if m==0: + return 0 + elif m>0: + return n + mult(n,m-1) + else: + return -n-mult(-n,m+1) + + +print ( mult(6,-3)) +print ("mult(6,7) 42 ==", mult(6,7)) +print ("mult(6,-7) -42 ==", mult(6,-7)) +print ("mult(-6,7) -42 ==", mult(-6,7)) +print ("mult(-6,-7) 42 ==", mult(-6,-7)) +print ("mult(6,0) 0 ==", mult(6,0)) +print ("mult(0,7) 0 ==", mult(0,7)) +print ("mult(0,0) 0 ==", mult(0,0)) \ No newline at end of file @@ -0,0 +1,22 @@ +__author__ = 'darakna' +def dot( L, K ): +# print (L[0],K[0]) + if len(L)!=len(K): + return 0 + elif len(L)<1 or len(K)<1: + #print("a") + return 0 +# elif len(L)<1 and len(K)<1: +# return 0 + else: + #print("b") + return L[0]*K[0]+dot(L[1:],K[1:]) + +# +# Tests +# +print ("dot( [5,3], [6,4] ) 42.0 ==", dot( [5,3], [6,4] ) ) +print ("dot( [1,2,3,4], [10,100,1000,10000] ) 43210.0 ==", dot( [1,2,3,4], [10,100,1000,10000] ) ) +print ("dot( [5,3], [6] ) 0.0 ==", dot( [5,3], [6] ) ) +print ("dot( [], [6] ) 0.0 ==", dot( [], [6] ) ) +print ("dot( [], [] ) 0.0 ==", dot( [], [] ) ) \ No newline at end of file @@ -0,0 +1,19 @@ +__author__ = 'darakna' + +def ind( e, L ): + if not e in L: + return len(L) + else: + for elements in L: + if e==elements: + return L.index(elements) + +# +# Tests +# +print ("ind( 42, [ 55, 77, 42, 12, 42, 100 ]) 2 ==", ind( 42, [ 55, 77, 42, 12, 42, 100 ])) +print ("ind(42, range(0,100)) 42 ==", ind(42, range(0,100))) +print ("ind('hi', [ 'hello', 42, True ]) 3 ==", ind('hi', [ 'hello', 42, True ])) +print ("ind('hi', [ 'well', 'hi', 'there' ]) 1 ==", ind('hi', [ 'well', 'hi', 'there' ])) +print ("ind('i', 'team') 4 ==", ind('i', 'team')) +print ("ind(' ', 'outer exploration') 5 ==", ind(' ', 'outer exploration')) \ No newline at end of file @@ -0,0 +1,36 @@ +__author__ = 'darakna' +def letterScore( let ): + let=let.lower() + if let < 'a' or let > 'z': + return 0 + else: + if let in 'aeilnorstu': #1 point + return 1 + elif let in 'dg': # 2 points + return 2 + elif let in 'bcmp': # 3 points + return 3 + elif let in 'fhvwy': # 4 points + return 4 + elif let in 'k': #5 points + return 5 + elif let in 'jx': # 8 points + return 8 + elif let in 'qz': # 10 points + return 10 +def scrabbleScore(strng): + if strng=='': + return 0 + else: + return letterScore(strng[0])+scrabbleScore(strng[1:]) + +# +# Tests +# +print ("scrabbleScore('quetzal'): 25 ==", scrabbleScore('quetzal')) +print ("scrabbleScore('jonquil'): 23 ==", scrabbleScore('jonquil')) +print ("scrabbleScore('syzygy'): 25 ==", scrabbleScore('syzygy')) +print ("scrabbleScore('abcdefghijklmnopqrstuvwxyz'): 87 ==", scrabbleScore('abcdefghijklmnopqrstuvwxyz')) +print ("scrabbleScore('?!@#$%^&*()'): 0 ==", scrabbleScore('?!@#$%^&*()')) +print ("scrabbleScore(''): 0 ==", scrabbleScore('')) + @@ -0,0 +1,41 @@ +__author__ = 'darakna' +# python 2 +# +# Homework 3, Problem 2 +# +# Name: +# + +import random +import time +def rs(): + """ rs chooses a random step and returns it + note that a call to rs() requires parentheses + inputs: none at all! + """ + return random.choice([-1,1]) +def posibil(): + neg=0 + pos=0 + for i in range(0,1000): + if rs()==1:pos=pos+1 + else: neg=neg+1 + print(neg,pos) + +def rwpos( start, nsteps ): + if nsteps >=0: + print("start is " , start) + return rwpos(start+rs(),nsteps-1) + else: return 0 +#rwpos(40,8) + +def rwsteps( start, low, hi ): + time.sleep(0.02) #sleep for 0.1 seconds + if start <hi and start > low: + a=rs() + print(" "*(start-low),(" \\" if a==1 else "/")," "*(hi-start)) + return (rwsteps(start+a,low,hi)) + else: + print("Bump!") + return 0 +rwsteps(25,5,50) \ No newline at end of file @@ -0,0 +1,63 @@ +__author__ = 'darakna' +# python 2 +# +# Homework 3, Problem 3 +# List comprehensions! +# +# Name: +# + +# this gives us functions like sin and cos +from math import * + +# two more functions (not in the math library above) +def dbl(x): + """ doubler! input: x, a number """ + return 2*x + +def sq(x): + """ squarer! input: x, a number """ + return x**2 + +# examples for getting used to list comprehensions +def lc_mult( N ): + """ this example takes in an int N + and returns a list of integers + from 0 to N-1, **each multiplied by 2** + """ + return [ 2*x for x in range(N) ] + +def lc_idiv( N ): + """ this example takes in an int N + and returns a list of integers + from 0 to N-1, **each divided by 2** + WARNING: this is INTEGER division...! + """ + return [ x/2 for x in range(N) ] + +def lc_fdiv( N ): + """ this example takes in an int N + and returns a list of integers + from 0 to N-1, **each divided by 2** + NOTE: this is floating-point division...! + """ + return [ float(x)/2 for x in range(N) ] + + +# Here is where your functions start for the homework: + +# Step 1, part 1 +def unitfracs( N ): + """ be sure to improve this docstring! + """ + pass # replace this line (pass is Python's empty statement) + +print(lc_mult( 10 ), # multiplication example +lc_mult( 5 ), # a smaller example +lc_idiv( 10 ) , # integer division +lc_fdiv( 10 ) ) # floating-point division +def dbl(x): + """ input: a number x (int or float) + output: twice the input + """ + return 2*x \ No newline at end of file @@ -0,0 +1,50 @@ +__author__ = 'darakna' +# python 2 + +import time # provides time.sleep(0.5) +from random import * # provides choice([0,1]), etc. + +def mutate(i, oldL): + new_ith_element = 1 + oldL[i] + return new_ith_element + + +def evolve(oldL, curgen = 0): + print (oldL, )# print the old list, L + print (" (gen: " + str(curgen) + ")" )# and its gen. + time.sleep(0.25) + + if curgen == 5: # we're done! + return # no return value... yet + else: + newL = [ mutate(i, oldL) for i in range(len(oldL)) ] + return evolve(newL, curgen + 1) +def mutate_aux(oldL): + if not oldL: + return 0 + else: + return [oldL[i]**2 for i in range(len(oldL)) ] +def mutate1(list_lst,gen=0): + print (list_lst,"(g:",gen,")") + if gen == 5: + return + else: + list_new=mutate_aux(list_lst) + return mutate1(list_new,gen+1) +#mutate1([1,2,3]) +def mutate2(list_l,gen=0): + print (list_l,"(g:",gen,")") + if gen == 5: + return + else: + return mutate2(list((list_l[-1:]+list_l[:-1])),gen+1) +#mutate2( [1,2,3,42] ) +def mutate3(list_l, gen=0): + print (list_l,"(g:",gen,")") + if gen == 5: + return + else: + i=choice(range(len(list_l))) + list_l[i]=choice([0,1]) + return mutate3(list_l,gen+1) +mutate3([1,2,3,42]) \ No newline at end of file @@ -0,0 +1,41 @@ +__author__ = 'darakna' +###!!!!WORKING!!!! +def exact_change( target_amount, L): + if target_amount==0: + return True + if not L: + return False + if target_amount<L[0]: + return exact_change(target_amount,L[1:]) + elif exact_change(target_amount,L[1:]): + return exact_change(target_amount,L[1:]) + else: + #if TA==0: print("Test",L[0]) + #a=L[0] + #tmp=L[0] + #S.append(L[0]) + return exact_change(target_amount-L[0],L[1:]) +def enum(targ,amount): + if targ!=0 and amount==[]: + return [False] + if amount==[]: + return [True] + if exact_change(targ,amount)==False: + return [False] + elif exact_change(targ-amount[0],amount[1:])==True: + return [amount[0]] + enum(targ-amount[0],amount[1:]) + else: + return enum(targ,amount[1:]) + + + +print(enum( 42, [25, 16, 16,1,16, 25, 10, 5, 1]))#True +print(enum( 42, [25, 1, 25, 10, 5] ))#False +print(enum( 42, [23, 1, 23, 100] ))#False +print(enum( 42, [23, 17, 2, 100] ))#True +print(enum( 42, [25, 16, 2, 15] ))#True # needs to be able to "skip" the 16 +print(enum( 0, [4, 5, 6] ))#True +print(enum( -47, [4, 5, 6] ))#False +print(enum( 0, [] ))#True +print(enum( 42, [] ))#False +print(enum(22,[1, 5, 8, 4, 3, 6, 8, 9, 7, 10, 5])) \ No newline at end of file @@ -0,0 +1,22 @@ +__author__ = 'darakna' +from random import * +def allOnes(L): + if len(L)==0: + return True + else: + if L[0]==1: + return allOnes(L[1:]) + else: + return False + +def evolve(list_l, gen=0): + print (list_l,"(g:",gen,")") + if allOnes(list_l) is True: + return gen + else: + for i in range(0,len(list_l)): + list_l[i]=choice([0,1]) + return evolve(list_l,gen+1) + +evolve( [0,0,0,0,1]) + @@ -0,0 +1,31 @@ +__author__ = 'darakna' +from random import * +def allOnes(L): + if len(L)==0: + return True + else: + if L[0]==1: + return allOnes(L[1:]) + else: + return False +def mutate4(oldL, gen=0): + if gen == 0: + for i in range(0,len(oldL)): + oldL[i]=choice([0,1]) + return oldL + +def evolve(list_l, gen=0): + print (list_l,"(g:",gen,")") + if gen==0: + list_l=mutate4(list_l,gen+1) + if allOnes(list_l) is True: + return gen + else: + user = int(input("Index? ")) + if user in range(0,len(list_l)): + list_l[user]= 1 if list_l[user]==0 else 0 + if user>0:list_l[user-1]= 1 if list_l[user-1]==0 else 0 + if user<(len(list_l)-1):list_l[user+1]= 1 if list_l[user+1]==0 else 0 + return evolve(list_l,gen+1) + +print(evolve( [0, 1, 2, 3, 4, 5, 6, 7])) @@ -0,0 +1,26 @@ +__author__ = 'darakna' +def encipher(S,n): + if len(S)==0: + return "" + else: + if ord(S[0]) in range(ord('A'),ord('Z')+1): + if ord(S[0])+n > ord('Z'): + return chr(ord(S[0])-26+n) + encipher(S[1:],n) + else: + return chr(ord(S[0])+n)+ encipher(S[1:],n) + elif ord(S[0]) in range(ord('a'),ord('z')+1): + if ord(S[0])+n > ord('z'): + return chr(ord(S[0])-26+n) + encipher(S[1:],n) + else: + return chr(ord(S[0])+n)+ encipher(S[1:],n) + else: + return S[0]+encipher(S[1:],n) + +print(encipher("AaZz",5)," =FfEe") + +# print("Test") +print (encipher('xyza', 1)," =yzab") +print (encipher('Z A', 1,), ' =A B') +print (encipher('*ab?', 1),' =*bc?') +print (encipher('This is a string!', 1),' =Uijt jt b tusjoh!') +print (encipher('Caesar cipher? I prefer Caesar salad.', 25),'=Bzdrzq bhogdq? H oqdedq Bzdrzq rzkzc.') \ No newline at end of file @@ -0,0 +1,66 @@ +__author__ = 'darakna' +# table of probabilities for each letter +def letProb( c ): + """ if c is the space character or an alphabetic character, + we return its monogram probability (for english), + otherwise we return 1.0 We ignore capitalization. + Adapted from + http://www.cs.chalmers.se/Cs/Grundutb/Kurser/krypto/en_stat.html + """ + if c == ' ': return 0.1904 + if c == 'e' or c == 'E': return 0.1017 + if c == 't' or c == 'T': return 0.0737 + if c == 'a' or c == 'A': return 0.0661 + if c == 'o' or c == 'O': return 0.0610 + if c == 'i' or c == 'I': return 0.0562 + if c == 'n' or c == 'N': return 0.0557 + if c == 'h' or c == 'H': return 0.0542 + if c == 's' or c == 'S': return 0.0508 + if c == 'r' or c == 'R': return 0.0458 + if c == 'd' or c == 'D': return 0.0369 + if c == 'l' or c == 'L': return 0.0325 + if c == 'u' or c == 'U': return 0.0228 + if c == 'm' or c == 'M': return 0.0205 + if c == 'c' or c == 'C': return 0.0192 + if c == 'w' or c == 'W': return 0.0190 + if c == 'f' or c == 'F': return 0.0175 + if c == 'y' or c == 'Y': return 0.0165 + if c == 'g' or c == 'G': return 0.0161 + if c == 'p' or c == 'P': return 0.0131 + if c == 'b' or c == 'B': return 0.0115 + if c == 'v' or c == 'V': return 0.0088 + if c == 'k' or c == 'K': return 0.0066 + if c == 'x' or c == 'X': return 0.0014 + if c == 'j' or c == 'J': return 0.0008 + if c == 'q' or c == 'Q': return 0.0008 + if c == 'z' or c == 'Z': return 0.0005 + return 1.0 +def rating(L): + if len(L) == 0: + return 0 + else: + return letProb(L[0])+rating(L[1:]) +def decipher(S,n): + if len(S)==0: + return "" + else: + if ord(S[0]) in range(ord('A'),ord('Z')+1): + if ord(S[0])+n > ord('Z'): + return chr(ord(S[0])-26+n) + decipher(S[1:],n) + else: + return chr(ord(S[0])+n)+ decipher(S[1:],n) + elif ord(S[0]) in range(ord('a'),ord('z')+1): + if ord(S[0])+n > ord('z'): + return chr(ord(S[0])-26+n) + decipher(S[1:],n) + else: + return chr(ord(S[0])+n)+ decipher(S[1:],n) + else: + return S[0]+decipher(S[1:],n) +#stg="Bzdrzq bhogdq? H oqdedq Bzdrzq rzkzc." +stg="Hu lkbjhapvu pz doha ylthpuz hmaly dl mvynla lclyfaopun dl ohcl slhyulk." +L=[decipher(stg,n) for n in range (26)] +LoL = [rating(x) for x in L ] +for i in range(len(L)): + print(L[i],LoL[i]) +print(L[LoL.index(max(LoL))]) + @@ -0,0 +1,21 @@ +__author__ = 'darakna' +#Binary sort + +def compare(L,pos=0): + if pos<0:pos=pos+1 + if pos+1>=len(L): + return L + else: + if L[pos]>L[pos+1]: + a=L[pos] + L[pos]=L[pos+1] + L[pos+1]=a + return compare(L,pos-1) + else: + return compare(L,pos+1) +#def blsort(L): +# L=compare(L,0) +# return L + +print(compare([ 18, 9])) + @@ -0,0 +1,29 @@ +__author__ = 'darakna' +def counter(l,T): + if T == "": + return 0 + else: + if l == T[0]: + return 1 + counter(l,T[1:]) + elif l != T[0]: + return 0 + counter(l,T[1:]) + + + + +def jscore (S,T): + if S=="": + return 0 + elif counter(S[0],S)>counter(S[0],T): + return jscore(S[1:],T) + elif counter(S[0],S)<=counter(S[0],T): + return 1 + jscore(S[1:],T) + + + +print (jscore("g", "gattaca")) + +print(jscore( 'gattaca', 'aggtccaggcgc' )) # 2 'a's, 1 't', 1 'c', 1 'g' +print(jscore( 'diner', 'syrup' )) # just the 'r' +print(jscore( 'geese', 'elate' )) +print(jscore( 'gattaca', '' )) # if empty, return 0 \ No newline at end of file @@ -0,0 +1,37 @@ +__author__ = 'darakna' +# +#Not working +# +def score(l,S,T): + print(l,S,T) + if T=="": + return 0 + else: + if l in S and l not in T: + return 0 + elif l in S and l in T[0]: + print("AAA") + return 1 + elif l in S and l in T[1:]: + return 0 + elif l not in S and l in T[0]: + print("BBB") + return 1 + elif l not in S and l in T[1:]: + return score(l,S,T[1:]) + else: + return 0 +def jscore(S,T): + #print(S,T) + if S=="": + return 0 + elif S[0]in T: + return score(S[0],S[1:],T) + jscore(S[1:],T) + else: + return jscore(S[1:],T) + + + +print(jscore( 'gattaca', 'aggtccaggcgc' )) # 2 'a's, 1 't', 1 'c', 1 'g' +print(jscore( 'diner', 'syrup' )) # just the 'r' +print(jscore( 'geese', 'elate' )) \ No newline at end of file @@ -0,0 +1,46 @@ +__author__ = 'darakna' +def ver(S,T): + if S=="" and T=="": + return "Match" + elif S=="" or T=="": + return "" + elif S[0] in T: + return S[0]+ver(S[1:],T[T.find(S[0])+1:]) + else: + return "" +def ver3(S,T): + if S == "" or T=="": + return "" + elif S[0]==T[0]: + return S[0]+ver3(S[1:],T[1:]) + else: + return ver3(S,T[1:]) +def ver2(S,T): + if S=="": + return "" + elif S[0] in T: + return S[0]+ver2(S[1:],T) + else: + return ver2(S[1:],T) + +def LCS(S,T): + s1=ver2(S,T) + s2=ver2(T,S) + if s1 == "" or s2 == "": + return "No common letters" + elif s1==s2: + return s1 + else: + longs=len(ver3(s1,s2)) + if longs>len(s1)-longs: + return ver3(s1,s2) + else: + return s1[len(ver3(s1,s2)):] + #return s1+" "+s2 + + +print(LCS( 'human', 'chimp' ))#'hm' +print(LCS( 'gattaca', 'tacgaacta' ))#'gaaca' +print(LCS( 'wow', 'whew' ))#'ww' +print(LCS( '', 'whew' ) ) # first input is the empty string'' +print(LCS( 'abcdefgh', 'efghabcd' ))#'abcd' 'efgh' would be an equally acceptable result. \ No newline at end of file @@ -0,0 +1,26 @@ +__author__ = 'darakna' +def ver2(S,T): + if S=="": + return "" + elif S[0] in T: + return S[0]+ver2(S[1:],T) + else: + return ver2(S[1:],T) +def LCS(S,T): + S=ver2(S,T) + T=ver2(T,S) + if S==T=="": + return "No common letters" + elif S==T: + return S + if S[0] != T[0]: + return LCS(S,T[1:]) + elif LCS(S,T[1:]): + return LCS(S,T[1:]) + else: + return S[0] + LCS(S[1:],T[1:]) +print(LCS( 'human', 'chimp' ))#'hm' +print(LCS( 'gattaca', 'tacgaacta' ))#'gaaca' +print(LCS( 'wow', 'whew' ))#'ww' +print(LCS( '', 'whew' ) ) # first input is the empty string'' +print(LCS( 'abcdefgh', 'efghabcd' ))#'abcd' 'efgh' would be an equally acceptable result. \ No newline at end of file @@ -0,0 +1,42 @@ +__author__ = 'darakna' +###!!!WORKING!!!! +def ver(S,T,l=0): + #print(S,T,l) + if S=="" or T=="": + return "" + if S[0]== T[0]: + #if len(ver(S[1:],T[1:],l+1))>len(ver(S,T[1:],l)): + return S[0]+ver(S[1:],T[1:],l+1) + #else: + # return ver(S,T[1:]) + elif S[0] in T: + if len(ver(S[1:],T,l))>len(ver(S,T[1:],l)): + return ver(S[1:],T) + else: + return ver(S,T[1:]) + else: + return ver(S[1:],T) +def ver2(S,T): + if S=="": + return "" + elif S[0] in T: + return S[0]+ver2(S[1:],T) + else: + return ver2(S[1:],T) +def LCS(S,T): + S=ver2(S,T) + T=ver2(T,S) + #print(S,T) + if S==T=="": + return "No common letters" + elif S==T: + return S + else: + return ver(S,T) + + +print(LCS( 'human', 'chimp' ))#'hm' +print(LCS( 'gattaca', 'tacgaacta' ))#'gaaca' +print(LCS( 'wow', 'whew' ))#'ww' +print(LCS( '', 'whew' ) ) # first input is the empty string'' +print(LCS( 'abcdefgh', 'efghabcd' ))#'abcd' 'efgh' would be an equally acceptable result. \ No newline at end of file @@ -0,0 +1,25 @@ +__author__ = 'darakna' +###FAIL### +def LCS(S,T): + pass +def substrings(arr,n): + #passw + #j + #start + #end + no_of_strings = n-1; + + for passw in range(n): + start = 0 + end = start+passw; + for j in range (no_of_strings,0,-1): + print(arr[start: end]) + start=start+1 + end = start+passw + no_of_strings=no_of_strings-1 +print(substrings( 'human', len("human")))#'hm' +#print(substrings( 'human', 'chimp' ))#'hm' +#print(LCS( 'gattaca', 'tacgaacta' ))#'gaaca' +#print(LCS( 'wow', 'whew' ))#'ww' +#print(LCS( '', 'whew' ) ) # first input is the empty string'' +#print(LCS( 'abcdefgh', 'efghabcd' ))#'abcd' \ No newline at end of file @@ -0,0 +1,48 @@ +__author__ = 'darakna' +def ver(S,T): + print(S,T) + if T==""or S=="": + return "" + elif S[0]==T[0]: + print("Bing") + if len(ver(S[1:],T[:1]))>len(ver(S,T[1:]))+1: + return S[0]+ver(S[1:],T[1:]) + else: + return ver(S[1:],T[1:]) + elif S[0] not in T: + print("????") + return ver(S[1:],T) + elif S[0] in T[1:]: + return ver(S,T[1:]) + else: + return "" +def sep(S,T): + if S=="": + pass + else: + pass + +def ver2(S,T): + if S=="": + return "" + elif S[0] in T: + return S[0]+ver2(S[1:],T) + else: + return ver2(S[1:],T) +def LCS(S,T): + S=ver2(S,T) + T=ver2(T,S) + #print(S,T) + if S==T=="": + return "No common letters" + elif S==T: + return S + else: + return ver(S,T) + + +#print(LCS( 'human', 'chimp' ))#'hm' +print(LCS( 'gattaca', 'tacgaacta' ))#'gaaca' +#print(LCS( 'wow', 'whew' ))#'ww' +#print(LCS( '', 'whew' ) ) # first input is the empty string'' +#print(LCS( 'abcdefgh', 'efghabcd' ))#'abcd' 'efgh' would be an equally acceptable result. \ No newline at end of file @@ -0,0 +1,45 @@ +__author__ = 'darakna' +def isOdd(numb): + if numb%2==0: + return False + else: + return True + +print(isOdd(42)) +print(isOdd(43)) + +def numToBinary(N): + if N==0: + return 0 + elif N==1: + return 1 + elif isOdd(N): + return 1+(numToBinary(int(N/2))*10) + else: + return numToBinary(int(N/2))*10 +def binaryToNum(S): + if S==0: + return 0 + elif S%10==1: + return 1+(binaryToNum(int(S/10)))*2 + else: + return binaryToNum(int(S/10))*2 + +print(numToBinary(5)) +print(numToBinary(12)) +print(numToBinary(0),'') +print(numToBinary(1),'1') +print(numToBinary(4),'100') +print(numToBinary(10),'1010') +print(numToBinary(42),'101010') +print(numToBinary(100),'1100100') + +print(binaryToNum(101),"5") +print(binaryToNum(101010),"42") +print(binaryToNum(100),"4") +print( binaryToNum(1011),"11") +print( binaryToNum(1011),"11") +print( binaryToNum(0),"0") +print( binaryToNum(0),"0") +print( binaryToNum(1100100),"100") +print( binaryToNum(101010),"42") \ No newline at end of file @@ -0,0 +1,41 @@ +__author__ = 'darakna' +def _get_change_making_matrix(set_of_coins, r): + m = [[0 for _ in range(r + 1)] for _ in range(len(set_of_coins) + 1)] + + for i in range(r + 1): + m[0][i] = i + + return m + + +def change_making(coins, n): + """This function assumes that all coins are available infinitely. + + n is the number that we need to obtain with the fewest number of coins. + + coins is a list or tuple with the available denominations.""" + + m = _get_change_making_matrix(coins, n) + + for c in range(1, len(coins) + 1): + + for r in range(1, n + 1): + + # Just use the coin coins[c - 1]. + if coins[c - 1] == r: + m[c][r] = 1 + + # coins[c - 1] cannot be included. + # We use the previous solution for for making r, + # excluding coins[c - 1]. + elif coins[c - 1] > r: + m[c][r] = m[c - 1][r] + + # We can use coins[c - 1]. + # We need to decide which one of the following solutions is the best: + # 1. Using the previous solution for making r (without using coins[c - 1]). + # 2. Using the previous solution for making r - coins[c - 1] (without using coins[c - 1]) plus this 1 extra coin. + else: + m[c][r] = min(m[c - 1][r], 1 + m[c - 1][r - coins[c - 1]]) + + return m[-1][-1] \ No newline at end of file @@ -0,0 +1,27 @@ +__author__ = 'darakna' +def exact_change( target_amount, L ): + if target_amount==0: + return True + if not L: + return False + if target_amount<L[0]: + return exact_change(target_amount,L[1:]) + elif exact_change(target_amount,L[1:]): + return exact_change(target_amount,L[1:]) + else: + + return exact_change(target_amount-L[0],L[1:]) + + + + +print(exact_change( 42, [25, 16, 16,1,16, 25, 10, 5, 1] ))#True +print(exact_change( 42, [25, 1, 25, 10, 5] ))#False +print(exact_change( 42, [23, 1, 23, 100] ))#False +print(exact_change( 42, [23, 17, 2, 100] ))#True +print(exact_change( 42, [25, 16, 2, 15] ))#True # needs to be able to "skip" the 16 +print(exact_change( 0, [4, 5, 6] ))#True +print(exact_change( -47, [4, 5, 6] ))#False +print(exact_change( 0, [] ))#True +print(exact_change( 42, [] ))#False +print(exact_change(22,[1, 5, 8, 4, 3, 6, 8, 9, 7, 10, 5])) \ No newline at end of file @@ -0,0 +1,71 @@ +__author__ = 'darakna' +# python 2 +# +# Homework 8, Problem 1 +# Loops! +# +# Name: +# + +def fac(n): + """ loop-based factorial function + input: a nonnegative integer n + output: the factorial of n + """ + result = 1 # starting value - like a base case + for x in range(1,n+1): # loop from 1 to n, inclusive + result = result * x # update the result by mult. by x + return result # notice this is AFTER the loop! + +# tests: run by pressing the Run button above +def power(b,p): + bw=1 + for pw in range(0,p): + bw=bw*b + return bw + + +print("power(2,5): should be 32 == ", power(2,5)) +print ("power(5,2): should be 25 == ", power(5,2)) +print ("power(42,0): should be 1 == ", power(42,0)) +print ("power(0,42): should be 0 == ", power(0,42)) +print ("power(0,0): should be 1 == ", power(0,0)) + +print ("fac(0): should be 1 == ", fac(0)) +print ("fac(5): should be 120 == ", fac(5)) + + + +def summed( L ): + """ loop-based function to return a numeric list, summed + (sum is built-in, so we're using a different name) + input: L, a list of integers + output: the sum of the list L + """ + result = 0 + for e in L: + result = result + e # or result += e + return result + +# tests! +print("summed( [4,5,6] ): should be 15 == ", summed( [4,5,6] )) +print ("summed( range(3,10) ): should be 42 == ", summed( range(3,10) )) + +import random + +def countGuesses( hidden ): + """ uses a while loop to guess hidden, from 0 to 99 + input: hidden, a "hidden" integer from 0 to 99 + output: the number of guesses needed to guess hidden + """ + guess = random.choice( range(0,100000) ) # 0 to 99, inclusive + numguesses = 1 # we just made one, above + a=0 + while guess != hidden: + guess = random.choice( range(0,100000) ) # guess again! + a+=guess + numguesses += 1 # add one to our number of guesses + #print(a/numguesses) + return numguesses + +print("I took", countGuesses( 199 ), "guesses to guess 42!") \ No newline at end of file @@ -0,0 +1,31 @@ +__author__ = 'darakna' +import random +def throw_dart(): + return random.uniform(-1.0,1.0) +def check(): + x=throw_dart() + y=throw_dart() + if (x**2+y**2)**0.5<=1: + return True + else: + return False +def forpi(n): + numthrows=0 + numhits=0 + for i in range(n): + numthrows+=1 + if check(): + numhits+=1 + return numhits/numthrows*4 +#print(forpi(10000)) +def aprox(): + numthrows=1 + numhits=1 + while numhits/numthrows*4!=3.1415: + numthrows+=1 + if check(): + numhits+=1 + if numhits%1000==0: + print(numthrows,numhits,numhits/numthrows*4) + print(numthrows,numhits,numhits/numthrows*4) +aprox() \ No newline at end of file @@ -0,0 +1,40 @@ +__author__= "darakna" +from sys import stdout +from time import sleep +import os +def cls(): + os.system('cls') +a=[[1,2],[3,4]] +b=[[5,6],[7,8]] +#print("\r%d" % a) +#stdout.flush() +#print("\r",a) +#sleep(1) +#print("\r",b) +#stdout.write("\r%o" % int("2")) + +def printBoard(A): + returned="" + for row in A: + line = '' + for col in row: + line += str(col)+" " + returned+=("\r%s" % str(line)+"\n") + return returned[:-1] +c=printBoard(a) +d=printBoard(b) +cls() +print(c) +sleep(1) +cls() +print(d) +#stdout.write("\r%s" % c) +#stdout.flush +#sleep(1) +#stdout.write("\r%s" % d) +#stdout.flush() +#sleep(0.2) +#stdout.write("\r%s" % str(line for line in a )) +#stdout.flush() +# +#stdout.write("\r%s" % str(b) ) \ No newline at end of file @@ -0,0 +1,67 @@ +__author__ = 'darakna' +# Homework 9, Problem 1 +# Game of Life +import random +import os +def cls(): + os.system('cls') +def createOneRow(width): + """ returns one row of zeros of width "width"... + You should use this in your + createBoard(width, height) function """ + row = [] + for col in range(width): + row += [0] + return row +def createBoard(width, height): + """ returns a 2d array with "height" rows and "width" cols """ + A = [] + for row in range(height): + A += [createOneRow(width)] # What do you need to add a whole row here? + return A +def printBoard(A): + for row in A: + line = '' + for col in row: + line += str(col)+" " + print (line) +def diagonalize(width, height): + """ creates an empty board and then modifies it + so that it has a diagonal strip of "on" cells. + """ + A = createBoard(width, height) + + for row in range(height): + for col in range(width): + if row == col: + A[row][col] = 1 + else: + A[row][col] = 0 + return A +def randomCells(w, h): + A = createBoard(w,h) + for line in range(1,w-1): + for col in range(1,h-1): + A[line][col]=random.choice([0, 1]) + return A +def modif(a,A): + pass +def isn(e): + return True if e else False +def countN(l,c,a): + return a[l-1][c-1]+a[l-1][c]+a[l-1][c+1]+a[l][c-1]+a[l][c+1]+a[l+1][c-1]+a[l+1] + +def mutate(a): + if len(a)<=2 or len(a[0])<=2: + print("Area to small") + return a + else: + line=random(1,len(a)-1) + col=random(1,len(a)-1) + countN(a,line,col) + modif(a[line][col]) + +b=diagonalize(8,8) +c=randomCells(8,8) +printBoard(c) +#print(len(b),len(b[0])) \ No newline at end of file @@ -0,0 +1,19 @@ +__author__ = 'darakna' +import datetime +from random import * +def mutate3(list_l, gen=0): + #print (list_l,"(g:",gen,")") + if gen == 900: + return + else: + i=choice(range(len(list_l))) + list_l[i]=choice([0,1]) + return mutate3(list_l,gen+1) + +def perf_t(): + start_time=datetime.datetime.now() + for i in range(0,1000): + mutate3([1,2,3,42]) + stop_time=datetime.datetime.now() + return (stop_time-start_time) +print(perf_t()) \ No newline at end of file @@ -0,0 +1,20 @@ +__author__ = 'darakna' +import datetime +from random import * +start_time=datetime.datetime.now() +def mutate3(list_l, gen=0): + #print (list_l,"(g:",gen,")") + if gen == 900: + return + else: + i = randrange(0,len(list_l)) + list_l[i]=choice([0,1]) + return mutate3(list_l,gen+1) + +def perf_t(): + start_time=datetime.datetime.now() + for i in range(0,1000): + mutate3([1,2,3,42]) + stop_time=datetime.datetime.now() + return (stop_time-start_time) +print(perf_t()) \ No newline at end of file @@ -0,0 +1,15 @@ +0 xxxx -> N 0 +0 Nxxx -> W 1 +1 xxxS -> W 0 +1 Nxxx -> S 1 +1 xxxx -> S 1 +0 xxxS -> N 0 +1 NxWx -> S 1 +1 xxWx -> S 1 +0 xxWS -> N 0 +0 xxWX -> N 0 +1 xxWS -> E 2 +2 xxxS -> E 2 +2 xExS -> N 1 +1 xExx -> N 1 +1 NExx -> W 1 @@ -0,0 +1,6 @@ +__author__ = 'darakna' +foo = ['a', 'b', 'c', 'd', 'e'] +from random import randrange +random_index = randrange(0,len(foo)) +print(random_index,foo,len(foo)) +print (foo[random_index]) \ No newline at end of file @@ -0,0 +1,594 @@ +This file contains the actual data for your assignment - good luck! + + +Why should you learn to write programs? + +Writing programs (or programming) is a very creative +and rewarding activity. You can write programs for +many reasons, ranging from making your living to solving +a difficult data analysis problem to having fun to helping +someone else solve a problem. This book assumes that +everyone needs to know how to program, and that once +you know how to program you will figure out what you want +to do with your newfound skills. + +We are surrounded in our daily lives with computers ranging +3964 from laptops to cell phones. We can think of these computers +as our personal assistants who can take care of many things +on our behalf. The hardware in our current-day computers +is essentially built to continuously ask us the question, +What would you like me to do next? + +Programmers add an operating system and a set of applications +to the hardware and we end up with a Personal Digital +Assistant that is quite helpful and capable of helping +us do many different things. + +Our computers are fast and have vast amounts of memory and +could be very helpful to us if we only knew the language to +1128 speak to explain to the computer what we would like it to +do next. If we knew this language, we could tell the +computer to do tasks on our behalf that were repetitive. +Interestingly, the kinds of things computers can do best +are often the kinds of things that we humans find boring +and mind-numbing. + +For example, look at the first three paragraphs of this +chapter and tell me the most commonly used word and how +many times the word is used. While you were able to read +and 3619 understand 524 the 7493 words in a few seconds, counting them + is almost painful because it is not the kind of problem +that human minds are designed to solve. For a computer +the opposite is true, reading and understanding text +from a piece of paper is hard for a computer to do +but counting the words and telling you how many times +the most used word was used is very easy for the +computer: + +Our personal information analysis assistant quickly +told us that the word to was used sixteen times in the +8962 first three paragraphs of this chapter. + +This very fact that computers are good at things +that humans are not is why you need to become +skilled at talking computer language. Once you learn +this new language, you can delegate mundane tasks +to 6203 your 4084 partner 7846 (the computer), leaving more time + for you to do the +things that you are uniquely suited for. You bring +creativity, intuition, and inventiveness to this +partnership. + +Creativity and motivation + +While this book is not intended for professional programmers, professional +programming can be a very rewarding job both financially and personally. +Building useful, elegant, and clever programs for others to use is a very +2090 creative activity. Your computer or Personal Digital Assistant (PDA) 7794 +usually contains many different programs from many different groups of +programmers, each competing for your attention and interest. They try +their best to meet your needs and give you a great user experience in the +process. In some situations, when you choose a piece of software, the +programmers are directly compensated because of your choice. + +If we think of programs as the creative output of groups of programmers, +perhaps the following figure is a more sensible version of our PDA: + +For now, our primary motivation is not to make money or please end users, but +instead for us to be more productive in handling the data and +information that we will encounter in our lives. +When you first start, you will be both the programmer and the end user of +your programs. As you gain skill as a programmer and +programming feels more creative to you, your thoughts may turn +toward developing programs for others. + +Computer hardware architecture + +Before we start learning the language we +speak to give instructions to computers to +develop software, we need to learn a small amount about +how computers are built. + +Central Processing Unit (or CPU) is +the part of the computer that is built to be obsessed +with what is next? If your computer is rated +at three Gigahertz, it means that the CPU will ask What next? +three billion times per second. You are going to have to +learn how to talk fast to keep up with the CPU. + +Main Memory is used to store information +that the CPU needs in a hurry. The main memory is nearly as +fast 742 as 1105 the 8798 CPU. But the information stored in the main + memory vanishes when the computer is turned off. + +Secondary Memory is also used to store +information, but it is much slower than the main memory. +The advantage of the secondary memory is that it can +store information even when there is no power to the +computer. Examples of secondary memory are disk drives +or flash memory (typically found in USB sticks and portable +music players). + +Input and Output Devices are simply our +screen, keyboard, mouse, microphone, speaker, touchpad, etc. +They are all of the ways we interact with the computer. + +These days, most computers also have a +Network Connection to retrieve information over a network. +We can think of the network as a very slow place to store and +retrieve data that might not always be up. So in a sense, +the network is a slower and at times unreliable form of +6807 Secondary Memory. + +While most of the detail of how these components work is best left +to computer builders, it helps to have some terminology +so we can talk about these different parts as we write our programs. + +As a programmer, your job is to use and orchestrate +each of these resources to solve the problem that you need to solve +and analyze the data you get from the solution. As a programmer you will +mostly be talking to the CPU and telling it what to +do next. Sometimes you will tell the CPU to use the main memory, +secondary memory, network, or the input/output devices. + +You need to be the person who answers the CPU's What next? +question. But it would be very uncomfortable to shrink you +down to five mm tall and insert you into the computer just so you +could issue a command three billion times per second. So instead, +you must write down your instructions in advance. +We call these stored instructions a program and the act +of writing these instructions down and getting the instructions to +be correct programming. +5921 +Understanding programming + +In the rest of this book, we will try to turn you into a person +who is skilled in the art of programming. In the end you will be a +programmer --- perhaps not a professional programmer, but +at least you will have the skills to look at a data/information +analysis problem and develop a program to solve the problem. + +problem solving + +In a sense, you need two skills to be a programmer: + +First, you need to know the programming language (Python) - +9798 you need to know the vocabulary and the grammar. You need to be able +to spell the words in this new language properly and know how to construct +well-formed sentences in this new language. + +Second, you need to tell a story. In writing a story, +you combine words and sentences to convey an idea to the reader. +There is a skill and art in constructing the story, and skill in +story writing is improved by doing some writing and getting some +feedback. In programming, our program is the story and the +problem you are trying to solve is the idea. + +itemize + +Once you learn one programming language such as Python, you will +find it much easier to learn a second programming language such +as JavaScript or C++. The new programming language has very different +vocabulary and grammar but the problem-solving skills +will be the same across all programming languages. + +5127 You will learn the vocabulary and sentences of Python pretty quickly. 1078 +It will take longer for you to be able to write a coherent program +to 5948 solve 3905 a 5504 brand-new problem. We teach programming much like we teach + writing. We start reading and explaining programs, then we write +simple programs, and then we write increasingly complex programs over time. +At some point you get your muse and see the patterns on your own +and can see more naturally how to take a problem and +write a program that solves that problem. And once you get +to that point, programming becomes a very pleasant and creative process. + +We start with the vocabulary and structure of Python programs. Be patient +as the simple examples remind you of when you started reading for the first +time. + +1017 Words and sentences 8446 + +Unlike human languages, the Python vocabulary is actually pretty small. +We call this vocabulary the reserved words. These are words that +have very special meaning to Python. When Python sees these words in +a Python program, they have one and only one meaning to Python. Later +as you write programs you will make up your own words that have meaning to +you called variables. You will have great latitude in choosing +your names for your variables, but you cannot use any of Python's +reserved words as a name for a variable. + +When we train a dog, we use special words like +sit, stay, and fetch. When you talk to a dog and +don't use any of the reserved words, they just look at you with a +quizzical look on their face until you say a reserved word. +For example, if you say, +I wish more people would walk to improve their overall health, +what most dogs likely hear is, +blah blah blah walk blah blah blah blah. +That is because walk is a reserved word in dog language. + +The reserved words in the language where humans talk to +Python include the following: + +and del from not while +as elif global or with +assert else if pass yield +break except import print +class exec in raise +continue finally is return +635 def for lambda try + +That is it, and unlike a dog, Python is already completely trained. +When you say try, Python will try every time you say it without +9638 fail. 8862 + +We will learn these reserved words and how they are used in good time, +but for now we will focus on the Python equivalent of speak (in +human-to-dog language). The nice thing about telling Python to speak +is that we can even tell it what to say by giving it a message in quotes: + +And we have even written our first syntactically correct Python sentence. +Our sentence starts with the reserved word print followed +by a string of text of our choosing enclosed in single quotes. + +Conversing with Python + +Now that we have a word and a simple sentence that we know in Python, +we need to know how to start a conversation with Python to test +our new language skills. + +Before you can converse with Python, you must first install the Python +software on your computer and learn how to start Python on your +computer. That is too much detail for this chapter so I suggest +that you consult www.pythonlearn.com where I have detailed +instructions and screencasts of setting up and starting Python +on Macintosh and Windows systems. At some point, you will be in +a terminal or command window and you will type python and +the Python interpreter will start executing in interactive mode +and appear somewhat as follows: +interactive mode + +The >>> prompt is the Python interpreter's way of asking you, What +do you want me to do next? Python is ready to have a conversation with +you. All you have to know is how to speak the Python language. + +3364 Let's say for example that you did not know even the simplest Python language 6702 +words or sentences. You might want to use the standard line that astronauts +use when they land on a faraway planet and try to speak with the inhabitants +of the planet: + +This is not going so well. Unless you think of something quickly, +the inhabitants of the planet are likely to stab you with their spears, +put you on a spit, roast you over a fire, and eat you for dinner. + +At this point, you should also realize that while Python +is amazingly complex and powerful and very picky about +the 1280 syntax 3928 you 3632 use to communicate with it, Python is + not intelligent. You are really just having a conversation +with yourself, but using proper syntax. + +In a sense, when you use a program written by someone else +the conversation is between you and those other +programmers with Python acting as an intermediary. Python +is a way for the creators of programs to express how the +conversation is supposed to proceed. And +in just a few more chapters, you will be one of those +programmers using Python to talk to the users of your program. + +Before we leave our first conversation with the Python +interpreter, you should probably know the proper way +to say good-bye when interacting with the inhabitants +of Planet Python: + +You will notice that the error is different for the first two +incorrect attempts. The second error is different because +if is a reserved word and Python saw the reserved word +and thought we were trying to say something but got the syntax +of the sentence wrong. + +Terminology: interpreter and compiler + +Python is a high-level language intended to be relatively +straightforward for humans to read and write and for computers +to read and process. Other high-level languages include Java, C++, +PHP, Ruby, Basic, Perl, JavaScript, and many more. The actual hardware +inside the Central Processing Unit (CPU) does not understand any +of these high-level languages. + +The CPU understands a language we call machine language. Machine +language is very simple and frankly very tiresome to write because it +is represented all in zeros and ones. + +Machine language seems quite simple on the surface, given that there +9310 are only zeros and ones, but its syntax is even more complex 9300 +and far more intricate than Python. So very few programmers ever write +machine language. Instead we build various translators to allow +programmers to write in high-level languages like Python or JavaScript +and these translators convert the programs to machine language for actual +execution by the CPU. + +Since machine language is tied to the computer hardware, machine language +is not portable across different types of hardware. Programs written in +high-level languages can be moved between different computers by using a +different interpreter on the new machine or recompiling the code to create +a machine language version of the program for the new machine. +4047 1914 +5073 These programming language translators fall into two general categories: +(one) interpreters and (two) compilers. + +An interpreter reads the source code of the program as written by the +programmer, parses the source code, and interprets the instructions on the fly. +Python is an interpreter and when we are running Python interactively, +we can type a line of Python (a sentence) and Python processes it immediately +and is ready for us to type another line of Python. + +Some of the lines of Python tell Python that you want it to remember some +value for later. We need to pick a name for that value to be remembered and +we can use that symbolic name to retrieve the value later. We use the +term variable to refer to the labels we use to refer to this stored data. + +In this example, we ask Python to remember the value six and use the label x +so 1289 we 2474 can 7683 retrieve the value later. We verify that Python has actually remembered + 3204 the value using x and multiply 7643 +it by seven and put the newly computed value in y. Then we ask Python to print out +the value currently in y. + +Even though we are typing these commands into Python one line at a time, Python +is treating them as an ordered sequence of statements with later statements able +9493 to retrieve data created in earlier statements. We are writing our first 4204 +simple paragraph with four sentences in a logical and meaningful order. + +It is the nature of an interpreter to be able to have an interactive conversation +as shown above. A compiler needs to be handed the entire program in a file, and then +it runs a process to translate the high-level source code into machine language +and then the compiler puts the resulting machine language into a file for later +execution. + +If you have a Windows system, often these executable machine language programs have a +suffix of .exe or .dll which stand for executable and dynamic link +library respectively. In Linux and Macintosh, there is no suffix that uniquely marks +a file as executable. + +If you were to open an executable file in a text editor, it would look +completely crazy and be unreadable: +6951 2470 +It is not easy to read or write machine language, so it is nice that we have +compilers that allow us to write in high-level +languages 1173 like 9594 Python 1947 or C. + +Now at this point in our discussion of compilers and interpreters, you should +be 4927 wondering 1114 a 1352 bit about the Python interpreter itself. What language is + it written in? Is it written in a compiled language? When we type +python, what exactly is happening? + +The Python interpreter is written in a high-level language called C. +You can look at the actual source code for the Python interpreter by +going to www.python.org and working your way to their source code. +So Python is a program itself and it is compiled into machine code. +When you installed Python on your computer (or the vendor installed it), +you copied a machine-code copy of the translated Python program onto your +system. In Windows, the executable machine code for Python itself is likely +in a file. + +That is more than you really need to know to be a Python programmer, but +sometimes it pays to answer those little nagging questions right at +the beginning. + +Writing a program + +Typing commands into the Python interpreter is a great way to experiment +with Python's features, but it is not recommended for solving more complex problems. + +When we want to write a program, +we use a text editor to write the Python instructions into a file, +which is called a script. By +convention, Python scripts have names that end with .py. + +script + +To execute the script, you have to tell the Python interpreter +the name of the file. In a Unix or Windows command window, +you would type python hello.py as follows: + +We call the Python interpreter and tell it to read its source code from +the file hello.py instead of prompting us for lines of Python code +interactively. + +4829 You will notice that there was no need to have quit() at the end of 4453 +the Python program in the file. When Python is reading your source code +from a file, it knows to stop when it reaches the end of the file. + +What is a program? + +The definition of a program at its most basic is a sequence +of Python statements that have been crafted to do something. +Even our simple hello.py script is a program. It is a one-line +program and is not particularly useful, but in the strictest definition, +it is a Python program. + +It might be easiest to understand what a program is by thinking about a problem +that a program might be built to solve, and then looking at a program +that would solve that problem. + +Lets say you are doing Social Computing research on Facebook posts and +you are interested in the most frequently used word in a series of posts. +You could print out the stream of Facebook posts and pore over the text +looking for the most common word, but that would take a long time and be very +mistake prone. You would be smart to write a Python program to handle the +task quickly and accurately so you can spend the weekend doing something +fun. + +For example, look at the following text about a clown and a car. Look at the +text and figure out the most common word and how many times it occurs. + +Then imagine that you are doing this task looking at millions of lines of +text. Frankly it would be quicker for you to learn Python and write a +Python program to count the words than it would be to manually +scan the words. + +The even better news is that I already came up with a simple program to +find the most common word in a text file. I wrote it, +tested it, and now I am giving it to you to use so you can save some time. + +You don't even need to know Python to use this program. You will need to get through +Chapter ten of this book to fully understand the awesome Python techniques that were +used to make the program. You are the end user, you simply use the program and marvel +at its cleverness and how it saved you so much manual effort. +You simply type the code +into a file called words.py and run it or you download the source +code from http://www.pythonlearn.com/code/ and run it. + +This is a good example of how Python and the Python language are acting as an intermediary +between you (the end user) and me (the programmer). Python is a way for us to exchange useful +instruction sequences (i.e., programs) in a common language that can be used by anyone who +installs Python on their computer. So neither of us are talking to Python, +instead we are communicating with each other through Python. + +The building blocks of programs + +In the next few chapters, we will learn more about the vocabulary, sentence structure, +paragraph structure, and story structure of Python. We will learn about the powerful +capabilities of Python and how to compose those capabilities together to create useful +programs. + +There are some low-level conceptual patterns that we use to construct programs. These +constructs are not just for Python programs, they are part of every programming language +from machine language up to the high-level languages. + +description + +Get data from the outside world. This might be +reading data from a file, or even some kind of sensor like +a microphone or GPS. In our initial programs, our input will come from the user +typing data on the keyboard. + +Display the results of the program on a screen +or store them in a file or perhaps write them to a device like a +speaker to play music or speak text. + +Perform statements one after +another in the order they are encountered in the script. + +Check for certain conditions and +then execute or skip a sequence of statements. + +Perform some set of statements +repeatedly, usually with +some variation. + +Write a set of instructions once and give them a name +and then reuse those instructions as needed throughout your program. + +description + +It sounds almost too simple to be true, and of course it is never +so simple. It is like saying that walking is simply +putting one foot in front of the other. The art +of writing a program is composing and weaving these +basic elements together many times over to produce something +that is useful to its users. + +The word counting program above directly uses all of +these patterns except for one. + +What could possibly go wrong? + +As we saw in our earliest conversations with Python, we must +communicate very precisely when we write Python code. The smallest +deviation or mistake will cause Python to give up looking at your +program. + +Beginning programmers often take the fact that Python leaves no +room for errors as evidence that Python is mean, hateful, and cruel. +While Python seems to like everyone else, Python knows them +personally and holds a grudge against them. Because of this grudge, +Python takes our perfectly written programs and rejects them as +unfit just to torment us. + +There is little to be gained by arguing with Python. It is just a tool. +It has no emotions and it is happy and ready to serve you whenever you +need it. Its error messages sound harsh, but they are just Python's +call for help. It has looked at what you typed, and it simply cannot +understand what you have entered. + +Python is much more like a dog, loving you unconditionally, having a few +key words that it understands, looking you with a sweet look on its +face (>>>), and waiting for you to say something it understands. +When Python says SyntaxError: invalid syntax, it is simply wagging +its tail and saying, You seemed to say something but I just don't +understand what you meant, but please keep talking to me (>>>). + +As your programs become increasingly sophisticated, you will encounter three +general types of errors: + +description + +These are the first errors you will make and the easiest +to fix. A syntax error means that you have violated the grammar rules of Python. +Python does its best to point right at the line and character where +it noticed it was confused. The only tricky bit of syntax errors is that sometimes +the mistake that needs fixing is actually earlier in the program than where Python +noticed it was confused. So the line and character that Python indicates in +a syntax error may just be a starting point for your investigation. + +A logic error is when your program has good syntax but there is a mistake +in the order of the statements or perhaps a mistake in how the statements relate to one another. +A good example of a logic error might be, take a drink from your water bottle, put it +in your backpack, walk to the library, and then put the top back on the bottle. + +A semantic error is when your description of the steps to take +is syntactically perfect and in the right order, but there is simply a mistake in +the program. The program is perfectly correct but it does not do what +you intended for it to do. A simple example would +be if you were giving a person directions to a restaurant and said, ...when you reach +the intersection with the gas station, turn left and go one mile and the restaurant +is a red building on your left. Your friend is very late and calls you to tell you that +they are on a farm and walking around behind a barn, with no sign of a restaurant. +Then you say did you turn left or right at the gas station? and +they say, I followed your directions perfectly, I have +them written down, it says turn left and go one mile at the gas station. Then you say, +I am very sorry, because while my instructions were syntactically correct, they +sadly contained a small but undetected semantic error.. + +description + +Again in all three types of errors, Python is merely trying its hardest to +do exactly what you have asked. + +The learning journey + +As you progress through the rest of the book, don't be afraid if the concepts +don't seem to fit together well the first time. When you were learning to speak, +it was not a problem for your first few years that you just made cute gurgling noises. +And it was OK if it took six months for you to move from simple vocabulary to +simple sentences and took five or six more years to move from sentences to paragraphs, and a +few more years to be able to write an interesting complete short story on your own. + +We want you to learn Python much more rapidly, so we teach it all at the same time +over the next few chapters. +But it is like learning a new language that takes time to absorb and understand +before it feels natural. +That leads to some confusion as we visit and revisit +topics to try to get you to see the big picture while we are defining the tiny +fragments that make up that big picture. While the book is written linearly, and +if you are taking a course it will progress in a linear fashion, don't hesitate +to be very nonlinear in how you approach the material. Look forwards and backwards +and read with a light touch. By skimming more advanced material without +fully understanding the details, you can get a better understanding of the why? +of programming. By reviewing previous material and even redoing earlier +exercises, you will realize that you actually learned a lot of material even +if the material you are currently staring at seems a bit impenetrable. + +Usually when you are learning your first programming language, there are a few +wonderful Ah Hah! moments where you can look up from pounding away at some rock +with a hammer and chisel and step away and see that you are indeed building +a beautiful sculpture. + +If something seems particularly hard, there is usually no value in staying up all +night and staring at it. Take a break, take a nap, have a snack, explain what you +are having a problem with to someone (or perhaps your dog), and then come back to it with +fresh eyes. I assure you that once you learn the programming concepts in the book +you will look back and see that it was all really easy and elegant and it simply +took you a bit of time to absorb it. +42 +The end @@ -0,0 +1,594 @@ +This file contains the sample data + + +Why should you learn to write programs? + +Writing programs (or programming) is a very creative +and rewarding activity. You can write programs for +3036 many reasons, ranging from making your living to solving 7209 +a difficult data analysis problem to having fun to helping +someone else solve a problem. This book assumes that +everyone needs to know how to program, and that once +you know how to program you will figure out what you want +to do with your newfound skills. + +We are surrounded in our daily lives with computers ranging +from laptops to cell phones. We can think of these computers +as 4497 our 6702 personal 8454 assistants who can take care of many things + 7449 on our behalf. The hardware in our current-day computers +is essentially built to continuously ask us the question, +What would you like me to do next? + +Programmers add an operating system and a set of applications +to the hardware and we end up with a Personal Digital +Assistant that is quite helpful and capable of helping +us do many different things. + +Our computers are fast and have vast amounts of memory and +could be very helpful to us if we only knew the language to +speak to explain to the computer what we would like it to +do 3665 next. 7936 9772 If we knew this language, we could tell the + computer to do tasks on our behalf that were repetitive. +Interestingly, the kinds of things computers can do best +are often the kinds of things that we humans find boring +and mind-numbing. + +For example, look at the first three paragraphs of this +chapter and tell me the most commonly used word and how +many times the word is used. While you were able to read +and understand the words in a few seconds, counting them +is almost painful because it is not the kind of problem +that human minds are designed to solve. For a computer +the opposite is true, reading and understanding text +from a piece of paper is hard for a computer to do +but counting the words and telling you how many times +the most used word was used is very easy for the +computer: +7114 +Our personal information analysis assistant quickly +told us that the word to was used sixteen times in the +first three paragraphs of this chapter. + +This very fact that computers are good at things +that humans are not is why you need to become +skilled at talking computer language. Once you learn +956 this new language, you can delegate mundane tasks 2564 +to 8003 your 1704 partner 3816 (the computer), leaving more time + for you to do the +things that you are uniquely suited for. You bring +creativity, intuition, and inventiveness to this +partnership. + +Creativity and motivation + +While this book is not intended for professional programmers, professional +programming can be a very rewarding job both financially and personally. +Building useful, elegant, and clever programs for others to use is a very +creative 6662 activity. 5858 7777 Your computer or Personal Digital Assistant (PDA) + usually contains many different programs from many different groups of +programmers, each competing for your attention and interest. They try +their best to meet your needs and give you a great user experience in the +process. In some situations, when you choose a piece of software, the +programmers are directly compensated because of your choice. + +If we think of programs as the creative output of groups of programmers, +perhaps the following figure is a more sensible version of our PDA: + +For now, our primary motivation is not to make money or please end users, but +instead for us to be more productive in handling the data and +information that we will encounter in our lives. +When you first start, you will be both the programmer and the end user of +your programs. As you gain skill as a programmer and +programming feels more creative to you, your thoughts may turn +toward developing programs for others. + +Computer hardware architecture + +Before we start learning the language we +speak to give instructions to computers to +develop software, we need to learn a small amount about +how computers are built. + +Central Processing Unit (or CPU) is +the part of the computer that is built to be obsessed +with what is next? If your computer is rated +at three Gigahertz, it means that the CPU will ask What next? +three billion times per second. You are going to have to +learn how to talk fast to keep up with the CPU. + +Main Memory is used to store information +that the CPU needs in a hurry. The main memory is nearly as +fast as the CPU. But the information stored in the main +memory vanishes when the computer is turned off. + +Secondary Memory is also used to store +6482 information, but it is much slower than the main memory. +The advantage of the secondary memory is that it can +store information even when there is no power to the +computer. Examples of secondary memory are disk drives +or flash memory (typically found in USB sticks and portable +music players). +9634 +Input and Output Devices are simply our +screen, keyboard, mouse, microphone, speaker, touchpad, etc. +They are all of the ways we interact with the computer. + +These days, most computers also have a +Network Connection to retrieve information over a network. +We can think of the network as a very slow place to store and +8805 retrieve data that might not always be up. So in a sense, 7123 +the network is a slower and at times unreliable form of +9703 4676 6373 + +While most of the detail of how these components work is best left +to computer builders, it helps to have some terminology +so we can talk about these different parts as we write our programs. + +As a programmer, your job is to use and orchestrate +each of these resources to solve the problem that you need to solve +and analyze the data you get from the solution. As a programmer you will +mostly be talking to the CPU and telling it what to +do next. Sometimes you will tell the CPU to use the main memory, +secondary memory, network, or the input/output devices. + +You need to be the person who answers the CPU's What next? +question. But it would be very uncomfortable to shrink you +down to five mm tall and insert you into the computer just so you +could issue a command three billion times per second. So instead, +you must write down your instructions in advance. +We call these stored instructions a program and the act +of writing these instructions down and getting the instructions to +be correct programming. + +Understanding programming + +In the rest of this book, we will try to turn you into a person +who is skilled in the art of programming. In the end you will be a +programmer --- perhaps not a professional programmer, but +at least you will have the skills to look at a data/information +analysis problem and develop a program to solve the problem. +2834 +7221 problem solving + +2981 In a sense, you need two skills to be a programmer: + +First, you need to know the programming language (Python) - +5415 you need to know the vocabulary and the grammar. You need to be able +to spell the words in this new language properly and know how to construct +well-formed sentences in this new language. + +Second, you need to tell a story. In writing a story, +you combine words and sentences to convey an idea to the reader. +There is a skill and art in constructing the story, and skill in +story writing is improved by doing some writing and getting some +feedback. In programming, our program is the story and the +problem you are trying to solve is the idea. + +itemize + +Once you learn one programming language such as Python, you will +find it much easier to learn a second programming language such +as JavaScript or C++. The new programming language has very different +vocabulary and grammar but the problem-solving skills +will be the same across all programming languages. + +You will learn the vocabulary and sentences of Python pretty quickly. +It will take longer for you to be able to write a coherent program +to solve a brand-new problem. We teach programming much like we teach +writing. We start reading and explaining programs, then we write +simple programs, and then we write increasingly complex programs over time. +At some point you get your muse and see the patterns on your own +and can see more naturally how to take a problem and +write a program that solves that problem. And once you get +6872 to that point, programming becomes a very pleasant and creative process. + +We start with the vocabulary and structure of Python programs. Be patient +as the simple examples remind you of when you started reading for the first +time. + +Words and sentences +4806 +Unlike human languages, the Python vocabulary is actually pretty small. +We call this vocabulary the reserved words. These are words that +5460 have very special meaning to Python. When Python sees these words in 8533 +3538 a Python program, they have one and only one meaning to Python. Later +as you write programs you will make up your own words that have meaning to +you called variables. You will have great latitude in choosing +your 9663 names 8001 for 9795 your variables, but you cannot use any of Python's + reserved 8752 words 1117 as 5349 a name for a variable. + +When we train a dog, we use special words like +sit, stay, and fetch. When you talk to a dog and +4509 don't use any of the reserved words, they just look at you with a +quizzical look on their face until you say a reserved word. +For example, if you say, +I wish more people would walk to improve their overall health, +what most dogs likely hear is, +blah blah blah walk blah blah blah blah. +That is because walk is a reserved word in dog language. + +The reserved words in the language where humans talk to +Python include the following: + +and del from not while +as elif global or with +assert else if pass yield +break except import print +class exec in raise +continue finally is return +def for lambda try + +That is it, and unlike a dog, Python is already completely trained. +When 1004 you 9258 say 4183 try, Python will try every time you say it without + fail. + +4034 We will learn these reserved words and how they are used in good time, 3342 +but for now we will focus on the Python equivalent of speak (in +human-to-dog language). The nice thing about telling Python to speak +3482 is that we can even tell it what to say by giving it a message in quotes: 8567 + +And we have even written our first syntactically correct Python sentence. +Our sentence starts with the reserved word print followed +by a string of text of our choosing enclosed in single quotes. + +Conversing with Python + +1052 Now that we have a word and a simple sentence that we know in Python, 8135 +we need to know how to start a conversation with Python to test +our new language skills. + +Before 5561 you 517 can 1218 converse with Python, you must first install the Python + software on your computer and learn how to start Python on your +computer. That is too much detail for this chapter so I suggest +that you consult www.pythonlearn.com where I have detailed +instructions and screencasts of setting up and starting Python +on Macintosh and Windows systems. At some point, you will be in +a terminal or command window and you will type python and +8877 the Python interpreter will start executing in interactive mode +and appear somewhat as follows: +interactive mode + +The >>> prompt is the Python interpreter's way of asking you, What +do you want me to do next? Python is ready to have a conversation with +you. All you have to know is how to speak the Python language. + +Let's say for example that you did not know even the simplest Python language +words or sentences. You might want to use the standard line that astronauts +use when they land on a faraway planet and try to speak with the inhabitants +of the planet: + +This is not going so well. Unless you think of something quickly, +the inhabitants of the planet are likely to stab you with their spears, +put you on a spit, roast you over a fire, and eat you for dinner. + +At this point, you should also realize that while Python +is amazingly complex and powerful and very picky about +the syntax you use to communicate with it, Python is +not intelligent. You are really just having a conversation +with yourself, but using proper syntax. +8062 1720 +In a sense, when you use a program written by someone else +the conversation is between you and those other +programmers with Python acting as an intermediary. Python +is a way for the creators of programs to express how the +conversation is supposed to proceed. And +in just a few more chapters, you will be one of those +programmers using Python to talk to the users of your program. + +279 Before we leave our first conversation with the Python +interpreter, you should probably know the proper way +to say good-bye when interacting with the inhabitants +of Planet Python: + +2054 You will notice that the error is different for the first two 801 +incorrect attempts. The second error is different because +if is a reserved word and Python saw the reserved word +and thought we were trying to say something but got the syntax +of the sentence wrong. + +Terminology: interpreter and compiler + +Python is a high-level language intended to be relatively +straightforward for humans to read and write and for computers +to read and process. Other high-level languages include Java, C++, +918 PHP, Ruby, Basic, Perl, JavaScript, and many more. The actual hardware +inside the Central Processing Unit (CPU) does not understand any +of these high-level languages. + +The CPU understands a language we call machine language. Machine +language is very simple and frankly very tiresome to write because it +is represented all in zeros and ones. + +Machine language seems quite simple on the surface, given that there +are only zeros and ones, but its syntax is even more complex +8687 and far more intricate than Python. So very few programmers ever write +machine language. Instead we build various translators to allow +programmers to write in high-level languages like Python or JavaScript +and these translators convert the programs to machine language for actual +execution by the CPU. + +Since machine language is tied to the computer hardware, machine language +is not portable across different types of hardware. Programs written in +high-level languages can be moved between different computers by using a +different interpreter on the new machine or recompiling the code to create +a machine language version of the program for the new machine. + +These programming language translators fall into two general categories: +(one) interpreters and (two) compilers. +7073 1865 7084 +An interpreter reads the source code of the program as written by the +programmer, parses the source code, and interprets the instructions on the fly. +Python is an interpreter and when we are running Python interactively, +we can type a line of Python (a sentence) and Python processes it immediately +and is ready for us to type another line of Python. +2923 63 +Some of the lines of Python tell Python that you want it to remember some +value for later. We need to pick a name for that value to be remembered and +we can use that symbolic name to retrieve the value later. We use the +term variable to refer to the labels we use to refer to this stored data. + +In this example, we ask Python to remember the value six and use the label x +so we can retrieve the value later. We verify that Python has actually remembered +the value using x and multiply +it by seven and put the newly computed value in y. Then we ask Python to print out +8824 the value currently in y. +1079 5801 5047 +Even though we are typing these commands into Python one line at a time, Python +is treating them as an ordered sequence of statements with later statements able +to retrieve data created in earlier statements. We are writing our first +simple paragraph with four sentences in a logical and meaningful order. +5 +It is the nature of an interpreter to be able to have an interactive conversation +as shown above. A compiler needs to be handed the entire program in a file, and then +it runs a process to translate the high-level source code into machine language +2572 and then the compiler puts the resulting machine language into a file for later +execution. + +If you have a Windows system, often these executable machine language programs have a +suffix of .exe or .dll which stand for executable and dynamic link +library respectively. In Linux and Macintosh, there is no suffix that uniquely marks +a file as executable. + +If you were to open an executable file in a text editor, it would look +completely crazy and be unreadable: + +It is not easy to read or write machine language, so it is nice that we have +compilers that allow us to write in high-level +languages like Python or C. + +Now at this point in our discussion of compilers and interpreters, you should +be 5616 wondering 171 a 3062 bit about the Python interpreter itself. What language is + 9552 it written in? Is it written in a compiled language? When we type 7655 +python, 829 what 6096 exactly 2312 is happening? + +The Python interpreter is written in a high-level language called C. +You can look at the actual source code for the Python interpreter by +going to www.python.org and working your way to their source code. +So Python is a program itself and it is compiled into machine code. +When you installed Python on your computer (or the vendor installed it), +6015 you copied a machine-code copy of the translated Python program onto your 7100 +system. In Windows, the executable machine code for Python itself is likely +in a file. + +That is more than you really need to know to be a Python programmer, but +sometimes it pays to answer those little nagging questions right at +the beginning. + +Writing a program + +Typing commands into the Python interpreter is a great way to experiment +with Python's features, but it is not recommended for solving more complex problems. + +When we want to write a program, +we use a text editor to write the Python instructions into a file, +which 9548 is 2727 called 1792 a script. By + convention, Python scripts have names that end with .py. + +script + +To execute the script, you have to tell the Python interpreter +the name of the file. In a Unix or Windows command window, +you would type python hello.py as follows: + +We call the Python interpreter and tell it to read its source code from +the file hello.py instead of prompting us for lines of Python code +interactively. + +You will notice that there was no need to have quit() at the end of +the Python program in the file. When Python is reading your source code +from a file, it knows to stop when it reaches the end of the file. + +8402 What is a program? + +The definition of a program at its most basic is a sequence +of Python statements that have been crafted to do something. +Even our simple hello.py script is a program. It is a one-line +program and is not particularly useful, but in the strictest definition, +it is a Python program. + +It might be easiest to understand what a program is by thinking about a problem +that a program might be built to solve, and then looking at a program +that would solve that problem. + +Lets say you are doing Social Computing research on Facebook posts and +you are interested in the most frequently used word in a series of posts. +You could print out the stream of Facebook posts and pore over the text +looking for the most common word, but that would take a long time and be very +mistake prone. You would be smart to write a Python program to handle the +task quickly and accurately so you can spend the weekend doing something +fun. + +For example, look at the following text about a clown and a car. Look at the +text and figure out the most common word and how many times it occurs. + +Then imagine that you are doing this task looking at millions of lines of +text. Frankly it would be quicker for you to learn Python and write a +Python program to count the words than it would be to manually +scan the words. + +The even better news is that I already came up with a simple program to +find the most common word in a text file. I wrote it, +tested it, and now I am giving it to you to use so you can save some time. + +You don't even need to know Python to use this program. You will need to get through +Chapter ten of this book to fully understand the awesome Python techniques that were +used to make the program. You are the end user, you simply use the program and marvel +at its cleverness and how it saved you so much manual effort. +You simply type the code +into a file called words.py and run it or you download the source +code from http://www.pythonlearn.com/code/ and run it. + +This is a good example of how Python and the Python language are acting as an intermediary +between you (the end user) and me (the programmer). Python is a way for us to exchange useful +instruction sequences (i.e., programs) in a common language that can be used by anyone who +installs Python on their computer. So neither of us are talking to Python, +instead we are communicating with each other through Python. + +The building blocks of programs + +In the next few chapters, we will learn more about the vocabulary, sentence structure, +paragraph structure, and story structure of Python. We will learn about the powerful +capabilities of Python and how to compose those capabilities together to create useful +programs. + +There are some low-level conceptual patterns that we use to construct programs. These +constructs are not just for Python programs, they are part of every programming language +from machine language up to the high-level languages. + +description + +Get data from the outside world. This might be +reading data from a file, or even some kind of sensor like +a microphone or GPS. In our initial programs, our input will come from the user +typing data on the keyboard. + +Display the results of the program on a screen +or store them in a file or perhaps write them to a device like a +speaker to play music or speak text. + +Perform statements one after +another in the order they are encountered in the script. + +Check for certain conditions and +then execute or skip a sequence of statements. + +Perform some set of statements +repeatedly, usually with +some variation. + +Write a set of instructions once and give them a name +and then reuse those instructions as needed throughout your program. + +description + +It sounds almost too simple to be true, and of course it is never +so simple. It is like saying that walking is simply +putting one foot in front of the other. The art +of writing a program is composing and weaving these +basic elements together many times over to produce something +that is useful to its users. + +The word counting program above directly uses all of +these patterns except for one. + +What could possibly go wrong? + +As we saw in our earliest conversations with Python, we must +communicate very precisely when we write Python code. The smallest +deviation or mistake will cause Python to give up looking at your +program. + +Beginning programmers often take the fact that Python leaves no +room for errors as evidence that Python is mean, hateful, and cruel. +While Python seems to like everyone else, Python knows them +personally and holds a grudge against them. Because of this grudge, +Python takes our perfectly written programs and rejects them as +unfit just to torment us. + +There is little to be gained by arguing with Python. It is just a tool. +It has no emotions and it is happy and ready to serve you whenever you +need it. Its error messages sound harsh, but they are just Python's +call for help. It has looked at what you typed, and it simply cannot +understand what you have entered. + +Python is much more like a dog, loving you unconditionally, having a few +key words that it understands, looking you with a sweet look on its +face (>>>), and waiting for you to say something it understands. +When Python says SyntaxError: invalid syntax, it is simply wagging +its tail and saying, You seemed to say something but I just don't +understand what you meant, but please keep talking to me (>>>). + +As your programs become increasingly sophisticated, you will encounter three +general types of errors: + +description + +These are the first errors you will make and the easiest +to fix. A syntax error means that you have violated the grammar rules of Python. +Python does its best to point right at the line and character where +it noticed it was confused. The only tricky bit of syntax errors is that sometimes +the mistake that needs fixing is actually earlier in the program than where Python +noticed it was confused. So the line and character that Python indicates in +a syntax error may just be a starting point for your investigation. + +A logic error is when your program has good syntax but there is a mistake +in the order of the statements or perhaps a mistake in how the statements relate to one another. +A good example of a logic error might be, take a drink from your water bottle, put it +in your backpack, walk to the library, and then put the top back on the bottle. + +A semantic error is when your description of the steps to take +is syntactically perfect and in the right order, but there is simply a mistake in +the program. The program is perfectly correct but it does not do what +you intended for it to do. A simple example would +be if you were giving a person directions to a restaurant and said, ...when you reach +the intersection with the gas station, turn left and go one mile and the restaurant +is a red building on your left. Your friend is very late and calls you to tell you that +they are on a farm and walking around behind a barn, with no sign of a restaurant. +Then you say did you turn left or right at the gas station? and +they say, I followed your directions perfectly, I have +them written down, it says turn left and go one mile at the gas station. Then you say, +I am very sorry, because while my instructions were syntactically correct, they +sadly contained a small but undetected semantic error.. + +description + +Again in all three types of errors, Python is merely trying its hardest to +do exactly what you have asked. + +The learning journey + +As you progress through the rest of the book, don't be afraid if the concepts +don't seem to fit together well the first time. When you were learning to speak, +it was not a problem for your first few years that you just made cute gurgling noises. +And it was OK if it took six months for you to move from simple vocabulary to +simple sentences and took five or six more years to move from sentences to paragraphs, and a +few more years to be able to write an interesting complete short story on your own. + +We want you to learn Python much more rapidly, so we teach it all at the same time +over the next few chapters. +But it is like learning a new language that takes time to absorb and understand +before it feels natural. +That leads to some confusion as we visit and revisit +topics to try to get you to see the big picture while we are defining the tiny +fragments that make up that big picture. While the book is written linearly, and +if you are taking a course it will progress in a linear fashion, don't hesitate +to be very nonlinear in how you approach the material. Look forwards and backwards +and read with a light touch. By skimming more advanced material without +fully understanding the details, you can get a better understanding of the why? +of programming. By reviewing previous material and even redoing earlier +exercises, you will realize that you actually learned a lot of material even +if the material you are currently staring at seems a bit impenetrable. + +Usually when you are learning your first programming language, there are a few +wonderful Ah Hah! moments where you can look up from pounding away at some rock +with a hammer and chisel and step away and see that you are indeed building +a beautiful sculpture. + +If something seems particularly hard, there is usually no value in staying up all +night and staring at it. Take a break, take a nap, have a snack, explain what you +are having a problem with to someone (or perhaps your dog), and then come back to it with +fresh eyes. I assure you that once you learn the programming concepts in the book +you will look back and see that it was all really easy and elegant and it simply +took you a bit of time to absorb it. +42 +The end @@ -0,0 +1,8 @@ +Why should you learn to write programs? 7746 +12 1929 8827 +Writing programs (or programming) is a very creative +7 and rewarding activity. You can write programs for +many reasons, ranging from making your living to solving +8837 a difficult data analysis problem to having fun to helping 128 +someone else solve a problem. This book assumes that +everyone needs to know how to program ... \ No newline at end of file @@ -0,0 +1,23 @@ + +def reversed(text): + rev = '' + for i in range(len(text), 0, -1): + rev += text[i-1] + return rev + +class Palindrome: + @staticmethod + def is_palindrome(word): + word = word.lower() + for elem in range(len(word)): + if word[elem] == reversed(word)[elem]: + #print(word[elem], word[-1:elem]) + pass + else: + return False + return True +#word = input() +word = "test" +print(Palindrome.is_palindrome(word)) +print(Palindrome.is_palindrome("Deleveled")) +print(Palindrome.is_palindrome("adam")) @@ -0,0 +1,26 @@ +itd.umich.edu 141.211.144.50 +umich.edu 141.211.243.44 +bugs.sakaiproject.org 72.249.101.17 +cam.ac.uk 131.111.150.25 +rsug.itd.umich.edu 141.213.231.23 +ring.mr.itd.umich.edu 141.211.14.79 +fightclub.rsug.itd.umich.edu 141.211.14.36 +driveangry.mr.itd.umich.edu 141.211.14.43 +uits.iupui.edu 129.79.78.247 +berkeley.edu 169.229.216.200 +ghostship.mr.itd.umich.edu 141.211.14.91 +anantes-551-1-153-3.w2-1.abo.wanadoo.fr 2.1.0.3 +shmi.uhi.ac.uk 194.35.219.182 +nakamura.uits.iupui.edu Fail +source.sakaiproject.org 72.249.148.216 +iupui.edu 129.79.78.166 +collab.sakaiproject.org 74.213.159.72 +sakaiproject.org 140.211.9.16 +mail.umich.edu 141.211.144.49 +uhi.ac.uk 194.35.219.16 +anantes-651-1-49-3.w2-0.abo.wanadoo.fr 2.0.0.3 +uct.ac.za 137.158.158.44 +firestarter.mr.itd.umich.edu 141.211.14.83 +media.berkeley.edu 128.32.61.200 +wanadoo.fr 193.252.122.103 +gmail.com 216.58.209.197 \ No newline at end of file Binary files /dev/null and b/Pyton_stuff/Teme_BD/PyAppReadCons.7z.fake differ @@ -0,0 +1,36 @@ +__author__ = 'darakna' +import os.path +import shutil +cale_fisier_citire="BDFLT_times.txt" +if os.path.exists(cale_fisier_citire) is True: + filehandler = open(cale_fisier_citire) +else: + cale_fisier_citire=input("Fisierul "+cale_fisier_citire+" nu a fost gasit. Introdu cale si nume fisier citire:") + filehandler = open(cale_fisier_citire) +filehandler_w=open("Files_not_found.txt",'w') +stream_read=filehandler.readlines() +lines_number=0 +index_f=0 +index_v=0 +for line in stream_read: + lines_number=lines_number+1 + cale_inceput = 9 + cale_final = line.find("------")-1 + cale_origine=line[cale_inceput:cale_final] + cale_destinatie="Dest_Folder"+line[cale_inceput+2:cale_final] + #print (cale_origine,cale_destinatie) + if os.path.exists(cale_origine) is True: + if not os.path.exists(cale_destinatie[:cale_destinatie.rfind("\\")]): + os.makedirs(cale_destinatie[:cale_destinatie.rfind("\\")]) + shutil.copyfile(cale_origine, cale_destinatie) + index_v=index_v+1 + else: + filehandler_w.write(str(index_f)) + index_f=index_f+1 + filehandler_w.write(" ") + filehandler_w.write(cale_origine) + #time_position=line.find("------ Time ")+12 + filehandler_w.write(line[cale_final+12:]) +cale_script=os.path.abspath(__file__) +print("Directorul scriptului este:",cale_script,"Numarul de fisiere copiate este:",index_v) +#print(lines_number) @@ -0,0 +1,17 @@ +__author__ = 'darakna' +import subprocess + +def var1(s_process): + print ('\nread:') + proc = subprocess.Popen([s_process, '"to stdout"'], + stdout=subprocess.PIPE, + ) + stdout_value = proc.communicate()[0] +# print ('\tstdout:', repr(stdout_value)) + print(stdout_value) +def var2(s_process2): + print ('\npopen2:') + proc = subprocess.Popen([s_process2, '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE,) + stdout_value = proc.communicate('through stdin to stdout','-')[0] #'through stdin to stdout' + print ('\tpass through:', repr(stdout_value)) +var2('PyAppReadCons.exe') \ No newline at end of file @@ -0,0 +1,11 @@ +__author__ = 'darakna' +#import wmi +#c = wmi.WMI () + +#for process in c.Win32_Process (): +# print (process.ProcessId, process.Name) +import subprocess +cmd = 'WMIC PROCESS get Caption,Commandline,Processid' +proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) +for line in proc.stdout: + print(line) \ No newline at end of file @@ -0,0 +1,18 @@ +__author__ = 'darakna' +import subprocess +from subprocess import PIPE +proces_vanat="pyappreadcons.exe" +mesaje_trimise=["test1", "test2", "test3", "exit"] +print ("Test 1") +proc = subprocess.Popen(proces_vanat,stdin=PIPE,stdout=PIPE) +print ("Test 2") + + + +proc.stdin.Pope(mesaje_trimise[0].encode('UTF-8')) +print ("Test 3") + +a=proc.stdout.read() +print ("Test 4") +print (a) +proc.kill() \ No newline at end of file @@ -0,0 +1,6 @@ +__author__ = 'darakna' +import os +os.system('WMIC /OUTPUT:D:\ProcessList.txt PROCESS get Caption,Commandline,Processid') +f = open("D:\ProcessList.txt") +plist = f.readlines() +f.close() \ No newline at end of file @@ -0,0 +1,21 @@ +__author__ = 'darakna' +def process_exists(name): + i = psutil.get_pid_list() + for a in i: + try: + if str(psutil.Process(a).name) == name: + return True + except: + pass + return False +#print(process_exists("Chrome")) + +import psutil + +for proc in psutil.process_iter(): + try: + if proc.name() == u"chrome.exe": + print(proc) + print(proc.cmdline()) + except psutil.AccessDenied: + print ("Permission error or access denied on process") \ No newline at end of file @@ -0,0 +1,38 @@ +__author__ = 'darakna' +import subprocess +from subprocess import PIPE +import threading +import time +threadList = [] +num_threads=5 +proces_vanat="PyAppReadCons.exe" +mesaje_trimise=["test1", "test2", "test3", "exit"] +print ("...alocare ok...") +def pornire_proces(nume): + return subprocess.Popen(nume,stdin=PIPE,stdout=PIPE) +def trimite_mesaj(mesaj): + proc.stdin.write((mesaj+"\n").encode('UTF-8')) + proc.stdin.flush() + print ("...trimitere mesaj proces: ",mesaj) + +def primeste_mesaj(): + print ("...initializare asteptare mesaj ") + print("...Mesaj: ",proc.stdout.read().decode("ASCII")[:-1]) + print ("...mesaj proces primit cu succes \n") + +print ("...initializare bucla...") +for thread_ind in mesaje_trimise: + proc = pornire_proces(proces_vanat) + print ("...start bucla cu parametru ",mesaje_trimise.index(thread_ind)) + worker=threading.Thread(target=trimite_mesaj,args=(thread_ind,)) + worker.start() + threadList.append(worker) + worker2=threading.Thread(target=primeste_mesaj,args=()) + worker2.start() + threadList.append(worker2) + print ("...stop bucla cu parametru ",mesaje_trimise.index(thread_ind)) + time.sleep(0.1) + if proc.poll()!=0: + proc.kill() + time.sleep(0.5) + @@ -0,0 +1,33 @@ +__author__ = 'darakna' +__author__ = 'darakna' +import subprocess +from subprocess import PIPE +import threading +threadList = [] +num_threads=5 +proces_vanat="PyAppReadCons.exe" +mesaje_trimise=["test1", "test2", "test3", "exit"] +proc = subprocess.Popen(proces_vanat,stdin=PIPE,stdout=PIPE) +print ("...alocare ok...") +def trimite_mesaj(mesaj): + proc.stdin.write((mesaj+"\n").encode('UTF-8')) + proc.stdin.flush() + print ("...trimitere mesaj proces: ",mesaj) + +def primeste_mesaj(): + print ("...initializare asteptare mesaj ") + print(proc.stdout.read().decode("ASCII")) + print ("... mesaj proces primit cu succes ") + + #proc.kill() +worker2=threading.Thread(target=primeste_mesaj,args=()) +worker2.start() +threadList.append(worker2) +print ("...initializare bucla...") +for thread_ind in mesaje_trimise: + print ("...start bucla cu parametru ",mesaje_trimise.index(thread_ind)) + worker=threading.Thread(target=trimite_mesaj,args=(thread_ind,)) + worker.start() + threadList.append(worker) + print ("...stop bucla cu parametru ",mesaje_trimise.index(thread_ind)) + @@ -0,0 +1,9 @@ +__author__ = 'darakna' +import subprocess +from subprocess import PIPE +import threading +threadList = [] +num_threads=5 +#proces_vanat="PyAppReadCons.exe" +mesaje_trimise=["test1", "test2", "test3", "exit"] +proc = subprocess.Popen("PyAppReadCons.exe",stdin=PIPE,stdout=PIPE) \ No newline at end of file @@ -0,0 +1,21 @@ +__author__ = 'darakna' +from threading import Thread +import subprocess,os +from queue import * + +num_threads = 10 +queue = Queue() +ips = ["k.ro", "google.ro", "example.com"] +def pinger(i, q): + print(i," ??? ",q) + response = os.system("ping -n 1 " + ip) +for i in range(num_threads): + worker = Thread(target=pinger, args=(i, queue)) + worker.setDaemon(True) + worker.start() +for ip in ips: + + pinger(ip,queue) + queue.put(ip) + # Wait until worker threads are done to exit + queue.join() \ No newline at end of file @@ -0,0 +1,11 @@ +__author__ = 'darakna' +import subprocess,datetime +ips = ["k.ro", "google.ro", "example.com","wiki.com"] +def perftest(hostname): + start_time=datetime.datetime.now() + subprocess.run("ping -n 1 " + hostname) + stop_time=datetime.datetime.now() + return stop_time-start_time + +for ip in ips: + print(perftest(ip)) \ No newline at end of file @@ -0,0 +1,15 @@ +__author__ = 'darakna' +from time import * +import threading +threadList = [] +nameList = ["One", "Two", "Three", "Four", "Five"] +num_threads=10 +def wait_and_print(worker): + print(worker," starting work") + print(threadList) + sleep(3) + print(worker, " finished") +for thread_ind in range(num_threads): + worker=threading.Thread(target=wait_and_print,args=(thread_ind,)) + worker.start() + threadList.append(worker) \ No newline at end of file @@ -0,0 +1,7 @@ +a +A +a +A +abc +Abc +a @@ -0,0 +1,2 @@ +4 +1 \ No newline at end of file @@ -0,0 +1,11 @@ +__author__ = 'darakna' +filehandler = open("in.txt") +filehandler_w=open("out.txt",'w') +string_read=filehandler.read() +#print(string_read) +counter_a=string_read.count("a",0,len(string_read)) +counter_abc=string_read.count("abc",0,len(string_read)) +#print(counter_a,"\n",counter_abc) +filehandler_w.write(str(counter_a)) +filehandler_w.write("\n") +filehandler_w.write(str(counter_abc)) \ No newline at end of file @@ -0,0 +1,23 @@ +__author__ = 'darakna' +import os,subprocess +ips = ["k.kro", "google.ro"]#, "example.com","ele.ool"] +def pingping(host): + response = os.system("ping -n 5 " + host) + print(response) + if response == 0: + print (host, 'is up!') + else: + print (host, 'is down!') + +for ip in ips: + #pingping(ip) + pass +#chost=subprocess.run("ping -n 5 " + "k.ro") +#print("Test") +#print(chost) + +#with subprocess.run("ping -n 5 " + "k.ro"): +# print("Test1") +# print(proc.stdout.read()) +# Print("Test2") + @@ -0,0 +1,24 @@ +__author__ = 'darakna' + +from threading import * +import time + +# Define a function for the thread +def print_time( threadName, delay): + count = 0 + while count < 5: + time.sleep(delay) + count += 1 + print("%s: %s" % ( threadName, time.ctime(time.time()) )) + +# Create two threads as follows +try: + Thread.start_new_thread( print_time, ("Thread-1", 2, ) ) + Thread.start_new_thread( print_time, ("Thread-2", 4, ) ) +except: + print("Error: unable to start thread") + +while 1: + pass + +print(threading.stack_size()) \ No newline at end of file @@ -0,0 +1,13 @@ +__author__ = 'vpaun' +import os +pid_name="calc.exe" +tmp_location="D:\DllsList.txt" +os.system('listdlls '+pid_name + " >>"+tmp_location) +readFileTemp=open(tmp_location) +if "injct64.dll" in readFileTemp.read(): + print("Simulator injection found in ",pid_name) +else: + print("Simulator injection not found in",pid_name) +readFileTemp.close() +os.remove(tmp_location) +print(ord("")) \ No newline at end of file @@ -0,0 +1,56 @@ +__author__ = 'darakna' +import os +import time +import codecs + +def get_filepaths(directory): + """ + This function will generate the file names in a directory + tree by walking the tree either top-down or bottom-up. For each + directory in the tree rooted at directory top (including top itself), + it yields a 3-tuple (dirpath, dirnames, filenames). + """ + file_paths = [] # List which will store all of the full filepaths. + + # Walk the tree. + for root, directories, files in os.walk(directory): + for filename in files: + # Join the two strings in order to form the full filepath. + filepath = os.path.join(root, filename) + file_paths.append(filepath) # Add it to the list. + + return file_paths # Self-explanatory. + +# Run the above function and store its results in a variable. +full_file_paths = get_filepaths("path_with_logs") +g=open("Errors.txt","w") +for i in range(len(full_file_paths)): + print(full_file_paths[i]) + f=open(full_file_paths[i]) + try: + print("Test1") + f=codecs.open(full_file_paths[i], "r", "utf-16") + text=f.read() + print("Test2") + except: + print("Test3") + f=open(full_file_paths[i]) + text=f.read() + print("Test4") + #text=f.read() + time.sleep(0.3) + #print(text) + text=text.split("\n") + #print(text) + g.write("\n\n\n") + g.write(full_file_paths[i]) + g.write("\n") + for words in text: + #print(words) + if "WARNING" in words or "ERROR" in words: + print(words) + g.write(words) + g.write("\n") + f.close() +g.close() + @@ -0,0 +1,83 @@ +__author__ = 'darakna' +import os +import time +import codecs + +def get_filepaths(directory): + """ + This function will generate the file names in a directory + tree by walking the tree either top-down or bottom-up. For each + directory in the tree rooted at directory top (including top itself), + it yields a 3-tuple (dirpath, dirnames, filenames). + """ + file_paths = [] # List which will store all of the full filepaths. + + # Walk the tree. + for root, directories, files in os.walk(directory): + for filename in files: + # Join the two strings in order to form the full filepath. + filepath = os.path.join(root, filename) + file_paths.append(filepath) # Add it to the list. + + return file_paths # Self-explanatory. + +# Run the above function and store its results in a variable. +full_file_paths = get_filepaths("folder_with_logs") +process_name = "calc.exe" + +domain_char_list=list(range(0,127)) +def stripall(word): + if word=="": + return "" + else: + if ord(word[0]) in domain_char_list: + return word[0]+stripall(word[1:]) + else: + return stripall(word[1:]) + + +h=open("Logfiles.txt","w") +no_of_lines=0 +for i in range(len(full_file_paths)): + print(full_file_paths[i]) + h.write(full_file_paths[i]) + h.write("\n") + f=open(full_file_paths[i]) + myEncoding = "utf-8" + try: + print("Try decode utf-16") + myEncoding = 'utf-16' + f=codecs.open(full_file_paths[i], "r", "utf-16") + text=f.read() + + print("Succses decode utf-16") + except: + print("Fail decode utf-16, decode ASCII") + f=open(full_file_paths[i]) + text=f.read() + print("Succses decode ASCII") + #text=f.read() + #time.sleep(0.3) + #print(text) + text=text.split("\n") + #print(text) + g=open("Errors.txt","a", encoding=myEncoding) + g.write("\n\n\n") + g.write(full_file_paths[i]) + g.write("\n") + no_of_lines+=1 + for words in text: + #print(words) + if process_name in words.lower(): + try: + print(words) + g.write(words) + g.write("\n") + except: + print(stripall(words)) + g.write(stripall(words)) + g.write("\n") + f.close() + g.close() +h.write("No of log files = "+str(no_of_lines)) +h.close() @@ -0,0 +1,82 @@ +__author__ = 'darakna' +import os +import time +import codecs + +def get_filepaths(directory): + """ + This function will generate the file names in a directory + tree by walking the tree either top-down or bottom-up. For each + directory in the tree rooted at directory top (including top itself), + it yields a 3-tuple (dirpath, dirnames, filenames). + """ + file_paths = [] # List which will store all of the full filepaths. + + # Walk the tree. + for root, directories, files in os.walk(directory): + for filename in files: + # Join the two strings in order to form the full filepath. + filepath = os.path.join(root, filename) + file_paths.append(filepath) # Add it to the list. + + return file_paths # Self-explanatory. + +# Run the above function and store its results in a variable. +full_file_paths = get_filepaths("folder_with_logs") + +domain_char_list=list(range(0,127)) +def stripall(word): + if word=="": + return "" + else: + if ord(word[0]) in domain_char_list: + return word[0]+stripall(word[1:]) + else: + return stripall(word[1:]) + + +h=open("Logfiles.txt","w") +no_of_lines=0 +for i in range(len(full_file_paths)): + print(full_file_paths[i]) + h.write(full_file_paths[i]) + h.write("\n") + f=open(full_file_paths[i]) + myEncoding = "utf-8" + try: + print("Try decode utf-16") + myEncoding = 'utf-16' + f=codecs.open(full_file_paths[i], "r", "utf-16") + text=f.read() + + print("Succses decode utf-16") + except: + print("Fail decode utf-16, decode ASCII") + f=open(full_file_paths[i]) + text=f.read() + print("Succses decode ASCII") + #text=f.read() + #time.sleep(0.3) + #print(text) + text=text.split("\n") + #print(text) + g=open("Errors.txt","a", encoding=myEncoding) + g.write("\n\n\n") + g.write(full_file_paths[i]) + g.write("\n") + no_of_lines+=1 + for words in text: + #print(words) + if "WARNING" in words or "ERROR" in words: + try: + print(words) + g.write(words) + g.write("\n") + except: + print(stripall(words)) + g.write(stripall(words)) + g.write("\n") + f.close() +g.close() +h.write("No of log files = "+str(no_of_lines)) +h.close() @@ -0,0 +1,18 @@ +__author__ = 'darakna' +import subprocess +cmd = 'WMIC PROCESS get Caption,Commandline,Processid' +proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) +for line in proc.stdout: + #print(line) + pass + +import os +os.system('WMIC /OUTPUT:D:\ProcessList.txt PROCESS get Caption,Commandline,Processid') +f = open("D:\ProcessList.txt") +plist = f.readlines() +f.close() + + +pid_name="Calculator.exe" +import os +os.system('D:\Dropbox\@Munca\WORK\MagicWandTools\#1SysinternalsSuite\listdlls '+pid_name) \ No newline at end of file @@ -0,0 +1,47 @@ +__author__ = 'darakna' +import os +import subprocess +import sys +import time +tested_proc=r"c:\windows\system32\calc.exe" +listdlls_location=r"D:\WORK\MagicWandTools\#1SysinternalsSuite\listdlls.exe" +injected_dll_name = "injct" +domain_char_list=list(range(1,127)) +if os.path.isfile(tested_proc) is False: + print(tested_proc, " not found, script will not work ") +else: + print(tested_proc, " found") +if os.path.exists(listdlls_location) is False: + print(listdlls_location, " not found, script will not work ") +else: + print(listdlls_location, "found") + +def stripall(word): + if word=="": + return "" + else: + if ord(word[0]) in domain_char_list: + return word[0]+stripall(word[1:]) + else: + return stripall(word[1:]) +def verify_(nume): + var1=os.popen(listdlls_location+' -v '+nume).read() + var="" + for chars in var1: + var=var+stripall(chars) + if "avcuf" in var: + print(var[ + var[:var.index(injected_dll_name)].rindex("\n") + : + var[:var.index(injected_dll_name)+var[var.index(injected_dll_name)+12:].index("dll")].rindex("\n") + ]) + else: + print("Injection not found") +def pornire_proces(nume): + return subprocess.Popen(nume) +proc=pornire_proces(tested_proc) +verify_(tested_proc[tested_proc.rindex("\\")+1:]) +if proc.poll()!=0: + proc.kill() +time.sleep(3) + @@ -0,0 +1,113 @@ +__author__ = 'darakna' +#!/usr/bin/python + +# Objective of the script: +# - Create a sorted view for psscan output +# - Identify the processes that are currently located in pslist +# - Number the processes in the order they appear in psscan +# - Sort by PIDs in the psscan output + +# Modify the below files for the output that you receive from volatility +psscanFile='txt.psscan' # Generated with the psscan volatility 2.4 plugin +pslistFile='txt.pslist-P' # Generated with the pslist -P volatility 2.4 plugin # -P gives you the physical offset instead of the virtual + +# Offset(P) # Name # PID # PPID #PDB # Time #Created #Time Exited +# list[0] list[1] list[2] list[3] list[4] list[5] list[6] list[7] +# Function to find the name of the parent process +def findName(ppid, dictP): + namePID = '' + for i in range(0,len(dictP['name'])): + if dictP['pid'][i] == ppid: + namePID = dictP['name'][i] + return namePID + +# Function to find if the offset in the psscan output is found in the pslist output +def findPSList(oVal): + exists = 'False' + f = open(pslistFile, 'r') + for line in f: + if (('Offset' not in line) and ('-------' not in line)): + list = line.split() + psOffset = list[0] + if (oVal[-8:] == psOffset[-8:]): + exists='True' + return exists + +# The keys that make up the dictionary for the input of the psscan output +keys = ['offset', 'name', 'pid', 'ppid', 'pdb', 'createDate', 'createTime', 'createTimeZone', 'exitDate', 'exitTime', 'exitTimeZone'] +dictPsscan = {} + +# Open the File where the psscan output is located +file = open(psscanFile, 'r') +for line in file: + # Ignore the header lines that are in the output + if (('Offset' not in line) and ('-------' not in line)): + list = line.split() + # The line being read may not have all 12 values so append to the list until it does (Time Exited sometimes does not exist) + while len(list) != 12: + list.append('') + # Add the values of the list into my dictionary + for x in range(0,11): + dictPsscan.setdefault(keys[x], []).append(list[x]) + +# Identify the length of the dictionary +dictLen = len(dictPsscan['offset']) +# Take from the dictionary dictPsscan and the values of the PID values. Create a list, sort and remove duplicates +listPID = [] +for i in range(0, dictLen): + listPID.append(dictPsscan['pid'][i]) + # Remove duplicate PID values and then sort them as an integer + listPID = sorted(set(listPID), key=int) + +titleTable = "Offset(P) pslist # name pid pName ppid pdb createdDate cTime cTZ exitDate eTime eTZ" +table = titleTable.split() +# Format the output to make it easier to read +print('{0:20s} {1:6s} {2:3s} {3:16s} {4:5} {5:16} {6:5} {7:12} {8:11} {9:9} {10:9} {11:11} {12:9} {13:9}'.format(table[0], table[1], table[2], table[3], table[4], table[5], table[6], table[7], table[8], table[9], table[10], table[11], table[12], table[13])) +print("-"*20 + " " + "-"*6 + " " + "-"*3 + " " + "-"*16 + " " + "-"*5 + " " + "-"*16 + " " + "-"*5 + " " + "-"*12 + " " + "-"*11 + " " + "-"*9 + " " + "-"*9 + " " + "-"*11 + " " + "-"*9 + " " + "-"*9) + +# Loop through the PID values +for i in range(0, len(listPID)): + # The counter is to count the number of instances of the PID coming out of psscan + counter = 1 + for j in range(0, dictLen): + if listPID[i] == dictPsscan['pid'][j]: + outputInfo = dictPsscan['offset'][j] + " " + outputInfo += findPSList(dictPsscan['offset'][j]) + " " + outputInfo += str(counter) + " " + outputInfo += dictPsscan['name'][j] + " " + outputInfo += dictPsscan['pid'][j] + " " + ppidName = findName(dictPsscan['ppid'][j], dictPsscan) + if ppidName == '': + ppidName = '(Unavailable)' + outputInfo += ppidName + " " + outputInfo += dictPsscan['ppid'][j] + " " + outputInfo += dictPsscan['pdb'][j] + " " + if (dictPsscan['createDate'][j]): + outputInfo += dictPsscan['createDate'][j] + " " + else: + outputInfo += " * " + if (dictPsscan['createTime'][j]): + outputInfo += dictPsscan['createTime'][j] + " " + else: + outputInfo += " * " + if (dictPsscan['createTimeZone'][j]): + outputInfo += dictPsscan['createTimeZone'][j] + " " + else: + outputInfo += " * " + if (dictPsscan['exitDate'][j]): + outputInfo += dictPsscan['exitDate'][j] + " " + else: + outputInfo += " * " + if (dictPsscan['exitTime'][j]): + outputInfo += dictPsscan['exitTime'][j] + " " + else: + outputInfo += " * " + if (dictPsscan['exitTimeZone'][j]): + outputInfo += dictPsscan['exitTimeZone'][j] + else: + outputInfo += " * " + table = outputInfo.split() + # Format the output to make it easier to read + print('{0:20s} {1:6s} {2:3s} {3:16s} {4:5} {5:16} {6:5} {7:12} {8:11} {9:9} {10:9} {11:11} {12:9} {13:9}'.format(table[0], table[1], table[2], table[3], table[4], table[5], table[6], table[7], table[8], table[9], table[10], table[11], table[12], table[13])) + # Find the relevant PID files for that PPID + counter += 1 @@ -0,0 +1,96 @@ +__author__ = 'darakna' +# Volatility +# Copyright (C) 2007-2013 Volatility Foundation +# +# This file is part of Volatility. +# +# Volatility is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# Volatility is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Volatility. If not, see <http://www.gnu.org/licenses/>. +# + +""" +@author: Andrew Case +@license: GNU General Public License 2.0 +@contact: atcuno@gmail.com +@organization: +""" +import volatility.obj as obj +import volatility.plugins.mac.common as common +import volatility.debug as debug + +class mac_pslist(common.AbstractMacCommand): + """ List Running Processes """ + + def __init__(self, config, *args, **kwargs): + common.AbstractMacCommand.__init__(self, config, *args, **kwargs) + self._config.add_option('PID', short_option = 'p', default = None, help = 'Operate on these Process IDs (comma-separated)', action = 'store', type = 'str') + + def calculate(self): + common.set_plugin_members(self) + + pidlist = None + + try: + if self._config.PID: + pidlist = [int(p) for p in self._config.PID.split(',')] + except: + pass + + p = self.addr_space.profile.get_symbol("_allproc") + + procsaddr = obj.Object("proclist", offset = p, vm = self.addr_space) + proc = obj.Object("proc", offset = procsaddr.lh_first, vm = self.addr_space) + seen = [] + + while proc.is_valid(): + + if proc.obj_offset in seen: + debug.warning("Recursive process list detected (a result of non-atomic acquisition). Use mac_tasks or mac_psxview)") + break + else: + seen.append(proc.obj_offset) + + if not pidlist or proc.p_pid in pidlist: + yield proc + + proc = proc.p_list.le_next.dereference() + + def render_text(self, outfd, data): + self.table_header(outfd, [("Offset", "[addrpad]"), + ("Name", "20"), + ("Pid", "8"), + ("Uid", "8"), + ("Gid", "8"), + ("PGID", "8"), + ("Bits", "12"), + ("DTB", "#018x"), + ("Start Time", "")]) + + for proc in data: + if not proc.is_valid() or len(proc.p_comm) == 0: + continue + + # Strip the "TASK_MAP_" prefix from the enumeration + bit_string = str(proc.task.map.pmap.pm_task_map or '')[9:] + + self.table_row(outfd, proc.v(), + proc.p_comm, + str(proc.p_pid), + str(proc.p_uid), + str(proc.p_gid), + str(proc.p_pgrpid), + bit_string, + proc.task.dereference_as("task").map.pmap.pm_cr3, + proc.start_time()) + + @@ -0,0 +1,49 @@ +__author__ = 'darakna' +import os +import time +from platform import machine +simulator_location = "sim_path" +def dir_exist(location): + if os.path.exists(location) is False: + print(location, " could not be found") + return False + else: + print(location, " found") + return True + +def simulator_daemon(arg, ver ): + if ver == "32": + result=os.popen(simulator_location+"\\simulator"+ver+".exe "+arg).write() + return result + else: + result1=os.popen(simulator_location+'\\simulator32.exe '+arg).read() + if "simulator has not been killed!" not in result1: + result1="simulator has been killed! \n" + else: + result1="simulator has not been killed! \n" + result2=os.popen(simulator_location+"\\simulator"+ver+".exe "+arg).read() + if "simulator has not been killed!" not in result2: + result2="simulator has been killed! \n" + else: + result2="simulator has not been killed! \n" + print("Running \"simulator32.exe "+arg+"\"\n"+result1) + print("Running \"simulator64.exe "+arg+"\"\n"+result2) + +def os_architecture(): + if machine().endswith("64"): + print("OS architecture is 64") + return "64" + else: + print("OS architecture is 32") + return "32" +os_arch = os_architecture() +dir_exist(simulator_location) +dir_exist(simulator_location+"\\simulator"+os_arch+".exe") +if os_arch == "64": + dir_exist(simulator_location+"\\simulator"+"32.exe") +simulator_daemon("/exploit1",os_arch) +simulator_daemon("/exploit2",os_arch) +simulator_daemon("/exploit3",os_arch) +simulator_daemon("/exploit4",os_arch) +simulator_daemon("/exploit5",os_arch) +time.sleep(7) \ No newline at end of file @@ -0,0 +1,33 @@ +from os import walk +import os + +path_file = "WordList Collection" +os.chdir(path_file) +f = [] +for (dirpath, dirnames, filenames) in walk(path_file): + f.extend(filenames) + break +size = 0 +g =[] +for a in f: + size = os.path.getsize(a) + g.extend([(a, size)]) +g_ordonat = [] +while (len(g) > 0): + minsize = g[0][1] + gasit = 0 + #print(minsize) + for a in range(len(g)): + if minsize > g[a][1]: + minsize = g[a][1] + gasit = a + g_ordonat.extend([g[gasit]]) + g.pop(gasit) +for elem in range(len(g_ordonat)): + if elem > 8: + os.rename(g_ordonat[elem][0], "{0:03d}".format(elem) + "_" + g_ordonat[elem][0]) + #print(g_ordonat[elem][0], "{0:03d}".format(elem) + "_" + g_ordonat[elem][0]) + #print(g_ordonat[elem]) + #print(g_ordonat[elem]) + + @@ -0,0 +1,41 @@ +__author__ = 'darakna' +import os +import re +from os import walk + +extensions_list = [".mpeg", ".mpe",".mpg",".mpeg",".mpeg-1",".mpeg-2",".m1s",".mpa",".mp2" + ,".m2a",".mp2v",".m2v",".m2s",".avi",".mov",".qt",".asf",".asx",".wmv",".wma",\ + ".wmx",".rm",".ra",".ram",".rmvb",".mp4",".3gp",".ogm",".mkv"] + + +listmov="Movie_list.txt" +outfile = open(listmov,"w") +search_path = "L:\\" +def list_files(outlist): #returns a list of files (full path) of a given directory + f = [] + for (dirpath, dirnames, filenames) in walk(outlist): + for file in filenames: + extension = re.findall("[.][0-9a-zA-Z-]*$",file) + #print(extension) + #print(re.findall("[.][0-9a-zA-Z-]*$",file)[0]) + #print(extensions_list) + try: + extension_0 = extension[0] + if extension_0 in extensions_list: + print(file) + f.append(dirpath+"\\"+file) + except: + pass + return f + +def write_list(inlist,outfile): #writes the list returned by list_files function in given parameter + outfile = open(outfile,"w") + for e in inlist: + if re.findall("[.]([0-9a-zA-Z]*$)",e)[0] in extensions_list: + outfile.write((e)+"\n") + outfile.close() + +#write_list(list_files(search_path),listmov) +for lines in list_files(search_path): + outfile.write(lines) + outfile.write("\n") \ No newline at end of file @@ -0,0 +1,79 @@ +__author__ = 'darakna' +# table of probabilities for each letter +def letProb( c ): + """ if c is the space character or an alphabetic character, + we return its monogram probability (for english), + otherwise we return 1.0 We ignore capitalization. + Adapted from + http://www.cs.chalmers.se/Cs/Grundutb/Kurser/krypto/en_stat.html + """ + if c == ' ': return 0.1904 + if c == 'e' or c == 'E': return 0.1017 + if c == 't' or c == 'T': return 0.0737 + if c == 'a' or c == 'A': return 0.0661 + if c == 'o' or c == 'O': return 0.0610 + if c == 'i' or c == 'I': return 0.0562 + if c == 'n' or c == 'N': return 0.0557 + if c == 'h' or c == 'H': return 0.0542 + if c == 's' or c == 'S': return 0.0508 + if c == 'r' or c == 'R': return 0.0458 + if c == 'd' or c == 'D': return 0.0369 + if c == 'l' or c == 'L': return 0.0325 + if c == 'u' or c == 'U': return 0.0228 + if c == 'm' or c == 'M': return 0.0205 + if c == 'c' or c == 'C': return 0.0192 + if c == 'w' or c == 'W': return 0.0190 + if c == 'f' or c == 'F': return 0.0175 + if c == 'y' or c == 'Y': return 0.0165 + if c == 'g' or c == 'G': return 0.0161 + if c == 'p' or c == 'P': return 0.0131 + if c == 'b' or c == 'B': return 0.0115 + if c == 'v' or c == 'V': return 0.0088 + if c == 'k' or c == 'K': return 0.0066 + if c == 'x' or c == 'X': return 0.0014 + if c == 'j' or c == 'J': return 0.0008 + if c == 'q' or c == 'Q': return 0.0008 + if c == 'z' or c == 'Z': return 0.0005 + return 1.0 +def rating(L): + if len(L) == 0: + return 0 + else: + return letProb(L[0])+rating(L[1:]) +def decipher(S,n): + if len(S)==0: + return "" + else: + if ord(S[0]) in range(ord('A'),ord('Z')+1): + if ord(S[0])+n > ord('Z'): + return chr(ord(S[0])-26+n) + decipher(S[1:],n) + else: + return chr(ord(S[0])+n)+ decipher(S[1:],n) + elif ord(S[0]) in range(ord('a'),ord('z')+1): + if ord(S[0])+n > ord('z'): + return chr(ord(S[0])-26+n) + decipher(S[1:],n) + else: + return chr(ord(S[0])+n)+ decipher(S[1:],n) + else: + return S[0]+decipher(S[1:],n) +def the_winner_is(stg): + print("Problem:",stg) + L=[decipher(stg,n) for n in range (26)] + LoL = [rating(x) for x in L ] + for i in range(len(L)): + #print(L[i],LoL[i]) //for debug + pass + print("Solution:", L[LoL.index(max(LoL))]) + print ("\n") + +sta="Bzdrzq bhogdq? H oqdedq Bzdrzq rzkzc." +stb="Hu lkbjhapvu pz doha ylthpuz hmaly dl mvynla lclyfaopun dl ohcl slhyulk." +stc = "PDA MQEYG XNKSJ BKT FQILO KRAN PDA HWVU ZKC KB YWAOWN WJZ UKQN QJEMQA OKHQPEKJ EO XJNLBYYBHJWA" +std = "KP BZA IGUSFZBP FHE PHO WIX RAIE BZSY UP TRSAXE S IU SUQRAYYAE JARP LAGG EHXA PHOR YHGOBSHX CAP SY AUFXWTHRTXQU BZSY GSBBGA WZIGGAXFA LIY XHB BHH ZIRE LIY SB" +the_winner_is(sta) +the_winner_is(stb) +the_winner_is(stc) +the_winner_is(std) + + + @@ -0,0 +1,23 @@ +from mutagen.mp3 import MP3 +import os + +f = open("all_mp3s.txt", "rb") +bulk_file = f.read() +g = open("toata_muzica.txt", "wb") +for a in bulk_file.split("\n".encode()): + try: + if os.path.exists(a): + amp3 = MP3(a) + if amp3.info.length / 60 > 2: + time_min_sec = "{:02d}:{:02d}".format(int(amp3.info.length / 60), int(amp3.info.length % 60)) + size_kb = "{:6.3f} mb".format(os.path.getsize(a) / 1024 / 1024) + line = time_min_sec.encode() + " :: ".encode() + size_kb.encode() + " :: ".encode() + a + "\n".encode() + g.write(line) + except: + line = "err :: err :: ".encode() + a + "\n".encode() + g.write(line) + print("MP3 Header Error on file: ", a) + + +f.close() +g.close() @@ -0,0 +1,114 @@ +__author__ = 'vpaun' +import sys +# table of probabilities for each letter +def letProb( c ): + """ if c is the space character or an alphabetic character, + we return its monogram probability (for english), + otherwise we return 1.0 We ignore capitalization. + Adapted from + http://www.cs.chalmers.se/Cs/Grundutb/Kurser/krypto/en_stat.html + """ + if c == ' ': return 0.1904 + if c == 'e' or c == 'E': return 0.1017 + if c == 't' or c == 'T': return 0.0737 + if c == 'a' or c == 'A': return 0.0661 + if c == 'o' or c == 'O': return 0.0610 + if c == 'i' or c == 'I': return 0.0562 + if c == 'n' or c == 'N': return 0.0557 + if c == 'h' or c == 'H': return 0.0542 + if c == 's' or c == 'S': return 0.0508 + if c == 'r' or c == 'R': return 0.0458 + if c == 'd' or c == 'D': return 0.0369 + if c == 'l' or c == 'L': return 0.0325 + if c == 'u' or c == 'U': return 0.0228 + if c == 'm' or c == 'M': return 0.0205 + if c == 'c' or c == 'C': return 0.0192 + if c == 'w' or c == 'W': return 0.0190 + if c == 'f' or c == 'F': return 0.0175 + if c == 'y' or c == 'Y': return 0.0165 + if c == 'g' or c == 'G': return 0.0161 + if c == 'p' or c == 'P': return 0.0131 + if c == 'b' or c == 'B': return 0.0115 + if c == 'v' or c == 'V': return 0.0088 + if c == 'k' or c == 'K': return 0.0066 + if c == 'x' or c == 'X': return 0.0014 + if c == 'j' or c == 'J': return 0.0008 + if c == 'q' or c == 'Q': return 0.0008 + if c == 'z' or c == 'Z': return 0.0005 + return 1.0 +def rating(L): + if len(L) == 0: + return 0 + else: + return letProb(L[0])+rating(L[1:]) +def decipher(S,n): + if len(S)==0: + return "" + else: + if ord(S[0]) in range(ord('A'),ord('Z')+1): + if ord(S[0])+n > ord('Z'): + return chr(ord(S[0])-26+n) + decipher(S[1:],n) + else: + return chr(ord(S[0])+n)+ decipher(S[1:],n) + elif ord(S[0]) in range(ord('a'),ord('z')+1): + if ord(S[0])+n > ord('z'): + return chr(ord(S[0])-26+n) + decipher(S[1:],n) + else: + return chr(ord(S[0])+n)+ decipher(S[1:],n) + else: + return S[0]+decipher(S[1:],n) +def the_winner_is(stg): + print("Problem:",stg) + L=[decipher(stg,n) for n in range (26)] + LoL = [rating(x) for x in L ] + for i in range(len(L)): + #print(L[i],LoL[i]) //for debug + pass + print("Solution:", L[LoL.index(max(LoL))]) + print ("\n") + +def extended_caesar(list): + fstream=open("out.txt","wb") + for i in range(0,128): + print (i+32,(chr(i+32))) + cstring = u"" + for letter in list: + if letter+i>160: + cstring=cstring+chr(i+letter-128) + #pass + elif letter + i < 32: + cstring = cstring + chr(160-letter - i) + else: + cstring=cstring+chr(letter+i) + #pass + print (cstring) + fstream.write(("\n"+str(i)+" "+str(rating(cstring))+"\n").encode('utf8')) + fstream.write(cstring.encode('UTF-8')) + fstream.close() + +sta="Bzdrzq bhogdq? H oqdedq Bzdrzq rzkzc." +stb="Hu lkbjhapvu pz doha ylthpuz hmaly dl mvynla lclyfaopun dl ohcl slhyulk." +stc = "PDA MQEYG XNKSJ BKT FQILO KRAN PDA HWVU ZKC KB YWAOWN WJZ UKQN QJEMQA OKHQPEKJ EO XJNLBYYBHJWA" +std = "60 08 08 7D 20 03 08 7B 45 20 12 08 0E 20 0C 08 05 0F 7E 7D 20 08 07 7E 20 06 08 0B 7E 20 7C 01 7A 05 05 7E 07 00 7E 20 02 07 20 12 08 0E 0B 20 03 08 0E 0B 07 7E 12 47 20 6D 01 02 0C 20 08 07 7E 20 10 7A 0C 20 7F 7A 02 0B 05 12 20 7E 7A 0C 12 20 0D 08 20 7C 0B 7A 7C 04 47 20 70 7A 0C 07 40 0D 20 02 0D 58 20 4A 4B 51 20 04 7E 12 0C 20 02 0C 20 7A 20 0A 0E 02 0D 7E 20 0C 06 7A 05 05 20 04 7E 12 0C 09 7A 7C 7E 45 20 0C 08 20 02 0D 20 0C 01 08 0E 05 7D 07 40 0D 20 01 7A 0F 7E 20 0D 7A 04 7E 07 20 12 08 0E 20 0D 08 08 20 05 08 07 00 20 0D 08 20 7D 7E 7C 0B 12 09 0D 20 0D 01 02 0C 20 06 7E 0C 0C 7A 00 7E 47 20 70 7E 05 05 20 7D 08 07 7E 45 20 12 08 0E 0B 20 0C 08 05 0E 0D 02 08 07 20 02 0C 20 7F 7C 01 7E 0B 7D 7F 7C 7F 7F 7D 08 47" +std_nospace = '6008087D2003087B452012080E200C08050F7E7D2008077E2006080B7E207C017A05057E07007E2002072012080E0B2003080E0B077E1247206D01020C2008077E20107A0C207F7A020B0512207E7A0C12200D08207C0B7A7C044720707A0C07400D20020D58204A4B5120047E120C20020C207A200A0E020D7E200C067A050520047E120C097A7C7E45200C0820020D200C01080E057D07400D20017A0F7E200D7A047E072012080E200D08082005080700200D08207D7E7C0B12090D200D01020C20067E0C0C7A007E4720707E0505207D08077E452012080E0B200C08050E0D02080720020C207F7C017E0B7D7F7C7F7F7D0847' + +#std_str = map(ord, std_nospace.decode('hex')) +std_str=std.split(" ") +print(std_str) +std_int = [] +for a in std_str: + std_int.extend([int(a,16)]) +print (std_int) +max = std_int[0] +for i in std_int: + if max < i: + max = i +print (max) +extended_caesar(std_int) + +#the_winner_is(sta) +#the_winner_is(stb) +#the_winner_is(stc) + + + @@ -0,0 +1,43 @@ +import os +import string + +def get_valid_drives(): + print("Getting valid drives...") + valid_drives = [] + for elem in string.ascii_lowercase: + path = elem + ":\\" + #if os.path.isdir(path): + # print(path) + if os.path.exists(path): + valid_drives.append(path) + #print(path) + print("Got %s..." % (valid_drives)) + return valid_drives + +import os + +def get_filepaths(directory, extension=""): + print("Getting files with extension: [%s] for path %s..." % (extension, directory)) + file_paths = [] # List which will store all of the full filepaths. + # Walk the tree. + for root, directories, files in os.walk(directory): + for filename in files: + # Join the two strings in order to form the full filepath. + filepath = os.path.join(root, filename) + if filepath.lower().endswith(extension): + file_paths.append(filepath) # Add it to the list. + print("Got %s files for path %s..." % (len(file_paths), directory)) + return file_paths # Self-explanatory. + +# Run the above function and store its results in a variable. +valid_drives = get_valid_drives() +extensions_list2 = ".mp3" +valid_mp3s = [] +#valid_drives = ["d:\\games\\Counter-Strike1.6 v.42"] +for drive in valid_drives: + valid_mp3s.extend(get_filepaths(drive, extensions_list2)) +f = open("all_mp3s.txt","wb") +for file in valid_mp3s: + f.write(file.encode()) + f.write("\n".encode()) +f.close() @@ -0,0 +1,64 @@ +__author__ = 'darakna' +import itertools +def lenght_str(st): + print("String: \n",st) + print("Lenght: ",len(st)) + print("Number of letters: ", len(st.replace(" ",""))) + letters = "" + working_str=st.replace(" ","") + for letter in range(ord("A"),ord("Z")+1): + if (chr(letter) in working_str): + letters += chr(letter) + working_str.replace(chr(letter),"") + print("Unique letters in string: ", len(letters), letters) + pseudokey = "ETAOINHSRDLUMCWFYGPBVKXJQZ" + calckey = "ABHSGIXYPREUZFLOTWQCJKdfmn" + alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + #for a in range (26): + + + +def pema(text,key): + fileh = open("strings.txt","w") + ll = [] + for letter in key: + print(letter," : ",text.count(letter)) + ll.append((letter,text.count(letter))) + print(ll) + st = "" + for a in sorted(ll, key=lambda letter: letter[1], reverse=True): + st+=a[0] + print (st) + #for a in itertools.permutations(text,len(text)): + #fileh.write("".join(a)+"\n") + #print("".join(a),"\n") + fileh.close() + +def swap_letters(str,word,key): + result = "" + for letter in str: + if letter in word: + result += (key[word.index(letter)]) + else: + result += letter + print (result) + + +std = "KP BZA IGUSFZBP FHE PHO WIX RAIE BZSY UP TRSAXE S IU SUQRAYYAE JARP LAGG EHXA PHOR YHGOBSHX CAP SY AUFXWTHRTXQU BZSY GSBBGA WZIGGAXFA LIY XHB BHH ZIRE LIY SB" +word = "WZIGGAXFABSYLHERTUQPOJCK" +key = "challengetiswodrfmpyuvkb" + + +stc = "ABCEFGHIJKLOPQRSTUWXYZ" +#lenght_str(std) +#lenght_str(stc) +#pema(std,stc) +#lenght_str("WZIGGAXFABSYLHERTUQPOJCK") + + +std = "ER WTB UASIXTWR XDO RDV HUF PBUO WTIG SR MPIBFO I US ISZPBGGBO JBPR KBAA ODFB RDVP GDAVWIDF YBR IG BSXFHMDPMFZS WTIG AIWWAB HTUAABFXB KUG FDW WDD TUPO KUG IW" +word = "HTUAABFXBWKIGDPOSZRVYMJE" +key = "challengetwisordmpyukfvb" +swap_letters(std,word,key) +lenght_str(word) +lenght_str(key.upper()) \ No newline at end of file @@ -0,0 +1,76 @@ +__author__ = 'darakna' +# table of probabilities for each letter +def letProb( c ): + """ if c is the space character or an alphabetic character, + we return its monogram probability (for english), + otherwise we return 1.0 We ignore capitalization. + Adapted from + http://www.cs.chalmers.se/Cs/Grundutb/Kurser/krypto/en_stat.html + ETAOINHSRDLUMCWFYGPBVKXJQZ + """ + if c == ' ': return 0.1904 + if c == 'e' or c == 'E': return 0.1017 + if c == 't' or c == 'T': return 0.0737 + if c == 'a' or c == 'A': return 0.0661 + if c == 'o' or c == 'O': return 0.0610 + if c == 'i' or c == 'I': return 0.0562 + if c == 'n' or c == 'N': return 0.0557 + if c == 'h' or c == 'H': return 0.0542 + if c == 's' or c == 'S': return 0.0508 + if c == 'r' or c == 'R': return 0.0458 + if c == 'd' or c == 'D': return 0.0369 + if c == 'l' or c == 'L': return 0.0325 + if c == 'u' or c == 'U': return 0.0228 + if c == 'm' or c == 'M': return 0.0205 + if c == 'c' or c == 'C': return 0.0192 + if c == 'w' or c == 'W': return 0.0190 + if c == 'f' or c == 'F': return 0.0175 + if c == 'y' or c == 'Y': return 0.0165 + if c == 'g' or c == 'G': return 0.0161 + if c == 'p' or c == 'P': return 0.0131 + if c == 'b' or c == 'B': return 0.0115 + if c == 'v' or c == 'V': return 0.0088 + if c == 'k' or c == 'K': return 0.0066 + if c == 'x' or c == 'X': return 0.0014 + if c == 'j' or c == 'J': return 0.0008 + if c == 'q' or c == 'Q': return 0.0008 + if c == 'z' or c == 'Z': return 0.0005 + return 1.0 +def rating(L): + if len(L) == 0: + return 0 + else: + return letProb(L[0])+rating(L[1:]) +def decipher(S,n): + if len(S)==0: + return "" + else: + if ord(S[0]) in range(ord('A'),ord('Z')+1): + if ord(S[0])+n > ord('Z'): + return chr(ord(S[0])-26+n) + decipher(S[1:],n) + else: + return chr(ord(S[0])+n)+ decipher(S[1:],n) + elif ord(S[0]) in range(ord('a'),ord('z')+1): + if ord(S[0])+n > ord('z'): + return chr(ord(S[0])-26+n) + decipher(S[1:],n) + else: + return chr(ord(S[0])+n)+ decipher(S[1:],n) + else: + return S[0]+decipher(S[1:],n) +def the_winner_is(stg): + print("Problem:",stg) + L=[decipher(stg,n) for n in range (26)] + LoL = [rating(x) for x in L ] + for i in range(len(L)): + print(L[i],LoL[i]) #for debug + pass + print("Solution:", L[LoL.index(max(LoL))]) + print ("\n") + + +std = "KP BZA IGUSFZBP FHE PHO WIX RAIE BZSY UP TRSAXE S IU SUQRAYYAE JARP LAGG EHXA PHOR YHGOBSHX CAP SY AUFXWTHRTXQU BZSY GSBBGA WZIGGAXFA LIY XHB BHH ZIRE LIY SB" + +the_winner_is(std) + + + @@ -0,0 +1,86 @@ +import binascii +import base64 + +req_n = "5203054907932715072219463010433671501242324999101031961778551414523203642794654633954122128718395475257091609045094294305282429283375416003959025668410070733743" +resp_n = "131618988864947543213776229531634193412737234854212651796818129365118569829291789642298561838219946234914193882865537745361589944691738337361923969834323672753213" + + +#req_n = "321682001638621484560335075095507393230746499319112395413345734508561395841716256209503480440122408356196694552170136827691509607517848131461840553581088359803526847604866029189" +#resp_n = "129933656511779963167442542838852527261285746367852251381491658328954729449657923715297657634799729363497601683837417149328627845965213565543021934386297536927567961363693245472667" + +#req_n = "132752679009221621974424157119055405668892042595778428973751767008896088687960962058901693159841975248499249835571219034924880485719595053013906268929618431426022723233136913645060276155426395971" +#resp_n = "121912844982339629176832774451185569235725668957286601326991833849575967441611698281396529582394583714754529674837173412218177687691781396442281828465865117438279845726846959841393955282492411534487" + +req_n = "4524534914863856075318572321251413488936046039067401564596991828706906852704171724928727799968714377343721934522283998377651546992172322004415314402246051761653738903416118187189" +resp_n = "254239257533814359267852692761437331391922428319477921595965149711974391684634973376665789732855676833477979795253392954532649849776372456667217889116832653486841943556221436464217" + +#req_n = "1893337371170074321646616782232907752619374562068712860454591829671881387602079105829821458728608198515060273004738560920851587297336513881468192796945266862542950950920462165307" +#resp_n = "158411637293917703298313128588223857349676152117948267465736224998959757611165578765169507656269526538265291767399699459739917837736937622125341974762215384448371978798789241515497" + +numb_req = int(req_n) +numb_resp = int(resp_n) + +def is_3(big_n): + if len(big_n) == 0: + return 0 + elif len(big_n) == 1: + return int(big_n) + else: + return int(big_n[0]) + is_3(big_n[1:]) + +def findAllFactors(number): + factors = list() + for i in range(1, number): + if number % i == 0: + factors.append(i) + return factors + + +def isPrime(n): + n = abs(int(n)) + if n < 2: + return 0 + if n == 2: + return 1 + if not n & 1: + return 0 + for x in range(3, int(n ** 0.5) + 1, 2): + if n % x == 0: + return 0 + return 1 + +def long_search(arg_num): + factors = findAllFactors(arg_num) + primeFactors = list() + for f in factors: + if isPrime(f) == 1: + primeFactors.append(f) + primeFactors.sort() + print("%d" % (primeFactors[-1])) + +def short_search(arg_num): + #F = factor(arg_num) + arg_num.sagemath.factor() + +if __name__ == "__main__": + print(len(req_n), len(resp_n)) + for lenght in range(1, len(resp_n)): + if int(numb_req % int(resp_n[0:lenght])) == 0: + print("%s %s = %s" % (req_n, resp_n[0:lenght], numb_req % int(resp_n[0:lenght]))) + print("%s" % int(numb_req / int(resp_n[0:lenght]) * int(resp_n[0:lenght]))) + + #print(binascii.hexlify((req_n.encode()))) + #print(binascii.hexlify((resp_n.encode()))) + #print(binascii.hexlify((str(numb_resp - numb_req).encode()))) + #print(base64.b64encode(req_n.encode())) + #print(base64.b64encode(resp_n.encode())) + #print(base64.b64encode(str(numb_resp - numb_req).encode())) + #print(bin(numb_req)) + #print(bin(numb_resp)) + #print(bin(numb_resp - numb_req)) + #print(numb_resp) + #print(numb_req) + #print(numb_resp - numb_req) + #print(numb_req / numb_resp) + #print(numb_resp % numb_req) + @@ -0,0 +1,12 @@ +def computepay(h,r): + if h<=40: + sum=(h*r) + else: + sum=(40*r+((h-40)*1.5*r)) + return sum +hrs=input("Enter Hours:") +hrs=float(hrs) +rate=input("Enter pay:") +rate=float(rate) +p=computepay(hrs,rate) +print ("Pay",p) \ No newline at end of file @@ -0,0 +1,59 @@ +import os +import bisect + +def get_filepaths(directory): + """ + This function will generate the file names in a directory + tree by walking the tree either top-down or bottom-up. For each + directory in the tree rooted at directory top (including top itself), + it yields a 3-tuple (dirpath, dirnames, filenames). + """ + file_paths = [] # List which will store all of the full filepaths. + + # Walk the tree. + for root, directories, files in os.walk(directory): + for filename in files: + # Join the two strings in order to form the full filepath. + filepath = os.path.join(root, filename) + file_paths.append(filepath) # Add it to the list. + + return file_paths # Self-explanatory. + +# Run the above function and store its results in a variable. + +search_path = "e:\\" +full_file_paths = get_filepaths(search_path) +wordlist = [] +short_wordlist = [] +for elem in full_file_paths: + if elem.endswith(".txt"): + if os.path.isfile(elem): + if os.path.getsize(elem) < 100000: + print(elem) + f = open(elem, errors='ignore') + words_unclean = f.read() + words = "" + for w in words_unclean: + if w.isalpha() and w.isascii() or w in [" ", "\r", "\n"]: + words += w + for w in words.split(): + w = w[0].upper() + w[1:].lower() + if 2 < len(w) < 12: + if w in wordlist and w not in short_wordlist: + bisect.insort(short_wordlist, w) + if w not in wordlist: + bisect.insort(wordlist, w) +print(wordlist) + +with open("e:\\wordlist.txt", 'w') as f: + for item in wordlist: + f.write("%s\n" % item) +with open("e:\\wordlist_short.txt", 'w') as f: + for item in short_wordlist: + f.write("%s\n" % item) + + + +#print(len(full_file_paths)) + +