text
stringlengths
37
1.41M
#!/usr/bin/python3 import math contents = [] print("please input a set of instruction:") while True: try: a = input("") except EOFError: break contents.append(a) x = 0 y = 0 distant = 0 for value in contents: new_value = value.split(" ") if new_value[0] == "UP": y += int(new_value[1]) elif new_value[0] == "DOWN": y -= int(new_value[1]) elif new_value[0] == "RIGHT": x += int(new_value[1]) elif new_value[0] == "LEFT": x -= int(new_value[1]) distant = math.hypot(x, y) print("the distant is:", distant)
#!/usr/bin/python3 """input plaintext and shift""" plainText = input("Insert your ciphertext: ") shift = int(input("Enter your shift: ")) """decrypt function""" def decrypt(plainText, shift): cipherText = "" for ch in range(0, len(plainText)): if (ch + shift) < len(plainText): cipherText += plainText[ch] while ch < (len(plainText) - shift): ch += shift cipherText += plainText[ch] print ("Your ciphertext is: ", cipherText) return cipherText decrypt(plainText, shift)
phrase = "Phrase en camel case" phrase_split = phrase.split() resultat = [phrase_split.pop(0).lower()] for mot in phrase_split: resultat.append(mot.capitalize()) resultat_formate = "".join(resultat) print(resultat_formate)
# https://adventofcode.com/ # # Implementation of the challage intcode computer as a class as it was needed for challenge 7 # import unittest def get_program( filename ): with open( filename ) as fp: line = fp.readline() prog = [] for d in line.strip().split(","): prog.append(int(d)) return prog class computer: def __init__(self, prog, input = None ): self.prog = prog.copy() self.prog_size = len(self.prog) self.additional_memory = {} self.pc = 0 self.relative_base_offset = 0 self.stopped = False self.paused = False self.debugging = False self.inputs = [] self.input_handler = None if input != None: self.inputs.append(input) def set_input_handler(self,handler): self.input_handler = handler def set_phase(self, phase): self.inputs.insert(0, phase) def add_input(self, data): self.inputs.append(data) def is_input_queue_empty(self): return len(self.inputs) == 0 def set_debugging(self, debug): self.debugging = debug def get_op_and_mode(self, d ): op = d % 100 # pad to 5 chars with "0" d = str(d).zfill(5) return op, int(d[2]), int(d[1]), int(d[0]) def get_program(self): return self.prog[0:self.prog_size] def get_relative_base_offset(self): return self.relative_base_offset def is_stopped(self): return self.stopped def is_paused(self): return self.paused def set_paused(self,state): self.paused = state def halt(self): self.stopped = True def get_param_value(self,addr): try: return self.prog[addr] except IndexError: try: return self.additional_memory[addr] except KeyError: self.additional_memory[addr] = 0 return 0 def set_param_value(self,addr,value): try: self.prog[addr] = value except IndexError: self.additional_memory[addr] = value def get_param(self,mode): if mode == 0: addr = self.prog[self.pc] self.pc+=1 return self.get_param_value(addr) if mode == 1: a = self.prog[self.pc] self.pc+=1 return a if mode == 2: a = self.prog[self.pc] if self.debugging: print("pc",self.pc,"base offset",self.relative_base_offset,"offset",a) self.pc+=1 return self.get_param_value(self.relative_base_offset + a) raise Exception("illegal addressing mode",mode) def set_param(self,mode,value): if mode == 0: addr = self.prog[self.pc] self.pc+=1 self.set_param_value(addr,value) return if mode == 1: self.prog[self.pc] = value self.pc+=1 return if mode == 2: rel_addr = self.prog[self.pc] self.pc+=1 self.set_param_value(self.relative_base_offset + rel_addr,value) return raise Exception("illegal addressing mode",mode) def run(self): if self.stopped: return while True: if self.paused: return if self.debugging: print("pc",self.pc) op,mode1,mode2,mode3 = self.get_op_and_mode( self.prog[self.pc] ) if self.debugging: print("decode opcode",self.prog[self.pc],":",op,mode1,mode2,mode3) self.pc+=1 if ( op == 1 or op == 2 ): # addition or multiplication a = self.get_param(mode1) b = self.get_param(mode2) c = 0 if ( op == 1 ): c = a + b if self.debugging: print("add",a,"with",b,"=",c) else: c = a * b if self.debugging: print("multiply",a,"with",b,"=",c) self.set_param(mode3,c) elif ( op == 3): # input if self.input_handler == None: if len(self.inputs) == 0: raise Exception("program asking for input and none available") else: a = self.inputs.pop(0) if self.debugging: print("using",a,"input",self.inputs) self.set_param(mode1,a) else: self.set_param(mode1,self.input_handler()) elif ( op == 4): # output a = self.get_param(mode1) if self.debugging: print("outputing",a) return a elif ( op == 5 or op == 6 ): # jump if param 1 is non-zero (5) or jump if zero (6), move to location specified by second param a = self.get_param(mode1) b = self.get_param(mode2) if ( op == 5 ): if ( a != 0 ): self.pc = b elif ( op == 6 ): if ( a == 0 ): self.pc = b elif ( op == 7 or op == 8 ): # less than store 1 in position param 3 if param 1 less than param 2, equal store 1 if param 1 = param 2 a = self.get_param(mode1) b = self.get_param(mode2) s = 0 if ( op == 7 ): if ( a < b ): s = 1 else: if ( a == b ): s = 1 self.set_param(mode3,s) elif ( op == 9): # adjust relative base offset a = self.get_param(mode1) self.relative_base_offset += a if self.debugging: print("adjust relative base offset by",a,"now",self.relative_base_offset ) elif ( op == 99): # exit self.stopped = True self.pc+=1 return else: raise Exception("illegal opcode " + str(op)) class AdventTestCase(unittest.TestCase): def get_op_and_mode(self): ic = computer([3,0,0,99],0) self.assertEqual( ic.get_op_and_mode(),(3,0,0,0)) ic = computer([103,0,0,99],0) self.assertEqual( ic.get_op_and_mode(),(3,1,0,0)) ic = computer([12303,0,0,99],0) self.assertEqual( ic.get_op_and_mode(),(3,1,2,3)) def test_add_basic(self): ic = computer([1,0,0,0,99]) ic.run() self.assertEqual( ic.get_program(),[2,0,0,0,99]) def test_multiple_basic(self): ic = computer([2,3,0,3,99]) ic.run() self.assertEqual( ic.get_program(),[2,3,0,6,99]) ic = computer([2,4,4,5,99,0]) ic.run() self.assertEqual( ic.get_program(),[2,4,4,5,99,9801]) def test_add_and_jump(self): ic = computer([1,1,1,4,99,5,6,0,99]) ic.run() self.assertEqual( ic.get_program(), [30,1,1,4,2,5,6,0,99] ) def test_output(self): ic = computer([4,00,99]) self.assertEqual( ic.run(),4 ) def test_input_output1(self): ic = computer([3,1,4,1,99],22) self.assertEqual( ic.run(), 22 ) def test_abs_param1(self): ic = computer([103,0,4,1,99],22) self.assertEqual( ic.run(), 22 ) def test_abs_param2(self): ic = computer([103,0,104,33,99],22) self.assertEqual( ic.run(), 33 ) def test_abs_param3(self): ic = computer([1101,100,-1,4,0]) self.assertEqual( ic.run(), None ) def test_illegal_opcode(self): ic = computer([1,0,0,1,55]) self.assertRaises( Exception, ic.run ) ic = computer([12,99]) self.assertRaises( Exception, ic.run ) def test_halt(self): ic = computer([1,0,0,0,99]) ic.run() self.assertTrue( ic.is_stopped() ) def test_input_output2(self): ic = computer([3,9,8,9,10,9,4,9,99,-1,8],8) self.assertEqual( ic.run(), 1 ) def test_relative_base(self): prog = [109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99] ic = computer(prog) output = [] while not ic.is_stopped(): d = ic.run() if d != None: output.append(d) self.assertListEqual(prog,output) # should output a 16 digit number prog = [1102,34915192,34915192,7,4,7,99,0] ic = computer(prog) d = str(ic.run()) self.assertEqual(len(d),16) ic = computer([104,1125899906842624,99]) self.assertEqual(ic.run(),1125899906842624) if __name__ == '__main__': pass
class CardGame: def __init__(self): self.deck = Deck() self.deck.shuffle_v2 class Deck: def __init__(self): self.cards = [] for suit in range(4): for rank in range(1,14): self.cards.append(Card(suit, rank)) def print_deck(self): for card in self.cards: print(card) def __str__(self): s = "" for i in range(len(self.cards)): s= s + " "*i + str(self.cards[i]) + "\n" return s def shuffle_v1(self): import random rng = random.Random() num_cards = len(self.cards) for i in range(num_cards): j = rng.randrange(i, num_cards) (self.cards[i], self.cards[j]) = (self.cards[j], self.cards[i]) def shuffle_v2(self): import random rng = random.Random() rng.shuffle(self.cards) def remove(self, card): if card in self.cards: self.cards.remove(card) return True else: return False def pop(self): return self.cards.pop() def is_empty(self): return self.cards == [] def deal(self, hands, num_cards = 999): num_hands = len(hands) for i in range(num_cards): if self.is_empty(): break # Break if out of cards card = self.pop() # Take the top card hand = hands[i % num_hands] # Whose turn is next? hand.add(card) # Add the card to the hand class Hand(Deck): def __init__(self, name=''): self.cards = [] self.name = name def add(self, card): self.cards.append(card) def __str__(self): s = "Hand " + self.name if self.is_empty(): s += " is empty\n" else: s += " contains\n" return s + Deck.__str__(self)
import turtle import random def tree(branchLen,t, thickness, colorN): if branchLen > 5: color = ["green", "red", "yellow", "blue"] if colorN >= len(color): colorN = len(color) -1 t.color(color[colorN]) angle = random.randrange(15, 45) subBranch = random.randrange(12, 16) t.pensize(thickness) t.forward(branchLen) t.right(angle) tree(branchLen-subBranch,t, thickness-2, colorN-1) t.left(2*angle) tree(branchLen-subBranch,t, thickness-2, colorN-1) t.right(angle) t.backward(branchLen) def main(): t = turtle.Turtle() myWin = turtle.Screen() t.left(90) t.up() t.backward(100) t.down() t.color("green") tree(75,t, 9, 5) myWin.exitonclick() main()
from linkedlist2 import Node class ImprovedQueue: def __init__(self): self.root = None self.last = None self.length = 0 def is_empty(self): return self.length == 0 def insert(self, data): node = Node(data) if self.root == None: self.root = self.last = node if node.data > self.root.data: node.next = self.root self.root = node if node.data < self.last.data: self.last.next = node self.last = node if node.data > self.last.data and node.data < self.root.data: temp = self.root p = self.root.next while p != None: if p.data > node.data: temp = temp.next p = p.next break node.next = temp.next temp.next = node self.length += 1
testArray = [31, -41, 59, 26, -53, 58, 97, -93, -23, 84] def maxSubarray(array): maxEndingHere = maxSoFar = array[0] maxBegin = maxEnd = 0 for i in range(1, len(array)): print('i is: {}\nvalue of i is: {}\nmaxEndingHere is: {}\nmaxEndingHere + i is: {}'.format(i, array[i], maxEndingHere, maxEndingHere + array[i])) maxEndingHere = max(array[i], maxEndingHere + array[i]) if maxEndingHere == array[i]: print('NEW START POINT SHOULD BE {}'.format(i)) maxBegin = i print('maxSoFar is: {}'.format(maxSoFar)) maxSoFar = max(maxSoFar, maxEndingHere) if maxSoFar == maxEndingHere: print('NEW END POINT SHOULD BE {}'.format(i)) maxEnd = i print('\n') return [maxSoFar, maxBegin, maxEnd, maxEndingHere] print(maxSubarray(testArray))
import numpy as np def normalize(X, mu, sigma): """Returns a normalized matrix. Subtracts average and divides by standard deviation. """ return (X - mu) / sigma
#!/usr/bin/env python # coding: utf-8 # In[8]: i=1 while(i<5): print(i) i+=1 # In[9]: i=1 while(i<=5): print(i) if i==3: break i+=1 # In[10]: i=1 while(i<=5): i+=1 if i==3: continue print(i) # In[11]: def funcexample(): print("This is a sample function") funcexample() # In[1]: def func(): print("This is a sample function") print("testing") func() # In[2]: #one argument func lastname="Ponnusamy" def func(firstname): print(firstname+" "+lastname) func("Sankar") # In[3]: lastname="Ponnusamy" def func(firstname): print(firstname+" "+lastname) func("Sankar") func("Baskar") func("Ravi") # In[6]: #Multiple argument func lastname="Ponnusamy" def func(firstname,city,phonenum): print(firstname+" "+lastname,city,phonenum) func("Sankar","Pondicherry",12345) func("Baskar","chennai",56789) func("Ravi","Bangalore",78547) # In[7]: #Func with formatted string lastname="Ponnusamy " def funcexample(firstname,city,phonenum): print(f"Hello ,{firstname.title()}"+" "+lastname,f"your city is {city.upper()}",f" and contact number is {phonenum}") funcexample("sankar","Pondicherry",12345) funcexample("baskar","chennai",56789) funcexample("ravi","Bangalore",78547) # In[ ]:
class Team(object): """Football team""" def __init__(self, name: str): self.name = name self.W = 0 self.D = 0 self.L = 0 @property def MP(self) -> int: return self.W + self.D + self.L @property def points(self) -> int: return 3 * self.W + self.D def tally(rows: list) -> list: """Tally the results of a small football competition.""" teams = dict() for result in rows: name1, name2, res = result.split(';') for name in (name1, name2): if name not in teams: teams[name] = Team(name) if res == 'win': teams[name1].W += 1 teams[name2].L += 1 if res == 'loss': teams[name1].L += 1 teams[name2].W += 1 if res == 'draw': teams[name1].D += 1 teams[name2].D += 1 return ([f'{"Team":30} | MP | W | D | L | P'] + [f'{team.name:30} | {team.MP:2d} | {team.W:2d} | ' f'{team.D:2d} | {team.L:2d} | {team.points:2d}' for team in sorted(teams.values(), key=lambda x: (-x.points, x.name))])
def recite(start: int, take: int = 1) -> list: """List the famous beer song""" song = list() for i in range(start, start-take, -1): if i == 0: song.append("No more bottles of beer on the wall, " "no more bottles of beer.") song.append("Go to the store and buy some more, " "99 bottles of beer on the wall.") break song.append(f"{i} bottle{'s' if i > 1 else ''} of beer on the wall, " f"{i} bottle{'s' if i > 1 else ''} of beer.") song.append((f"Take one down and pass it around, " f"{i - 1} bottle{'s' if i - 1 > 1 else ''} " f"of beer on the wall.") if i > 1 else (f"Take it down and pass it around, " f"no more bottles of beer on the wall.")) if i > start - take + 1: song.append("") return song
#!/usr/bin/env python3 from argparse import ArgumentParser from typing import Iterator from itertools import permutations def parse_input(data: Iterator[str]) -> Iterator[tuple[list[str], list[str]]]: """Data is split into input and output, each containing a list of corresponding segments""" for line in data: inp, out = line.split(' | ') yield ([i.strip() for i in inp.split(' ')], [o.strip() for o in out.split(' ')]) def count_easy_digits(data: Iterator[str]) -> int: """Count how many entries in data are easy digits to recognize. Considering only the unique segment counts for digit 1, 4, 7 and 8. (see README part 1)""" one = 'cf' four = 'bcdf' seven = 'acf' eight = 'abcdefg' lengths = (len(one), len(four), len(seven), len(eight)) count = 0 for _, output in parse_input(data): count += sum(len(o) in lengths for o in output) return count def solution_part_2(data: Iterator[str]) -> int: """Sums all digits for output in data. (see README part 2)""" return sum(decipher_output(inp, out) for inp, out in parse_input(data)) def decipher_output(inp: list[str], out: list[str]) -> int: """Tries to find a fitting translation wichs translates all segments in data-input to corresponding valid digits, returns the translation of the output""" for p in permutations('abcdefg'): trans = ''.maketrans(''.join(p), 'abcdefg') if all(parse_digits(i.translate(trans) for i in inp)): return int(''.join(parse_digits(o.translate(trans) for o in out))) print('No translation found!') exit(1) def parse_digits(data: Iterator[str]) -> Iterator[str]: """All digits have a unique combination of active segments. Returns the corresponding digit if found, else an empty string is returned.""" digits = { 'abcefg': '0', 'cf': '1', 'acdeg': '2', 'acdfg': '3', 'bcdf': '4', 'abdfg': '5', 'abdefg': '6', 'acf': '7', 'abcdefg': '8', 'abcdfg': '9', } for line in data: yield digits.get(''.join(sorted(line)), '') def main(): parser = ArgumentParser(description="Day 8 solution") parser.add_argument('path', nargs='?', type=str, default='./input', help="The path to the input file (default: ./input)") parser.add_argument('-2', '--part2', action='store_true', help=("Print the solution for part 2 " "(default: part 1 is printed)")) args = parser.parse_args() with open(args.path, 'r') as data: if args.part2: r = solution_part_2(data) else: r = count_easy_digits(data) print(r) if __name__ == '__main__': main()
from itertools import count class Primes(object): """Iterable primes using Sieve of Eratosthenes""" def __init__(self, end=None): if not isinstance(end, (int, None)): raise ValueError(f'Not a valid end ({end})') self.numbers = count(2) self.end = end def __iter__(self): return self def __next__(self): p = next(self.numbers) if self.end is not None and p > self.end: raise StopIteration self.numbers = filter(lambda n: n % p, self.numbers) return p def primes(limit: int) -> list: """Just to pass test""" return [*Primes(limit)]
#!/usr/bin/env python3 from argparse import ArgumentParser from typing import Iterator from functools import reduce from numpy import sign class Field: """A simple field (or grid) for drawing lines and accumelating overlapping coords. With a method `add` for adding a range of points.""" def __init__(self, max_x: int, max_y: int): self.grid = [[0 for _ in range(max_x + 1)] for _ in range(max_y + 1)] def add(self, r: Iterator[tuple[int, int]]): for x, y in r: self.grid[y][x] += 1 def overlapping(self): return sum(1 for row in self.grid for i in row if i >= 2) def parse_input(data: Iterator[str])\ -> Iterator[tuple[tuple[int, int], tuple[int, int]]]: """Each line in data has a start and end seperated by ->. Returns an iterator which yields these points as tuples.""" for line in data: start, end = line.split(' -> ') x1, y1 = start.split(',') x2, y2 = end.split(',') yield (int(x1), int(y1)), (int(x2), int(y2)) def grid_limit_reducer(acc, curr) -> tuple[int, int]: """Can be used to reduce an (start, end) iterator of points to calculate the max x and y coords of the field.""" xa, ya = acc start, end = curr x1, y1 = start x2, y2 = end return max(xa, x1, x2), max(ya, y1, y2) def count_overlapping_coords(data: Iterator[str], diagonal = False) -> int: """Count each point in the grid (or field) where lines are overlapping. (see README)""" coords = list(parse_input(data)) max_x, max_y = reduce(grid_limit_reducer, coords, (0, 0)) field = Field(max_x, max_y) for start, end in coords: x1, y1 = start x2, y2 = end x_sign = sign(x2 - x1) y_sign = sign(y2 - y1) if y1 == y2 and x1 != x2: field.add((x, y1) for x in range(x1, x2 + x_sign, x_sign)) elif x1 == x2 and y1 != y2: field.add((x1, y) for y in range(y1, y2 + y_sign, y_sign)) if diagonal and x1 != x2 and y1 != y2: field.add(zip(range(x1, x2 + x_sign, x_sign), range(y1, y2 + y_sign, y_sign))) return field.overlapping() def main(): parser = ArgumentParser(description="Day 5 solution") parser.add_argument('path', nargs='?', type=str, default='./input', help="The path to the input file (default: ./input)") parser.add_argument('-2', '--part2', action='store_true', help=("Print the solution for part 2 " "(default: part 1 is printed)")) args = parser.parse_args() with open(args.path, 'r') as data: if args.part2: result = count_overlapping_coords(data, True) else: result = count_overlapping_coords(data) print(result) if __name__ == '__main__': main()
from string import ascii_uppercase from string import digits from random import randint from itertools import product class Robot(object): """Creates a Robot with a random name, e.g. XE137""" def __init__(self): self.NAMES = [''.join(char + dig) for char, dig in product( product(ascii_uppercase, repeat=2), product(digits, repeat=3) )] self.name = self.pick_name() def pick_name(self) -> str: r = randint(0, len(self.NAMES)) n = self.NAMES[r] self.NAMES = self.NAMES[:r] + self.NAMES[r+1:] return n def reset(self): self.name = self.pick_name()
def deviders(number: int) -> int: """Generates all deviders for a given number""" for i in range(1, number // 2 + 1): if number % i == 0: yield i def classify(number: int) -> str: """Determine the class of a number""" if number <= 0: raise ValueError("Error: positive integer required") aliquot_sum = sum(deviders(number)) if aliquot_sum == number: return "perfect" elif aliquot_sum > number: return "abundant" elif aliquot_sum < number: return "deficient"
#!/usr/bin/python3 # A cenetic algorithm for finding the key # in a mono-alphabetic substitution cipher import string import sys import re from random import randint from random import shuffle from random import choice MAX_GENERATIONS = 1000 # Max number of generations MAX_BEST_KEYS = 20 POPULATION_SIZE = 20 # Max population size TOP_POPULATION = 4 # Top population size CROSSOVER_COUNT = 2 # Number of times to apply crossover MUTATION_COUNT = 1 # Number of times to apply mutation CHARS = string.ascii_uppercase DICTIONARY = './dictionaries/dictionary.txt' WORDS = "./dictionaries/words" MONOGRAMS = "./dictionaries/monograms" BIGRAMS = "./dictionaries/bigrams" TRIGRAMS = "./dictionaries/trigrams" QUADGRAMS = "./dictionaries/quadgrams" NGRAMS = {0: None, 1: None, 2: None, 3: None, 4: None} # TOOLS # --------------------------------------------------------- def get_ngram(N=1): """Returns corresponding ngram as an dictionary object, e.g.: bigram = { 'TH': 0.0270569804001 'HE': 0.0232854497343 'IN': 0.0202755339125 ... string: float } Arguments: N -- ngram integer, choices: 0 - words 1 - monogram (default) 2 - bigram 3 - trigram 4 - quadgram""" sources = [ WORDS, MONOGRAMS, BIGRAMS, TRIGRAMS, QUADGRAMS ] assert N < len(sources) if NGRAMS[N] is None: NGRAMS[N] = {} print("Reading from file {}...".format(sources[N])) with open(sources[N]) as fl: data = fl.read().splitlines() result = [d.split(' ') for d in data] for a, b in result: NGRAMS[N][a.strip()] = float(b) return NGRAMS[N] # Sort list of tuples by value in reverse order (high-low) def sort_by_value(tuples, reverse=True): return sorted(tuples, key=lambda k: k[1], reverse=reverse) # Print two dimensional list in nice columns def column_print(data, head=[], nr_of_rows=0, max_width=79): # print(out all the data) if not nr_of_rows: nr_of_rows = len(data) # print(out the head first) if head: data = [head] + data nr_of_rows += 1 # calculate the column width for each column column_width = [max(map(len, map(str, col))) + 2 for col in zip(*data)] # Factor in the max-width while sum(column_width) > max_width: i = column_width.index(max(column_width)) column_width[i] -= 1 def adjust(string, length): if len(string) < length: return string.ljust(length) else: # Padding is reduced too 1 return string[:length-3] + ".. " for row in data[:nr_of_rows]: print("".join([adjust(str(attr), column_width[i]) for i, attr in enumerate(row)])) # Make sure datastrinc is all uppercase # and contains no blank chars def clean_datastr(datastr): if datastr.find(' ') or datastr.find('\n') or datastr.find('\r'): datastr = "".join(datastr.split()) if not datastr.isupper(): datastr = datastr.upper() return datastr # Create block-groups of characters def block_group(datastr, blksize): datastr = clean_datastr(datastr) return [datastr[i:i+blksize] for i in range(0, len(datastr), blksize)] # Create shift-groups of characters def shift_group(datastr, blksize): datastr = clean_datastr(datastr) return [datastr[i:i+blksize] for i in range(len(datastr)-blksize+1)] def block_freq(datastr, blksize=1, shift=True): datastr = clean_datastr(datastr) diction = {} if shift: blocks = shift_group(datastr, blksize) else: blocks = block_group(datastr, blksize) for sub in blocks: if sub not in diction: diction[sub] = blocks.count(sub) return diction.items() def block_freq_analyses(datastr, blksize=1, shift=True): freq = block_freq(datastr, blksize, shift) total = len(datastr) return [(f[0], float(f[1]*len(f[0]))/total) for f in freq] def initial_keys(encrypt): # monogram = [k for k, _ in sort_by_value(get_ngram().items())] # freq = [k for k, _ in sort_by_value(block_freq(encrypt))] # key = list(alphabetic_compose_key(freq, monogram)) keys = [] for i in range(POPULATION_SIZE): key = list(CHARS) shuffle(key) keys.append("".join(key)) return keys def alphabetic_encrypt(datastr, key): if len(key) != 26 or len(set(key)) != 26: print("Not a complete alhabet found in mono alphabetic cipher key: " + str(key)) exit(2) key = key.upper() skip = string.punctuation + string.whitespace + string.digits result = '' for c in datastr: if c in skip: result += c else: result += key[ord(c.upper()) - 65].lower() return result # Alphabetic cipher compose keys # Given two alphabets def alphabetic_compose_key(from_alpha, to_alpha): EN_ALPHABET = "ETAONISRHLDUCMFWGPYBVKXJQZ" key = [''] * 26 # from_alpha = from_alpha.upper() # to_alpha = to_alpha.upper() for i in range(len(key)): try: key[ord(from_alpha[i])-65] = to_alpha[i] except IndexError: break # fill the gaps... while True: try: indx = key.index('') except ValueError: break else: for c in EN_ALPHABET: if c not in key: key[indx] = c break return "".join(key) # Mono aplhabetic substitution decryption def alphabetic_decrypt(datastr, key): decr_key = alphabetic_compose_key(key, string.ascii_uppercase) return alphabetic_encrypt(datastr, decr_key) # def fitness(text): # # Get all the words from the DICTIONARY file # with open(DICTIONARY) as f: # english_words = f.read().split() # # and make sorted list, largest word first # english_words.sort(key = lambda s: len(s), reverse=True) # # Calculate a score based on the remaining text # t = clean_datastr(text) # for w in english_words: # if len(w) > len(t): # continue # if w in t: # t = "".join(t.split(w)) # if len(t) == 0: # break # return float(len(text) - len(t)) / len(text) * 100 def fitness(text): chi = 0 for i in range(1, 4): freq_an = block_freq(text, i) dictio = get_ngram(i) total = sum(f[1] for f in freq_an) for [l, c] in freq_an: try: e = total * dictio[l] except KeyError: e = 0.01 chi += (c-e)**2/e return chi # def fitness(text): # a = b = c = 1 # scores = [] # for i in range(1, 4): # freq = sorted(block_freq_analyses(text, i)) # ngram = get_ngram(i) # score = 0.0 # for k, v in freq: # try: # score += abs(ngram[k]-v) # except KeyError: # score += v # scores.append(score) # return a*scores[0] + b*scores[1] + c*scores[2] # def stochasticly_pick(keys, pick): # picks = [] # r = randint(0, len(keys)) # step = len(keys)/pick # for i in range(pick): # picks.append(keys[(r+step*i)%len(keys)]) # return picks def random_pick(selection, N=2): s = list(selection) selected = [] for i in range(N): selected += [s.pop(randint(0, len(s)-1))] return selected def form_pairs(selection): select = list(selection) pairs = [] while len(select) > 1: parent1 = select.pop(randint(0, len(select))-1) parent2 = select.pop(randint(0, len(select))-1) pairs.append([parent1, parent2]) return pairs def fill(gen, complete): for g in complete: if g not in gen: gen[gen.index('')] = g return gen # Apply crossover # to generate two children def crossover(parents): parent1 = list(parents[0]) parent2 = list(parents[1]) r = randint(0, len(parent1)) parent11 = parent1[:r] parent12 = parent1[r:] parent21 = parent2[:r] parent22 = parent2[r:] child1 = [''] * len(parent12) child2 = [''] * len(parent22) # crossover for i, (p12, p22) in enumerate(zip(parent12, parent22)): if p12 not in parent21: child2[i] = p12 if p22 not in parent11: child1[i] = p22 child1 = fill(parent11 + child1, string.ascii_uppercase) child2 = fill(parent21 + child2, string.ascii_uppercase) return ["".join(child1), "".join(child2)] # # fill # for g in string.ascii_uppercase: # if g not in child1: # child1[child1.index('')] = g # if g not in child2: # child2[child2.index('')] = g # Pick two parents randomly from selection # Mutatate them, # to generate two children def mutation(parents): parent1 = list(parents[0]) parent2 = list(parents[1]) gen = [randint(0, 1) for _ in range(26)] child1 = [''] * 26 child2 = [''] * 26 # mutation for i, (g, p1, p2) in enumerate(zip(gen, parent1, parent2)): if g: child1[i] = p1 else: child2[i] = p2 # fill child1 = fill(child1, parent2) child2 = fill(child2, parent1) # for g in parent1: # if g not in child2: # child2[child2.index('')] = g # for g in parent2: # if g not in child1: # child1[child1.index('')] = g return ["".join(child1), "".join(child2)] def swap_gen(child, gen, repl): s = gen + repl return re.sub( r'(.*)([%s])(.*)([%s])(.*)' % (s, s), r'\1\4\3\2\5', child ) def genetic(population, environment): while True: # Sort population by fittest fit = [(person, fitness(alphabetic_decrypt(environment, person))) for person in population] fit.sort(key=lambda k: k[1]) # Keep strongest population = [k for k, _ in fit][:TOP_POPULATION] while len(population) < POPULATION_SIZE: # children = crossover(random_pick(population)) # if len(population) % 4 == 0: # children = mutation(children) # population += children p1, p2 = random_pick(population) for i in range(CROSSOVER_COUNT): char = choice(CHARS) indx = ord(char)-65 child = swap_gen(p1, char, p2[indx]) for i in range(MUTATION_COUNT): char = choice(CHARS) repl = choice(CHARS) child = swap_gen(child, char, repl) population.append(child) yield population def main(): with open(sys.argv[1]) as fl: text = fl.read() keys = initial_keys(text) generation = 0 population = genetic(keys, text) best_key = '' prt = [] best_keys = 0 while generation < MAX_GENERATIONS and best_keys < MAX_BEST_KEYS: keys = next(population) new_best_key = keys[0] if new_best_key == best_key: best_keys += 1 else: best_key = new_best_key best_keys = 0 prt.append(['generation'+str(generation+1)+':'] + keys) if generation % 4 == 3: z = list(zip(*prt)) column_print(z, max_width=120) print('\n') prt = [] generation += 1 fit = [(key, fitness(alphabetic_decrypt(text, key))) for key in keys] fit.sort(key=lambda k: k[1]) column_print(fit, head=['recent population', 'score']) print(fitness(alphabetic_decrypt(text, best_key))) print(alphabetic_decrypt(text, best_key)) if __name__ == '__main__': # key: FIQWRTNKZLMBYCHSEXVPGUJDOA # file: aplhabetic/encrypted.txt # plain: plain/plaintext.txt # chi-squared(1): 109.3 # chi-squared(1-4): 49525.86 # chi-squared(3): 15272.4187 # chi-squared(4): 129903.5196 # score_english: 97.8177% # main() with open(sys.argv[1]) as fl: encr = fl.read() encr = clean_datastr(encr) print(encr) # print(decr) print(fitness(encr)) # keys = initial_keys(encr) # key = 'FIQWRTNKZLMBYCHSEXVPGUJDOA' # key = CHARS[19:] + CHARS[:19] # decr = alphabetic_decrypt(encr, key) # print(decr) # print(fitness(decr)) # print(keys) # print(swap_gen('FWZXIKCJPANRTYBOQSGDHVLMUE', 'K', 'C')) # print(random_pick(keys)) # selection = random_pick(keys, 10) # parents = random_pick(selection) # print(crossover(parents)) # parents: # - Keep 20% (2 best keys) # - Stochasticly select 8 more keys # - apply crossover (10 more children) # - apply mutation of 0.02% (too children) # - apply replacement
#!/usr/bin/env python3 from argparse import ArgumentParser from typing import Iterator from math import ceil, floor def calc_cheapest_horz_position(data: Iterator[str]) -> int: """Finds a point which requires all points in a given input to travel the least amount of distance combined""" positions = list(sorted(int(h) for h in next(data).split(','))) b = positions[round(len(positions) / 2)] return sum(abs(p - b) for p in positions) def calc_cheapest_horz_position_crab_engineering(data: Iterator[str]) -> int: """Finds a point which requires each point in a given input to travel the least amount of distance""" positions = list(int(h) for h in next(data).split(',')) # I would suspect round here ?!? low = floor(sum(positions) / len(positions)) high = ceil(sum(positions) / len(positions)) return min(sum(int(abs(p - low) * (abs(p - low) + 1) / 2) for p in positions), sum(int(abs(p - high) * (abs(p - high) + 1) / 2) for p in positions)) def main(): parser = ArgumentParser(description="Day 7 solution") parser.add_argument('path', nargs='?', type=str, default='./input', help="The path to the input file (default: ./input)") parser.add_argument('-2', '--part2', action='store_true', help=("Print the solution for part 2 " "(default: part 1 is printed)")) args = parser.parse_args() with open(args.path, 'r') as data: if args.part2: r = calc_cheapest_horz_position_crab_engineering(data) else: r = calc_cheapest_horz_position(data) print(r) if __name__ == '__main__': main()
#!/usr/bin/env python3 from argparse import ArgumentParser from typing import Iterator from numpy import prod class Cloud: """A helper class for easily retrieving data and checking conditions from a grid like data structure.""" def __init__(self, data: Iterator[str]): self._cloud = [[int(i) for i in line.strip()] for line in data] def in_bound(self, point) -> bool: x, y = point return x >= 0 and x < len(self._cloud) and y >= 0 and y < len(self._cloud[x]) def get(self, point: tuple[int, int]) -> int: x, y = point return self._cloud[x][y] def all_coords(self): for i, row in enumerate(self._cloud): for j, _ in enumerate(row): yield (i, j) def is_low_point(self, coord) -> bool: if not self.in_bound(coord): raise ValueError("Lowest point coord not in cloud") return all((not self.in_bound(surr) or self.get(surr) > self.get(coord) for surr in surrounding_points(coord))) def lowest_points(self) -> Iterator[tuple[int, int]]: for point in self.all_coords(): if self.is_low_point(point): yield point def get_basin(self, coord: tuple[int, int]): basin = {coord} ext = self._extra_basin_coords(basin) while len(ext) > 0: basin |= ext ext = self._extra_basin_coords(basin) return basin def _extra_basin_coords(self, basin: set[tuple[int, int]]): return {s for point in basin for s in filter(lambda p: p not in basin, surrounding_points(point)) if (self.in_bound(s) and self.get(s) != 9)} def surrounding_points(point: tuple[int, int]) -> Iterator[tuple[int, int]]: """Yields all points (coords) surrounding a given point.""" x, y = point yield x - 1, y yield x + 1, y yield x, y - 1 yield x, y + 1 def calc_total_risk(data: Iterator[str]) -> int: """Calculates the total risk. (see README part 1)""" cloud = Cloud(data) return sum(cloud.get(point) + 1 for point in cloud.lowest_points()) def three_largest_basins(data: Iterator[str]): """Multiplies the size of the three largest basins. (see README part 2)""" cloud = Cloud(data) basins = sorted((cloud.get_basin(point) for point in cloud.lowest_points()), key=len) return prod([len(basin) for basin in basins[-3:]]) def main(): parser = ArgumentParser(description="Day 9 solution") parser.add_argument('path', nargs='?', type=str, default='./input', help="The path to the input file (default: ./input)") parser.add_argument('-2', '--part2', action='store_true', help=("Print the solution for part 2 " "(default: part 1 is printed)")) args = parser.parse_args() with open(args.path, 'r') as data: if args.part2: r = three_largest_basins(data) else: r = calc_total_risk(data) print(r) if __name__ == '__main__': main()
class Solution: # @return a string def convert(self, s, nRows): if not s or nRows <= 1: return s res = '' for si in range(nRows): for i in range(si, len(s))[::2 * nRows - 2]: res += s[i] if si > 0 and si < nRows - 1 and i - 2 * si + 2 * nRows - 2 < len(s): res += s[i - 2 * si + 2 * nRows - 2] return res s = Solution() print s.convert('ABCDEF', 1)
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: # @param root, a tree node # @return nothing def connect(self, root): if not root: return next_node = None root_next = root.next while root_next and not next_node: if root_next.left: next_node = root_next.left else: next_node = root_next.right root_next = root_next.next if root.left: if root.right: root.left.next = root.right else: root.left.next = next_node if root.right: root.right.next = next_node self.connect(root.right) self.connect(root.left)
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param a list of ListNode # @return a ListNode def mergeKLists(self, lists): def sort_list(list_a, list_b): if not list_a: return list_b elif not list_b: return list_a start = ListNode(-1) node_a = list_a node_b = list_b node = start while node_a and node_b: if node_a.val > node_b.val: node.next = node_b node = node_b node_b = node_b.next else: node.next = node_a node = node_a node_a = node_a.next if node_a: node.next = node_a if node_b: node.next = node_b return start.next if not lists: return None while len(lists) >= 2: new_list = [] while len(lists) >= 2: list_a = lists.pop() list_b = lists.pop() new_list.append(sort_list(list_a, list_b)) new_list.extend(lists) lists = new_list return lists[0] s = Solution() n1 = ListNode(2) n2 = ListNode(-1) print s.mergeKLists([n1,None,n2])
class Solution: # @return a boolean def isValid(self, s): stack = [] for c in s: if c in ['(', '[', '{']: stack.append(c) else: if not stack: return False if c == ')' and stack.pop() != '(': return False elif c == ']' and stack.pop() != '[': return False elif c == '}' and stack.pop() != '{': return False return len(stack) == 0 s = Solution() print s.isValid('([])')
# Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param root, a tree node # @return an integer def __init__(self): self.max_sum = -10000000 def maxPathSum(self, root): def iter(root): if root == None: return 0 left_sum = iter(root.left) right_sum = iter(root.right) one_path = max(root.val, max(left_sum, right_sum) + root.val) arch_path = left_sum + root.val + right_sum self.max_sum = max(self.max_sum, one_path, arch_path) return one_path self.max_sum = max(iter(root), self.max_sum) return self.max_sum s = Solution() n1 = TreeNode(-2) n2 = TreeNode(6) n3 = TreeNode(0) n4 = TreeNode(-6) n1.left = n2 n2.left = n3 n2.right = n4 print s.maxPathSum(n1)
""" Some of this code is based on the tutorial at http://ischlag.github.io/2016/06/19/tensorflow-input-pipeline-example/. This is sort of an extension of that blog post to a full example of using Tensorflow's Readers, Queues, etc., for training a CNN on MNIST Author: Patrick Emami """ import os import tensorflow as tf from tensorflow.python.framework import ops from tensorflow.python.framework import dtypes dataset_path = os.path.join(os.getcwd(), "mnist") test_labels_file = "test-labels.csv" train_labels_file = "train-labels.csv" BATCH_SIZE = 50 NUM_CHANNELS = 1 tf.set_random_seed(24601) # Helper functions for pre-processing def encode_label(label): return int(label) def read_label_file(file): f = open(file, "r") filepaths = [] labels = [] for line in f: if line == "\n": continue filepath, label = line.split(",") filepaths.append(os.path.join(dataset_path, filepath)) labels.append(encode_label(label)) return filepaths, labels # reading labels and file path def input_pipeline(filenames): filepaths, labels = read_label_file(filenames) # convert filepaths and labels to usable format with correct dtype images = ops.convert_to_tensor(filepaths, dtype=dtypes.string) # We'll use TF's one_hot op for fast pre-processing of labels labels_one_hot = tf.one_hot(ops.convert_to_tensor(labels, dtype=dtypes.int32), 10) # This allows you to group images and labels together into a queue input_queue = tf.train.slice_input_producer([images, labels_one_hot], shuffle=False) labels_queue = input_queue[1] # we need to read in the images, decode them, give them a shape, and make sure they # have the right dtype images_queue = tf.cast(tf.reshape( tf.image.decode_jpeg(tf.read_file(input_queue[0]), NUM_CHANNELS), shape=[28, 28, NUM_CHANNELS]), dtype=tf.float32) return images_queue, labels_queue # Code for CNN based on Deep MNIST for Experts tutorial # https://www.tensorflow.org/get_started/mnist/pros # Modified to use tf.get_variable :) def weight_variable(shape, name): initial = tf.truncated_normal(shape, stddev=0.1) return tf.get_variable(name=name, initializer=initial) def bias_variable(shape, name): initial = tf.constant(0.1, shape=shape) return tf.get_variable(name=name, initializer=initial) def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def build_training_model(x, y): with tf.variable_scope('my_graph'): W_conv1 = weight_variable([5, 5, 1, 32], 'W_conv1') b_conv1 = bias_variable([32], 'b_conv1') h_conv1 = tf.nn.relu(conv2d(x, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) W_conv2 = weight_variable([5, 5, 32, 64], 'W_conv2') b_conv2 = bias_variable([64], 'b_conv2') h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) W_fc1 = weight_variable([7 * 7 * 64, 1024], 'W_fc1') b_fc1 = bias_variable([1024], 'b_fc1') h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) W_fc2 = weight_variable([1024, 10], 'W_fc2') b_fc2 = bias_variable([10], 'b_fc2') y_conv = tf.matmul(h_fc1, W_fc2) + b_fc2 cross_entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=y_conv)) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) return train_step, accuracy def build_inference_model(x, y): with tf.variable_scope('my_graph', reuse=True): W_conv1 = weight_variable([5, 5, 1, 32], 'W_conv1') b_conv1 = bias_variable([32], 'b_conv1') h_conv1 = tf.nn.relu(conv2d(x, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) W_conv2 = weight_variable([5, 5, 32, 64], 'W_conv2') b_conv2 = bias_variable([64], 'b_conv2') h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) W_fc1 = weight_variable([7 * 7 * 64, 1024], 'W_fc1') b_fc1 = bias_variable([1024], 'b_fc1') h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) W_fc2 = weight_variable([1024, 10], 'W_fc2') b_fc2 = bias_variable([10], 'b_fc2') y_conv = tf.matmul(h_fc1, W_fc2) + b_fc2 correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) return accuracy if __name__ == '__main__': # Normally you also want to split off a validation set, but we omit that for this example train_images, train_labels = input_pipeline(os.path.join(dataset_path, train_labels_file)) test_images, test_labels = input_pipeline(os.path.join(dataset_path, test_labels_file)) num_preprocess_threads = 3 min_after_dequeue = 10000 train_image_batch = tf.train.shuffle_batch([train_images, train_labels], batch_size=BATCH_SIZE, capacity=min_after_dequeue + 3 * BATCH_SIZE, min_after_dequeue=min_after_dequeue, num_threads=num_preprocess_threads) test_image_batch = tf.train.shuffle_batch([test_images, test_labels], batch_size=BATCH_SIZE, capacity=min_after_dequeue + 3 * BATCH_SIZE, min_after_dequeue=min_after_dequeue, num_threads=num_preprocess_threads) # Create two graphs for training and inference, with shared weights train, train_accuracy = build_training_model(train_image_batch[0], train_image_batch[1]) inference = build_inference_model(test_image_batch[0], test_image_batch[1]) init_op = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init_op) # This is the standard "skeleton" for running code using Tensorflow queues coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) try: for i in range(20000): if i % 100 == 0: # The magic part - no feed_dict necessary! # Every call to train_accuracy grabs the next batch # automatically acc = train_accuracy.eval() print("step {}, training accuracy {}".format(i, acc)) sess.run([train]) acc = 0. for i in range(100): acc += inference.eval() print("test accuracy {}".format(acc / 100.)) except tf.errors.OutOfRangeError: print('Done training -- epoch limit reached') finally: # When done, ask the threads to stop. coord.request_stop() # Wait for threads to finish. coord.join(threads) sess.close()
import colorsys import pandas as pd import numpy as np import logging import re def hex_to_rgb(hex_color: str) -> list: """Converting hexadecimal color to rgb params: hex_color (str): color represented in hexadecimal format eg '#FFFFFF' returns: list: RGB color representation, list with 3 integers eg [255, 255, 255] """ if not isinstance(hex_color, str): raise ValueError('The provided hexadecimal definition has to be string eg #000000.') elif len(hex_color) != 7 or not hex_color.startswith('#'): raise ValueError('The provided hexadecimal definition has to starts with #') hex_color = hex_color.lower() # Pass 16 to the integer function for change of base return [int(hex_color[i:i + 2], 16) for i in range(1, 6, 2)] def rgb_to_hex(rgb_color: list) -> str: """Converting rgb color to hexadecimal representation params: rgb_color (list): RGB color representation, list with 3 integers returns: str: color represented in hexadecimal values eg. '#ffffff' """ # Components need to be integers for hex to make sense rgb_color = [int(x) for x in rgb_color] return "#" + "".join( ["0{0:x}".format(v) if v < 16 else "{0:x}".format(v) for v in rgb_color] ) def linear_gradient(start_hex: str, finish_hex: str = "#FFFFFF", length: int = 10) -> list: """Generating color gradient between two hexadecimal color of a given length Params: start_hex (str): starting color in hexadecimal format, requried finish_hex (str): ending color in hexadecimal format, default: '#FFFFFF' length (int): number of colors in the gradient Returns: list: 'length' number of colors in hexadecimal format """ # Starting and ending colors in RGB form start_rgb = hex_to_rgb(start_hex) finish_rgb = hex_to_rgb(finish_hex) # Initilize a list of the output colors with the starting color rgb_list = [start_hex.lower()] if not isinstance(length, int): raise ValueError('The number of returned colors have to be specified by an integer.') elif length == 0: return [] # Calcuate a color at each evenly spaced value of t from 1 to n for step in range(1, length): # Interpolate RGB vector for color at the current value of t curr_vector = [ int(start_rgb[j] + (float(step) / (length - 1)) * (finish_rgb[j] - start_rgb[j])) for j in range(3) ] # Add it to our list of output colors rgb_list.append(rgb_to_hex(curr_vector)) return rgb_list def color_darkener(color: str, x: int, width: int, threshold: float, max_diff_value: float) -> str: """Function to decrease the luminosity of a hex color Params: color (str): primary color assigned based on primary annotation eg. intergenic, exon etc, x (int): x position of the chunk width (str): how many chunks do we have in one line. (always >= row['x']) threshold (float): fraction of the width, where the darkening starts (<= 1.0) max_diff_value (float): the max value of darkening (<=1) Returns: str: the darkness adjusted color in hex """ if not isinstance(color, str) or not re.match(r'#[0-9A-Fa-f]{6}', color): raise TypeError(f'Color is expected to be given as a hexadecimal value (eg. "#F12AC4"). Given: {color}.') if not isinstance(x, int): raise TypeError('x has to be integer giving the numeric position of the chunk.') if not isinstance(width, int): raise TypeError('width has to be an integer.') if not isinstance(threshold, float) or (threshold > 1): raise TypeError('threshold has to be a float below 1. The fraction of the width where the darkening starts') if not isinstance(max_diff_value, float) or (max_diff_value > 1): raise TypeError('The darkening has to be a float below 1.') col_frac = x / width # We have the color, now based on the column we make it a bit darker: if col_frac > threshold: diff = (col_frac - threshold) / (1 - threshold) factor = 1 - max_diff_value * diff # Get rgb code of the hexa code: rgb_code = hex_to_rgb(color) # Get the hls code of the rgb: hls_code = colorsys.rgb_to_hls( rgb_code[0] / 255, rgb_code[1] / 255, rgb_code[2] / 255 ) # Scaling luminosity then convert to RGB: new_rgb = colorsys.hls_to_rgb(hls_code[0], hls_code[1] * factor, hls_code[2]) # Get the modifed hexacode: color = rgb_to_hex([x * 255 for x in new_rgb]) return(color) class ColorPicker(object): # These are the supported and expected features: features = ['exon', 'gene', 'intergenic', 'centromere', 'heterochromatin', 'dummy'] def __init__(self, colors: dict, dark_max: float = None, dark_threshold: float = None, count: int = 20, width: int = None) -> None: """Initializing ColorPicker Params: colors (dict): dark_max (float): How much darker color should be reached. dark_threshold (float): Where the darkenin should be started. count (int): Number of steps in the gradient. width (int): Number of chunks in a row. Returns: None """ # Checking if colors is of the good type: if not isinstance(colors, dict): raise TypeError(f'The color object has to be a dictionary. {type(colors)} is given.') # Checking if all features can be found in the color set: if not pd.Series(self.features).isin(list(colors.keys())).all(): raise ValueError(f'The following keys must be defined in the color sets: {",".join(self.features)}') # Checking if all the values are good: for hex_color in colors.values(): if not re.match(r'#[0-9A-F]{6}', hex_color) or not isinstance(hex_color, str): raise ValueError('All colors should be in hexadecimal format eg "#1ED5FA"') # Checking dark max and the threshold: for val in [dark_max, dark_threshold]: if (not isinstance(val, float)) or (val >= 1) or (val <= 0): raise ValueError(f'dark_max and dark_threshold has to be float between 0 and 1 instead: {val}') # Checking dark max and the threshold: for val in [count, width]: if not isinstance(val, int): raise ValueError(f'Count and width have to be integers. Got: {val}') # Generating color gradients for a given length: self.color_map = {x: linear_gradient(colors[x], length=count) for x in self.features} self.dark_max = dark_max self.dark_threshold = dark_threshold self.width = width self.count = count def map_color(self, feature: str, gc_content: float) -> str: if feature == 'dummy': color = self.color_map['dummy'][0] elif gc_content is None or np.isnan(gc_content): color = self.color_map['heterochromatin'][0] else: try: color = self.color_map[feature][int(gc_content * (self.count - 1))] except KeyError: logging.error(f'Feature {feature} was not found in color mapper. Returning black.') color = '#000000' return color def pick_color(self, row: pd.Series) -> str: expected_columns = ['GC_ratio', 'GENCODE', 'x'] if not isinstance(row, pd.Series) or not pd.Series(expected_columns).isin(row.index).all(): raise TypeError(f'The row has to be a pd.Series with the following keys: {",".join(expected_columns)}') # Get the base color: color = self.map_color(row['GENCODE'], row['GC_ratio']) # Darken the color: if (row['GENCODE'] != 'dummy') and self.width is not None and (row['x'] / self.width) > self.dark_threshold: color = color_darkener(color, row['x'], self.width, self.dark_threshold, self.dark_max) return color
import turtle import math turtle.shape('turtle') turtle.shapesize(1) turtle.speed(10000000) turtle.penup() turtle.forward(200) turtle.left(90) def arc(theta, r): turtle.pendown() for i in range (theta//3): turtle.forward(2*(math.pi)*r/(360/3)) turtle.left(3) turtle.penup() turtle.fillcolor('yellow') turtle.begin_fill() arc(360,40*5) turtle.end_fill() turtle.fillcolor('blue') turtle.goto(-70, 4.5*25) turtle.begin_fill() arc(360, 28) turtle.goto(130, 4.5*25) arc(360, 28) turtle.end_fill() turtle.goto(2, -20) turtle.pendown() turtle.color('black') turtle.width(20) turtle.forward(70) turtle.penup() turtle.goto(-70-28*2, -30) turtle.left(180) turtle.color('red') arc(180, 28+100)
'''2. Write a python program to input the temperature of a user in degree celcius and convert it into farenheit.''' #Taking values from the user celsius = float(input('Enter temperature in celsius: ')) #Calcuate Temperature in Fahrenheit fahrenheit = (celsius*1.8)+32 print("The temperature in Fahrenheit is: ", fahrenheit)
class Node: '''Created by krishna kant sharma B.tech 3rd year ''' def __init__(self, data): self.data = data self.next = None class SinglyLinkedList: def __init__(self): self.head = None def printList(self): temp = self.head while temp: print(temp.data, '-->', end=" ") temp = temp.next def insertAtBeggning(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node def insertInBetween(self, data, node_after): if node_after is None: print("Please provide valid node_after value") return new_node = Node(data) temp = self.head new_node.next = node_after.next node_after.next = new_node def insertAtEnd(self, data): new_node = Node(data) if self.head is None: self.head = new_node return temp = self.head while temp.next: temp = temp.next temp.next = new_node def deleteAtBegging(self): self.head = self.head.next def deleteAtEnd(self): if self.head is None: print('No element to delete') return temp = self.head while temp.next.next: temp = temp.next temp.next = None def deleteAnyNode(self, val): if self.head is None: print('No value to delete') return if self.head.data == val: self.head = self.head.next temp = self.head while temp: if temp.data == val: pre.next = temp.next return pre = temp temp = temp.next print("element not found") def deleteAtPosition(self, position): if position < 0 or position > self.listLength(): print('Enter valid position') return if position == 0: self.head = self.head.next return temp = self.head count = 0 pre = self.head while count <= position: if count == position: pre.next = temp.next return count = count + 1 pre = temp temp = temp.next def listLength(self): c = 0 temp = self.head while temp: temp = temp.next c = c + 1 return c ll = SinglyLinkedList() ll.deleteAtEnd() # No element to delete ll.insertAtEnd(20) # 20 ll.insertAtEnd(30) # 30 ll.insertInBetween(40, ll.head.next) # 20 30 40 ll.insertAtEnd(50) # 20 30 40 50 ll.insertAtBeggning(10) # 10 20 30 40 50 ll.deleteAtEnd() # 10 20 30 40 ll.deleteAnyNode(30) # 10 20 40 ll.deleteAtPosition(2) # 10 20 ll.printList() # will print print(ll.listLength()) # 2 ''' output ----------------------------------------------------------- No element to delete 10 20 2 '''
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. # By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... import platform from functools import reduce import time import sys if sys.platform == 'win32': default_timer = time.perf_counter else: default_timer = time.time start = default_timer() print("Using: " + platform.python_version()) sum = 2 term_one = 1 term_two = 2 limit = 4000000 while term_two < limit: term = term_one + term_two if(term % 2 == 0): sum += term term_one = term_two term_two = term end = default_timer() elapsed = (end - start) * 1000 * 1000 print("{:.2f}".format(elapsed) + " ns") print("The term sum is: " + str(sum))
from misc.titlecase import titlecase def getWOSValues (): """ read WOS values from a file (normalizing on the way) """ path = '../uniqueWOSvalues_pubname.txt' s = open(path).read() raw = s.split('\n') values = [] for v in raw: if not v.strip(): continue values.append(normalizeItem (v)); return values def normalizeItem (item): s = titlecase (item.lower()) # s = s.replace ("&", "&amp;") return s.strip() def normalizeList (l): return map (lambda x: normalizeItem(x), l) def diffLists (list_1, list_2): """ what items are present in list_1 but not in list_2) """ ret = [] # print "ret has %d items" % len (ret) list_2_lower = listToLower (list_2) for item in list_1: if not item.lower() in list_2_lower: ret.append(item) # print 'non-dup: %s' % item ret.sort(lambda a,b: cmp (a.lower(), b.lower())) return ret def mergeLists (base, tomerge): """ add those items in tomerge that aren't present in base sort by lower case """ # intitialze ret by copying base ret = [] map (lambda x: ret.append(x), base) # print "ret has %d items" % len (ret) baseLower = listToLower (ret) for item in tomerge: if not item.lower() in baseLower: ret.append(item) # print 'non-dup: %s' % item ret.sort(pubNameCmp) return ret def listToLower (l): return map (lambda x: x.lower(), l) def pubNameCmp (a, b): return cmp (a.lower(), b.lower()) if __name__ == '__main__': list_1 = ['a', 'b', 'c', 'd','D'] list_2 = ['a', 'e'] print "merge" for item in mergeLists (list_1, list_2): print item print "diff" for item in diffLists (list_1, list_2): print item
''' Initial thought process Okay so this program's purpose is to help a sick workaholics remind themselves that they must take a break. Step 1. get current time Step 2. From Current time it goes off every X amount of time e.g 30 mins Step 3. Get the time current time + x amount of time Step 4. As current time updates and keep checking with current time + x until its equivalent. Step 5. When it is finally equivalent, play a youtube link ''' import webbrowser import time i = 0 print("this is a program that helps you manage your break") print("This program executed today on: " + time.ctime()) while i < 3: time.sleep(60*30)#30 minute break sttarts webbrowser.open("https://www.youtube.com/watch?v=CVEuPmVAb8o") i = i + 1;
#Christian Walker #9/12/2019 #Meal, Tip, and Tax Calculator #A program that calculates the total amount #of a meal purchased at a restaurant #Intro print("Hello!, Welcome to the Meal, Tip, and Tax Calculator") print("All percentages should be entered in the following format: '.xx'") print("---------------------------------------------------------------------") #Ask user to enter the charge for food meal = float(input("Enter price of the meal: $")) #Ask user to enter the tip for server tipP = float(input("Enter tip percentage for the server: ")) #Ask user to enter the Tax amount taxP = float(input("Enter tax percentage: ")) #Calculate tip and tax tip = meal * tipP tax = meal * taxP #Calculate price of full meal Fmeal = meal + tax + tip #Display total cost of meal print("---------------------------------------------------------------------") print("Meal: $", meal) print("Tip: $", tip) print("Tax: $", tax) print("Your total bill is: $", Fmeal)
x = 4.33 y = 2.33 z = x * y #sep='' removes spaces from print funtions print("The value of z is:",z,".") #The value of z is: 10.0889 . print("The value of z is:",z,".",sep='') #The value of z is:10.0889. print("The value of z is:" +str(z) +".") #The value of z is:10.0889. print("The value of z is:",format(z,',.2f'),'.') #The value of z is: 10.09 . print("The value of z is: ",format(z,',.2f'),".",sep='' ) #The value of z is: 10.09. print("---------------------------------------------------------------") print(x,y,z) #4.33 2.33 10.0889 print(str(x) + str(y) + str(z)) #4.332.3310.0889 print(str(x).rjust(10) + str(y).rjust(10) + str(z).rjust(10)) # 4.33 2.33 10.0889 print(str(x).ljust(10) + str(y).ljust(10) + str(z).ljust(10)) #4.33 2.33 10.0889 print("Center".center(80)) # Center
"""mystring = 'McGill' print(mystring) print(mystring.lower()) """ #_________________________________________________________________________________________________________ """mystring = 'McGill is my university' mystring_split = mystring.split(' ') print(mystring_split) """ #_________________________________________________________________________________________________________ """mylist = [1,2.0, 3+4j , "Hello"] # lists can take in multiple data types print(mylist) print(type(mylist)) """ #__________________________________________________________________________________________________________ """mydict = {} # similar to hash maps in Java print(type(mydict)) mydict['myfirstkey'] = 1 print(mydict['myfirstkey']) """ #__________________________________________________________________________________________________________ """"def addTwoNumbers (a,b): return a+b print(addTwoNumbers (5,2)) """ #_________________________________________________________________________________________________________ mystring = 'Ma Blonde Mange Des Processeurs Et Des Gits' a = range(len(mystring)) print(a) print(a+"Romania")
input = open("input.txt", "r"); frequency = 0 for line in input: frequency += int(line); print(frequency)
from coins.coin_types import CoinTypes class CoinsTable: max_coins_count = 7 max_any_color_count = 5 def __init__(self): self.coins_count = { CoinTypes.WHITE : CoinsTable.max_coins_count, CoinTypes.BLUE : CoinsTable.max_coins_count, CoinTypes.GREEN : CoinsTable.max_coins_count, CoinTypes.RED : CoinsTable.max_coins_count, CoinTypes.BLACK : CoinsTable.max_coins_count, CoinTypes.ANY_COLOR : CoinsTable.max_any_color_count } def getCoinsCount(self, coin): return self.coins_count[coin] def getAvailableCoins(self, min_coins_count = 1): availableCoins = () for coin, coins_count in self.coins_count.items(): if coins_count >= min_coins_count and coin != CoinTypes.ANY_COLOR: availableCoins += (coin, ) return availableCoins def takeCoins(self, coin, coins_count=1): assert((self.coins_count[coin] - coins_count) >= 0), "no more {0} coins".format(coin.name) self.coins_count[coin] -= coins_count return True def returnCoins(self, coin, coins_count=1): if coin == CoinTypes.ANY_COLOR: assert((self.coins_count[CoinTypes.ANY_COLOR] + coins_count) <= CoinsTable.max_any_color_count), "all ANY_COLOR coins are at table" assert((self.coins_count[coin] + coins_count) <= CoinsTable.max_coins_count), "all {0} coins are at table".format(coin.name) self.coins_count[coin] += coins_count return True
import pandas df1 = pandas.DataFrame({"col1": [1, 5, 9], "col2":[2, 6, 0]}) #print(df1) df2 = pandas.DataFrame({"col1": [11, 15, 19], "col2":[21, 61, 10]}) #print(df2) df1.loc[df2.index[0]] = df2.iloc[1] #print(df1) print(df2.shape) for row in df2.iterrows(): df1.loc[df1.shape[0]] = row[1] print(row[1].col1, " ", row[1].col2) print(df1)
x= int(input("ingresa un numero X \n")) y= int(input("ingresa un numero Y \n")) div=x%y if div == 0: print("Es entero") else: print("NO es entero") print("2--------------------\n") a= int(input("ingresa un numero a \n")) b= int(input("ingresa un numero b \n")) if a<b : print("El numero mayor es"+ str(b)) else: print("El numero mayor es"+ str(a)) print("3---------------------------\n\n") """print("4---------------------------\n") d= int(input("ingresa el primer numero \n")) e= int(input("ingresa el segundo numero \n")) f= int(input("ingresa el tercer numero \n")) if d==e: print("dos son iguales") elif d==f: print("dos son iguales") elif e==f: print("dos son iguales") elif d==f and f==e: print("Los tres son iguales") else: print("Los tres so diferentes ")""" print("4---------------------------\n\n") d= int(input("ingresa un numero a \n")) e= int(input("ingresa un numero b \n")) f= int(input("ingresa un numero c \n")) if(d>e and d>c) print("A es el mayor")
#!/usr/bin/python #-*- coding: utf-8 -*- x= int(input("ingresa un numero X \n")) y= int(input("ingresa un numero Y \n")) print(type(x)) if x == 3 and y == 3: print("se cumplio AND") else: print("NO") if x == 3 or y ==3: print("se cumplio OR") else: print("NO")
"""un/comment to de/activate ########################### # types # int, float # bool # < > <= >= == != # not, and, or # str # None # abstractsions # variables # functions # classes # control flow # if, elif, else # if <condition>: <consequent> # iteration # for # while #######################################################""" """un/comment to de/activate ########################### a = 5 b = 5 if a < b: print("a is less than b") elif a == b: print("a is equal to b") else: print("a is greater than b") print("program finished") #######################################################""" """un/comment to de/activate ########################### def factorial(n): prod = 1 for i in range(2, n+1): prod *= i return prod print( factorial(5) ) #######################################################""" """un/comment to de/activate ########################### # IPO # input : any 2 numbers, either int or float # porcess : subtract the second from the first # output : <int> or <float> the difference between the first and second input def subtract(a, b): difference = a - b return difference print( subtract(5, 2) ) #######################################################""" """un/comment to de/activate ########################### print(0.9) print(0.99) print(0.999) print(0.9999) print(0.99999) print(0.999999) print(0.9999999) print(0.99999999) print(0.999999999) print(0.9999999999) print(0.99999999999) print(0.999999999999) print(0.9999999999999) print(0.99999999999999) print(0.999999999999999) print(0.9999999999999999) print(0.99999999999999999) print(0.999999999999999999) print(0.9999999999999999999) print(0.99999999999999999999) print(0.999999999999999999999) # print(1/100**100000) #######################################################""" """un/comment to de/activate ########################### def subtract(a, b): difference = a - b return difference print( subtract(5, 2) + 3 ) def subtract(a, b): difference = a - b print(difference) print( subtract(5, 2) ) #######################################################""" """un/comment to de/activate ########################### # def subtract(a=10, b): # SyntaxError: non-default argument follows default argument def subtract(a, b): difference = a - b return difference print( subtract(7, 3) ) # print( subtract(a=7, b=3) ) # TypeError: subtract() missing 1 required positional argument: 'b' #######################################################""" """un/comment to de/activate ########################### name = "Joanne" age = 38 print( "{} is {} years old".format(name, age) ) #######################################################""" """un/comment to de/activate ########################### def some_unknown_number(a, b): difference = a - b return difference x = 10 y = 30 print( some_unknown_number(x, y) ) #######################################################""" """un/comment to de/activate ########################### def user_info(username, email, age): return f"{username} is {age} years old, their email is {email}" print(user_info("clark", "[email protected]", 97)) #######################################################""" """un/comment to de/activate ########################### ''' Implement the function dbl_seq_sum which takes two lists of positive integers and computes the summation Where a[k] and b[k] refer to the k-th elements in the two given lists. Notice that there is no upper bound on the summation. This just means "sum over all the elements". Assume that both lists will be the same length, and take note of the starting index of the summation. ''' def dbl_seq_sum(nums_a, nums_b): summation = 0 for idx, numa in enumerate(nums_a, 1): summation += ((-1)**idx) * ((numa + nums_b[idx-1]) / ((1 + numa * nums_b[idx-1] ))) return summation print( dbl_seq_sum([3, 5, 2], [7, 1, 9]) ) def dbl_seq_sum(nums_a, nums_b): acc = 0 for k, (a, b) in enumerate(zip(nums_a, nums_b), 1): acc += ((-1)**k) * ((a + b) / (1 + (a * b))) return acc print( dbl_seq_sum([3, 5, 2], [7, 1, 9]) ) # #######################################################""" # """un/comment to de/activate ########################### #######################################################"""
"""un/comment to de/activate ########################### # data types # int, float # + - * / // % ** # bool # == != < > <= >= # not, and, or # in # str # None # list # indexing / subscripting / slicing # .append # len, range # in # abstraction # variables # functions # control flow # if elif else # condition is any expression that evaluates to True or False # iteration # for # while #######################################################""" """un/comment to de/activate ########################### a = 0 # assaignment and initialization a = 1 # assaignment or reassaignment a = a + 1 a += 1 a -= 1 a *= 1 a /= 1 a //= 1 a %= 1 #######################################################""" """un/comment to de/activate ########################### # [3.14, 87, "hello", [1, 2, 3, "hi"]] lst = [3, 4, 5, 6, 7] print(lst) # [3, 4, 5, 6, 7] #######################################################""" """un/comment to de/activate ########################### my_range = range(10) my_lst = list(my_range) print( "X", my_lst ) print( "Y", my_range ) # Will this line print A. or B. # A. range(0, 10) # B. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] #######################################################""" """un/comment to de/activate ########################### lst = [] print(lst) lst.append(5) lst = [5] print(lst) #######################################################""" """un/comment to de/activate ########################### lst = [55, 44, 77, 22, 33, 99, 55, 22] lst.append("foo") lst.append("bar") lst.append("bas") print( lst[4] ) #######################################################""" """un/comment to de/activate ########################### # len IPO # input: some type that has a length # output: int, representing the lenghth of the argument # range # input: # 1 (stop (exclusive)) # output: generates a range from 0 - stop # 2 (start (inclusive), stop (exclusive)) # output: generates a range from start - stop # 3 (start (inclusive), stop (exclusive), step) # output: generates a range from start - stop in "steps" of step # print( list( range(0, 31, 3) ) ) #######################################################""" """un/comment to de/activate ########################### num_lst = [55, 44, 77, 22, 33, 99, 55, 22] print(num_lst) print(len(num_lst)) idx_lst = list( range( len(num_lst) ) ) print(idx_lst) #######################################################""" """un/comment to de/activate ########################### # membership num_lst = [55, 44, 77, 22, 33, 99, 55, 22] print( 99 in num_lst ) #######################################################""" """un/comment to de/activate ########################### num_lst = [55, 44, 77, 22, 33, 99, 55, 22] print( num_lst[7] ) # print( num_lst[8] ) # IndexError: list index out of range # print( num_lst[-9] ) # IndexError: list index out of range print( num_lst[-8] ) # print( num_lst[-9] ) #######################################################""" """un/comment to de/activate ########################### # slicing num_lst = [55, 44, 77, 22, 33, 99, 55, 22] # print( num_lst[1] ) # range - start (inclusive), stop (exclusive), step print( num_lst[::] ) # [55, 44, 77, 22, 33] #######################################################""" """un/comment to de/activate ########################### # id # input: any obj # output: the internal ID of that obj lst = ["hello"] print( id(lst), lst ) other_lst = lst.copy() other_lst.append("world") print( id(lst), lst ) print( id(other_lst), other_lst ) #######################################################""" """un/comment to de/activate ########################### def is_prime(num): if num < 2: return False for factor in range(2, int(num**.5)+1 ): if num % factor == 0: return False return True def next_prime(anchor): counter = anchor while True: counter += 1 if is_prime(counter): return counter def twin_prime(nth): ''' The twin prime conjecture is a theory in which there are an infinite number of pairs of primes that differ by 2. This function finds the 'nth' twin prime pair. For example, the 5th twin prime pair is (29, 31). Parameters: --------------- nth: (int) This function finds the 'nth' twin prime pair Return: --------------- list The 'nth' pair of twin primes ''' prime_anchor = 2 pair_counter = 0 while True: prime_anchor = next_prime(prime_anchor) if is_prime(prime_anchor + 2): pair_counter += 1 if pair_counter >= nth: return [prime_anchor, prime_anchor + 2] for i in range(15): print(i, twin_prime(i) ) #######################################################""" """un/comment to de/activate ########################### def is_prime(num): if num < 2: return False for factor in range(2,int((num**.5)+1)): if num % factor == 0: return False return True def next_prime(anchor): counter = anchor while True: counter += 1 if is_prime(counter): return counter def twin_prime(nth): ''' The twin prime conjecture is a theory in which there are an infinite number of pairs of primes that differ by 2. This function finds the 'nth' twin prime pair. For example, the 5th twin prime pair is (29, 31). Parameters: --------------- nth: (int) This function finds the 'nth' twin prime pair Return: --------------- list The 'nth' pair of twin primes ''' prime_anchor = 1 pair_counter = 1 while True: second_prime = next_prime(prime_anchor) if second_prime - prime_anchor == 2: if pair_counter >= nth: return [prime_anchor, second_prime] pair_counter += 1 prime_anchor = second_prime #######################################################""" # """un/comment to de/activate ########################### #######################################################"""
"""un/comment to de/activate ########################### # python overview # data types # int, float # bool # None # str # list # discribe mutability vs immutability # abstractions # variables # functions # control flow # if, elif, else # iteration # for # while ###################################################### """ """un/comment to de/activate ########################### txt = "hello" print(txt) txt = txt + " world" print(txt) ###################################################### """ """un/comment to de/activate ########################### ''' * Write a function that computes and returns a list of all of the divisors of some positive number. Use a while loop. Things to think about: * How do you determine if a single number is a divisor of another? * What is your stopping condition? * BONUS: rewrite this with a for loop IPO (input, process, output): input: n <int>: a positive integer output: <list <int> >: representing all the divisors of n ''' def divisors_list(n): lst = [] for i in range(1, n + 1): if n % i == 0: lst.append(i) return lst def divisors_list(n): lst = [] i = 0 while i <= n: i += 1 if n % i == 0: lst.append(i) return lst for i in range(20): print( i, divisors_list(i) ) ###################################################### """ """un/comment to de/activate ########################### lst = [] while True: # loop forever menu_string = '''Select from this list: 1 : bread 2 : butter 3 : potatoes 4 : broccoli q to quit''' print(menu_string) inp = input("please make a selection 1-4: ") if inp.lower() == "q": break lst.append( int(inp) ) print(lst) ###################################################### """ """un/comment to de/activate ########################### txt = ''' hello world ''' txt = 'that\'s' print(txt) ###################################################### """ """un/comment to de/activate ########################### txt = "hello " print( txt + "world" ) print( txt * 3 ) print( txt ) ###################################################### """ """un/comment to de/activate ########################### a = 10 print(a) a = str(a) print(a) b = 3.5 print(b) print(str(b)) c = [4, 5, 2] print(c) print(str(c)) d = None print(d) print(str(d)) e = True print(e) print(str(e)) f = False print(f) print(str(f)) ###################################################### """ """un/comment to de/activate ########################### a = "10" print(a) b = float(a) print(b) ###################################################### """ """un/comment to de/activate ########################### print( bool("hello") ) # True print( bool("") ) # False ###################################################### """ """un/comment to de/activate ########################### text = ''' Whose woods these are I think I know His house is in the village though He will not see me stopping here To watch his woods fill up with snow ''' world_lst = [] word = "" for el in text: if el == " ": world_lst.append(word) word = "" else: word += el print(world_lst) print(text.split()) ###################################################### """ """un/comment to de/activate ########################### text = ''' Whose woods these are? I think I know. His house is in the village though; He will not see me stopping here To watch his woods fill up with snow. My little horse must think it queer To stop without a farmhouse near Between the woods and frozen lake The darkest evening of the year. He gives his harness bells a shake To ask if there is some mistake. The only other sound's the sweep Of easy wind and downy flake. The woods are lovely, dark and deep, But I have promises to keep, And miles to go before I sleep, And miles to go before I sleep. ''' # print( list(text) ) # print(text.split()) # for word in text.split(): # print(word) # # print(text.split(".")) # for sentance in text.split("."): # print(sentance) sentances_lst = text.split(".") print(sentances_lst) print( " ".join(sentances_lst) ) ###################################################### """ """un/comment to de/activate ########################### text = ''' Whose woods these are? I think I know. His house is in the village though; He will not see me stopping here To watch his woods fill up with snow. My little horse must think it queer To stop without a farmhouse near Between the woods and frozen lake The darkest evening of the year. He gives his harness bells a shake To ask if there is some mistake. The only other sound's the sweep Of easy wind and downy flake. The woods are lovely, dark and deep, But I have promises to keep, And miles to go before I sleep, And miles to go before I sleep. ''' print( text[7:22:] ) ###################################################### """ """un/comment to de/activate ########################### lst = [5, 4, 3, 2, 1] print(6 in lst) print(2 in lst) txt = "hello world" print("o" in txt) print("p" in txt) print("ello" in txt) ###################################################### """ """un/comment to de/activate ########################### lst = [5, 4, 3, 2, 1] txt = "hello world" # for ch in txt: # print(ch) for idx, ele in enumerate(txt): print(idx, ele) ###################################################### """ """un/comment to de/activate ########################### lst = [4, 3, 5, 0, 1] # 4351 # print( list( map(bool, lst) ) ) def my_map(fn, lst): acc = [] for ele in lst: acc.append(fn(ele)) return acc digits = "".join( my_map(str, lst) ) print(digits) ###################################################### """ # """un/comment to de/activate ########################### ###################################################### """
from tkinter import * from PIL import ImageTk, Image import speech_recognition as sr from tkinter import messagebox from control.VoiceController import VoiceController class MainView: def exit(self): exit() def load(self): self.main=Tk() self.main.title("Voice Based Directory Search") self.main['background']='midnight blue' self.main.geometry("1080x550+0+0") self.main.resizable("False","False") self.bg = PhotoImage(file="views\ground.png") pic = PhotoImage(file = "views\mic.png") self.mic = pic.subsample(2,2) bg = Label(self.main,image=self.bg) bg.grid() title = Label(self.main,text="*VOICE BASED DIRECTORY SEARCH APP*",font=("Helvetica",21,"bold"),bg="midnight blue",fg="SlateBlue1",bd=7,relief=RAISED) title.place(x=0,y=0,relwidth=1) MicFrame = Frame(self.main,bg="midnight blue") MicFrame.place(x=300,y=120) l1 = Label(MicFrame,text = "INSTRUCTIONS\n1.ASK FOR EITHER ONLINE OR OFFLINE\n 2.TRY 'OPEN DOCUMENTS' OR 'GOOGLE.COM'",bg="midnight blue",fg="SlateBlue1",font=("Times 10 bold", 18)) l1.grid(row=0,column=0) l2 = Label(MicFrame,text="click the mic and ask for your choice ",fg="SlateBlue1",bg="midnight blue",font=("Helvetica", 15)) l2.grid(row=1,column=0) def voice(): vc = VoiceController() go_ahead = Label(MicFrame,text="Go Ahead,we are listening!",font=("Times 10",15),fg="SlateBlue1",bg="midnight blue").grid(row=3,column=0,padx=10,pady=5) messagebox.showinfo('Speak...',"waiting for your command") res1=vc.user_command() fc = Label(MicFrame,text="You : "+res1,font=("Times 10",15),fg="SlateBlue1",bg="midnight blue").grid(row=4,column=0,padx=15,pady=15) messagebox.showinfo('Speak...',"waiting for your command") res2=vc.user_command() fc = Label(MicFrame,text="You : "+res2,font=("Times 10",15),fg="SlateBlue1",bg="midnight blue").grid(row=5,column=0,padx=15,pady=15) if res1 == "offline": try: vc.open_func(res2) except: messagebox.showinfo('Sorry!',"No application Found.") else: try: vc.online(res2) except: messagebox.showinfo('Sorry!',"Try again") b1 = Button(MicFrame,image = self.mic,command = voice,width=85,height=85,font=("Helvetica",14,"bold"),bg="midnight blue",fg="SlateBlue1",bd=3,relief=RAISED) b1.grid(row=6,column=0) b2 = Button(MicFrame,text="EXIT",command=self.exit,width=5,font=("Helvetica",14,"bold"),bg="midnight blue",fg="SlateBlue1",bd=3,relief=RAISED) b2.grid(row=7,column=0) self.main.mainloop() if __name__ == '__main__': mv = MainView() mv.load()
#import the xlrd module import xlrd import xlwt #Open the spreadsheet file (or workbook) workbook = xlrd.open_workbook("Book1.xlsx") print("workbook nsheets : {0}".format(workbook.nsheets)) print("workbook sheet names : ", workbook.sheet_names()) first_sheet=workbook.sheet_by_index(0) print("row values : ", first_sheet.row_values(0)) cell=first_sheet.cell(4,1) print("Cell(4,1) : ", cell) print("==> col values : ", first_sheet.col_values(0)) # To write to excel print("** xlwt import ") workbook2 = xlwt.Workbook(encoding = "utf-8") sheet1=workbook2.add_sheet("Python Sheet1") sheet2=workbook2.add_sheet("Python Sheet2") sheet3=workbook2.add_sheet("Python Sheet3") sheet1.write(0,0, "This is Sheet 1") sheet2.write(10,0, "This is Sheet 2") sheet3.write(0,10, "This is Sheet 3") workbook2.save("Pythonspreadsheet1.xlsx") print("Workbook2 created <Pythonspreadsheet1.xlsx") #Open a sheet: #if you know the name of the sheet, you can open it by running the following: worksheet = workbook.sheet_by_name("Users") #if you are not sure of the name of the sheet, # you can open the first worksheet by it's index as follows: worksheet = workbook.sheet_by_index(0) #once you have selected the worksheet, #you can extract the value of a particular data cell as follows: print("the value at row 4 and column 2 is : {0}".format(worksheet.cell(4,2).value)) #if you want to know the number of sheets, #use the property nsheets on the workbook object: sheet_count = workbook.nsheets print("the total number of sheets : {0}".format(sheet_count)) #if you wan to have a list of the names of the sheets present in the file, #use the function sheet_names() on the workbook object sheets_name = workbook.sheet_names() print("sheet names: {0}".format(sheets_name)) #to find the total number of rows and columns in the sheet use the property nrows and ncols with #the sheet object total_rows = worksheet.nrows total_cols = worksheet.ncols print("number of rows : {0}, and number of columns : {0}".format(total_rows,total_cols)) #final tip: #let's loop in every record in the worksheet and store them in a list then display the final list: table = list() record = list() for x in range(total_rows): for y in range(total_cols): record.append(worksheet.cell(x,y).value) table.append(record) record = [] x +=1 print("Printing table : \n", table)
def testmethod(test123): if test123 == 'Hi': return "Hi there" else: return 'Goodbye' returnedfromtest = testmethod('Hi') print(returnedfromtest) print("Hello world", end="\n test 123") a = True b = "How am I here?" print("\n", b[5:]) print(b[-5:]) print("\n", b[2], "\n") print('Message length of b is: ' + str(len(b)) + " \t long") print(id(a)) print(id(b)) if not a: print('False') else: print("\n", a) ages = [12, 13, 14, 69, 420, 'test123', ["electric", "and", "boogaloo"]] ages[0] = "electric boogaloo" print(ages[6][2]) print(ages) print(len(ages)) print(ages[1:3]) ages2 = ages[:] # do like this so when ages 2 is changed, it doesnt change the original ages2 = ages when ages2 is # changed, ages changes with it. also can do ages2 = ages() print('Hey whats your name?') name = input('Please enter your name:') print('Hi', name) thing1 = '1' thing2 = int(thing1) print(type(thing2)) thing3 = 10 print(str(thing3)) # have to put str in front if not string booltest = True if booltest: print('boolean is true') if not booltest: print('boolean is false') print('Hi, where do you live?') location = input('Please input location: ') if location == 'Texas': print('Welcome to texas') elif location == 'California' or location == 'Grand poggers': print('Im so sorry for you') else: print('Where again?') # elif is else if for x in ages: print(x) # x is the var that the number is put into # ages is where the info is located numbers = [3, 4, 5, 6] numberlist = 0 i = 0 for x in numbers: numberlist = +x i = +1 answer = numberlist / i print(str(answer)) for i in range(10, 100): print(str(i)) # 10 is included, 100 is not. Start at 10 end with 99 sum(range(10)) listofnumbers = [] for i in range(0, 10): listofnumbers.append(i) print(listofnumbers) listofnumbers2 = list(range(11)) print(listofnumbers2) for i in listofnumbers2: print(i) if i == 5: break print("What are you looking for?") number = input() for i in listofnumbers2: print(i) if i == number: print('Found ' + number) continue print("What are you looking for?") number = input() for i in listofnumbers2: print(i) if i == number: print('Found ' + number) break else: print("Not found") while i < 10: print(i) i += 1 # to multiply it by a power do **. Example below: nummmer = 10 print(nummmer ** 2) inputt = input("Please say 1, 2, 3, 4") if inputt == 1 or 2: print("You picked correct") else: print("Ok boomer") thing4 = "TEST" if not thing4.islower(): print(thing4.lower()) else: print(thing4) for gg in range(11): print("Iteration number " + str(gg)) for j in range(gg): print(j) def greet(name="User", benice=True): if name == "Ryan": print('Ellooooo') return "Hey man" if not benice: return 'Hey asshole. Your name is ' + name else: return 'Hey ' + name returned = greet("Roman") print(greet('Roman', False))
from collections import Counter lst = [] n = int(input("Enter number of elements : ")) for i in range(0, n): ele = input() lst.append(ele) lst for i in lst: names = i.split()[0] names ls = [] for i in lst: nm = i.split()[0] ls.append(nm) ls times = Counter(ls) rp = times.values() max_v = max(times.values()) max_v temp = [] for key, value in sorted(times.items()): if value == max_v: print(key, value)
""" This module creates a rudimentary form entering system within an ipython notebook and creates a food stack plot with the entered data. """ import ipywidgets as widgets from IPython.display import clear_output from stack_plotting import stack_plot, food_stack_plot # a list of lists of values to be plotted in each row plot_list = [] # a list of values to be plotted in a row row_vals = [] # set up all the widgets for the form colFood = widgets.Text( value='', placeholder='Type the food you\'d like to add', description='Food:', disabled=False ) colCals = widgets.Text( value='', placeholder='How many kCals does it have?', description='kCals:', disabled=False ) colCO2 = widgets.Text( value='', placeholder='How much CO2e does it produce?', description='CO2e:', disabled=False ) submit_button = widgets.Button( description='Add to stack plot', disabled=False, button_style='success', tooltip='Add to stack plot', icon='check' ) clear_button = widgets.Button( description='Clear form', disabled=False, button_style='warning', tooltip='Clear submitted values', icon='check' ) clearall_button = widgets.Button( description='Clear everything and start over', disabled=False, button_style='danger', tooltip='Clear everything', icon='check' ) # At this point, limiting users to only three columns def check_length(alist): if len(alist) == 3: print('Add {} with {} kCals and {} CO2e cost to stack plot?'.format( alist[1], alist[0], alist[2])) display(submit_button) if len(alist) > 3: print('You entered too many values! Try again.') row_vals.clear() display(colFood) # x: text widget object def add_to_foodlist(x): print('Adding food: {}, please enter kCals below...'.format(x.value)) row_vals.append(x.value) check_length(row_vals) display(colCals) def add_to_calslist(x): try: a = int(x.value) print('{} has {} kCals, please add CO2e below...'.format(row_vals[0], x.value)) row_vals.append(a) check_length(row_vals) display(colCO2) except ValueError: print('Please enter an integer value:') and display(colCals) def add_to_CO2list(x): try: a = int(x.value) row_vals.insert(0, a) check_length(row_vals) except ValueError: print('Please enter an integer value:') and display(colCO2) def submit_row(x): a = list(row_vals) plot_list.append(a) print('Added!') plot = food_stack_plot(["CO2e", "Food", "kCals"], plot_list) plot display(clearall_button) def clear_row(x): row_vals.clear() colFood.value = '' colCals.value = '' colCO2.value = '' print('Cleared.') clear_output() display(clear_button) display(clearall_button) display(colFood) def clear_all(x): row_vals.clear() plot_list.clear() colFood.value = '' colCals.value = '' colCO2.value = '' print('Reset all.') clear_output() display(clear_button) display(colFood) colFood.on_submit(add_to_foodlist) colCals.on_submit(add_to_calslist) colCO2.on_submit(add_to_CO2list) submit_button.on_click(submit_row) clear_button.on_click(clear_row) clearall_button.on_click(clear_all)
import random import socket import string import threading import json from packet import Packet, PacketType """ Chat Room Client Completed: Feb.10.2020 Written By: Michael Nichol & Bobby Horth Purpose: The purpose of this application is to connect to a localhost server, and allow the user chat with other connected clients through a series of commands. For simplicity, the client must be on the same computer of the server, but this can be changed to the same LAN by changing the 'SERVER' variable to the IP of the server host computer on the same network. Parameters: - None """ PORT = 54004 # Port is decided from last 4 digits of SID + 50000 DISCONNECT_MESSAGE = "bye" # Disconnect message determines when a user leaves the chat room SERVER = socket.gethostbyname(socket.gethostname()) # IP address of the server the client is attempting to connect to ADDR = (SERVER, PORT) # Address, port tuple # ======================================================= # Routine Name: sendPacket # Author: Michael Nichol & Bobby Horth # Date: 24.2.2020 # Purpose: Encodes and sends a generated packet from the client to the server # Parameters: # - data: packet contents # - destination: packet destination # - type: packet type # ======================================================= def sendPacket(data: str, destination: str, pType: PacketType): global CURRENT_PACKET, USERNAME, PACKETS_SENT # Create packet from provided arguments, enciphers the packet packet = Packet.createPacket(rot47(data), USERNAME, destination, pType, encryptionType="ROT47") # Store last packet sent in case it needs to be resent CURRENT_PACKET = packet # Increment packet count PACKETS_SENT += 1 # corrupt every 6th packet if PACKETS_SENT % 6 == 0: packet = packet.copy() # Just fill data with random character garbage packet['data'] = ''.join(random.choices(string.ascii_letters, k=10)) # Send packet to the client to_send = json.dumps(packet) client.send(to_send.encode()) # ======================================================= # Routine Name: sendPacket # Author: Michael Nichol & Bobby Horth # Date: 24.2.2020 # Purpose: Resends the last sent packet to the client # ======================================================= def resendPacket(): global CURRENT_PACKET, RESEND_PACKET # Mark that we've resent the packet RESEND_PACKET = False # Resend the last packet to_send = json.dumps(CURRENT_PACKET) client.send(to_send.encode()) # ======================================================= # Routine Name: awaitSend # Author: Michael Nichol & Bobby Horth # Date: 24.2.2020 # Purpose: Continuous loop that waits for messages the client sends to the server # Parameters: # - canSend a lock object representing whether the write thread can send a message # ======================================================= def awaitSend(canSend): global CONNECTED, RESEND_PACKET, CURRENT_PACKET, USERNAME # Initially acquire the canSend lock since we know we're allowed to send canSend.acquire() # User enters their preferred username USERNAME = input("Enter username: ") # Send username to server sendPacket(USERNAME, "", PacketType.username) # Wait until the lock is released so we know we can send another packet canSend.acquire() while CONNECTED: # If RESEND_PACKET boolean is true the read thread is telling us the last packet got corrupted and we must # resend if RESEND_PACKET: # Resend the packet and wait until we can send another packet via thread lock resendPacket() canSend.acquire() continue # User enters their message msg = input(USERNAME + ": ") # If message is the disconnect keyword, last message is sent and loop is terminated if msg == DISCONNECT_MESSAGE: CONNECTED = False sendPacket("", "", PacketType.disconnect) print("\n\nYou have disconnected from the chat.\n\n") # Debug break elif msg == "who": sendPacket("", "", PacketType.clientList) elif msg.count(":"): identifier = msg[:msg.index(":")] # Splits the string at the first colon to acquire message identifier if identifier == "all": sendPacket(msg[msg.index(":") + 1:], "", PacketType.broadcast) else: sendPacket(msg[msg.index(":") + 1:], msg[:msg.index(":")], PacketType.privateMessage) else: print("Invalid command.") continue # We just sent a packet so wait until the read thread tells us we can send another canSend.acquire() # ======================================================= # Routine Name: awaitRecieve # Author: Michael Nichol & Bobby Horth # Date: 24.2.2020 # Purpose: Continuous loop that waits for messages the server sends to the client # Parameters: # - canSend a lock object representing whether the write thread can send a message # ======================================================= def awaitReceive(canSend): global CONNECTED, RESEND_PACKET, CURRENT_PACKET while CONNECTED: jsonString = client.recv(1024).decode() if jsonString is None or jsonString == "": break while jsonString.find("}") != -1: bracketPos = jsonString.find("}") data = jsonString[:bracketPos + 1] jsonString = jsonString[bracketPos + 1:] packet = json.loads(data) # Gets the packet from the server message packet_length = len(packet) if packet['encryptionType'] == "ROT47": packet['data'] = rot47(packet['data']) # Decrypts the message using ROT47 if packet_length: # Checks if the message has substance verb = packet['verb'] # Obtains the verb from the packet to determine action # Below statement determines proper action, and formats output client-side if verb == "broadcast": print(f"(Broadcast) {packet['sender']}: {packet['data']}") elif verb == "private message": print(f"{packet['sender']}" + "-->You: " + packet['data']) elif verb == "client list": data_length = len(packet['data']) if data_length: print("List of Online Clients") print(f">> {packet['data']}") else: print("This chat room is empty") elif verb == "disconnect": print(f"{packet['sender']} has disconnected from the chat...") elif verb == "user not found": print("Destination or command not found...") elif verb == "valid packet": # Since we've received an acknowledgement from the server, let the write thread send another packet by # releasing the lock canSend.release() elif verb == "corrupted packet": # Since we've received an non-acknowledgement from the server, tell the write thread to resend the last # packet and release the lock RESEND_PACKET = True canSend.release() else: # Default case simply prints the data print(packet["data"]) def rot47(message): newString = [] for index in range(len(message)): # Iterates over the string charNum = ord(message[index]) # Finds the unicode value if 32 < charNum < 127: # If character is a ASCII value, rotate newString.append(chr(33 + ((charNum+14) % 94))) else: # Otherwise, append as is newString.append(message[index]) return "".join(newString) client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Creates the socket connection with the server client.connect(ADDR) CONNECTED = True # Represents whether or not the client is connected RESEND_PACKET = False # Represents whether or not the write thread should resend the last packet CURRENT_PACKET = None # Stores the last send packet USERNAME = "" # Stores the client's username PACKETS_SENT = 0 # Counts the total number of sent packets print("Welcome to the Chat Room\n" "All messages must be have prefix arg:message\n" "Arguments are:\n" " - 'all' send a message to the whole group\n" " - 'username' send a message to an individual\n" " - 'who' get a list of all connected client names\n" ) print(f"Enter {DISCONNECT_MESSAGE} to disconnect from the group chat\n") # Create a shared lock that determines whether or not the write thread can send a packet canSend = threading.Lock() # Begin separate read and write threads for the client, so the tasks are done simultaneously sendThread = threading.Thread(target=awaitSend, args=(canSend,)) recvThread = threading.Thread(target=awaitReceive, args=(canSend,)) sendThread.start() # Threads for the local client are started recvThread.start()
from plant import Plant class Tomato(Plant): 'This is the class that represents the tomato, being a child of class Tomato():' ######################################################## CLASS VARIABLES TOMATO_STAGES = ['Seedling','Growing','Flowering','Fruiting'] tomatoRid = 1 TOMATO_VARIETY = 'Fruit' TOMATO_FAMILY = 'Tomato' ######################################################## INTERNAL METHODS def __init__(self, tomatoName, tomatoPerPlant): # Plant.__init__(self, variety, family) # the same as 'super().__init__(variety, family)' Plant.__init__(self, Tomato.TOMATO_VARIETY, Tomato.TOMATO_FAMILY, tomatoName) # VARIABLES IN CLASS Plum(): self.size = 0 self.weight = 0 self.qty = tomatoPerPlant self.qtyFlag = False self._yield = 0 self.tomatoRid = Tomato.tomatoRid Tomato.tomatoRid += 1 self.stage = Tomato.TOMATO_STAGES[0] self.stageIndex = 0 self.eaten = 0 self.eatList = [] self.drunk = 0 self.drinkList = [] self.tanned = 0 self.tanList = [] # self.grew = 0 def __str__(self): return 'Tomato() ID:{}/{}/{}/{}/{}/{}'.format(self.tomatoRid, self.name, self.family, self.variety, self.birthday, self.get_age()) def __repr__(self): return "{}('{}',{})".format(self.__class__.__name__, self.name, self.qty) ######################################################## VALIDATION METHODS ######################################################## SETTER METHODS ######################################################## GETTER METHODS OR PROCEDURES def get_tomato_stages(self): return Tomato.TOMATO_STAGES def get_weight(self): return self.weight def get_size(self): return self.size def get_qty(self): return self.qty def get_yield(self): try: if self.qtyFlag: # print('getyield from if') return ( self.weight * self.qty ) else: # print('getyield from else') return self._yield except Exception as e: print(e) else: pass finally: pass # print('finnaly I function..') def get_qty_flag(self): return self.qtyFlag ######################################################## SPECIAL METHODS def speak(self, msg = ''): # return (Plant.speak(self, ', more specifically a {} tomato {}'.format(self.name, msg))) return (super().speak(', more specifically a {} tomato {}'.format(self.name, msg))) ######################################################## TESTS ######################################################## TESTS ######################################################## TESTS # t1 = Tomato('Cherry1','24') # # print(t1) # t2 = Tomato('Cherry2','24') # t3 = Tomato('Cherry3','24') # t4 = Tomato('Cherry4','24') # t5 = Tomato('Cherry5','24') # t6 = Tomato('Cherry6','24') # t7 = Tomato('Cherry7','24') # t8 = Tomato('Cherry8','24') # t9 = Tomato('Cherry9','24') # t0 = Tomato('Cherry0','24') # tAll = [t1, t2, t3, t4, t5, t6, t7, t8, t9, t0] # for t in tAll: # print(str(t)) # print(t0.speak()) # print(Plant.speak(t0, 'self.name')) # print(Plant.__bases__)
nome1 = input("digite seu nome: ") nome2 = input("digite seu nome: ") idade1 = int(input("digite a sua idade:")) idade2 = int(input("digite a sua idade:")) print("concatenado:", nome1,"e",nome2) print("somando:", idade1 + idade2) # Comentário para commit
""" window.py -- Defines functions to window an array of data samples """ ### ADD YOUR CODE AT THE SPECIFIED LOCATIONS ### import numpy as np ### Problem 1.d ### def SineWindow(dataSampleArray): """ Returns a copy of the dataSampleArray sine-windowed Sine window is defined following pp. 106-107 of Bosi & Goldberg, "Introduction to Digital Audio..." book """ ### YOUR CODE STARTS HERE ### N = np.size(dataSampleArray) nVec = np.linspace(0,N-1,N) nVec = np.add(nVec,0.5) arg = np.multiply(np.pi/N,nVec) window = np.sin(arg) dataOut = np.multiply(dataSampleArray,window) return dataOut ### YOUR CODE ENDS HERE ### def HanningWindow(dataSampleArray): """ Returns a copy of the dataSampleArray Hanning-windowed Hann window is defined following pp. 106-107 of Bosi & Goldberg, "Introduction to Digital Audio..." book """ ### YOUR CODE STARTS HERE ### N = np.size(dataSampleArray) nVec = np.linspace(0,N-1,N) nVec = np.add(nVec,0.5) arg = np.multiply((2.0*np.pi)/N,nVec) cosVec = np.cos(arg) window = np.add(0.5,np.multiply(-0.5,cosVec)) dataOut = np.multiply(dataSampleArray,window) return dataOut ### YOUR CODE ENDS HERE ### ### Problem 1.d - OPTIONAL ### def KBDWindow(dataSampleArray,alpha=4.): """ Returns a copy of the dataSampleArray KBD-windowed KBD window is defined following pp. 108-109 and pp. 117-118 of Bosi & Goldberg, "Introduction to Digital Audio..." book """ ### YOUR CODE STARTS HERE ### N = np.size(dataSampleArray) M = N/2.0 #for 50 percent overlap besselnVec = np.linspace(0,M,M+1) denom = np.i0(np.pi*alpha) besselnVec = np.subtract(besselnVec,M/2.0) besselnVec = np.square(np.divide(besselnVec,M/2.0)) rad = np.sqrt(np.subtract(1.0,besselnVec)) arg = np.multiply(np.pi*alpha,rad) num = np.i0(arg) window = np.divide(num,denom) #now perform window normalization on 'window' for 50% overlap win_sq = np.square(window) #nVecWindow = np.linspace(0,N-1,N) win_sq_top = win_sq[0:np.size(win_sq)-1] win_sq_bot = win_sq[1:np.size(win_sq)] #for the top portion of the guide #from n=0,...,N/2 - 1s nVecTop = np.linspace(0,(N/2.0) - 1, (N/2.0)) topSize = np.size(nVecTop) denom = np.sum(win_sq) onesy = np.ones((topSize,topSize)) lowTri = np.tril(onesy) #will be used to compute the summing of top nVecTopOut = np.dot(lowTri,win_sq_top) nVecTopOut = np.sqrt(np.divide(nVecTopOut,denom)) #now do the bottom of the piecewise #note the triangularity of the matrix is reversed, now we want to use upper triangular nVecBot = np.linspace((N/2.0),N-1,(N/2.0)) botSize = np.size(nVecBot) onesy = np.ones((botSize,botSize)) upTri = np.triu(onesy) nVecBotOut = np.dot(upTri,win_sq_bot) nVecBotOut = np.sqrt(np.divide(nVecBotOut,denom)) #concatentate top and bottom norm_windowOut = np.concatenate((nVecTopOut,nVecBotOut)) dataOut = np.multiply(dataSampleArray,norm_windowOut) return dataOut ### YOUR CODE ENDS HERE ### """----------------------------------------EDIT--------------------------------------------------""" def TransitionWindow(dataSampleArray,a,b): """ Reutrns a copy of the dataSampleArray transition windowed by the window WindowDef. The AC-2A trasition window utilized is defined following pp. 135-136 of Bosi & Goldberg, "Introduction to Digital Audio..." book """ # Window the first 'a' samples with a window of length 2*a aExtension = np.zeros(a) leftWindowed = KBDWindow(np.append(dataSampleArray[:a],aExtension)) # Window the following 'b' samples with a window of length 2*b bExtension = np.zeros(b) rightWindowed = KBDWindow(np.append(bExtension,dataSampleArray[a:])) # Combine the windowed samples into one signal windowedData = np.append(leftWindowed[:a],rightWindowed[b:]) return windowedData """------------------------------------END-EDIT--------------------------------------------------""" #----------------------------------------------------------------------------- #Testing code if __name__ == "__main__": ### YOUR TESTING CODE STARTS HERE ### pass # THIS DOES NOTHING ### YOUR TESTING CODE ENDS HERE ###
def shout(word): if word == "french toast": return word.upper() elif word == "candy": return word else: return word.lower()
import threading i = 0 def increment_i(): global i for _ in range(1000*1000): i = i+1 def decrement_i(): global i for _ in range(1000*1000): i = i-1 def main(): # Configure threads increment_thread = threading.Thread(target=increment_i) decrement_thread = threading.Thread(target=decrement_i) # Start threads increment_thread.start() decrement_thread.start() # Wait for threads to terminate increment_thread.join() decrement_thread.join() # Print i global i print(i) main()
# Project Euler problem 98. import csv import re import numpy import itertools import string # Check if two strings are anagrams def isAna(st1, st2): return (sorted(st1) == sorted(st2)) # Read in data dat = [] with open('words2.txt','rb') as csvfile: spamreader = csv.reader(csvfile) for row in spamreader: dat.append(row) # Find commas in data dat = str(dat) cms = [] p = re.compile(",") for m in p.finditer(dat): cms.append(m.start()) #print m.start(), m.group() # Build a list of words words = ['A'] # build a list of words for i in xrange(0,len(cms)-1): words.append(str(dat[cms[i]+3:cms[i+1]-1])) awords = numpy.array(words) alens = map(len,awords) # Sort words by size atb = [] # atb[i][j] is jth word with length i for i in xrange(0,max(alens)): tpr = [] for j in xrange(0,len(awords)): if alens[j]==i: tpr.append(awords[j]) atb.append(tpr) # Find anagram pairs and store them in angwrd angwrd = [] for k in xrange(1,len(atb)): tplst = atb[k][:] for i in tplst: for j in tplst: if i!=j and isAna(i,j) is True: angwrd.append([i,j]) # Remove duplicates pairs tpres = map(sorted,angwrd) tpres.sort() flst = tpres[1::2] # Substitute values into flst eps = 1e-10 mxsqr = [] for k in xrange(1,len(flst)): # find unique chrs tpchrs = list(set([flst[k][0][x] for x in xrange(0,len(flst[k][0]))])) #list of all possible permutations of letters pms = list(itertools.permutations(xrange(0,10),len(tpchrs))) print k,flst[k] for j in xrange(0,len(pms)): flstp1 = flst[k][0] flstp2 = flst[k][1] for i in xrange(0,len(pms[0])): flstp1 = str(flstp1).replace(tpchrs[i],str(pms[j][i])) flstp2 = str(flstp2).replace(tpchrs[i],str(pms[j][i])) if (int(flstp1[0]) is not 0) and (int(flstp2[0]) is not 0): sq1 = numpy.sqrt(float(flstp1)) sq2 = numpy.sqrt(float(flstp2)) tst1 = numpy.abs(sq1-numpy.round(sq1)) tst2 = numpy.abs(sq2-numpy.round(sq2)) if (tst1 < eps) and (tst2 < eps): mxsqr.append(max(int(flstp1),int(flstp2))) # DEBUG LINE print max(int(flstp1),int(flstp2)), flstp1, flstp2 print "Max Square is %r" %(max(mxsqr))
#Crie um programa que leia um número real qualquer e mostre na tela a sua porção inteira. #Autor: Daniel Marques from math import trunc print("\nARRENDODAMENTO SUPERIOR") a = float(input("\nNúmero: ")) print("\nPORÇÃO INTEIRA: {}".format(trunc(a)))
#Escreva um programa que pergunte a quantidade de kilômetros percorridos por um carro alugado e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa 600 reais por dia e 0.15 reais por kilmetros rodados.^ print("\nALUGUEL DE CARROS") d = float(input("\nDias: ")) km = float(input("\nKm: ")) dia = 60 * d kilometro = km * 0.15 print("\nValor à pagar:",kilometro + dia)
# Time: O(n) # Space: O(1) def reverse(string): return ''.join([string[i] for i in range(len(string)-1, -1, -1)]) # More Pythonic, and includes the null-termination # Time: O(n) # Space: O(1) def reverse(string): return string[-2::-1] + '\0'
# Time: O(n) # Space: O(n) def all_unique(string): character = {} for char in string: if character.get(char): return False return True # Time: O(n^2) # Space: O(1) def all_unique2(string): for i, char in enumerate(string): for other_char in string[i+1:]: if char == other_char: return False return True
# Doubly Linked List Queue ''' In the Queue Adjust the tail when adding item Adjust the head when removing item ''' #n1 = bldg.head #lowest floor #n10 = bldg.tail #highest floor from node import DNode class Queue: def __init__(self): self.head = None self.tail = None # This method adds item to the queue def add(self,item): if self.head == None: #If the queue is empty self.head = item self.tail = item else: self.tail.next = item # establish the link from this item to the current tail item item.previous = self.tail # change the tail to point to this item self.tail = item def append(self, data): if self.head is None: new_node = DNode(data) new_node.prev = None self.head = new_node else: new_node = DNode(data) cur = self.head while cur.next: cur = cur.next cur.next = new_node new_node.prev = cur new_node.next = None # This method removes the item to the queue def remove(self,item): item = self.head # temporarily save the head to item print('Removing ...',item.data) # adjust the head to point to the next item in Queue self.head = item.next #self.head.previous = None return item # This method checks if the queue is empty def isEmpty(self): if self.head == None: return True else: return False def insert(self, item, position): nodeN = self.getItem(DNode(position)) nodeP = nodeN.previous item.next = nodeN nodeP.next = item nodeN.previous = item item.previous = nodeP def getCount(self): temp = self.head # Initialise temp count = 0 # Initialise count # Loop while end of linked list is not reached while (temp): count += 1 temp = temp.next return count def sortedInsert(self, new_node): # Special case for the empty linked list if self.head is None: new_node.next = self.head self.head = new_node # Special case for head at end elif int(self.head.data) >= int(new_node.data): new_node.next = self.head self.head = new_node else : # Locate the node before the point of insertion current = self.head while(current.next is not None and int(current.next.data) < int(new_node.data)): current = current.next new_node.next = current.next current.next = new_node ## def delete(self,item): ## item = self.getItem(DNode(item)) ## nodep = item.previous ## noden = item.next ## nodep.next = noden ## noden.previous = nodep ## return item def delete(self, key): cur = self.head while cur: if cur.data == key and cur == self.head: # Case 1: if not cur.next: cur = None self.head = None return # Case 2: else: nxt = cur.next cur.next = None nxt.previous = None cur = None self.head = nxt return elif cur.data == key: # Case 3: if cur.next: nxt = cur.next previous = cur.previous previous.next = nxt nxt.previous = previous cur.next = None cur.previous = None cur = None return # Case 4: else: previous = cur.previous previous.next = None cur.previous = None cur = None return cur = cur.next def delete_node(self, node): cur = self.head while cur: if cur == node and cur == self.head: # Case 1: if not cur.next: cur = None self.head = None return # Case 2: else: nxt = cur.next cur.next = None nxt.previous = None cur = None self.head = nxt return elif cur == node: # Case 3: if cur.next: nxt = cur.next previous = cur.previous previous.next = nxt nxt.previous = previous cur.next = None cur.previous = None cur = None return # Case 4: else: previous = cur.previous previous.next = None cur.previous = None cur = None return cur = cur.next def remove_duplicates(self): cur = self.head seen = dict() while cur: if cur.data not in seen: seen[cur.data] = 1 cur = cur.next else: nxt = cur.next self.delete_node(cur) cur = nxt def getItem(self, item): node = self.head while node.next != None: if node.data == item.data: return node node = node.next # Function to insert a new node at the beginning def push(self, new_data): new_node = DNode(new_data) new_node.next = self.head self.head = new_node # Utility function to print it the linked LinkedList def printList(self): temp = self.head while(temp): print (temp.data) temp = temp.next class Building(): def __init__(self,floors): self.__floors = floors def getFloors(self): return self.__floors class Elevator(): def __init__(self): self.currentfloor=0 self.elevatorstatus= bldg.head.data def set_elevatorStatus(self,s): self.elevatorstatus=s def get_elevatorStatus(self): return self.elevatorstatus class Request(): def __init__(self): # super.__init__(self) self.direction= 0 self.requestedfloor=0 self.currentfloor=0 def set_currentFloor(self,c): self.currentfloor=c def get_currentFloor(self): return self.currentfloor def set_Direction(self,d): self.direction=d def get_Direction(self): #0=down , 1=up if self.direction == 0: return "down" if self.direction == 1: return "up" def set_RequestedFloor(self,f): self.requestedfloor =f def get_RequestedFloor(self): return self.requestedfloor queue = Queue() #bldg = Building() floors=int(input("How many floors does this bulding have?")) #Sets floor 1 as lobby, floor will be range total_floors=Building(floors) new_node = DNode(int(1)) queue.sortedInsert(new_node)#This will be the lobby flag = 'y' while flag == 'y': floorrequest=int(input("What floor do you want to go to?")) #Conditional Statement to remove redundancies # if floorrequest == data #Conditonal Statement for request to not be higher than number than floors # if floorrequest >> floor... return try again. new_node = DNode(int(floorrequest)) queue.append(int(floorrequest)) queue.sortedInsert((new_node)) #queue.remove_duplicates() flag = input("Do you want to add a floor request :") print ("Create Linked List") queue.printList() queue.remove_duplicates() print ("Create Linked List After Removing Duplicates") queue.printList() print("Sort Request and add top floor") queue.sortedInsert(int(floors)) queue.printList() marshall=queue.getCount() print("Number of Nodes", marshall)
import os menu_print = "¿Qué desea hacer?\n1) Insertar Usuario\n2) Buscar Usuario\n3) Actualizar Usuario\n4) Eliminar Usuario\n5) Mostrar todos\n6) Salir del menú" #aux = {"cedula": 0, "nombre": "", "apellidos": "", "direccion": ""} menu = True def menu(seleccion:int): if seleccion ==1: insertar() elif seleccion==3: actualizar() elif seleccion ==4: borrar() else: select_all() def buscar(cedula:str=""): contador = 0 with open('prueba.txt', 'r') as archivo: for linea in archivo.readlines(): aux = linea.split(";") if aux[0]==cedula: contador +=1 print(f"Cedula: {aux[0]} | Nombre: {aux[1]} | Apellidos: {aux[2]} | Dirección: {aux[3]}") else: continue if contador ==0: print("El usuario que busca no se encuentra registrado") return aux def select_all(): with open('prueba.txt') as archivo: lineas = archivo.readlines() for linea in lineas: aux = linea.split(";") print(f"Cedula: {aux[0]} | Nombre: {aux[1]} | Apellidos: {aux[2]} | Dirección: {aux[3]}") def insertar(): cedula = input("Ingrese la cédula de la persona: ") nombre = input("Ingrese el nombre de la persona: ") apellidos = input("Ingrese apellidos de la persona: ") direccion = input("Ingrese la direccion de la persona: ") with open('prueba.txt','a') as archivo: tupla = cedula,nombre,apellidos,direccion cadena = ";".join(tupla) archivo.write(cadena+"\n") print("usuario ingresado con exito") def actualizar(): contador = 0 lineas = [] cedula = input("Ingrese la cédula de la persona para actualizar: ") persona = [] persona.append(cedula) persona2 = buscar(cedula) aux = int(input("¿Que valor desea actualizar ?\n1) Nombre\n2) Apellido\n3) Direccion\n4) Todos los anteriores ")) if aux ==1: nombre = input("Ingrese el nombre de la persona: ") persona.append(nombre) persona.append(persona2[2]) persona.append(persona2[3]+'\n') elif aux ==2: apellidos = input("Ingrese apellidos de la persona: ") persona.append(persona2[1]) persona.append(apellidos) persona.append(persona2[3]+'\n') elif aux==3: direccion = input("Ingrese la direccion de la persona: ") persona.append(persona2[1]) persona.append(persona2[2]) persona.append(direccion+'\n') elif aux == 4: nombre = input("Ingrese el nombre de la persona: ") apellidos = input("Ingrese apellidos de la persona: ") direccion = input("Ingrese la direccion de la persona: ") persona.append(nombre) persona.append(apellidos) persona.append(direccion) with open('prueba.txt','r') as archivo: for linea in archivo.readlines(): persona_aux = linea.split(";") if persona_aux[0]!=cedula: lineas.append(persona_aux) else: lineas.append(persona) with open('prueba.txt','w') as archivo: for linea in lineas: ingreso = ';'.join(linea) #print(type(ingreso)) archivo.write(ingreso) def borrar(): cedula = input("ingrese la cédula: ") contador = 0 aux = 0 lineas = [] with open('prueba.txt','r') as archivo: for linea in archivo.readlines(): contador+=1 persona = linea.split(";") if persona[0]!=cedula: lineas.append(persona) with open('prueba.txt','w') as archivo: for linea in lineas: ingreso = ';'.join(linea) archivo.write(ingreso) while menu: print(menu_print) try: seleccion = int(input("Ingrese un numero de acuerdo a la acción que desea realizar ")) os.system('cls') if seleccion ==6: menu = False elif seleccion == 2: cedula = input("Ingrese la cedula: ") persona = buscar(cedula) elif seleccion<1 or seleccion>5: raise ValueError("Ingrese un número entre 1 y 4 dependiendo la acción que desea realizar ") else: menu(seleccion) except ValueError as ve: print("Ingrese un valor válido-->"+ve) except Exception as ex: print(f"Error -> {ex}")
import numpy as np matriz= [[4,3],[3,4],[6,8]] #filas y columnas m(i,j) for i in range(3): for j in range(2): print(matriz[i][j]) #numpy es una biblioteca para soporte de vectores y matrices en python # a.shape --> me da la longitud de la matriz-
from ConstraintSatisfactionProblem import ConstraintSatisfactionProblem class CircuitBoardProblem(ConstraintSatisfactionProblem): def __init__(self, variables, board, mrv=False, lcv=False, mac=False): self.variables = variables self.domains = self.build_domains(board) self.constraints = self.build_constraints(board) self.mrv = mrv self.lcv = lcv self.mac = mac self.nodes_visited = 0 self.BOARD = board self.nodes_explored = 0 self.num_of_inconsistency = 0 # The domain for each component would be a set of possible coordinates of the component's bottom-left corner. def build_domains(self, board): domains = {} for v in range(len(self.variables)): domains[v] = set() x = len(board) - len(self.variables[v]) y = len(board[0]) - len(self.variables[v][0]) for i in range(x + 1): for j in range(y + 1): domains[v].add((i, j)) return domains # The constraint for each pair of component pieces is a set of possible coordinates of the two pieces # within each's domain where the two pieces do not overlap. def build_constraints(self, board): constraints = {} for i in range(len(self.variables)): for j in range(len(self.variables)): constraints[(i, j)] = set() v_1 = self.variables[i] v_2 = self.variables[j] if v_1 == v_2: continue for d_1 in self.domains[i]: for d_2 in self.domains[j]: upperbound_x = max(d_1[0] + len(v_1), d_2[0] + len(v_2)) upperbound_y = max(d_1[1] + len(v_1[0]), d_2[1] + len(v_2[0])) lowerbound_x = min(d_1[0], d_2[0]) lowerbound_y = min(d_1[1], d_2[1]) if (upperbound_x - lowerbound_x >= len(v_1) + len(v_2)) or (upperbound_y - lowerbound_y >= len(v_1[0]) + len(v_2[0])): if upperbound_x <= len(board) and upperbound_y <= len(board[0]): constraints[(i, j)].add((d_1, d_2)) return constraints def solve(self): solution = self.backtrack_search() return solution def __str__(self): solution = self.solve() if solution is None: return "No solution exists" board = [['.' for i in range (len(self.BOARD[0]))] for j in range((len(self.BOARD)))] for key in solution.keys(): for x in range(len(self.variables[key])): for y in range(len(self.variables[key][0])): x_index = x + solution[key][0] y_index = y + solution[key][1] board[x_index][y_index] = self.variables[key][x][y] res = "MRV=" + str(self.mrv) + " LCV=" + str(self.lcv) + " MAC-3=" + str(self.mac) + "\n" res += "Number of nodes visited : " + str(self.nodes_visited) + "\n" res += "Number of nodes explored : " + str(self.nodes_explored) + "\n" res += "Number of Inconsistencies Encountered : " + str(self.num_of_inconsistency) + "\n" for j in range(len(board[0]) - 1, -1, -1): for i in range(len(board)): res += board[i][j] res += '\n' return res
""" Module containing class DenseSymmMatrix representing a dense symmetric matrix and various operations on it. """ import numpy as np from numpy import linalg as la import time import copy import numbers from numbers import Number class DenseSymmMatrix(object): """ Class for dense symmetric matrix """ def __init__(self, inp = 0): """ Initialize matrix :param int, optional n: size :returns: symmetric matrix :rtype: DenseSymmMatrix """ if type(inp) is int: if inp < 0: raise ValueError('Matrix size has to be non-negative') self.rand_symm_matrix(inp) self.size = inp else: raise ValueError('Input type should be int') def copy(self): """ Create a copy of a matrix. :returns: symmetric matrix :rtype: DenseSymmMatrix """ return copy.deepcopy(self) def __len__(self): """ Get matrix size :returns: matrix size :rtype: int """ return self.size def set_matrix(self, A): """ Create a DenseSymmMatrix from a given input: * if A is numpy.matrix or numpy.ndarray: create matrix containing data from the array * if A is list: create diagonal matrix with a diagonal from a list :param A: matrix or matrix diagonal :returns: symmetric matrix :rtype: DenseSymmMatrix """ if type(A) is np.matrix: self.X = A.copy() (n,m) = A.shape assert(n==m) self.size = n else: if type(A) is np.ndarray: (n,m) = A.shape assert(n==m) self.size = n self.X = np.matrix(A) else: if type(A) is list: self.X = np.diag(A) self.size = len(A) else: raise ValueError('Input type should be np.matrix, np.ndarray or list') def get_matrix(self): """ Get matrix as an numpy.array :returns: matrix :rtype: numpy.array """ return np.asarray(self.X).copy() def rand_symm_matrix(self, n): """ Generate random symmetric matrix :param int n: matrix size :returns: random symmetric matrix :rtype: DenseSymmMatrix """ self.X = np.matrix(np.random.rand(n,n)) self.X = np.tril(self.X) + np.tril(self.X, -1).T self.size = n def rand_symm_matrix_given_eig(self, D): """ Generate random symmetric matrix with a given eigenvalues :param list D: desired eigenvalues :returns: random symmetric matrix :rtype: DenseSymmMatrix :raise LinAlgError: if qr factorization fails """ n = len(D) A = np.matrix(np.random.rand(n, n)) try: Q, R = np.linalg.qr(A) except(LinAlgError): print("rand_symm_matrix_given_eig: QR factorization failed") sys.exit() self.X = np.dot(np.dot(Q, np.diag(D)), Q.T) self.size = n def msquare(self): """ Compute matrix square :returns: matrix square :rtype: DenseSymmMatrix """ Xsq = DenseSymmMatrix() Xsq.X = np.dot(self.X, self.X) Xsq.size = self.size return Xsq def mtrace(self): """ Compute matrix trace :returns: matrix trace :rtype: float """ return np.trace(self.X); def mnorm2_diff(self, Y): """ Compute spectral norm of the matrix difference :param array_like Y: input matrix :returns: spectral norm of the matrix difference :rtype: float """ return la.norm(self.X-Y.X, 2); def mnormF_diff(self, Y): """ Compute Frobenius norm of the matrix difference :param array_like Y: input matrix :returns: Frobenius norm of the matrix difference :rtype: float """ T = self.X-Y.X return la.norm(T, 'fro') def get_eigv(self): """ Compute eigenvalues and eigenvectors of the matrix. :returns: tuple (eigenvalues, eigenvectors) :rtype: tuple """ # eigh: return the eigenvalues and eigenvectors of a Hermitian or symmetric matrix. return la.eigh(self.X) def __add__(self, V): if type(V) is DenseSymmMatrix: R = DenseSymmMatrix() R.X = self.X+V.X; R.size = self.size return R else: raise TypeError("Input should be DenseSymmMatrix") def __sub__(self, V): if type(V) is DenseSymmMatrix: R = DenseSymmMatrix() R.X = self.X-V.X; R.size = self.size return R else: raise TypeError("Input should be DenseSymmMatrix") def __mul__(self, v): if type(v) is int: R = DenseSymmMatrix() if v == 2: # use BLAS R.X = self.X+self.X else: R.X = v*self.X R.size = self.size return R else: if type(v) is DenseSymmMatrix: M = DenseSymmMatrix() M.X = np.dot(v.X,self.X) M.size = self.size return M else: raise TypeError("Input should be a number") return None def __rmul__(self, v): if type(v) is int: R = DenseSymmMatrix() if v == 2: # use BLAS R.X = self.X+self.X else: R.X = self.X*v R.size = self.size return R else: if type(v) is DenseSymmMatrix: M = DenseSymmMatrix() M.X=np.dot(self.X,v.X) M.size = self.size return M else: raise TypeError("Input should be a number") return None
import numpy as np import math #from Location import Location def get_random_location(): return [np.random.uniform(-90, 90), np.random.uniform(-180, 180)] def get_distance_between_two_locations(location1, location2): """ To get the distance between two locations. We use the 'haversine' formula to calculate the great-circle distance between two points. Returns the value in KM """ R = 6371e3 #Radius of the earth on meters l1 = math.radians(location1.latitude) l2 = math.radians(location2.latitude) dif_lat = math.radians(location2.latitude - location1.latitude) dif_long = math.radians(location2.longitude - location1.longitude) a = ((math.sin(dif_lat/2) * math.sin(dif_lat/2)) + (math.cos(l1) * math.cos(l2)) * (math.sin(dif_long/2) * math.sin(dif_long/2))) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a)) d = R * c d = d / 1000 #Convert meters to kilometers #print(str(d) + " KM") #print("Rounded:",str(d),"KM") return round(d) """ mexico = Location(getRandomLocation()) usa = Location(getRandomLocation()) print("Mexico location:", mexico.location) print("USA location:", usa.location) print("Distance between two points:", get_distance_2_locations(mexico, usa)) """
'''Detector de velocidade''' print('lembrando que a velocidade máxima permitida é de 60km/h') vel = float(input('Digite a velocidade do veículo: ')) exc = vel - 60 multa = exc * 7 if vel >60: print('O veículo recebeu uma multa de R$7,00 por kilômetro ultrapassado') print('Sua multa foi de R${} reais'.format(multa)) else: print('O veículo está dentro da velocidade permitida')
import numpy as np a=np.array(input('Enter any array:')) b=np.array(input('Enter another array:')) c=np.linalg.det(a) print('Det of a matrix a',c) d=np.linalg.matrix_rank(a) print('Rank of a matrix a',d) e=np.trace(a) print('Trace of a matrix a',e) f=np.linalg.inv(a) print('Inverse of a matrix a',f) g=np.linalg.eigvals(a) print('Eigen values of a matrix a',g) h=np.linalg.matrix_power(a,4) print('Matrix Power of a matrix a',h) j=np.add(a,b) print('Addition of two matrices',j) i=np.subtract(a,b) print('Subtraction of two matrices',i) k=np.multiply(a,b) print('Element by element multiplication of two matrices',k) l=np.dot(a,b) print('Multiplication of two matrices',l) m=np.divide(a,b) print('Element by element division of two matrices',m) n=np.linalg.solve(a,b) print('Solution of linear equations',n) o=np.linalg.qr(a) print('qr decomposition of matrix',o)
#an implementation of the single-dimensional parity check #by: Rayven Ingles, BSCS 4 #completed as a lab exercise for CMSC 137 def check_input(input_string) : ###loop through input string### for character in input_string: if not (character == "0" or character == "1"): print("Input must be a bit string!") input_string input("> Input again: ") check_input(input_string) ### ask for user input ### a = input("> Input A: ") check_input(a) while len(a) != 8: print("Input a must be an 8-bit string!") a = input("> Input A: ") check_input(a) b = input("> Input B: ") check_input(b) while len(b) != 9: print("Input b must be a 9-bit string!") b = input("> Input A: ") check_input(b) one_count=0 for character in a: if(character == '1'): one_count+=1 if((one_count % 2)==1): parity = "1" else: parity = "0" codeword = a+parity ###calculate syndrome### one_count=0 for character in b: if(character == '1'): one_count+=1 if((one_count % 2)==1): accept_status = "discarded" print("@Sender\n"+codeword) if((one_count % 2)==1): accept_status = "discarded" else: accept_status = b[0:8] print("@Receiver\nData Word:"+accept_status)
# Task: we've created Series containing the various variables we've been looking at this lesson. # Pick a country you're interested in and make a plot of each variable over time %pylab inline import pandas as pd import seaborn as sns #import matplotlib.pyplot as plt employment = pd.read_csv('/home/hayley/Documents/Data Analysis/employment_above_15.csv', index_col = 'Country') female_completion = pd.read_csv('/home/hayley/Documents/Data Analysis/female_completion_rate.csv', index_col = 'Country') male_completion = pd.read_csv('/home/hayley/Documents/Data Analysis/male_completion_rate.csv', index_col = 'Country') life_expectancy = pd.read_csv('/home/hayley/Documents/Data Analysis/life_expectancy.csv', index_col = 'Country') gdp = pd.read_csv('/home/hayley/Documents/Data Analysis/gdp_per_capita.csv', index_col = 'Country') employment_us = employment.loc['Brazil'] female_completion_us = female_completion.loc['Brazil'] male_completion_us = male_completion.loc['Brazil'] life_expectancy_us = life_expectancy.loc['Brazil'] gdp_us = gdp.loc['Brazil'] plt.hist(life_expectancy_us) life_expectancy_us.plot() # STILL NEED TO SEE WHY SEABORN DOESN'T SEEM TO WORK!!!
import pandas as import pd countries = [ 'Afghanistan', 'Albania', 'Algeria', 'Angola', 'Argentina', 'Armenia', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bhutan', 'Bolivia', 'Bosnia and Herzegovina', ] employment_values = [ 55.70000076, 51.40000153, 50.5 , 75.69999695, 58.40000153, 40.09999847, 61.5 , 57.09999847, 60.90000153, 66.59999847, 60.40000153, 68.09999847, 66.90000153, 53.40000153, 48.59999847, 56.79999924, 71.59999847, 58.40000153, 70.40000153, 41.20000076, ] # Employment data in 2007 for 20 countries employment = pd.Series(employment_values, index=countries) # idxgmax function (previously argmax) in a Pandas series returns the index where the maximum value occurs def max_employment(employment): max_country = employment.idxmax() max_value = employment.max() return(max_country, max_value) print(max_employment(employment))
a = '3' b = '1' c = 6 d = 2 if b > a: print(c + d, end=',') print(a + b) else: if a == b: print(a, d) else: print(a,b,c,d, sep='')
from tkinter import * from tkinter import messagebox #funciones def agregar(): print() #UI ventana = Tk() nombrePeluche = StringVar() cantidadPeluche = IntVar() precioPeluche = DoubleVar() ventana.geometry("400x400") ventana.title("Peluchitos.com") tituloLabel = Label(ventana, text="Peluchitos.com").place(relx=0.5, y=10, anchor=CENTER) nombreLabel = Label(ventana, text="Nombre del Peluche: ").place(x=10, y=40) nombreEntry = Entry(ventana, textvariable=nombrePeluche).place(x=160, y=40) cantidadLabel = Label(ventana, text="Cantidad del Peluche: ").place(x=10, y=70) cantidadEntry = Entry(ventana, textvariable=cantidadPeluche).place(x=160, y=70) precioLabel = Label(ventana, text="Precio del Peluche: ").place(x=10, y=100) precioEntry = Entry(ventana, textvariable=precioPeluche).place(x=160, y=100) AgregarButton = Button(ventana, text="Agregar", command=agregar).place(x=10, y=130) ventana.mainloop()
food='カレーライス' if 'カレー' in food: print('カレーが含まれています') food2='すし' if not 'カレー' in food2: print('カレーが含まれていません') if 'カレー' not in food2: print('カレーが含まれていませんね') score=80 if 60 < score < 80: pass isError=False n=50 if isError==False and n<100: pass num=2 if num%2==0: print('偶数') aisatsu='さようなら' if aisatsu=='こんにちは': print('ようこそ!') elif aisatsu=='景気は?': print('ぼちぼちです') elif aisatsu=='さようなら': print('お元気で'); month=int(input('今は何月ですか?(数字を入力)>>')) if month in [1,3,5,7,8,10,12]: print('31日までありますね') else: if month !=2: print('30日までですね') else: print('1年で一番寒い月ですね') print('年が明けてから') print('{}カ月が過ぎました'.format(month)) number=10 div= '偶数' if number % 2==0 else '奇数' print(div) result='優' if score>=80 else '良' if score>=60 else '可' if score>=40 else '不可'
def sumof2(n): return sum(range(1,n+1)) def sumof3(n): if n <1: return n else: return n+sumof3(n-1) num=int(input('正の整数')) ans=sumof3(num) print(ans)
is_awake=True count=0 while is_awake == True: count +=1 print('ひつじが{}匹'.format(count)) key=input('もう眠りそうですか?(y/n)>>') if key =='y': is_awake=False print('おやすみなさい')
import random as r i=0 input('Enterで対決開始[Enter]') while True: you_dice=[r.randint(1,6) for i in range(3)] pc_dice=[r.randint(1,6) for i in range(3)] print('あなたの出目') print(you_dice) print('コンピューターの出目') print(pc_dice) you_sum=0 pc_sum=0 for i in range(len(you_dice)): you_sum+=you_dice[i] for i in range(len(pc_dice)): pc_sum+=pc_dice[i] win_lose='' yous=set(you_dice) pcs=set(pc_dice) if len(yous)==1: you_sum*=2 if len(pcs)==1: pc_sum*=2 if you_sum>pc_sum: win_lose='あなたの勝ち' elif you_sum<pc_sum: win_lose='あなたの負け' else: win_lose='あいこ' print(f'{you_sum}対{pc_sum}で{win_lose}') select=input('もう一度対決しますか?<y/n>>>') if select=='n': break print('対決を終了します')
def eat(breakfast,lunch='ラーメン',dinner='カレー'): print('朝は{}を食べました'.format(breakfast)) print('昼は{}を食べました'.format(lunch)) print('夜は{}を食べました'.format(dinner)) print('8月1日') eat('トースト','おにぎり') print('8月2日') eat('トースト',dinner='やきそば') print('8月3日') eat('バナナ','そば','焼肉') print('8月4日') eat('トースト')
ages=[28,50,8,20,'ひみつ',78,25,'無回答',22,10,27,33] samples=list() for age in ages: if not isinstance(age,int): continue if 20 <= age < 30: samples.append(age) print(samples)
import random COINS=200 TW=5 table=[] def createTable(): global table table=[[random.randint(0,9) for j in range(TW)]for i in range(TW)] for row in table: print(row) #createTable() def countBingoLine(): global table vertical=[[table[j][i] for j in range(TW)]for i in range(TW)] cross=[[table[j][j] if i==0 else table[j][TW-1-j] for j in range(TW)]for i in range(2)] bingo_line=0 for row in table+vertical+cross: if len(set(row))==1: bingo_line+=1 return bingo_line while True: print(f'残り枚数:{COINS}') #bet=int(input(f'BET枚数を入力。1-{COINS}>>')) bet=1 if bet==0: break if bet>COINS: print('コインが不足してます') continue COINS -=bet createTable() bingo_line=countBingoLine() if bingo_line>0: get_coin=bingo_line*12*bet COINS+=get_coin print(f'{bingo_line} LINE BINGO !win:{get_coin}') else: print('boo') if COINS==0: print('コインがなくなりました') break print('Game Over')
#! /usr/bin/python print "Hello" printLine = """ Printing the whole text without changing the indentation. printing multiple lines without changing anything """ print printLine calculation = 10 + 2 - 3 / 2 print "Calculation is : %d " % calculation def function1(myString, myNum): print "String sent to function is : %s and digit sent is %d " % (myString, myNum) retString = "Hello" + myString retNum = myNum + 2 return retString, retNum getString, getNum = function1("Shubham", 2) print "String returned is : %s and number returned is : %d" % (getString, getNum)
#! /usr/bin/python number = [1, 2, 3, 4, 5] fruits = ['apple', 'orange', 'papaya', 'grapes', 'banana'] change = [1, 'roti', 2, 'kapda', 3, 'makan'] for num in number : print "Number is %d" % num for fruit in fruits : print "Fruit currentley selected is : %s" % fruit for i in change : print "I is %r" % i elements = [] for i in range (0, 10) : print "Appending %d " % i elements.append(i) for i in elements : print "Element is : %d " % i
# Name: Max Voisard # Class: Programming with Python CIT248S # Date: 4/4/2017 # Assignment: Chapter 9 Programming Challenge roomNumber = {'CS101':'3004', 'CS102':'4501', 'CS103':'6755', 'NT110':'1244', 'CM241':'1411'} # Creating dictionary for course number's room numbers instructor = {'CS101':'Haynes', 'CS102':'Alvarado', 'CS103':'Rich', 'NT110':'Burke', 'CM241':'Lee'} # Creating dictionary for course number's instructors meetingTime = {'CS101':'8 a.m.', 'CS102':'9 a.m.', 'CS103':'10 a.m.', 'NT110':'11 a.m.', 'CM241':'1 p.m.'} # Creating dictionary for course number's meeting times courseNumber = input("Enter a course number: ") # Getting input from user on course number print("The course's room number is", roomNumber[courseNumber]) # Getting user-specified course number's room number from dictionary print("The course's instructor is", instructor[courseNumber]) # Getting user-specified course number's instructor from dictionary print("The course's meeting time is", meetingTime[courseNumber]) # Getting user-specified course number's meeting time from dictionary
# Name: Max Voisard # Class: Programming with Python CIT248S # Date: 4/11/17 # Assignment: Chapter 10 Programming Exercise class Item: def __init__(self, description, units, price): # init method self.__description = description # Instantiating objects self.__units = units self.__price = price def set_description(self, description): # Setter method for description self.__description = description # Assigning argument to variable def set_units(self, units): # Mutator method for units self.__units = units # Assigning units argument to variable def set_price(self, price): # Setter method for price self.__price = price # Setting value to price def get_description(self): # Getter method for description return self.__description # Returning description to main def get_units(self): # Accessor method for units return self.__units # Return statement for units def get_price(self): # get_price method return self.__price # Returning price to main
import time from binary_search_tree import BinarySearchTree start_time = time.time() f = open('names_1.txt', 'r') names_1 = f.read().split("\n") # names_1 = sorted(names_1) # List containing 10000 names f.close() f = open('names_2.txt', 'r') names_2 = f.read().split("\n") # names_2 = sorted(names_2) # List containing 10000 names f.close() duplicates = [] # for name_1 in names_1: # for name_2 in names_2: # if name_1 == name_2: # duplicates.append(name_1) bst = BinarySearchTree("P") # print(len(names_1[1:])) # n=0 for i in names_1: # print(i) bst.insert(i) # print(n) # print(bst.left.value) # bst.insert # print(bst.right.value) for name_2 in names_2: if bst.contains(name_2): duplicates.append(name_2) end_time = time.time() print (f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n") print (f"runtime: {end_time - start_time} seconds")
from re import search def getFilenameAndExtensionFromPath(path): return search("(\w+)\.(\w{3})", path).groups() def replaceFilenameAndExtensionFromPath(path, filename, extension): # Get the path without the filename oldFilename, oldPath = getFilenameAndExtensionFromPath(path) path = path[0:-(len(oldFilename) + len(oldPath) + 1)] return path + filename + "." + extension
#1 #browse option # Python program to extract text from all the images in a folder # storing the text in corresponding files in a different folder from PIL import Image import pytesseract as pt import os def main(): # path for the folder for getting the raw images path ="E:\\mucomputer\\images" # path for the folder for getting the output tempPath ="E:\\mufile\\textFiles" # iterating the images inside the folder for imageName in os.listdir(path): inputPath = os.path.join(path, imageName) img = Image.open(inputPath) # applying ocr using pytesseract for python text = pt.image_to_string(img, lang ="eng") # for removing the .jpg from the imagePath imagePath = imagePath[0:-4] fullTempPath = os.path.join(tempPath, 'time_'+imageName+".txt") print(text) # saving the text for every image in a separate .txt file file1 = open(fullTempPath, "w") file1.write(text) file1.close() if __name__ == '__main__': main() # naming the GUI interface to image_conversion_APP root.title("Image_Conversion_App") # creating the Function which converts the jpg_to_png def jpg_to_png(): global im1 # import the image from the folder import_filename = fd.askopenfilename() if import_filename.endswith(".jpg"): im1 = Image.open(import_filename) # after converting the image save to desired # location with the Extersion .png export_filename = fd.asksaveasfilename(defaultextension=".png") im1.save(export_filename) # displaying the Messaging box with the Success messagebox.showinfo("success ", "your Image converted to Png") else: # if Image select is not with the Format of .jpg # then display the Error Label_2 = Label(root, text="Error!", width=20, fg="red", font=("bold", 15)) Label_2.place(x=80, y=280) messagebox.showerror("Fail!!", "Something Went Wrong...") button1 = Button(root, text="JPG_to_PNG", width=20, height=2, bg="green", fg="white", font=("helvetica", 12, "bold"), command=jpg_to_png) button1.place(x=120, y=120) root.geometry("500x500+400+200") root.mainloop() #2 as ‘fetch button’ and have a #functionality of fetching the weather on # a given location in text box # Python program to find current # weather details of any city # using openweathermap api # import required modules import requests, json # Enter your API key here api_key = "Your_API_Key" # base_url variable to store url base_url = "http://api.openweathermap.org/data/2.5/weather?" # Give city name city_name = input("Enter city name : ") # complete_url variable to store # complete url address complete_url = base_url + "appid=" + api_key + "&q=" + city_name # get method of requests module # return response object response = requests.get(complete_url) # json method of response object # convert json format data into # python format data x = response.json() # Now x contains list of nested dictionaries # Check the value of "cod" key is equal to # "404", means city is found otherwise, # city is not found if x["cod"] != "404": # store the value of "main" # key in variable y y = x["main"] # store the value corresponding # to the "temp" key of y current_temperature = y["temp"] # store the value corresponding # to the "pressure" key of y current_pressure = y["pressure"] # store the value corresponding # to the "humidity" key of y current_humidity = y["humidity"] # store the value of "weather" # key in variable z z = x["weather"] # store the value corresponding # to the "description" key at # the 0th index of z weather_description = z[0]["description"] # print following values print(" Temperature (in kelvin unit) = " + str(current_temperature) + "\n atmospheric pressure (in hPa unit) = " + str(current_pressure) + "\n humidity (in percentage) = " + str(current_humidity) + "\n description = " + str(weather_description)) else: print(" City Not Found ") #3 #Create two browse button and place # the .pdf file for the buttons and create # a merge pdf option - Watermark # Merger App from pathlib import Path from PyPDF2 import PdfFileReader # Change the path below to the correct path for your computer. pdf_path = ( Path.home() / "creating-and-modifying-pdfs" / "practice-files" / "Pride_and_Prejudice.pdf" ) # 1 pdf_reader = PdfFileReader(str(pdf_path)) output_file_path = Path.home() / "Pride_and_Prejudice.txt" # 2 with output_file_path.open(mode="w") as output_file: # 3 title = pdf_reader.documentInfo.title num_pages = pdf_reader.getNumPages() output_file.write(f"{title}\\nNumber of pages: {num_pages}\\n\\n") # 4 for page in pdf_reader.pages: text = page.extractText() output_file.write(text)
#list down Error #Name error list = 12 print(list1) #2 #TYpeError a = '123' a+= 123 #3 #TypeError l = [1,2,3,4,5,6] for i in range(2,1): print(i+1) #4 #syntax Error for i range(1,10): print(i) #5 #index error l = [1,2,3.4,5,56,7] for i in range(len(l)): print(l[i+1]) #6 #module not fount error import modulexyz #7 #design a simple calculator using try and except def calculate(): try: print('+') print('-') print('*') print('/') print('%') print('**') operation = input("Select an operator:n") print("Enter two numbers") number_1 = int(input()) number_2 = int(input()) if operation == '+': # To add two numbers print(number_1 + number_2) elif operation == '-': # To subtract two numbers print(number_1 - number_2) elif operation == '*': # To multiply two numbers print(number_1 * number_2) elif operation == '/': # To divide two numbers print(number_1 / number_2) elif operation == '%': # To remainder two numbers print(number_1 % number_2) elif operation == '**': # To num1 exponent num2 print(number_1 ** number_2) else: print('Invalid Input') except Exception as e: print(e) #8 #print one message if try block raises a nameError and another for other error try: a = 123 if a==123: print(b) raise NameError("Name error") if a >0: raise ValueError("Value error") except NameError as ne: print(ne) except ValueError as ve: pritn(ve) #9 #when try - except scenario is not required? #python Exception are error scenarios that alter the normal execution flow of the program the process of the code inside the elseblock is executed if there are no exception raised #10 #try getting an input inside try catch block try: age=int(input('Enter your age: ')) except: print ('You have entered an invalid value.')
""" Mad Libs are stories with blank spaces that a reader can fill in with their own words.""" #informing the user the program has started print "Mad Libs is starting!" name = raw_input("Enter a name: ") adjective1 = raw_input("Enter an adjective: ") adjective2 = raw_input("Enter another adjective: ") adjective3 = raw_input("Enter the last adjective: ") verb1 = raw_input("Enter a verb: ") verb2 = raw_input("Enter another verb: ") verb3 = raw_input("Enter the last verb: ") noun1 = raw_input("Enter a noun: ") noun2 = raw_input("Enter another noun: ") noun3 = raw_input("Enter the third noun: ") noun4 = raw_input("Enter the last noun: ") animal = raw_input("Enter a type of animal: ") food = raw_input("Enter a type of food: ") fruit = raw_input("Enter a type of fruit: ") number = raw_input("Enter a number: ") superhero = raw_input("Enter a superhero name: ") country = raw_input("Enter the name of a country: ") dessert = raw_input("Enter a type of dessert: ") year = raw_input("Enter a year: ") #The template for the story STORY = "This morning I woke up and felt %s because %s was going to finally %s over the big %s %s. On the other side of the %s were many %ss protesting to keep %s in stores. The crowd began to %s to the rythym of the %s, which made all of the %ss very %s. %s tried to %s into the sewers and found %s rats. Needing help, %s quickly called %s. %s appeared and saved %s by flying to %s and dropping %s into a puddle of %s. %s then fell asleep and woke up in the year %s, in a world where %ss ruled the world." print STORY % (adjective1, name, verb1, adjective2, noun1, noun2, animal, food, verb2, noun3, fruit, adjective3, name, verb3, number, name, superhero, superhero, name, country, name, dessert, name, year, noun4)
import time class Logger: def __init__(self, path, mode): self.path = path self.mode = mode def __enter__(self): self.file = open(self.path, self.mode) return self def write(self, value): self.file.write(f'{time.ctime()} {value}\n') def __exit__(self, exc_type, exc_val, exc_tb): return self.file.close() with Logger('files/log.txt', 'w') as logger: logger.write(12 + 14) logger.write('Hello World') logger.write(True)
import re def validate_passports_with_data(): with open('input.txt') as fin: input_list = fin.readlines() text_lst = [i.replace("\n", "") for i in input_list] required_fields = ["byr","iyr","eyr","hgt","hcl", "ecl","pid"] passport_list = [] temp_list = [] for i in range(len(text_lst)): if text_lst[i] != "": temp_list.append(text_lst[i]) else: if len(temp_list) > 0: passport_list.append(temp_list) temp_list = [] passport_field_list = [] for i in range(len(passport_list)): temp_field_list = [] for j in range(len(passport_list[i])): temp_list = passport_list[i][j].split(" ") temp_field_list += temp_list passport_field_list.append(temp_field_list) valid_passports = 0 for i in range(len(passport_field_list)): count = 0 for j in range(len(passport_field_list[i])): lst = passport_field_list[i][j].split(":") validate = data_validation(lst[0], lst[1]) if validate: count += 1 if count == 7: valid_passports += 1 return valid_passports def data_validation(key, value): if key == "byr": if value.isdigit() and int(value) >= 1920 and int(value) <= 2020: return True else: return False elif key == "iyr": if value.isdigit() and int(value) >= 2010 and int(value) <= 2020: return True else: return False elif key == "eyr": if value.isdigit() and int(value) >= 2020 and int(value) <= 2030: return True else: return False elif key == "hgt": if len(value) < 4: return False if value[-2:] == "cm": height_value = value[:-2] if height_value.isdigit() and int(height_value) >= 150 and int(height_value) <= 193: return True else: return False elif value[-2:] == "in": height_value = value[:-2] if height_value.isdigit() and int(height_value) >= 59 and int(height_value) <= 76: return True else: return False else: return False elif key == "hcl": if re.match("#[0-9a-f]{6}", value): return True else: return False elif key == "ecl": if value in ["amb","blu","brn","gry","grn","hzl","oth"]: return True else: return False elif key == "pid": if len(value) == 9 and value.isdigit(): return True else: return False else: return False total_validated_passports = validate_passports_with_data() print(total_validated_passports)
def map_traverse_trees(): with open('input.txt') as fin: input_list = fin.readlines() text_lst = [i.replace("\n", "") for i in input_list] tree_map = [list(i) for i in text_lst] num_cols = len(tree_map[0]) num_rows = len(tree_map) trees = 0 pos = [0,0] for i in range(num_rows-1): pos[0] += 1 pos[1] = (pos[1] + 3)% num_cols if tree_map[pos[0]][pos[1]] == "#": trees += 1 return trees trees = map_traverse_trees() print(trees)
from .Word import Verb, Adjective u_te_dict = {'す': 'して', 'く': 'いて', 'ぐ': 'いで', 'ぶ': 'んで', 'む': 'んで', 'ぬ': 'んで', 'る': 'って', 'つ': 'って', 'う': 'って'} def formName(): return "Te" def toolTip(): return "Te Form: 食べて/飲んで" def wordGroups(): return ["verb", "adjective"] def hasFormalities(): return False def isTensed(): return False def isPolarised(): return False def question(word, formality, tense, polarity, easy_mode, using_kanji): if easy_mode: question = "What is the Te form of \"{}\"? ({})".format(word.english, word.word_to_conjugate(using_kanji)) else: question = "What is the Te form of \"{}\"?".format(word.english) answer = conjugateTe(word, formality, tense, polarity, using_kanji) return question, answer def conjugateTe(word, formality, tense, polarity, using_kanji=False): if isinstance(word, Verb): return __verb(word, using_kanji) elif isinstance(word, Adjective): return __adjective(word, using_kanji) else: raise ValueError("Unexpected word class") def __verb(word, using_kanji): dict_form = word.word_to_conjugate(using_kanji) if word.group == "る" or word.group == "irregular": te_form = word.stem(using_kanji) + "て" elif dict_form[-2:] == "いく" or dict_form[-2:] == "行く": te_form = word.stem(using_kanji)[:-1] + "って" elif word.group == "う": te_form = dict_form[:-1] + u_te_dict[dict_form[-1]] return te_form def __adjective(word, using_kanji): if word.group == "な": te_form = word.stem(using_kanji) + "で" elif word.group == "い" or word.group == "いい": te_form = word.stem(using_kanji) + "くて" return te_form
# -*- coding: utf-8 -*- """ Created on Tue Mar 3 14:37:28 2020 @author: Dan_B """ import matplotlib.pyplot as plt #from scipy.stats import binom import numpy as np """plt.plot([0,0,1,3,0,5], 'ro') plt.axis([-1,10, 0, 20]) plt.ylabel('some numbers') plt.show()""" choice = int(input("choose the distribution")) minlim = int(input("lower bound")) maxlim = int(input("upper bound")) if choice == 1: #normal mu, sigma = (maxlim+minlim)/2, maxlim-minlim s = np.random.normal(mu, sigma, 1000) count, bins, ignored = plt.hist(s, 30, density=True) plt.plot(bins, 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(- (bins - mu) ** 2 / (2 * sigma ** 2)), linewidth=2, color='r') plt.title("Normal distrib") plt.show() elif choice == 2: #binomial n,p = 20, 0.5 s = np.random.binomial(n,p,100) plt.plot(s, 'bo') plt.title("Binomial distrib") plt.show()
#! /usr/bin/env python3 # -*- coding: utf8 -*- import random import pygame from pygame.locals import * pygame.init() class Maze: def __init__(self): self.tiles = Maze.make_level() self.count = 0 @staticmethod def make_level(): """Load the level and add 3 objects under random position""" with open("level.txt", "r") as file: build_level = [list(line) for line in file.read().split("\n")] for i in range(3): while True: x = random.randint(0, 14) y = random.randint(0, 14) if not build_level[x][y] in ("1", "2", "3", "4", "5", "6"): build_level[x][y] = str(i + 4) break return build_level def find_tile(self, tile): """Check the position about the tile in parameter""" for i in range(len(self.tiles)): for j in range(len(self.tiles[i])): if self.tiles[i][j] == tile: return i, j return None def find_mac(self): """Check the position of mac""" return self.find_tile("3") def move_right(self): """Make a new position for '3' if it don't '1'""" x, y = self.find_mac() if y < 14: if self.tiles[x][y + 1] != "1": self.tiles[x][y + 1] = "3" self.tiles[x][y] = "0" def move_left(self): """Make a new position for '3' if it don't '1'""" x, y = self.find_mac() if y > 0: if self.tiles[x][y - 1] != "1": self.tiles[x][y - 1] = "3" self.tiles[x][y] = "0" def move_up(self): """Make a new position for '3' if it don't '1'""" x, y = self.find_mac() if x > 0: if self.tiles[x - 1][y] != "1": self.tiles[x - 1][y] = "3" self.tiles[x][y] = "0" def move_down(self): """Make a new position for '3' if it don't '1'""" x, y = self.find_mac() if x < 14: if self.tiles[x + 1][y] != "1": self.tiles[x + 1][y] = "3" self.tiles[x][y] = "0" def component_counter(self): """Check the count of component""" cnt = 0 for i in range(len(self.tiles)): for y in range(len(self.tiles[i])): if self.tiles[i][y] == "4" or self.tiles[i][y] == "5" or self.tiles[i][y] == "6": cnt += 1 self.count = cnt def component_found(self): """Check if the component is under the maze""" return self.find_tile("4") or self.find_tile("5") or self.find_tile("6") def draw(self, pictures): """Blit all the pictures on the maze""" ORANGE = 255, 100, 0 # color for the text text = pygame.font.SysFont('freesans', 13) # Police and size screen = pygame.display.set_mode((450, 450)) # Set the size' screen screen.blit(pictures["00"], (0, 0)) # Picture for the font """Loop for blit all the pictures""" for n_line, line in enumerate(self.tiles): for n_tile, tile in enumerate(line): x = n_tile * 30 y = n_line * 30 if tile != "0": screen.blit(pictures[tile], (x, y)) """Set the rect for the counter in the screen""" self.component_counter() title_text = text.render("Number of object(s) to found: {}".format(self.count), True, ORANGE) textpos = title_text.get_rect() textpos.centerx = 350 textpos.centery = 10 screen.blit(title_text, textpos) pygame.display.flip() def check_final_condition(self): """Check if mac is on the guard""" return self.find_tile("2") is None
import cv2 ##import the module img = cv2.imread("Sample.jpg") ##read your image y = 0 ##HEIGHT from x = 0 ##WIDTH from h = 300 ##HEIGHT w = 510 ##WIDTH crop_image = img[x:w, y:h] cv2.imshow("Cropped", crop_image) ##display Cropped image cv2.waitKey(0)
text="ahmed elnakeeb" words=word_tokenize(text) for word in words : spell = SpellChecker() print (spell.correction(word))
dur = int(input("Введите количество секунд:")) if dur >= 0 and dur <= 59: print(str(dur) + " sec") elif dur >= 59 and dur <= 3599: print((str(dur // 60) + " min") + " " + (str(dur % 60) + " sec")) elif dur >= 3600 and dur <= 86399: print(((str(dur // 3600) + "h") + " " + (str(dur % 3600 // 60)) + "min") + " " + (str((dur - 3600) % 60) + "sec")) print("Finish")
class Car: def __init__(self, speed, color, name, is_police): self.speed = speed self.color = color self.name = name self.is_police = is_police def go(self): print('GO!') def stop(self): print('STOP!') def turn(self, direction): print(f'Turn {direction}') def show_speed(self): print(f'Current vehicle speed = {self.speed}') class TownCar(Car): def show_speed(self): if self.speed > 60: print('Over speed!!!') else: print(f'Current vehicle speed = {self.speed}') class SportCar(Car): pass class WorkCar(Car): def show_speed(self): if self.speed > 40: print('Over speed!!!') else: print(f'Current vehicle speed = {self.speed}') class PoliceCar(Car): pass car_1 = TownCar(45,'red', 'Lada', False) car_1.show_speed() car_2 = TownCar(120, 'yellow', 'Mazda', False) car_2.show_speed()
# -*- coding: utf-8 -*- """ Created on Tue Feb 13 09:23:41 2018 @author: patemi """ # https://chrisalbon.com/python/data_wrangling/pandas_dropping_column_and_rows/ import pandas as pd import os.path import numpy as np from functools import reduce path = '\\\\apw-grskfs01\\GVAR2\\Global Risk Management' file = 'Test.csv' ################################ ##Creating a new DF #http://pbpython.com/pandas-list-dict.html ################################# # Create new DF...using a dictionary data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy', 'Jake'], 'year': [2011, 2012, 2013, 2014, 2015, 2016], 'reports': [4, 24, 31, 2, 3,5]} idx=['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', 'Yuma', 'PPP'] df = pd.DataFrame(data, index = idx) def create_dataframe(data, index): df = pd.DataFrame(data, index=index) return df def create_dataframe_2(data, index=''): if index == '': df = pd.DataFrame.from_items(data) else: df = pd.DataFrame(data, index=index) return df def filter_df_columns(df, items): allcols = [] for item in items: cols = [col for col in df.columns if item.upper() in col.upper()] # cols = [col for col in df_input.columns if (item.upper() in col.upper() and ',5Y' in col.upper()) ] allcols.append(cols) allcols = reduce(lambda x, y: x + y, allcols) df = df.filter(items=allcols, axis=1) return df def df_differences(df, num_periods): df_diff=df.diff(periods=num_periods) return df_diff def df_correlations(df): return df.corr() def get_df_columns(df): return list(df.columns.values) # Creates an empty Data Frame df_test_K_b=pd.DataFrame() # Create new DF from list(s) sales = [('account', [' Jones LLC', 'Alpha Co', 'Blue Inc']), ('Jan', [150, 200, 50]), ('Feb', [200, 210, 90]), ('Mar', [140, 215, 95]), ] dfsales = pd.DataFrame.from_items(sales) dfsales2 = create_dataframe_2(sales) df_22 = create_dataframe_2(data,idx) df_100 = filter_df_columns(df_22,['rep']) yy=dfsales['account'].str.strip() # Copy a dataframe dfCopy=df.copy() ########################################## # Adding Column to existing DF ############################################## #Adding a column to an existing dataframe df['subject']=pd.Series(np.random.randn(6), index=df.index) ########################################## # Adding Row (s) to existing DF ############################################## a=np.array([[1,5]]) # Create data frame for the data we want to add data_add=pd.DataFrame(a, columns=['Bucket','K_b'], index=['Bucket']) # Append data df_test_K_b=df_test_K_b.append(data_add) a=np.array([[2,6]]) data_add=pd.DataFrame(a, columns=['Bucket','K_b'], index=['Bucket']) df_test_K_b=df_test_K_b.append(data_add) ########################################## # Unique items in a given column names=df['name'].unique().tolist() ############################################## # Multiply elements of df by 2 df=df*2 #dfsales #Top 5 rows of the DF print(dfCopy.head()) # Take away a number from each element of a DF column dfY=(df.reports-1999) # Take away a number from each element of a DF column ad return the index of the sorted values dfYIndex=(df.reports-1999).argsort() # Set a different column as index #df=df.set_index('reports') # Drop a row df.drop(['Cochice', 'Pima']) # Drop a column df.drop('reports', axis=1) # Drop a row by row number df.drop(df.index[2]) df.drop(df.index[[2,3]]) # Information about the DataFrame #print(df.info()) #################### Create new Dataframe column with elementwise multiplication of existing ones df[['reports','year']]=df[['reports','year']].astype(float) df['reports*year']=df['reports']*df['year'] ######################################################## # Adding a new column with the same value in all rows df['new col']=5 # Adding a new column using insert df.insert(0,'another col',4) # Filter by column name df2=df.filter(regex='rep') # Filter by column names #print(df.filter(items=['name','year'])) # Filter columns containing 'ear' #print(df.filter(like='ear',axis=1)) # print the dataframe index print(df.index) # print only specified columns print(df[['year','name']]) # Return the column names containing given string cols = [col for col in df.columns if 'ear' in col] # Number of columns in a dataframe num_cols=len(df.columns) print(df.describe()) # cast dataframe to boolean dfb=df.astype(bool) # Save the DF data to a CSV file #dfb.to_csv(path_or_buf=os.path.join(path,file)) yy=df.nlargest(2,['year','reports']) ########### Loc vs iLoc ###################### #https://www.shanelynn.ie/select-pandas-dataframe-rows-and-columns-using-iloc-loc-and-ix/ #iloc uses the Python stdlib indexing scheme, where the first element of the range is included and the last one excluded. #So 0:10 will select entries 0,...,9. loc, meanwhile, indexes inclusively. So 0:10 will select entries 0,...,10. # iLoc for index/integer based reference # Loc for logical reference (boolean) #DataFrame.loc #Access a group of rows and columns by label(s) or a boolean array. # iloc print(df.iloc[0]) print(df.iloc[0].year) # Square brackets to return as dataframe yyy=df['name'].iloc[[0]].item() # Dataframe column data types #print(df.dtypes) ##bb=df['name'].iloc[0].str #bb=df[['name']].iloc[[0]] #bb=df[['name']].iloc[[0]].astype(str) #bb=df['name'].iloc[0].to_string # Convert all columns to strings df=df.astype(str) #print(df.dtypes) # Get an item as string ff=df[df.name=='MollyMolly'].name.item() # Filter based on column 'name' contents - equivalent to SQL WHERE...LIKE.....plus OR df3 = df[(df.name.str.contains('ake')) | (df.name == 'JasonJason')] #Filter based on column 'name' contents - equivalent to SQL WHERE df4 = df[df.name == 'JasonJason'] ################################## #Iterating through DataFrames # https://erikrood.com/Python_References/iterate_rows_pandas.html # using iterrows to iterate through dataframes for index, row in df.iterrows(): print (row["name"], row.year) # using itertuples to iterate through dataframes for row in df.itertuples(index=True, name='Pandas'): print (getattr(row, "name"), getattr(row, "year")) ################################################# # Finding null (empty) elements in a dataframe print(pd.isnull(df['name'])) ######################################## #Using Loc df_rand = pd.DataFrame(np.random.randint(0,100,size=(100, 5)), columns=list('ABCDE')) print(df_rand['A']>50) print(df_rand['B']>50) print(df_rand.loc[(df_rand['A']>50) & (df_rand['B']>50),['A']]) i=(df_rand['A']>50) & (df_rand['B']>50) df2=df_rand.loc[(df_rand['A']>50) & (df_rand['B']>50),['A']] #print(df_rand.loc[df_rand['A']>50 & df_rand['B']>50,['A']]) ################# Fill na/Nan's with something #df_input_mapped['Market Cap Bucket'].fillna('SmallCap', inplace=True) ####### Renaming a column df4 = df4.rename(columns = {'name':'NAme'}) # Get the column names from dataframe print(list(df4.columns.values)) # Sorting the values in a dataframe column - inplace = False df = df.sort_values(by='subject', inplace=False) # Sorting the values in a dataframe column - inplace = True df.sort_values(by='subject', inplace=True)