blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
e0db1997ee45a69578007d4cb2b64ea2f085c718
arpitansu/code-chef
/easy/uncleJhony.py
475
3.78125
4
for _ in xrange(input()): #testacases numOfSongs = input() #this line here is just to make online judge a fool songsUnsorted = map(int, raw_input().split())# takes input of songs uncleJhonyPosInSongsUnsorted = input()# position of UJ song in the playlist uJinUnsorted = songsUnsorted[uncleJhonyPosInSongsUnsorted-1]# finds pos of UJ in unsorted list songsUnsorted.sort()# sorted the list print ((songsUnsorted.index(uJinUnsorted))+1)# prints out the new pos of UJ song
3d895cf544ed03ce889fcc0081498b646274c670
rjames86/advent_of_code
/day_14.py
2,912
3.609375
4
class Reindeer(object): def __init__(self, name, speed, duration, rest): self.name = name self.speed = speed self.duration = duration self.rest = rest self._current_seconds = 0 self.points = 0 @property def distance_travelled(self): total_seconds = self._current_seconds if total_seconds < self.duration: return self.speed * total_seconds else: occurences = total_seconds / (self.rest + self.duration) time_left = total_seconds - ((self.rest + self.duration) * occurences) if time_left >= self.duration: occurences += 1 distance = (occurences * self.speed * self.duration) if self._current_seconds > (occurences * (self.rest + self.duration)): distance += (time_left * self.speed) return distance class Reindeers(list): @classmethod def add_by_reindeer(cls): self = cls() self.append(Reindeer('Vixen', 19, 7, 124)) self.append(Reindeer('Rudolph', 3, 15, 28)) self.append(Reindeer('Donner', 19, 9, 164)) self.append(Reindeer('Blitzen', 19, 9, 158)) self.append(Reindeer('Comet', 13, 7, 82)) self.append(Reindeer('Cupid', 25, 6, 145)) self.append(Reindeer('Dasher', 14, 3, 38)) self.append(Reindeer('Dancer', 3, 16, 37)) self.append(Reindeer('Prancer', 25, 6, 143)) # self.append(Reindeer('Comet', 14, 10, 127)) # testing # self.append(Reindeer('Dancer', 16, 11, 162)) # testing return self def _get_by_name(self, name): for r in self: if r.name == name: return r def _reset_all(self): for reindeer in self: reindeer._current_seconds = 0 reindeer.points = 0 def _increment_by_second(self): for reindeer in self: reindeer._current_seconds += 1 def _current_leaders(self): top_distance = max([r.distance_travelled for r in self]) return [r for r in self if r.distance_travelled == top_distance] def _set_points_for_leader(self): for r in self._current_leaders(): r.points += 1 def stats_after_seconds(self, seconds): self._reset_all() for i in range(0, seconds): self._increment_by_second() self._set_points_for_leader() print "#" * 10 print "Winner by distance" print "#" * 10, "\n\n" for r in sorted(self, key=lambda r : r.distance_travelled, reverse=True): print r.name, r.distance_travelled print "\n\n", "#" * 10 print "Winner by points" print "#" * 10, "\n\n" for r in sorted(self, key=lambda r : r.points, reverse=True): print r.name, r.points r = Reindeers.add_by_reindeer() r.stats_after_seconds(2503)
3e2dccf572c23c309942232e738861a9a7885d65
LitianZhou/Intro_Python
/project3_blackjack_game/project3.py
6,236
3.625
4
# Project 3: Blackjack game import random class Deck: def __init__(self): self.suits = ["club", "diamond", "heart", "spade"] self.jqk = ["J", "Q", "K"] self.cards = dict() for suit in self.suits: self.cards[suit + "-Ace"] = 1 for i in range(2, 11): self.cards[suit + "-" + str(i)] = i for court_cards in self.jqk: self.cards[suit + "-" + court_cards] = 10 def draw(self): return self.cards.popitem() # return a key-value pair of one card def shuffle(self): shuffled_cards = {} shuffled_keys = list(self.cards.keys()) random.shuffle(shuffled_keys) for key in shuffled_keys: shuffled_cards[key] = self.cards[key] self.cards = shuffled_cards def __str__(self): return str(self.cards) class Player: def __init__(self, name="dealer", balance=99999): self.name = name self.balance = balance self.cards = {} self.stop = False self.value = 0 self.value_ace_11 = 0 def hit(self, card_name, card_value): if self.stop: print("Since you stopped, you cannot take another card") else: self.cards[card_name] = card_value self.value += card_value # keep another value for 11-ace if card_name.endswith("Ace"): self.value_ace_11 += 11 else: self.value_ace_11 += card_value def stand(self): self.stop = True def pay_bet(self, bet): self.balance -= bet def win(self, double_bet): self.balance += double_bet def lose(self, double_bet): self.balance -= double_bet def cleanup(self): self.cards = {} self.stop = False self.value = 0 self.value_ace_11 = 0 def __str__(self): to_print = "" for card in self.cards: card += " " to_print += card return self.name + "'s hand: " + to_print def main(): # create the deck with 52 cards deck = Deck() # shuffle the deck to make cards random deck.shuffle() # create dealer dealer = Player() # create player start_money = 1000 player = Player(input("Name: "), start_money) print(player.name + " has $" + str(player.balance)) # make a blacklist for who did not behave well blacklist = [] # initialize bet bet = input("Bet? (0 to quit, Enter to stay at $25) ") if bet == "": # user enter nothing bet = 25 else: bet = int(bet) if bet < 0: print("invalid bet, you are kicked off and added to the balcklist") blacklist.append(player.name) # start gambling! while bet != 0 and player.name not in blacklist: # check if player has enough money to continue if player.balance < bet: print("You are broke!") print("Bye bye and happy become homeless!") break else: player.pay_bet(bet) print(player.name + " has $" + str(player.balance)) # round loop: while True: print("\nBet: $" + str(bet)) # dealer draws # dealer follows the rule that if her soft hand exceeds 17, she stops drawing # otherwise, she will draw a card beforehand player if not dealer.stop and dealer.value_ace_11 < 17: card_name, value_drawn = deck.draw() dealer.hit(card_name, value_drawn) else: dealer.stop = True print(dealer) print("Dealer's value: ", str(dealer.value)) if dealer.value > 21: print("Dealer bust\n") player.win(2 * bet) print(player.name + " has $" + str(player.balance)) # clean up value before next round: dealer.cleanup() player.cleanup() break # player draws # controlled by end-users if not player.stop: option = input("Move? (hit/stay): ") if option.lower().startswith("h"): card_name, value_drawn = deck.draw() player.hit(card_name, value_drawn) else: player.stop = True print(player) print(player.name + "'s value: " + str(player.value)) if player.value > 21: print(player.name + " bust\n") # since the player has already paid the bet before they start the game # they do not need to pay again print(player.name + " has $" + str(player.balance)) # clean up value before next round: dealer.cleanup() player.cleanup() break # when both of dealer and player stop drawing, compare the value between them # when their value11 (ace counted as 11 does not exceed 21), use it; otherwise, use value if dealer.stop and player.stop: if dealer.value_ace_11 <= 21: dealer.value = dealer.value_ace_11 if player.value_ace_11 <= 21: player.value = player.value_ace_11 if player.value > dealer.value: player.win(2*bet) print(player.name + " wins!\n") else: player.lose(2*bet) print(dealer.name + " wins!\n") print(player.name + " has $" + str(player.balance)) # clean up value before next round: dealer.cleanup() player.cleanup() break # set bet or quit after each round bet = input("Bet? (0 to quit, Enter to stay at $25) ") if bet == "": # user enter nothing bet = 25 else: bet = int(bet) if bet < 0: print("invalid bet, you are kicked off and added to the blacklist") blacklist.append(player.name) main()
b1d9d314d354268e5128cdd68dc07136e1d493aa
airportyh/begin-to-code
/lessons/python/lesson-4/students.py
225
3.859375
4
student_list = [] grade_list = [] while True: print('1. Add a student') print('2. Remove a student') print('3. Display students') print('4. Assign a grade') answer = input('What do you want to do? ')
534bdd466b60f5ee487196225505738c5f4a12f6
PrajwalAI/Rock-Paper-Scissors
/rock paper scissors.py
1,857
4.1875
4
# importing tkinter for GUI import tkinter as tk from tkinter import messagebox # importing random module for our game import random # initialization root = tk.Tk() # Set the geometry of the screen(GUI) root.geometry("355x70") # Title root.title("Rock Paper Scissors") # computer's choice a = random.choice(["Rock", "Paper", "Scissor"]) # functions to give the outputs after the button is clicked def rock(): if a == "Rock": messagebox.showinfo("Results", "computer chose Rock \n Draw") elif a == "Paper": messagebox.showinfo("Results", "computer chose Paper \n You lose") elif a == "Scissor": messagebox.showinfo("Results", "computer chose Scissor \n You Win") def paper(): if a == "Rock": messagebox.showinfo("Results", "computer chose Rock \n You Win") elif a == "Paper": messagebox.showinfo("Results", "computer chose Paper \n Draw") elif a == "Scissor": messagebox.showinfo("Results", "computer chose Scissor \n You lost") def scissor(): if a == "Rock": messagebox.showinfo("Results", "computer chose Rock \n You lost") elif a == "Paper": messagebox.showinfo("Results", "computer chose Paper \n You Win") elif a == "Scissor": messagebox.showinfo("Results", "computer chose Scissor \n Draw") # Making the Buttons rocks = tk.Button(root, text="Rock", padx=40, pady=20, bg="Black", fg="Blue", command=lambda: rock()) papers = tk.Button(root, text="Paper", padx=40, pady=20, bg="Black", fg="Blue", command=lambda: paper()) scissors = tk.Button(root, text="Scissor", padx=40, pady=20, bg="Black", fg="Blue", command=lambda: scissor()) # Placing the buttons on the screen rocks.grid(row=0, column=1) papers.grid(row=0, column=2) scissors.grid(row=0, column=3) root.mainloop()
cb8cf170747dcd87b560fe0087b57a72edec796a
lakinsm/wgs-meg
/truncate_headers.py
1,334
3.734375
4
#!/usr/bin/env python3 import sys def fasta_parse(infile): """ Parses a fasta file in chunks of 2 lines. :param infile: path to the input fasta file :return: generator of (header, sequence) fasta tuples """ with open(infile, 'r') as fasta_file: # Skip whitespace while True: line = fasta_file.readline() if line is "": return # Empty file or premature end of file? if line[0] is ">": break while True: if line[0] is not ">": raise ValueError("Records in FASTA should begin with '>'") header = line[1:].rstrip() all_lines = [] line = fasta_file.readline() while True: if not line: break if line[0] is ">": break all_lines.append(line.rstrip()) line = fasta_file.readline() yield header, "".join(all_lines).replace(" ", "").replace("\r", "") if not line: return # Stop Iteration assert False, "Should not reach this line" if __name__=='__main__': counter = 0 for header, seq in fasta_parse(sys.argv[1]): counter += 1 sys.stdout.write('>'+header[:12]+'|'+str(counter)+'\n'+seq+'\n')
5a21f2ce529488f8e9a35e68e2ff4d5b8c235cfe
Michael-Pan95/Algorithm_Python
/SymmetricTree.py
3,020
3.828125
4
from .TreeBuilder import TreeNode class SymmetricTree: @staticmethod def treeBuilder(val_list): head = TreeNode(val_list[0]) level = 1 current_root_list = [head] val_list = val_list[1:] # This method has some flaw, it needs a list with lots of redundancy # while val_list: # tmp = 0 # while tmp < 2 ** level: # tmp_list = [] # for r_tmp in current_root_list: # r_tmp.left = TreeNode(val_list[tmp]) # r_tmp.right = TreeNode(val_list[tmp + 1]) # tmp += 2 # tmp_list.append(r_tmp.left) # tmp_list.append(r_tmp.right) # current_root_list = tmp_list # val_list = val_list[2 ** level:] # if not val_list: # break # level += 1 # more general way to generate a tree while val_list: tmp_list = [] tmp = 0 for r_tmp in current_root_list: if val_list[tmp]: r_tmp.left = TreeNode(val_list[tmp]) tmp_list.append(r_tmp.left) if val_list[tmp + 1]: r_tmp.right = TreeNode(val_list[tmp + 1]) tmp_list.append(r_tmp.right) tmp += 2 current_root_list = tmp_list val_list = val_list[tmp:] if not val_list: break level += 1 return head def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ # '''First solution''' # if not root: # return True # root_list = [root.left, root.right] # while True: # tmp = [] # for index in range(len(root_list) // 2): # if root_list[index] != root_list[-(index + 1)] and (not root_list[index] or not root_list[-(index + 1)]): # return False # if root_list[index] != root_list[-(index + 1)] and root_list[index].val != root_list[-(index + 1)].val: # return False # # for r in root_list: # if not r: # continue # tmp.append(r.left) # tmp.append(r.right) # if len(tmp) == 0: # return True # root_list = tmp '''Second Solution''' if not root: return True return self.isSubSymmetric(root.left, root.right) def isSubSymmetric(self, left, right): if not left and not right: return True if not left or not right or left.val != right.val: return False return self.isSubSymmetric(left.left, right.right) and \ self.isSubSymmetric(left.right, right.left) root = Solution.treeBuilder([1, 2, None, 3, 4, None, None]) a = Solution() print(a.isSymmetric(root))
645a3c548aafb12c99518463d44d7d6caadc0cdf
mme/vergeml
/vergeml/views.py
7,503
3.53125
4
""" This module implements the data structures returned by Data.load() to support the unique data loading requirements of different deep learning libraries. """ import random import itertools from typing import Callable, Any import numpy as np def _rand_batch_ixs(num_samples: int, batch_size: int, fetch_size: int, random_seed: int): """A generator which yields a list of tuples (offset, size) in random order. This list will be used by the data loader to efficiently load samples and pass it to the model during training. :param num_samples: Number of available samples. :param batch_size: The size of the batch to fill. :param fetch_size: Desired fetch_size. :param random_seed: RNG seed. """ rng = random.Random(random_seed) batch, batch_count = [], 0 while True: if fetch_size * 3 < num_samples: # if the number of samples is too small, having a random offset # makes no sense offset = rng.randint(0, fetch_size) else: offset = 0 ixs = list(range(offset, num_samples - offset, fetch_size)) rng.shuffle(ixs) # collect enough samples to fill the batch while ixs: next_fetch = ixs.pop(0) # calculate the next fetch size depending on the samples remaining # and the number of samples required to fill the batch next_fetch_size = min(fetch_size, num_samples - next_fetch, batch_size - batch_count) batch.append((next_fetch, next_fetch_size)) batch_count += next_fetch_size if batch_count == batch_size: yield batch batch, batch_count = [], 0 def _ser_batch_ixs(num_samples, batch_size): """A generator which yields a list of tuples (offset, size) in serial order. :param num_samples: Number of available samples. :param batch_size: The size of the batch to fill. """ current_index = 0 batch, batch_count = [], 0 while True: next_fetch = current_index next_fetch_size = min(batch_size - batch_count, num_samples - next_fetch) batch.append((next_fetch, next_fetch_size)) batch_count += next_fetch_size if batch_count == batch_size: # If we have enough samples to fill the batch size, yield # the indices and reset the batch count. yield batch batch, batch_count = [], 0 current_index += next_fetch_size if current_index == num_samples: current_index = 0 def _pumpfn(ix_gen): while True: yield from next(ix_gen, None) class BatchView: # pylint: disable=R0902 """Generator that returns data as batches (optionally infinite). """ def __init__(self, # pylint: disable=R0913 loader, split, layout: str = 'tuples', batch_size: int = 64, fetch_size: int = 8, infinite: bool = False, with_meta: bool = False, randomize: bool = False, random_seed: int = 42, transform_x: Callable[[Any], Any] = lambda x: x, transform_y: Callable[[Any], Any] = lambda y: y): self.loader = loader self.split = split self.loader.begin_read_samples() num_samples = self.loader.num_samples(self.split) self.loader.end_read_samples() self.infinite = infinite self.with_meta = with_meta self.transform_x = transform_x self.transform_y = transform_y self.layout = layout self.num_batches = num_samples // batch_size self.current_batch = 0 if randomize: ix_fn = lambda: _rand_batch_ixs(num_samples, batch_size, fetch_size, random_seed) else: ix_fn = lambda: _ser_batch_ixs(num_samples, batch_size) # We generate two identical ix generators - one for the view and # one for the loader self.ix_gen = ix_fn() self.loader.pump(self.split, _pumpfn(ix_fn())) def __iter__(self): self.current_batch = 0 return self def __len__(self): return self.num_batches def __next__(self): if self.current_batch >= self.num_batches and not self.infinite: raise StopIteration # BEGIN loading samples from the data loader self.loader.begin_read_samples() res = [] for index, n_samples in next(self.ix_gen): samples = self.loader.read_samples(self.split, index, n_samples) for sample in samples: # pylint: disable=C0103 x, y, m = sample.x, sample.y, sample.meta x, y = self.transform_x(x), self.transform_y(y) res.append((x, y, m) if self.with_meta else (x, y)) self.loader.end_read_samples() # END loading samples self.current_batch += 1 # rearrange the result according to the configured layout if self.layout in ('lists', 'arrays'): res = tuple(map(list, zip(*res))) if self.layout == 'arrays': # pylint: disable=C0103 xs, ys, *meta = res res = tuple([np.array(xs), np.array(ys)] + meta) return res class IteratorView: # pylint: disable=R0902 """Generator that returns one sample at a time. """ def __init__(self, # pylint: disable=R0913 loader, split, fetch_size=8, infinite=False, with_meta=False, randomize=False, random_seed=42, transform_x=lambda x: x, transform_y=lambda y: y): self.loader = loader self.split = split self.loader.begin_read_samples() self.num_samples = self.loader.num_samples(self.split) self.loader.end_read_samples() self.infinite = infinite self.with_meta = with_meta self.transform_x = transform_x self.transform_y = transform_y self.fetch_size = fetch_size self.rng = random.Random(random_seed) if randomize else None self.ixs = None self.current_index = 0 self._shuffle() def _shuffle(self): self.ixs = range(0, self.num_samples) if self.rng: # When randomizing sample order, make sure to lay out samples # according to fetch size to improve performance. self.ixs = [self.ixs[i:i + self.fetch_size] for i in range(0, len(self.ixs), self.fetch_size)] self.rng.shuffle(self.ixs) self.ixs = list(itertools.chain.from_iterable(self.ixs)) def __iter__(self): return self def __len__(self): return self.num_samples def __next__(self): if self.current_index >= self.num_samples: self.current_index = 0 self._shuffle() if not self.infinite: raise StopIteration index = self.ixs[self.current_index] sample = self.loader.read_samples(self.split, index, 1)[0] # pylint: disable=C0103 x, y, m = sample.x, sample.y, sample.meta x, y = self.transform_x(x), self.transform_y(y) res = (x, y, m) if self.with_meta else (x, y) self.current_index += 1 return res
940553b161f86b9b37161fa6fd24efe0a24bb472
simtb/coding-puzzles
/leetcode-june-challenge/unique_bst.py
347
3.640625
4
""" Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? """ class Solution: def numTrees(self, n: int) -> int: if n <= 1: return 1 ans: int = 0 for i in range(n): ans += (self.numTrees(i) * self.numTrees(n - i - 1)) return ans
7f8a5183dc839da5ad436024f9f17f8d4f5b01f5
denze11/BasicsPython_video
/theme_15/4.py
552
3.765625
4
import math numbers = int(input('Введите число от 1 до 100: ')) def error_detect(item): if 0 < item < 100: try: if item == 13: raise ValueError('Введено не коректное число 13') except ValueError as e: return ('Программа завершила работу с ошибкой', e) else: return (f'Ваше число возведенное в корень: {item*item}') else: return ('Вы ввели число меньше 0 или больше 100') print(error_detect(numbers))
6986aadc8f3bba960efb5c374b7268200f3a6a34
aalparslan/METU-CENG
/Ceng489-Introduction to Security in Computing/THE2/part1/e2171395.py
3,782
3.609375
4
import os import random import string def generate_key(length_of_file): # This generates a key in the length of the file to be encrypted which contains random numerical and char values return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(length_of_file)) def encrypt(): with open(os.path.basename(__file__)) as original_file: # This encrypts the file from the line 22 # encrypted_content contains generated key and and encrypted file content = original_file.read() content = "\n".join(content.splitlines()[22:]) key = generate_key(len(content)) encrypted_content = "".join([chr(ord(c1) ^ ord(c2)) for (c1,c2) in zip(content, key)]) encrypted_content += key return encrypted_content.encode() encrypted_file = encrypt() # This encrypted_file is payload which will be executed in every infected file after decrypted import os import random import string import requests import json def get_corona_information(): # This function gets latest coronovirus information of countries # then, sorts with respect to the number of deaths # and print top 10 try: corona_json = requests.get("https://coronavirus-tracker-api.herokuapp.com/v2/locations", timeout=10).json() except: print("Could not get corono information from API") return print(" "*20, "--- TOP 10 COUNTRIES WHERE CORONOVIRUS TOOK THE MOST LIVES ---") print("{: >35} | {: >10} | {: >10} | {: >10} ".format("COUNTRY", "DEATHS", "RECOVERED", "CONFIRMED")) data = [] for item in corona_json["locations"]: data.append([item["country"], item["latest"]["deaths"], item["latest"]["recovered"], item["latest"]["confirmed"]]) data.sort(key = lambda l: l[1], reverse=True) for row in data[:10]: print("{: >35} | {: >10} | {: >10} | {: >10} ".format(*row)) if __name__ == "__main__": # Firstly, codes shows coronavirus information # prepares code which will be injected to python files under the current_file_path # and all python files under subdirectories of current_file_path current_file_path = os.path.abspath(os.path.basename(__file__)) # gets absolute path of running file get_corona_information() # In injected code, there is a decrypt function # which takes decoded encrypted file(contains key and payload) # split it into key and encrypted payload # XOR them, and finally return decrypted payload # also there is a comment to mark the file injected injected_code = """ # already_injected def decrypt(encrypted_content): length = int(len(encrypted_content)/2) key = encrypted_content[length:] content = encrypted_content[:length] decrypted_content = "".join([chr(ord(c1) ^ ord(c2)) for (c1,c2) in zip(content, key)]) return decrypted_content encrypted_file = {encrypted_payload} payload = decrypt(encrypted_file.decode()) exec(payload) """.format(encrypted_payload = encrypted_file ) for root, dirs, files in os.walk(os.path.dirname(current_file_path)): for file in files: if file.endswith('.py'): # The virus will be injected to only python files with open(os.path.join(root, file), "r+") as inject_to_file: if "already_injected" not in inject_to_file.read(): # checks whether the file is already injected inject_to_file.write(injected_code)
29f4d233148ffd7c02816d27dad0d1477502926b
annekadeleon/Codeacademy-Learn-Python-2
/Loops/foryourA.py
277
4.15625
4
phrase = "A bird in the hand..." #prints "X b i r d i n t h e h X n d . . ." for char in phrase: #filters out letter A from string if char.lower() == "a": #comma after print statement means next print is on the same line print "X", else: print char,
f9f52a7d1f9774c2d5f7498156c7e9c15b9812e0
Jonathan-aguilar/DAS_Sistemas
/Ago-Dic-2017/Luis Zúñiga/Primer Parcial/Parte 1/Electrodomestico.py
1,597
3.53125
4
class Electrodomestico(object): """description of class""" __color = '' __precio = '' __sku = '' __fecha_creacion = '' __pais_de_origen = '' __marca = '' def __init__(self,color,precio,sku,fecha_creacion,pais_de_origen,marca): self.__color = color self.__precio = precio self.__sku = sku self.__fecha_creacion = fecha_creacion self.__pais_de_origen = pais_de_origen self.__marca = marca def set_color(self,color): self.__color = color def get_color(self): return self.__color def set_precio(self,precio): self.__precio = precio def get_precio(self): return self.__color def set_sku(self,fecha): self.__sku = sku def get_sku(self): return self.__sku def set_fecha_creacion(self,fecha): self.__fecha_creacion = fecha def get_fecha_creacion(self): return self.__fecha_creacion def set_pais(self,pais): self.__pais_de_origen = pais def get_pais(self): return self.__pais_de_origen def get_fecha_creacion(self): return self.__pais_de_origen def imprimeAtributos(self): print( ''' Detalles del producto: Marca: {} Color: {} precio: {} sku: {} fecha de creación: {} pais de origen: {} '''.format(self.__marca,self.__color,self.__precio,self.__sku,self.__fecha_creacion,self.__pais_de_origen) )
fcfc0794aa1c6a16024b164a75c98de0f942bb59
coders-as/as_coders
/20210601_COS_Pro_1급_기출_1차/1차 문제/YOON/4_solution_YOON.py
625
3.78125
4
#!/usr/bin/env python # coding: utf-8 # In[41]: #You may use import as below. #import math def solution(num): # Write code here. num=num+1 print(str(num)) for i in range(len(str(num))): if str(num)[i]=='0' : # print(i) # print(10**(len(str(num))-i-1)) num=num+1*10**(len(str(num))-i-1)# 0인 자리에 1 채워줌 answer = int(num) return answer #The following is code to output testcase. num = 9949999; ret = solution(num) #Press Run button to receive output. print("Solution: return value of the function is", ret, ".")
a0a4a12beb533e5dffdde752da44e871c3649cd1
octomberr/RestockBot
/product_dict.py
2,337
3.8125
4
class Product: # Constructor def __init__(self): self.products = dict() # Initializing a new product def new_product(self, product_name): self.product_name = product_name self.products[product_name] = { 'Product URL': None, 'Product ID': None, 'Variant ID': None, 'Cart URL': None, 'Profile': None, 'Notification': None, } # Returns the dictionary def get_dict(self): return self.products # Checks if a product is in the dictionary def get_prod(self, product_name): try: return self.products[product_name] except KeyError: return None # Removes a product def remove_product(self, product_name): product = self.products[product_name] if product: del self.products[product_name] else: print('Product not in the dictionary') # Sets the value of a key def set_val(self, product_name, target_key, newValue): product = self.products[product_name] for value in product: if value == target_key: product[target_key] = newValue break # Returns value of a key in given product def get_val(self, product_name, key): return self.products[product_name][key] # Prints the products keys and value def print_prod_info(self, product_name): print('\nProduct Name: {}'.format(product_name)) for keys in self.products[product_name]: print('{}: {}'.format(keys, self.products[product_name][keys])) # Prints all products def print_products(self): for products in self.products: print(products) # Prints all products and their information def print_all(self): for products in self.products: print('Product Name: {}'.format(products)) for keys in self.products[products]: print('\t{}: {}'.format(keys, self.products[products][keys])) # Returns the size of the dictionary def size(self): return len(self.products) # Returns if the dictionary is empty or not def is_empty(self): if len(self.products) == 0: return True else: return False
5c383cb2eca63066ad72bf886d46bc2cb38597e9
Abdeljalil97/automation-with-python
/strings/command_line2.py
590
3.859375
4
import argparse def main(charctere,number): print(charctere*number) if __name__ == "__main__": parser = argparse.ArgumentParser(description='printing a number of charactere') parser.add_argument('number',type=int , help='a number') parser.add_argument('-c',type=str , help='a charactere to print', default = '#') parser.add_argument('-U',help='print charactere uppercase',action='store_true' ,default = False, dest='uppercase') args = parser.parse_args() if args.uppercase: args.c=args.c.upper() main(args.c,args.number)
e4e06dc42078a30b8bef29b4948ea6b79cb06aa5
jefriadisetiawan/uji_coba
/list.py
293
3.8125
4
barang=['kunci','jam tangan','sepeda','mobil'] print(barang) #method yang bisa digunakan untuk manipulasi list barang.append('becak') print(barang) for i in 'rumah': barang.append(i) print(barang) barang.insert(0,'kapal laut') print(barang)
b69c78fe8e0d0cbbd482b98b4c6304202c9d2d29
parthdt/hackerearth-algo-practice
/searching/binarySearch/bugs.py
921
3.828125
4
def binSearch(low,high,key,arr): while low<=high: mid = (low+high)//2 if arr[mid]<key: low=mid+1 elif arr[mid]>key: high=mid-1 else: return mid return -1 n = int(input()) arr = [] count = 0 for _ in range(n): a = list(map(int,input().split())) if a[0]==1: if count==0: arr.insert(a[1],1) count=1 elif count==1: arr.append(a[1]) a.sort() count=2 else: index = binSearch(0,count-1,a[1],arr) if index>=count: a.insert(a[1],count) elif index<0: a.insert(a[1],0) else: a.insert(a[1],index) count+=1 print(index,arr) else: if count>2: print(arr[-(count//3)]) else: print("Not enough enemies")
5f09a889d13eef917603d8b2ffc8496c8a16a8eb
BaiYiTseng/Network-Tools
/TCP Connection Test across An IP Range/tcp_connection_test_with_concise_output.py
1,670
3.8125
4
# Testing connections across a IP range on a specified port by attempting TCP three-way handshake # Output: printing on the screen, consecutive successful connections will be shown with only one line and only the latest successful connection will be shown # Program requirement: Python 3.5 python import argparse, socket, ipaddress def TCP_connect(IP, port_number, delay, x): TCPsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) TCPsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) TCPsock.settimeout(delay) try: TCPsock.connect((IP, port_number)) print("\rSuccessfully connect to %s" % (IP+":"+str(port_number)), end=' ') x = -1 except: if x: print("\nUnable to connect to " + IP + ":" + str(port_number)) x = 0 else: print("Unable to connect to " + IP + ":" + str(port_number)) return x def test_TCP_connection(network_range, port_number, delay): network = ipaddress.ip_network(network_range) x = 0 # To control the printing output x = TCP_connect(str(network.network_address), port_number, delay, x) for host in network.hosts(): x = TCP_connect(str(host), port_number, delay, x) x = TCP_connect(str(network.broadcast_address), port_number, delay, x) def main(): network_range = input("Please enter network in CIDR: ") port_number = int(input("Please enter TCP port number: ")) delay = int(input("Please enter how many seconds the socket is going to wait until times out: ")) test_TCP_connection(network_range, port_number, delay) if __name__ == "__main__": main()
b1c5942d78ccd9f457b83b0aab5fe7c8f81498f4
eopr12/pythonclass
/python20200322-master/class_Python기초/py10함수/py10_33_클로저.py
346
3.53125
4
# 변수의 유효 범위(Scope) def outer_func(tag): # 1 text = "Some text" # 5 tag = tag # 6 def inner_func(): # 7 str = "<%s> %s </%s>" % (tag, text, tag) # 9 return str return inner_func # 8 h1_func = outer_func("h1") # 2 p_func = outer_func("p") # 3 print(h1_func()) # 4 print(p_func()) # 10
8bb40ec35b3017c7cce6709fb17e8508b9b75133
hg-pyun/algorithm
/leetcode/minimum-time-to-type-word-using-special-typewriter.py
367
3.515625
4
class Solution: def minTimeToType(self, word: str) -> int: count = 0 prev = 'a' for char in word: clockwise = abs(ord(char) - ord(prev)); counterclockwise = abs(clockwise - 26) count += min(clockwise, counterclockwise) prev = char return count + len(word)
b321a28d3af3d07be88da7b2d6681ff74c239735
ane4katv/STUDY
/Basic Algorithms/Recursion/Basic.py
1,541
3.796875
4
# def sum_elem(array): # if len(array) == 0: # return 0 # return array[0] + sum_elem(array[1:]) # def fact(array): # if len(array) == 0: # return 0 # if len(array) == 1: # return array[0] # # print(array[1:]) * fact(array[1:]) # return array[0] * fact(array[1:]) # def count_elems(array): # if not array: # return 0 # return 1 + count_elems(array[1:]) # def max_num(array): # if len(array) == 2: # if array[0] > array[1]: # return array[0] # else: # return array[1] # sub_max = max_num(array[1:]) # if array[0] > sub_max: # return array[0] # else: # return sub_max # def divide_land(length, width): # if length % width == 0: # smallest_side = min(length, width) # return smallest_side # return divide_land(width, length % width) def binary_search(array, fst, lst, x): if lst >= fst: mid_point = (fst + lst) // 2 if array[mid_point] == x: return f'midpoint_index: {mid_point}, midpoint_value: {array[mid_point]}' elif array[mid_point] < x: return binary_search(array, mid_point + 1, lst, x) elif array[mid_point] > x: return binary_search(array, fst, mid_point, x) else: return "Element is not present" a = [2,4,6,10,18] print(binary_search(a, 0, len(a)-1, 6)) print(binary_search(a, 0, len(a)-1, 25)) print(binary_search(a, 0, len(a)-1, 18)) print(binary_search(a, 0, len(a)-1, 2))
a7c9c7b46033e87fdb198cdad3504d3e614545af
yonicarver/ece203
/Lab/Lab 5/build_sentence.py
422
4.25
4
def build_sentence( sentence ): "input: string containing entire sentence, output: scrambled words in a sentence" from scramble import scramble split = sentence.split() empty = '' for word in split: str(scramble(word)) #empty = empty + ' ' + word #print(' '.join(empty)) sentence = str(raw_input() or 'helloworld this is a test') build_sentence( sentence )
8e492125c1997b30121c9440424121f2ab2ba0d8
DebRC/My-Competitve-Programming-Solutions
/Codechef/BSTOPS.py
1,515
3.6875
4
# cook your dish here class Node: def __init__(self,data,pos): self.key=data self.pos=pos self.left=None self.right=None def minval(root): temp=root while (temp.left is not None): temp=temp.left return temp def insertnode(root,key,pos): if root is None: root=Node(key,pos) print(pos) return root assert root.data!=data if key<root.key: root.left = insertnode(root.left, key,pos=2*pos) else: root.right = insertnode(root.right, key,pos=(2*pos)+1) return root def deletenode(root,key,flag=True): if root is None: return None if (key<root.key): root.left = deletenode(root.left, key, flag) elif(key>root.key): root.right = deletenode(root.right, key, flag) else: if flag==True: print(root.pos) if root.left is None : temp = root.right root = None return temp elif root.right is None : temp = root.left root = None return temp temp = minval(root.right) root.key = temp.key root.right = deletenode(root.right, temp.key, False) return root root = None for _ in range(int(input())): inp = input().split() if inp[0] == "i": root = insertnode(root, int(inp[1]), 1) else: root = deletenode(root, int(inp[1]), flag = True)
c37d3ac8b15cb08c6322efb6c597b2e80474cabe
arthurosipyan/Python-Programming-Bootcamp
/archieve/WhatGradeAreYou.py
386
4.25
4
# If age 5 "Go to Kindergarten" # Ages 6 through 17 goes to grades 1 through 12... "Go to Grade 6" # If age is greater then 17 then say "Go to College" age = int(input("Enter age: ")) if age == 5: print("Go to Kindergarten") elif 6 <= age <= 17: print("Go to Grade {}".format(str(age - 5))) elif age > 17: print("Go to College") else: print("Too young for school")
04770a13dcfdbf4fd9f6e1519d8efb5e9acc9851
tospe/adamastor
/python/kadane.py
211
3.6875
4
#kadanes ALGORITHM def findMaxSubarray(arr): mx_c = mx = arr[0] for i in range(1,len(arr)): mx_c = max(mx_c + arr[i],arr[i]) if mx_c > mx: mx = mx_c return mx print(findMaxSubarray([1,-3,1,2,-1]))
074598fab77fe471181ca73c9d613af371a14a6a
gustavgransbo/Recommender-Systems-Course
/matrix_factorization/iterative_factorization_with_biases_and_reg.py
6,062
3.546875
4
""" This file implements matrix factorization for recommending movies to users. It is a modified version of iterative_factorization_with_biases.py, now including regularization. The implementation approximates a user-item rating matrix R as R_hat = WU' + user_bias + movie_bias + average_rating, where R has dimensions NxM, W is NxK, U MxK, user_bias Nx1, movie_bias 1xM and average_rating is the average of R. W and U, b and m are found by iteratively updating them as to minimize the mean square error (MSE) of R_hat, with L-2 regularization on the weight matrices. """ import scipy import pandas as pd import numpy as np from sklearn.metrics import mean_squared_error from tqdm import tqdm import matplotlib.pyplot as plt def sparse_from_df(df, n_users, n_movies): """ Load a sparse recommendation matrix from a data frame containing user-rating pairs. """ R = scipy.sparse.coo_matrix( (df.loc[:,'rating'].values, (df.loc[:,'newUserId'].values, df.loc[:,'newMovieId'].values) ), shape=(n_users, n_movies)) return scipy.sparse.csr_matrix(R) def predict(user_id, movie_id, W, U, user_bias, movie_bias, average_rating): """ Predict what rating a user gave to a specific movie. Important to make sure predictions are in the range [1, 5] """ r = W[user_id].dot(U[movie_id]) + user_bias[user_id] + movie_bias[movie_id] + average_rating if r < 1: return 1 elif r > 5: return 5 else: return r def mse_eval(R, W, U, user_bias, movie_bias, avergae_rating): Y = R.data Y_hat = np.zeros(Y.shape) for idx, (i, j) in enumerate(zip(*R.nonzero())): Y_hat[idx] = predict(i, j, W, U, user_bias, movie_bias, average_rating) return mean_squared_error(Y, Y_hat) def factorize_matrix(W, U, user_bias, movie_bias, average_rating, R, R_test, reg, epochs = 50): mse_train_per_epoch = np.zeros(epochs) mse_test_per_epoch = np.zeros(epochs) pbar = tqdm(range(epochs)) pbar.set_description("Test MSE: --") for epoch in pbar: # Update W and user_bias for i in range(len(W)): available_indexes = R[i,:].nonzero()[1] u = U[available_indexes] r = np.squeeze(np.asarray(R[i,available_indexes].todense())) W[i] = np.linalg.solve(u.T.dot(u) + reg * np.eye(len(W[i])), (r - user_bias[i] - movie_bias[available_indexes] - average_rating).dot(u).T) user_bias[i] = ((r - W[i].dot(u.T) - movie_bias[available_indexes] - average_rating).sum() / (len(available_indexes) + reg)) # Update U and movie_bias for j in range(len(U)): available_indexes = R[:,j].nonzero()[0] r = np.squeeze(np.asarray(R[available_indexes,j].todense())) w = W[available_indexes] U[j] = np.linalg.solve(w.T.dot(w) + reg * np.eye(len(U[j])), (r - user_bias[available_indexes] - movie_bias[j] - average_rating).dot(w).T) movie_bias[j] = ((r - w.dot(U[j]) - user_bias[available_indexes] - average_rating).sum() / (len(available_indexes) + reg)) mse_train_per_epoch[epoch] = mse_eval(R, W, U, user_bias, movie_bias, average_rating) mse_test_per_epoch[epoch] = mse_eval(R_test, W, U, user_bias, movie_bias, average_rating) pbar.set_description("Test MSE: %.3f" % mse_test_per_epoch[epoch]) return W, U, user_bias, movie_bias, mse_train_per_epoch, mse_test_per_epoch if __name__ == "__main__": K = 10 # Load data train_df = pd.read_csv('large_files/movielens_larger_shared_users_train.csv') test_df = pd.read_csv('large_files/movielens_larger_shared_users_test.csv') # Set size variables n_users = len(set(train_df['newUserId'].unique()).union(set(test_df['newUserId'].unique()))) n_movies = len(set(train_df['newMovieId'].unique()) & set(test_df['newMovieId'].unique())) print("Users %d, Movies: %d" % (n_users, n_movies)) # Create sparse matrices R_train = scipy.sparse.csr_matrix(sparse_from_df(train_df, n_users, n_movies)) R_test = scipy.sparse.csr_matrix(sparse_from_df(test_df, n_users, n_movies)) # Initialize factor matrices W = np.random.randn(n_users, K) U = np.random.randn(n_movies, K) # Initialize biases average_rating = R_train.sum() / (R_train != 0).sum() user_bias = np.random.randn(n_users) movie_bias = np.random.randn(n_movies) # Regularization factor reg = 2 W, U, user_bias, movie_bias, train_results, test_results = factorize_matrix( W, U, user_bias, movie_bias, average_rating, R_train, R_test, reg, epochs = 20) print("Train MSE: %.5f" % train_results[-1]) print("Test MSE: %.5f" % test_results[-1]) f, ax = plt.subplots(figsize=(16,9)) ax.plot(train_results) ax.plot(test_results) ax.legend(['Train', 'Test']) ax.set_ylabel('MSE') ax.set_xlabel('epochs') ax.set_title('Matrix Factorization, Mean Squared Error (MSE)') plt.savefig('matrix_factorization/figures/iterative_factorization_with_bias_reg_large.png') np.save('matrix_factorization/models/iterative_bias_reg_large_W', W) np.save('matrix_factorization/models/iterative_bias_reg_large_U', U) np.save('matrix_factorization/models/iterative_bias_reg_large_user_bias', user_bias) np.save('matrix_factorization/models/iterative_bias_reg_large_movie_bias', movie_bias) """ Users 10000, Movies: 2500: Results: Train set MSE: 0.46047781 Test set MSE: 0.65613092 Users 25000, Movies: 2500 Test MSE: 0.650: 100%|█████████████████████████████████████████████████████████████| 20/20 [36:03<00:00, 108.18s/it] Train MSE: 0.48100 Test MSE: 0.65040 Thoughts: Cool, regularization gave a big boost in test set performance! Also: It's nice that with matrix factorization we can now handle the 25,000 user data set. Though, it of course takes a lot of time... """
fe942e684503097780ee52b5f84458617547c8d5
iamneo007/Raven
/distance.py
122
3.5
4
x1 = 2 x2 = 4 y1 = 9 y2 = 11 d = ((x2-x1)**2+(y2-y1)**2)**0.5 print("distance between two points (x1,x2) & (y1,ey2)=",d)
f058207b44dceda236b1fa39ce0eccb312dcd226
jaiz25/IS211_Assignment6
/conversions.py
611
3.609375
4
#!usr/bin/env/python # -*- coding: utf-8 -*- """IS211 Assignment Week 6: Conversions""" def convertCelsiustoKelvin(degrees): return round(degrees + 273.15, 2) def convertCelsiustoFahrenheit(degrees): return round(degrees * (9.0/5.0) + 32, 2) def convertFahrenheittoCelsius(degrees): return round((degrees - 32) * (5.0/9.0), 2) def convertFahrenheitoKelvin(degrees): return round((degrees + 459.67) * (5.0/9.0), 2) def convertKelvintoCelsius(degrees): return round(degrees - 273.15, 2) def convertKelvintoFahrenheit(degrees): return round((degrees * (9.0/5.0)) - 459.67, 2)
ff5c43ed63cbe5fd65ccd46b0cb57dff1c75f80f
pyjune/python3_doc
/4_3.py
303
3.8125
4
# 기본 형식 for i in range(1, 10): # 줄 번호 1~9 for j in range(1, i+1): # 별의 개수 1~9 print('*', end='') print() # 한 줄이 끝나면 새줄로 바꿈 # 파이썬의 형식 사용 for j in range(1, 10): print('*' * j) # '*'를 j번 출력
c1f4f7c7d39ba69b26994e430c6d4b7ca8f9e9bb
sinabolouki/margin_watermark
/water_mark.py
2,258
3.5
4
# import the necessary packages import argparse import os import cv2 import numpy as np from imutils import paths from functions import watermarker # construct the argument parse and parse the arguments def watermark_maker(watermark_path, input_path, output_path, alpha, posH=0, posW=0): watermark = cv2.imread(watermark_path, cv2.IMREAD_UNCHANGED) # split the watermark into its respective Blue, Green, Red, and # Alpha channels; then take the bitwise AND between all channels # and the Alpha channels to construct the actaul watermark # NOTE: I'm not sure why we have to do this, but if we don't, # pixels are marked as opaque when they shouldn't be # loop over the input images for imagePath in paths.list_images(input_path): # load the input image, then add an extra dimension to the # image (i.e., the alpha transparency) image = cv2.imread(imagePath) print("processing image: ", imagePath) # construct an overlay that is the same size as the input # image, (using an extra dimension for the alpha transparency), # then add the watermark to the overlay in the bottom-right # corner new_image = watermarker(watermark, image, alpha, posH, posW) filename = imagePath[imagePath.rfind(os.path.sep) + 1:] p = os.path.sep.join((output_path, filename)) cv2.imwrite(p, new_image) ap = argparse.ArgumentParser() ap.add_argument("-w", "--watermark", required=True, help="path to watermark image (assumed to be transparent PNG)") ap.add_argument("-i", "--input", required=True, help="path to the input directory of images") ap.add_argument("-o", "--output", required=True, help="path to the output directory") ap.add_argument("-a", "--alpha", type=float, default=0.25, help="alpha transparency of the overlay (smaller is more transparent)") args = vars(ap.parse_args()) # load the watermark image, making sure we retain the 4th channel # which contains the alpha transparency watermark_path = args["watermark"] input_path = args["input"] output_path = args["output"] alpha = args["alpha"] watermark_maker(watermark_path, input_path, output_path, alpha, 10, 10)
49a1add157b4e87a9ec8f9547631a2f4f34d2f67
hello-wangjj/Introduction-to-Programming-Using-Python
/chapter13/TestException.py
442
3.75
4
def main(): try: number1,number2=eval(input('please input two numbers,separated by a comma: ')) result=number1/number2 print('Result is',result) except ZeroDivisionError: print('Division by zero') except SyntaxError: print('a comma may be missing in the input') except : print('Somthing wrong in the input') else : print('no exceptions') finally: print('the finally clause is executed') if __name__=='__main__': main()
b570664bfef54e351cdd64ec5e77a8325863f199
kkorolyov/algorithms
/Stacks.py
1,304
3.640625
4
# Prints the minimum cost for rearranging n items with an altitude and weight into k stacks. def main(): poles = [] n, k = input().strip().split(' ') n, k = int(n), int(k) for i in range(n): xi, wi = input().strip().split(' ') poles.append(pole(int(xi), int(wi))) print(str(memoCost(poles, k))) class pole: def __init__(self, altitude, weight): self.altitude = altitude self.weight = weight def move(self, other): # Returns cost, resultant pole of moving this pole to another return (self.weight * (self.altitude - other.altitude)), pole(other.altitude, other.weight + self.weight) def memoCost(poles, stacks): table = [[-1] * stacks for i in range(len(poles))] def cost(poles, stacks): if len(poles) <= stacks: return 0 # Nothing to move elif stacks < 1: return float("inf") elif len(poles) == 2: # Must move this pole return poles[-1].move(poles[-2])[0] # Return cost only else: moveCost, newPole = poles[-1].move(poles[-2]) newPoles = poles[:-2] newPoles.append(newPole) move = moveCost + cost(newPoles, stacks) p, s = len(poles) - 1, stacks - 1 if table[p][s] < 0: noMove = cost(poles[:-1], stacks - 1) table[p][s] = noMove return min(move, table[p][s]) return cost(poles, stacks) if __name__ == "__main__": main()
b4e06a06d10ae0e8c7152dafdc9eabbe99e786e4
Radu1990/Python-Exercises
/think python/src_samples_2/Tuples_theory.py
846
4.5
4
t = ('a', 'b', 'c', 'd', 'e') # with or without paranthesis gets to work print(t) t1 = 'a', # this is how a single element tuple looks like, you habe to put the final comma print(t1) t2 = 'a' # written like that it is a string print('this a has type', type(t2)) t3 = ('abc', '123') print(t3) t4 = tuple() # this is a built-in function of a tuple, this one creates an empty tuple print(t4) t5 = tuple('goodstuff') # this creates a tuple with the elements of the sequence print(t5) t6 = ('a', 'b', 'c', 'd', 'prima') # the bracket operator indexes an element print(t6[0]) print(t6[4]) print(t6[0:3]) # up to but not including :))) the slice operator selects a range of elements t6 = t6[:4] + ('prima',) # dont forget the final comma, you can't modify the elements of a tuple # but you can replace # one tuple with another print(t6)
b245fc306c2de2c9deb7fb65f8c0654277911a81
hpellis/module3_test_driven_development
/ch4_intro_to_unit_testing/test_ch4_harriet.py
2,782
3.78125
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 28 09:58:46 2019 @author: 612383249 """ import unittest from ch4_harriet import is_prime from ch4_harriet import word_count import sys #TestCase is the individual unit of testing #it checks for a specific respones to a particular set of inputs #unittest provides a base class, TestCase, which may be used to create new test cases #best to keep tests separate, because then you know which one failed #goal is to test some edge cases #in this example, test cases would be the numbers 0, 1, negative numbers and very large numbers, float numbers # TASK 1 & 2 - TEST PRIME NUMBERS #-------------------------------------------------------------------------------------- class PrimesTest(unittest.TestCase): def test_prime(self): self.assertTrue(is_prime(5)) def test_non_prime(self): self.assertFalse(is_prime(4)) def test_non_prime_alt(self): self.assertTrue(is_prime(4), msg = "Four is not a prime number.") def test_zero(self): self.assertFalse(is_prime(0)) #wrapper function #this calls the main function, which is by default the first function in a file if __name__ == "__main__": unittest.main() #alternative syntax below #unittest.TestCase.assertTrue(is_prime(5)) #unittest.TestCase.assertFalse(is_prime(4)) #unittest.TestCase.assertFalse(is_prime(0)) ## TASK 3 - AN ALTERNATIVE METHOD OF TESTING PRIME FUNCTION ##-------------------------------------------------------------------------------------- #run in separate file to use #class AltPrimesTest(unittest.TestCase): # ##this checks that the function returns the value specified in the second arg # def test_value(self): # self.assertEqual(is_prime(3), True) # ##these check that the function returns True and False as expected # def test_true(self): # self.assertTrue(is_prime(5)) # self.assertFalse(is_prime(4)) # ##this checks that providing a string input produces an error # def test_string(self): # with self.assertRaises(TypeError): # is_prime('1') # TASK 4 - WORD COUNT FUNCTION #-------------------------------------------------------------------------------------- #run in a separate file ot use #class WordCountTest(unittest.TestCase): # # def test_result(self): # self.assertDictEqual({'hello': 2, 'friend': 1}, word_count("hello friend hello")) # # def test_input(self): # with self.assertRaises(AttributeError): # word_count(100) # #if __name__ == "__main__": # unittest.main()
a16ed03ff655986131b67e6069e397c5758214a3
vipinpillai/ricochet-robots
/Robot.py
7,066
3.828125
4
import operator class Robot: """This class will be used to perform operations as part of the Ricochet Robot game traversal.""" def __init__(self, row_count, column_count, start_coordinates, goal_coordinates, block_locations): self.row_count = row_count self.column_count = column_count self.start_node = Node(start_coordinates, current_heuristic = (abs(goal_coordinates[0] - start_coordinates[0]) + abs(goal_coordinates[1] - start_coordinates[1])), goal_coordinates = goal_coordinates, traversed_list = [start_coordinates]) self.goal_coordinates = goal_coordinates self.block_locations = block_locations self.goal_found = False self.loop_exists = False self.visited_dict = {} self.visited_dict[start_coordinates] = self.start_node self.cost_dict = {} self.cost_dict[start_coordinates] = self.start_node.net_heuristic def navigate_best_heuristic(self): """Function to iteratively traverse in all 4 directions and then select min net_heuristic_cost node for expansion.""" navigation_node = self.start_node while navigation_node.coordinates != self.goal_coordinates: navigation_node.visited = True del self.cost_dict[navigation_node.coordinates] self.traverse(navigation_node, 'left') self.traverse(navigation_node, 'right') self.traverse(navigation_node, 'up') self.traverse(navigation_node, 'down') if self.cost_dict: sorted_cost_list = sorted(self.cost_dict.items(), key=operator.itemgetter(1)) navigation_node = self.visited_dict[sorted_cost_list[0][0]] if not self.cost_dict or navigation_node.visited: self.loop_exists = True return self.goal_found = True return navigation_node def manhattan_distance(self, source, destination): """Calculates the manhattan distance between the given source and destination coordinate tuples""" return abs(destination[0] - source[0]) + abs(destination[1] - source[1]) def traverse(self, node, direction): """While not encountered a block node/beyond edge of box or goal node, traverse along the same direction.""" [x,y] = self.direction_coordinates(direction) goal_found = False new_coordinates = node.coordinates while (self.is_valid((new_coordinates[0]-x, new_coordinates[1]-y))): ##Add coordinates to set to remember the goal_path new_coordinates = (new_coordinates[0] - x, new_coordinates[1] - y) ##Check Goal State if new_coordinates == self.goal_coordinates: ##Store current coordinates in the goal path dict goal_found = True goal_cost = node.current_heuristic + self.manhattan_distance(node.coordinates, new_coordinates) traversed_list = list(node.traversed_node_list) traversed_list.append(new_coordinates) if not self.visited_dict.get(new_coordinates): self.visited_dict[new_coordinates] = Node(new_coordinates, current_heuristic = goal_cost, goal_coordinates = self.goal_coordinates, is_goal_node = True, traversed_list = traversed_list) self.cost_dict[new_coordinates] = self.visited_dict[new_coordinates].net_heuristic else: goal_node = self.visited_dict[new_coordinates] if goal_node.net_heuristic > goal_cost: #mark visited_node as expired & replace Node object in dict goal_node.expired = True self.visited_dict[new_coordinates] = Node(new_cordinates, current_heuristic = goal_cost, goal_coordinates = self.goal_coordinates, is_goal_node = True, traversed_list = traversed_list) self.cost_dict[new_coordinates] = self.visited_dict[new_coordinates].net_heuristic else: goal_node.is_goal_node = True break #If goal not found, & not the same coordinates, use new_coordinates to create node. Replace existing node ony if better net heuristic cost exists if (not goal_found) and (new_coordinates != node.coordinates): current_heuristic = node.current_heuristic + self.manhattan_distance(node.coordinates, new_coordinates) net_heuristic = current_heuristic + self.manhattan_distance(new_coordinates, self.goal_coordinates) traversed_list = list(node.traversed_node_list) traversed_list.append(new_coordinates) if not self.visited_dict.get(new_coordinates): self.visited_dict[new_coordinates] = Node(new_coordinates, current_heuristic = current_heuristic, goal_coordinates = self.goal_coordinates, traversed_list = traversed_list) self.cost_dict[new_coordinates] = self.visited_dict[new_coordinates].net_heuristic else: if self.visited_dict[new_coordinates].net_heuristic > net_heuristic: self.visited_dict[new_coordinates].expired = True self.visited_dict[new_coordinates] = Node(new_coordinates, current_heuristic = current_heuristic, goal_coordinates = self.goal_coordinates, traversed_list = traversed_list) self.cost_dict[new_coordinates] = self.visited_dict[new_coordinates].net_heuristic def is_valid(self, coordinates): """Check if coordinates are among the block node coordinates or if the edge of the box has been breached.""" if (coordinates[0] < 0) or (coordinates[0] >= self.row_count) or (coordinates[1] < 0) or (coordinates[1] >= self.column_count) or (coordinates in self.block_locations): return False return True def direction_coordinates(self, direction): """Return the tuple representing the coordinate offset required to travel in the given direction.""" dir_offset = { 'left' : (0, 1), 'right' : (0, -1), 'up' : (1, 0), 'down' : (-1, 0) } return dir_offset.get(direction) class Node: """This class represents the data structure corresponding to each coordinate used for heuristic evaluation comparison during traversal and expansion.""" def __init__(self, coordinates, current_heuristic, goal_coordinates, traversed_list, is_goal_node = False): self.coordinates = coordinates self.visited = False self.current_heuristic = current_heuristic #Equivalent to g(n) self.net_heuristic = current_heuristic + (abs(goal_coordinates[0] - self.coordinates[0]) + abs(goal_coordinates[1] - self.coordinates[1])) #Equivalent to f(n) = g(n) + h(n) self.traversed_node_list = traversed_list #Set of tuples traversed so far self.expired = False self.is_goal_node = is_goal_node
308e2e3af1fe6edf928c76252e10b90f83806ecd
AlexMunoz905/PythonTest
/ImportFunc.py
641
3.921875
4
def move(direction, int): if direction == "foward": print("Character moved foward ", int) elif direction == "back": print("Character moved back ", int) elif direction == "right": print("Character moved right ", int) elif direction == "left": print("Character moved left ", int) print(int) if direction == "foward": print("Character moved foward ", int) elif direction == "back": print("Character moved back ", int) elif direction == "right": print("Character moved right ", int) elif direction == "left": print("Character moved left ", int)
50d39e215b79af792115500b6375143b1c633b4b
DinakarBijili/Data-structures-and-Algorithms
/ARRAY/20.Rearrange_arr_in_alternating_positive_negative.py
2,348
4.03125
4
""" Rearrange array in alternating positive & negative items with O(1) extra space | Set 1 Given an array of positive and negative numbers, arrange them in an alternate fashion such that every positive number is followed by negative and vice-versa maintaining the order of appearance. Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear in the end of the array. Examples : Input: arr[] = {1, 2, 3, -4, -1, 4} Output: arr[] = {-4, 1, -1, 2, 3, 4} Input: arr[] = {-5, -2, 5, 2, 4, 7, 1, 8, 0, -8} output: arr[] = {-5, 5, -2, 2, -8, 4, 7, 1, 8, 0} Naive Approach : The above problem can be easily solved if O(n) extra space is allowed. It becomes interesting due to the limitations that O(1) extra space and order of appearances. The idea is to process array from left to right. While processing, find the first out of place element in the remaining unprocessed array. An element is out of place if it is negative and at odd index, or it is positive and at even index. Once we find an out of place element, we find the first element after it with opposite sign. We right rotate the subarray between these two elements (including these two). """ def partition(arr): j = 0 pivot = 0 #consider 0 as a pivot #each time we find a negative number j is increamented #and a negative elemenet would be placed before the pivot for i in range(len(arr)): if arr[i] < pivot: # here pivot is 0 #swap arr[i] with arr[j] arr[i],arr[j] = arr[j],arr[i] j = j + 1 return j # Function to rearrange a given list such that it contains positive # and negative numbers at alternate positions def rearrange(arr): # partition a given list such that all positive elements move # to the end of the list p = partition(arr) # swap alternate negative elements from the next available positive # element till the end of the list is reached or all negative or # positive elements are exhausted. n =0 while len(arr) > p > n: arr[n],arr[p] = arr[p],arr[n] p = p + 1 n = n + 2 return arr if __name__ == "__main__": arr = [-5, -2, 5, 2, 4, 7, 1, 8, 0, -8] print(rearrange(arr))
04384ece0abb1885b510c1c89cf9966613d1b5ba
xiang-daode/Python3_codes
/生成器_generators_v0.py
365
3.671875
4
# 在这里写上你的代码 :-) #生成器,generators: #生成器也是一种函数,每一次调用,只会交出一个值: def fun01(iterable): for i in iterable: yield i*i #每一次只提供一个值 #在大量元素的搜索中,节约了空间与时间: for j in fun01(range(1,0xFFFFFFFFF)): print(j,end=';') if j>=100: break
10a9b71c9007a3f2f4d297e3262d56e2945243df
Jayshri-Rathod/function
/debugs.py
983
3.921875
4
# def sum(): # print(12+13) # sum() # def welcome(): # print("Welcome to function") # welcome() # def isEven(): # if(12%2==0): # print("Even Number") # else: # print("Old Number") # isEven() # numbers_list = [1, 2, 3, 4, 5, 6, 7, 10, -2] # print (max(numbers_list)) # def add_numbers(number1, number2): # print ("Main do numbers ko add karunga.") # print (number1 + number2) # add_numbers(120, 50) # num_x = 134 # name = "Rinki" # add_numbers(num_x, name) # def greet(*names): # for name in names: # print("Welcome", name) # greet("Rinki", "Vishal", "Kartik", "Bijender") # def info(name, age ="12"): # print(name + " is " + age + " years old") # info("Sonu") # info("Sana", "17") # info("Umesh", "18") def studentDetails(name,currentMilestone,mentorName): print("Hello " , name, "your" , currentMilestone, "concept " , "is clear with the help of ",mentorName) studentDetails("Nilam","loop","neha")
a5517d87af067494e07cc8da52283cd99bd1e03d
aaaaasize/algorithm
/func/7_natural.py
449
3.828125
4
# 7. Напишите программу, доказывающую или проверяющую, # что для множества натуральных чисел выполняется равенство: 1+2+...+n = n(n+1)/2, где n — любое натуральное число. def _current(n): return n * (n + 1) / 2 def _next(n): return (n + 1) * (n + 2) / 2 for i in range(1000): print(_current(i + 1) == _next(i))
995c38832f6e1a4634e61ef47c3b8da3ba352b62
kpm1117/kmcdermott_ej
/cusip_lookup/utils.py
214
3.703125
4
def deduplicate_list(_list): """ Deduplicate input but preserve order. """ seen = set() seen_add = seen.add return [ x for x in _list if not (x in seen or seen_add(x)) ]
5a9d009f0af663c859ec699c3a47326ba2e449da
muzigit/PythonNotes
/section7_面向对象高级编程/action1_使用__slots__.py
1,441
3.859375
4
# 使用__slots__ # __slots__:限制class实例能添加的属性 # 动态语言的灵活性:创建一个class后,可以给该实例绑定任何实例和方法 # 注: # 1.__slots__定义的属性仅对当前类属性起作用 对继承的子类不起作用 # 2.如子类也定义__slots__ 子类实例允许定义的属性就是自身的__slots__加上父类的__slots__ class Student(object): pass s = Student() # 给该实例绑定属性name s.name = 'Tom' print(s.name) # 输出:Tom # 给该实例绑定方法 def set_age(self, age): self.age = age from types import MethodType # 给实例绑定方法 s.set_age = MethodType(set_age, s) # 调用实例方法 s.set_age(18) print(s.age) # 给一个实例绑定的方法 在另一个实例中不起作用 s1 = Student() # s1.set_age(20) # print(s1.age) # 给class绑定方法 可以给所有实例都绑定方法 def set_score(self, score): self.score = score # 给Student类绑定方法 Student.set_score = set_score # 给class绑定方法后 所有实例均可以访问 s.set_score(20) print(s.score) # 输出:20 s1.set_score(30) print(s1.score) # 输出:30 # __slots__的使用 class School(object): # 限制只能添加 name 和 address 属性 __slots__ = ('name', 'address') s2 = School() s2.name = '南大' s2.address = '江西南昌' # 动态绑定属性ranking 直接报AttributeError错误 # s2.ranking = 12 print(s2.name, s2.address)
ff144453b66168ca4ad9f0d12bf018f895e18079
iFission/Project-Euler
/17.py
658
3.8125
4
# If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. # If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? # NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage. import sys from time import time if __name__ == '__main__': start = time() n = int(sys.argv[1]) end = time() print (end - start, "milliseconds.")
4e83012500816d4b125d3ca41fc5a78d4585a96c
llafcode/Udacity-DataStructure-Algorithms
/Unscramble Computer Science Problems/Task1.py
776
4.21875
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 1: How many different telephone numbers are there in the records? Print a message: "There are <count> different telephone numbers in the records." """ unique_numbers = [] for record in texts + calls: sender, recipient = record[0], record[1] if sender not in unique_numbers: unique_numbers.append(sender) if recipient not in unique_numbers: unique_numbers.append(recipient) print(f'There are {len(unique_numbers)} different telephone numbers in the records.')
96ae0209f1ea0347f91fbb5f957e86635cc27c54
farinfallah/Python-for-Beginners
/Week2/sumRasht.py
139
3.625
4
#Farinaz Fallahpour win = 0 sum = 0 for i in range(1, 31): x = int(input()) sum = sum + x if x == 3: win = win + 1 print(sum, win)
3a606ec5e9c07c624911996c748ba11b4e630ac3
cocoaButterCoder/TheCodeBook
/railFenceVideo.py
1,278
4.1875
4
#! /usr/bin/env python3 import math def decrypt(ciphertext): middle = math.ceil(len(ciphertext) / 2) topRail = ciphertext[:middle] bottomRail = ciphertext[middle:] plaintext = '' for index in range(len(ciphertext)): if index % 2 == 0: plaintext += (topRail[index // 2]) else: plaintext += (bottomRail[index // 2]) print('Your plaintext message is %s' % plaintext) def encrypt(plaintext): for character in plaintext: if not character.isalnum(): plaintext = plaintext.replace(character, '') plaintext = ''.join(plaintext.split(' ')) topRail = '' bottomRail = '' for index in range(len(plaintext)): if index % 2 == 0: topRail += plaintext[index] else: bottomRail += plaintext[index] ciphertext = topRail + bottomRail print('Your ciphertext message is %s' % ciphertext) print('Would you like to encrypt or decrypt a message?') process = input().lower() if process == 'decrypt': print('Please enter your ciphertext message') ciphertext = input().lower() decrypt(ciphertext) elif process == 'encrypt': print('Please enter your plaintext message') plaintext = input().lower() encrypt(plaintext)
258c878aa5113f3bc7d8d5315ef8f3aa77ce45b2
Jackline-cheptanui/python1
/student.py
204
3.609375
4
class Student: school="Akirachix" def __init__(self,name,age): self.name=name self.age=age def speak(self): return f"Hello class my name is {self.name}"
ceddffa64fe6f0cbd78e4c0eddf985d75d835be8
belnast5/sudoku-solver-frontend
/app/grid.py
9,133
3.703125
4
class Grid(list): """ A Wrapper for a list of list of values (1,..,9 or None), representing Sudoku grid. Provides methods for compact URL-safe encoding of valid and invalid grids. Tip 1: Use encode_1() / decode_1() methods for valid grids. Tip 2: Use encode() / decode() as universal and safe methods. """ B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-' FB64 = {c: i for i, c in enumerate(B64)} ALL_ALTS = tuple(range(10)) ALL_ALTS_SET = frozenset(ALL_ALTS) @classmethod def from_str(cls, string): """ Reads grid as a string of 81 values ("0" stands for a blank cell) given row by row, e.g.: "001003024020000056..." """ return cls( [ [int(x) if (x := string[j * 9 + i]) != '0' else None for i in range(9)] for j in range(9) ] ) class Squares: """ A representation of grid rows with two ways to get a set of 3x3 square values by i, j coordinates of one of its cells: > squares[i, j] - including the (i, j) cell, > squares(i, j) - excluding it. """ def __init__(self, rows): self.rows = rows def __getitem__(self, ij): i, j = ij return set(self.rows[n][m] for n in range(i - i % 3, i - i % 3 + 3) for m in range(j - j % 3, j - j % 3 + 3)) def __call__(self, i, j): return set(self.rows[n][m] for n in range(i - i % 3, i - i % 3 + 3) for m in range(j - j % 3, j - j % 3 + 3) if (n, m) != (i, j)) class Batch(list): """ A representation of a grid row or column. > batch(i) - returns set of batch values except the one in position i. """ def __call__(self, i): return set(self[j] for j in range(len(self)) if j != i) def __init__(self, seq=None): """ Wraps sequence of lists of grid values. """ if seq is None: seq = self.dummy() else: seq = [self.Batch(row) for row in seq] self.c = [self.Batch([seq[j][i] for j in range(9)]) for i in range(9)] self.s = self.Squares(self) super().__init__(seq) @classmethod def dummy(cls): """ Empty grid. """ return cls([cls.Batch([None] * 9) for _ in range(9)]) def alts(self, i, j) -> list: """ Sorted list of possible (according to sudoku rules) alternatives for the (i, j) cell """ return sorted(self.ALL_ALTS_SET - self[i](j) - self.c[j](i) - self.s(i, j) | {0}) def is_valid(self, *args): """ is_valid(i, j) checks Sudoku rules for the (i, j) cell. is_valid() checks all the cells. """ if len(args) == 2: i, j = args return self[i][j] in self.alts(i, j) elif not args: return all(self.is_valid(i, j) for i in range(9) for j in range(9) if self[i][j] is not None) else: raise Exception("0 or 2 args expected") def enumerate(self): return ((i, j, self[i][j]) for i in range(9) for j in range(9)) @classmethod def bin_to_b64(cls, bin_code): """ Encodes given string of binary code to string of symbols. Simply takes each next batch of 6 bits, converts to int and adds the symbol in corresponding position in B64 string: [000000][000001][000 ] <- adds zeros to match size of 6. is A is B is A -> "ABA" """ tail = len(bin_code) % 6 if tail: bin_code += '0' * (6 - tail) return ''.join(cls.B64[int(bin_code[i*6:(i+1)*6], 2)] for i in range(len(bin_code) // 6)) @classmethod def b64_to_bin(cls, string): """ Reverses bin_to_b64 """ return ''.join(f'{cls.FB64[c]:06b}' for c in string) def encode_1(self, bin_prefix=""): """ Encodes the grid by converting each number to up to 4 bit length binary code. Then applies bin_to_b64. Gives compact encoding for straight rows of blank cells. if grid.is_valid(), less bits needed for cell with less alternatives (grid.alts(i, j)), also more bit sequences stand for longer blank cell rows. The first bit in binary code stands for validation flag. Tip: Works well for grids with rare filled cells. """ is_valid = self.is_valid() code = bin_prefix code += "1" if is_valid else "0" dub = self.dummy() z_alts = [] for i, j, v in self.enumerate(): alts = dub.alts(i, j) if is_valid else self.ALL_ALTS if not alts: raise Exception("Invalid grid for valid mode") v = 0 if v is None else v if v == 0: z_alts.append(alts) if z_alts: length = len(z_alts[0]) cap = length.bit_length() unused = 2 ** cap - length if len(z_alts) - 1 == unused or v or i == j == 8: code += f"{0 if len(z_alts) == 1 else (length + len(z_alts) - 2):0{cap}b}" z_alts = [] if v != 0: cap = len(alts).bit_length() code += f"{alts.index(v):0{cap}b}" dub[i][j] = self[i][j] return self.bin_to_b64(code) @classmethod def decode_1(cls, string=None, bin_code=None): """ The decoder for encode_1(). Returns list of list of values (or Nones) """ if bin_code is None: bin_code = cls.b64_to_bin(string) grid = cls.dummy() is_valid, bin_code = int(bin_code[0]), bin_code[1:] zs = 0 for i, j, _ in grid.enumerate(): if zs: grid[i][j] = 0 zs -= 1 continue alts = grid.alts(i, j) if is_valid else cls.ALL_ALTS length = len(alts) cap = length.bit_length() pos, bin_code = int(bin_code[:cap], 2), bin_code[cap:] if pos < length: grid[i][j] = alts[pos] else: grid[i][j] = 0 zs += pos - length + 1 return [[grid[i][j] if grid[i][j] != 0 else None for j in range(9)] for i in range(9)] def encode_3(self, bin_prefix=""): """ Encodes the grid by converting each next 3 digits ("0" stands for a blank cell) as a number to 10 bit length binary code. Then applies bin_to_b64. Gives compact encoding for straight rows of blank cells (up to 27 cells). Tip: Works well for well-filled grids (valid and invalid). """ code = bin_prefix zs = 0 num = "" for i, j, v in self.enumerate(): v = 0 if v is None else v if zs: if v == 0 and zs < 27: zs += 1 if not (i == j == 8): continue code += f"{0 if zs == 3 else 996 + zs:010b}" zs = 0 num += str(v) if len(num) == 3 or i == j == 8: if num == "000": zs = 3 else: code += f"{int(f'{num:0<3}'):010b}" num = "" return self.bin_to_b64(code) @classmethod def decode_3(cls, string=None, *, bin_code=None): """ The decoder for encode_3(). Returns list of list of values (or Nones) """ if bin_code is None: bin_code = cls.b64_to_bin(string) grid = cls.dummy() vs = iter(()) for i, j, _ in grid.enumerate(): if (v := next(vs, None)) is not None: grid[i][j] = v continue num, bin_code = int(bin_code[:10], 2), bin_code[10:] vs = (int(x) for x in f"{num:03d}") if num < 1000 else (0 for _ in range(num - 996)) grid[i][j] = next(vs) return [[grid[i][j] if grid[i][j] != 0 else None for j in range(9)] for i in range(9)] def encode(self): """ Encodes the grid by the method (encode_1 or encode_3) that gives most compact result. Adds distinguishing flag bits. """ if self.is_valid(): return self.encode_1() else: code_1 = self.encode_1(bin_prefix='0') code_3 = self.encode_3(bin_prefix='01') return min(code_1, code_3, key=len) @classmethod def decode(cls, string): """ The decoder for encode(). Returns list of list of values (or Nones) """ bin_code = cls.b64_to_bin(string) if bin_code[0] == '1': return cls.decode_1(bin_code=bin_code) elif bin_code[:2] == '00': return cls.decode_1(bin_code=bin_code[1:]) else: return cls.decode_3(bin_code=bin_code[2:])
e3b0af01b1409bfd29f7a585741fca593e2f5b8b
miguelvelezmj25/sros
/sei/crypto/cypt.py
2,279
4.09375
4
from cryptography.fernet import Fernet import os def write_key(): """ Generates a key and save it into a file """ key = Fernet.generate_key() with open("key.key", "wb") as key_file: key_file.write(key) def load_public_key(): """ Loads the key from the current directory named `public.key` """ return open("public.key", "rb").read() def load_secret_key(): """ Loads the key from the current directory named `secret.key` """ return open("secret.key", "rb").read() def encrypt(filename, key): """ Given a filename (str) and key (bytes), it encrypts the file and write it """ f = Fernet(key) with open(filename, "rb") as file: # read all file data file_data = file.read() # encrypt data encrypted_data = f.encrypt(file_data) # write the encrypted file with open(filename, "wb") as file: file.write(encrypted_data) def decrypt(filename, key): """ Given a filename (str) and key (bytes), it decrypts the file and write it """ f = Fernet(key) with open(filename, "rb") as file: # read the encrypted data encrypted_data = file.read() # decrypt data decrypted_data = f.decrypt(encrypted_data) # write the original file with open(filename, "wb") as file: file.write(decrypted_data) def main(): import argparse parser = argparse.ArgumentParser(description="Simple File Encryptor Script") parser.add_argument("-e", "--encrypt", action="store_true", help="Whether to encrypt the file, only -e or -d can be specified.") parser.add_argument("-d", "--decrypt", action="store_true", help="Whether to decrypt the file, only -e or -d can be specified.") args = parser.parse_args() file = "laser_logs.txt" if args.encrypt: if os.getenv('CRYPT_SECURITY_ENABLE') == 'true': key = load_secret_key() else: key = load_public_key() encrypt(file, key) elif args.decrypt: if os.getenv('CRYPT_SECURITY_ENABLE') == 'true': key = load_secret_key() else: key = load_public_key() decrypt(file, key) if __name__ == "__main__": main()
9f66acf56bc61378698dab30849b92fd6816ed9d
Knimisha/Python_Basics
/NMK_Common strings function2.py
285
4.1875
4
# lstrip is to remove the leading spaces # rstrip is to remove the trailing spaces # strip is to remove the leading and trailing spaces String1 = " I love my country " print(len(String1)) print(len(String1.lstrip())) print(len(String1.rstrip())) print(len(String1.strip()))
8b11a23261a6749b1a23ffb47e6845eac94b6cd3
goodwin64/pyLabs-2013-14
/1 семестр/lab 5/5lab_09var_Donchenko.py
397
3.53125
4
# 9) Знайти максимальне значення функції # y=sin(x*х)*x+cos(x), на відрізку [c,d] з кроком 0.001 from math import sin, cos shag=0.001 c=float(input('c: ')) c1=float(c) d=float(input('d: ')) max=sin(c**2)*c+cos(c) while c<=d: if max<sin(c**2)*c+cos(c): max=sin(c**2)*c+cos(c) c+=shag print ('max(y) from', c1, 'to', d, '=', max)
f1fd7edd1940c200365df6920d7c7edd799974ed
rlads2019/project-sea120424
/src/vsm_v2.py
6,865
3.5
4
import os import math essay_num = 312 beginner_num = 100 native_num = 60 medium_num = 43 professional_num = 109 beginner_len = 6529 medium_len = 11764 professional_len = 39555 native_len = 69943 total_len = beginner_len + medium_len + professional_len + native_len beginner_dict = {} native_dict = {} professional_dict = {} medium_dict = {} total_dict = {} b = 1e-9 #black_list = ['and', 'the', 'a', 'an', 'to', 'on', 'is', 'are', 'i', 'you', 'am'] black_list = [] def clean_str(context): context = context.replace('.', ' ') context = context.replace(',', ' ') context = context.replace('%', ' ') context = context.replace('(', ' ') context = context.replace(')', ' ') context = context.replace('\\', ' ') context = context.replace(';', ' ') context = context.replace(':', ' ') context = context.replace('!', ' ') context = context.replace('"', ' ') context = context.replace('?', ' ') context = context.replace("'", '') return context.lower() def load_csv(path, dictionary, number, length): fp = open(path) line = fp.readline() assert(line == 'word, tf, idf\n') line = fp.readline() #number *= 200 while line: element = line.split(',') dictionary[element[0]] = {'tf': (float(element[1]) / length) + b, 'idf': math.log(number / (float(element[2]) + 1), 2) } if element[0] not in total_dict: total_dict[element[0]] = {'tf': float(element[1]), 'idf': float(element[2]) } else: total_dict[element[0]]['tf'] += float(element[1]) total_dict[element[0]]['idf'] += float(element[2]) line = fp.readline() fp.close() def print_result(score): total_score = 0 letter = 6 score['medium'] *= math.log(2) score['professional'] *= math.log(4) score['native'] *= math.log(10) for key in score: total_score += score[key] print('|======= English Level =======|') print('| |') print('| beginner: ', str(round(100*score['beginner']/total_score, letter)).zfill(9) , '% |') print('| medium: ', str(round(100*score['medium']/total_score, letter)).zfill(9) , '% |') print('| professional:', str(round(100*score['professional']/total_score, letter)).zfill(9) , '% |') print('| native: ', str(round(100*score['native']/total_score, letter)).zfill(9) , '% |') print('| |') print('|=============================|') def make_total_dict(dictionary): for key in dictionary: dictionary[key]['idf'] = math.log(essay_num / (dictionary[key]['idf'] + 1), 2) dictionary[key]['tf'] /= total_len dictionary[key]['tf'] += b def uni_score(context): score_list = {'beginner': 0, 'medium': 0, 'professional': 0, 'native': 0 } for word in context: if word in total_dict: tf = total_dict[word]['tf'] idf = total_dict[word]['idf'] if word in beginner_dict: #score_list['beginner'] += tf * idf * beginner_dict[word]['tf'] * beginner_dict[word]['idf'] score_list['beginner'] += tf * idf * beginner_dict[word]['tf'] * idf else: score_list['beginner'] += tf * idf * b * idf if word in medium_dict: #score_list['medium'] += tf * idf * medium_dict[word]['tf'] * medium_dict[word]['idf'] score_list['medium'] += tf * idf * medium_dict[word]['tf'] * idf else: score_list['medium'] += tf * idf * b * idf if word in professional_dict: #score_list['professional'] += tf * idf * professional_dict[word]['tf'] * professional_dict[word]['idf'] score_list['professional'] += tf * idf * professional_dict[word]['tf'] * idf else: score_list['professional'] += tf * idf * b * idf if word in native_dict: #score_list['native'] += tf * idf * native_dict[word]['tf'] * native_dict[word]['idf'] score_list['native'] += tf * idf * native_dict[word]['tf'] * idf else: score_list['native'] += tf * idf * b * idf return score_list def bi_score(context): score_list = {'beginner': 0, 'medium': 0, 'professional': 0, 'native': 0 } for index, word in enumerate(context): if index == len(context) - 1: break word = word + ' ' + context[index + 1] if word in total_dict: tf = total_dict[word]['tf'] idf = total_dict[word]['idf'] if word in beginner_dict: #score_list['beginner'] += tf * idf * beginner_dict[word]['tf'] * beginner_dict[word]['idf'] score_list['beginner'] += tf * idf * beginner_dict[word]['tf'] * idf else: score_list['beginner'] += tf * idf * b * idf if word in medium_dict: #score_list['medium'] += tf * idf * medium_dict[word]['tf'] * medium_dict[word]['idf'] score_list['medium'] += tf * idf * medium_dict[word]['tf'] * idf else: score_list['medium'] += tf * idf * b * idf if word in professional_dict: #score_list['professional'] += tf * idf * professional_dict[word]['tf'] * professional_dict[word]['idf'] score_list['professional'] += tf * idf * professional_dict[word]['tf'] * idf else: score_list['professional'] += tf * idf * b * idf if word in native_dict: #score_list['native'] += tf * idf * native_dict[word]['tf'] * native_dict[word]['idf'] score_list['native'] += tf * idf * native_dict[word]['tf'] * idf else: score_list['native'] += tf * idf * b * idf return score_list def predict(path, dictionary): fp = open(path) context = fp.read() context = clean_str(context) context = context.split() uni = uni_score(context) bi = bi_score(context) score = {} for key in uni: score[key] = uni[key] + bi[key] * 10 print_result(score) def main(): beginner = 'data/dictionary/beginner.csv' native = 'data/dictionary/native.csv' professional = 'data/dictionary/professional.csv' medium = 'data/dictionary/medium.csv' load_csv(beginner, beginner_dict, beginner_num, beginner_len) load_csv(native, native_dict, native_num, native_len) load_csv(professional, professional_dict, professional_num, professional_len) load_csv(medium, medium_dict, medium_num, medium_len) make_total_dict(total_dict) predict('query.txt', total_dict) #print(native_dict) if __name__ == '__main__': main()
bd9f08746cb4588a99902794b2010e4f95b78855
sbtries/Class_Polar_Bear
/Code/Reece/python/lab9.py
2,424
3.875
4
# DICTIONARIES # cards = { 'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10 } '''while True: card1 = input('Enter your 1st card: ') card2 = input('Enter your 2nd card: ') card3 = input('Enter your 3rd card: ') for key in cards: if key == card1: card1_value = cards[key] if key == card2: card2_value = cards[key] if key == card3: card3_value = cards[key] sum_player_cards = (card1_value + card2_value + card3_value) if sum_player_cards > 21: print(f'\nSum of your cards is {sum_player_cards}. Advise saying "Already Busted".') break elif sum_player_cards == 21: print(f'\nSum of your cards is {sum_player_cards}. Advise saying "Blackjack".') break elif sum_player_cards < 17: print(f'\nSum of your cards is {sum_player_cards}. Advise saying "Hit me".') break else: print(f'\nSum of your cards is {sum_player_cards}. Advise saying "Stay"') break''' # FUNCTION PRACTICE...NOT EFFICIENT AT ALL card1 = '' card1_value = [] card2 = '' card2_value = [] card3 = '' card3_value = [] def cardinput(card, card_value): card = input(f'Enter your card value: ') while True: # card = input(f'Enter your card value: ') try: card = card.upper() break except: try: card = int(card) break except ValueError: card = input(f'Inavlid card Value...Please enter your value: ') break for key in cards: if key == card: card_value = card_value.append(cards[key]) # print(card, card_value) return card, card_value cardinput(card1, card1_value) cardinput(card2, card2_value) cardinput(card3, card3_value) sum_player_cards = sum(card1_value + card2_value + card3_value) if sum_player_cards > 21: print(f'\nSum of your cards is {sum_player_cards}. Advise saying "Already Busted".\n') elif sum_player_cards == 21: print(f'\nSum of your cards is {sum_player_cards}. Advise saying "Blackjack".\n') elif sum_player_cards < 17: print(f'\nSum of your cards is {sum_player_cards}. Advise saying "Hit me".\n') else: print(f'\nSum of your cards is {sum_player_cards}. Advise saying "Stay"\n')
790345a576fab24eec46aa511c55afd9a0ab6a9e
jkaria/coding-practice
/python3/Chap-17_GreedyAlgosAndInvariants/17.6-gasup_problem.py
549
4
4
#!/usr/local/bin/python3 def find_ample_city(gallons, distances): """ gallons: """ MPG = 20 CityAndRemainingGas = collections.namedtuple('CityAndRemainingGas', ('city', 'gas_left')) tracker = CityAndRemainingGas(0, 0) gas_left = 0 for i in range(1, len(gallons)): gas_left += gallons[i - 1] - distances[i - 1] // MPG if gas_left < tracker.gas_left: tracker = CityAndRemainingGas(i, gas_left) return tracker.city if __name__ == '__main__': print('Gasup problem -> Find the ample city')
1e8bc356c964566b39fee90303b2802f35ee9261
roukaour/sudoku
/sudoku.py
1,755
3.765625
4
#!/usr/bin/python from __future__ import print_function from board import Sudoku from strategies import * from argparse import ArgumentParser import sys def solve_board(board, guess, verbose): """Solve a single board.""" board = Sudoku(board) exclude = None if guess else [999] board.solve(exclude=exclude, verbose=verbose) board.verify() def solve_boards(file, guess, verbose): """Solve each board in a text file.""" if verbose: print('#', 'solved?', 'board', 'strategy', sep='\t') exclude = None if guess else [999] with open(file, 'r') as boards: for line in boards: line = line.strip() if not line or line.startswith('#'): continue board = Sudoku(line) n = board.num_solved() hardest = board.solve(exclude=exclude) try: board.verify() except: print('*** ERROR:', line) Sudoku(line).solve(exclude=exclude, verbose=True) break if verbose: print(board.num_solved() - n, 'TRUE' if board.solved() else 'FALSE', line, hardest, sep='\t') def main(): parser = ArgumentParser(description='Human-style Sudoku solver') parser.add_argument('-g', '--guess', action='store_true', help='allow guessing to solve') parser.add_argument('-q', '--quiet', action='store_true', help='solve a board without printing anything') parser.add_argument('-f', '--file', help='solve each board in a text file and output overall results as tab-separated data') parser.add_argument('BOARD', nargs='?', help='a single board to solve') args = vars(parser.parse_args()) if args['BOARD']: solve_board(args['BOARD'], args['guess'], not args['quiet']) elif args['file']: solve_boards(args['file'], args['guess'], not args['quiet']) else: parser.print_usage() if __name__ == '__main__': main()
0101b92b380ddffa087c861efafa8e4b09d422f3
gilmana/Gilman_earning
/mortgage_calculator/mortgage_app.py
1,710
3.859375
4
import numpy as np import pandas as pd loan_params = [] def create_loan(): """ Everytime the function is run, the user will be asked to enter paramers of the loan. The parameters of each loan are appended as a dictionary to a list containing all the laons of interest. """ # enter terms of loan name = input("Assign name to the loan: ") principle = float(input("Loan ammount: ")) rate = (float(input("Annual interest rate (%): "))) duration = (int(input("loan duration in years: "))) p = principle r = rate / 12 / 100 n = duration * 12 # Calculating monthly payment numerator = r * p * ((1 + r) ** n) denomenator = ((1 + r) ** n) - 1 m = numerator / denomenator # append loan to loans list loan_params.append({"loan_id": name, "principle": principle, "rate": rate, "duration": duration, "m_payment": m}) def amortization_schedule(): """ generate an amortization schedule dataframe for each loan. input: loan_params list of dictionaries containing loan paramers keys:values :return: dictionary of dataframes, with loan name as keys, and dictionary of amortization schedule """ amortization = {} for i in loan_params: name = i["loan_id"] n = i["duration"] * 12 m = i["m_payment"] month_series = np.arange(1, (n + 1)) payment_series = np.full((n,), m) df = pd.DataFrame({"Month": month_series, "Payment": payment_series}) df["Total paid"] = df["Payment"].cumsum().round(1) # total paid amortization[name] = df return amortization
4981aee884cbc2ffa682075accd271551328e57f
deepanjanroy/206reviewsession
/python/todo/sliceme.py
156
3.859375
4
l = [1,2,3,4,5] def f(x): # Implement me! # return 3 elements, starting from the second element (element at index 1) return x[1:4] print f(l)
f4b6fe0476f53dec1144ccc600408ff7caab46ab
deepika087/CompetitiveProgramming
/LeetCodePractice/32. Longest Valid Parentheses.py
2,236
3.578125
4
class Solution(object): #such that ()()() will return 6 and ()(()) will return 6 def longestValidParentheses(self, arr): #tutorial : https://leetcode.com/problems/longest-valid-parentheses/solution/ stack = [] max_len = 0 for i in range(len(arr)): if arr[i] == '(': stack.append(i) else: if len(stack) > 0: popped = stack.pop(-1) if arr[popped] == '(': continue else: stack.append(i) if (len(stack) == 0): return len(arr) print stack a = len(arr) b = 0 longest = 0 while stack: b = stack.pop(-1) longest = max(longest, a-b-1) a = b longest = max(longest, a) return longest def longestValidParenthesesEasier(self, string): n = len(string) # Create a stack and push -1 as initial index to it. stk = [] stk.append(-1) # Initialize result result = 0 # Traverse all characters of given string for i in xrange(n): # If opening bracket, push index of it if string[i] == '(': stk.append(i) else: # If closing bracket, i.e., str[i] = ')' # Pop the previous opening bracket's index stk.pop() # Check if this length formed with base of # current valid substring is more than max # so far if len(stk) != 0: print "Value: ", stk[len(stk)-1] # I think this is next to top result = max(result, i - stk[len(stk)-1]) # If stack is empty. push current index as # base for next valid substring (if any) else: stk.append(i) return result s=Solution() print s.longestValidParenthesesEasier("()") print s.longestValidParenthesesEasier("(()") print s.longestValidParenthesesEasier("()()()") print s.longestValidParenthesesEasier(")()())()()(") #assert s.longestValidParenthesesIBM(")()())()()(") == 4
3108e4211a75e8cdd5c33bdfda07c15b08e15a30
Djenzenpan/Datavisualisatie
/Homework/Week_1/moviescraper.py
5,242
3.78125
4
#!/usr/bin/env python # Name: Jesse Pannekeet # Student number: 10151494 """ This script scrapes IMDB and outputs a CSV file with highest rated movies. """ import csv from requests import get from requests.exceptions import RequestException from contextlib import closing from bs4 import BeautifulSoup TARGET_URL = "https://www.imdb.com/search/title?title_type=feature&release_date=2008-01-01,2018-01-01&num_votes=5000,&sort=user_rating,desc" BACKUP_HTML = 'movies.html' OUTPUT_CSV = 'movies.csv' def extract_movies(dom): """ Extract a list of highest rated movies from DOM (of IMDB page). Each movie entry should contain the following fields: - Title - Rating - Year of release (only a number!) - Actors/actresses (comma separated if more than one) - Runtime (only a number!) """ # creates list of lists of actors in each movie # initialises moviesactors list for storage moviesactors = [] # determines when the program should start adding to the moviesactors list actortime = False for i in dom.find_all('p'): actors = [] # leaves first value for each movie out of the list as this is the director first = True director_and_actors = i.find_all('a', href=True) for director_or_actor in director_and_actors: if director_or_actor.string != None and first == False: actors.append(director_or_actor.string) first = False # only appends to moviesactors list if first movie is found and actors are found if len(actors) > 0: if actortime == True: moviesactors.append(actors) if actors[0] == 'Community': actortime=True # finds all movie ratings and puts them in list allratings = [] # determines when movies are found ratings = False for rating in dom.find_all('strong'): # appends rating to ratings list when first movie is found if ratings == True: allratings.append(rating.string) if 'User Rating' == rating.string: ratings = True # adds all relevant movie details to the movie list movies = [] # moves over each movie's rating, year, title, actors and runtime for rating, year, title, actors, runtime in zip(allratings, dom.find_all('span', 'lister-item-year text-muted unbold'), dom.find_all('h3'), moviesactors, dom.find_all('span', 'runtime')): # removes unused characters from release year if '(I)' in year.string: year.string = year.string[5:9] elif '(II)' in year.string: year.string = year.string[6:10] else: year.string = year.string[1:5] # removes unused characters from runtime runtime.string = runtime.string[:3] # adds relevant movie date to a list of movies movie = title.a.string, rating, year.string, actors, runtime.string movies.append(movie) # HIGHEST RATED MOVIES # NOTE: FOR THIS EXERCISE YOU ARE ALLOWED (BUT NOT REQUIRED) TO IGNORE # UNICODE CHARACTERS AND SIMPLY LEAVE THEM OUT OF THE OUTPUT return[movies] # REPLACE THIS LINE AS WELL IF APPROPRIATE def has_class_but_no_id(tag): return tag.has_attr('href') def save_csv(outfile, movies): """ Output a CSV file containing highest rated movies. """ writer = csv.writer(outfile) writer.writerow(['Title', 'Rating', 'Year', 'Actors', 'Runtime']) # adds all movies to the csv file for movie in movies: for value in movie: writer.writerow(value) def simple_get(url): """ Attempts to get the content at `url` by making an HTTP GET request. If the content-type of response is some kind of HTML/XML, return the text content, otherwise return None """ try: with closing(get(url, stream=True)) as resp: if is_good_response(resp): return resp.content else: return None except RequestException as e: print('The following error occurred during HTTP GET request to {0} : {1}'.format(url, str(e))) return None def is_good_response(resp): """ Returns true if the response seems to be HTML, false otherwise """ content_type = resp.headers['Content-Type'].lower() return (resp.status_code == 200 and content_type is not None and content_type.find('html') > -1) if __name__ == "__main__": # get HTML content at target URL html = simple_get(TARGET_URL) # save a copy to disk in the current directory, this serves as an backup # of the original HTML, will be used in grading. with open(BACKUP_HTML, 'wb') as f: f.write(html) # parse the HTML file into a DOM representation dom = BeautifulSoup(html, 'html.parser') # extract the movies (using the function you implemented) movies = extract_movies(dom) # write the CSV file to disk (including a header) with open(OUTPUT_CSV, 'w', newline='') as output_file: save_csv(output_file, movies)
dfc0a27b435d242d61789ca5693ccb1a7b3b28eb
dev2404/Python_Strings
/longest_palindrome.py
262
3.90625
4
def longest_palindrome(string): m="" for i in range(len(string)): for j in range(len(string)-1,i, -1): if len(m) >= j-i: break elif string[i:j] == string[i:j][::-1]: m = string[i:j] break return m print(longest_palindrome("cbbddd"))
f90c3417ee264062b3c5c64066d71ab66abc9cf8
wenchi53/LeetCode
/Python/26_removeDuplicates.py
356
3.609375
4
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 result = 0 for i in xrange(1,len(nums)): if nums[result] != nums[i]: result += 1 nums[result] = nums[i] return result+1 mySolution = Solution() print mySolution.removeDuplicates([1,1,2])
c0cc0a984151b5ebfc9e9a9c53957ef0ebf61814
grey-area/advent-of-code-2017
/day19/parts1_and_2.py
791
3.59375
4
with open('input') as f: data = f.read().splitlines() # Initial position x = data[0].index('|') y = 0 # Initial velocity dx = 0 dy = 1 letters_seen = '' steps = 0 while data[y][x] != ' ': # Step forwards x += dx y += dy steps += 1 # If we see a letter, add it to the sequence seen if data[y][x].isalpha(): letters_seen += data[y][x] # If we're at a corner elif data[y][x] == '+': # Look for a direction we can step that isn't where we just came from for dx1, dy1 in [(-1, 0), (1, 0), (0, -1), (0, 1)]: if data[y + dy1][x + dx1] != ' ' and not (dx1 == -dx and dy1 == -dy): dx = dx1 dy = dy1 break print(f'Letters seen: {letters_seen}') print(f'{steps} steps taken')
e85eb58c0ca0149e27a334e5fb0e3a745c316b0c
congthanh97/root
/Python/New folder (2)/bai3.py
572
3.75
4
array = [1,4,2,5,7,9,2,3] array.sort() num1 = int(input("input num1: ")) print("day so nho hon ",num1) for i in range(0,len(array)): if array[i] < num1: print("number %d "%array[i]) else: break a = list() for i in range(0,len(array)): if array[i] < num1: a.append(array[i]) else: break print(a) b = list() number = int(input("input so muon in: ")) for i in range(0,number): if array[i] < num1: b.append(array[i]) else: break print(b) print("áhfdjashkfdjahkjf") print([i for i in array if(i < 5)])
ff9bc4c029ec053412e6ec1bc24ed5d8ed5b2494
Einstellung/AlgorithmByPython
/BinarySearch.py
478
3.96875
4
# 实现一个二分查找 # 输入:一个顺序list # 输出: 待查找的元素的位置 def binarySearch(alist, item): first = 0 last = len(alist) - 1 while first <= last: mid = (first + last)//2 print(mid) if alist[mid] > item: last = mid - 1 elif alist[mid] < item: first = mid + 1 else: return mid+1 return -1 test = [0, 1, 2, 8, 13, 17, 19, 32, 42] print(binarySearch(test, 3))
40413d7298bc481abada5db93117edcef23aaa78
humbertoperdomo/practices
/python/PythonCrashCourse/PartI/Chapter04/cubes_comprehension.py
102
3.578125
4
#!/usr/bin/python3 cubes = [value**3 for value in range(1, 11)] for value in cubes: print(value)
d67c6a3284ebe5728f05d2c677fe11b5f3b341b1
kris71990/China_info
/china.py
13,795
3.5625
4
# This program stores information related to regions and cities in China in dicts and lists # Through user interaction, it then presents the desired information import webbrowser, requests, bs4 from num2words import num2words import chinadicts def start(): print(u'\n\u4f60\u597d, let\'s learn about China!') start_again() def start_again(): print("\nType 'province' or 'capital' for more information.") print("Type 'q' to quit.") prompt = input("> ").lower() while True: if prompt == 'province': province_info() more_info() break elif prompt == 'capital': capital_info() more_info() break elif prompt == 'q' or prompt == 'quit': print(u'\nHope you enjoyed learning about China, \u518d\u89c1!') exit(0) else: print("Type one of the keywords: ",) prompt = input() def province_info(): print("\nHere is a list of the " + num2words(len(provdicts.province)) + " provinces" \ " in China and their abbreviations: \n") for prov, abbrev in sorted(provdicts.province.items()): if prov == "Taiwan": print("* %s --> %s" % (prov, abbrev)) else: print("%s --> %s" % (prov, abbrev)) print("\nAdditionally, here are the " + num2words(len(mundicts.municipality)) + \ " municipalities and their abbreviations: \n") for mun, abbrev in sorted(mundicts.municipality.items()): print("%s --> %s" % (mun, abbrev)) print("\nHere are the " + num2words(len(autregdicts.autregion)) + " autonomous regions" \ " and their abbreviations: \n") for autreg, abbrev in sorted(autregdicts.autregion.items()): print("%s --> %s" % (autreg, abbrev)) print("\nThese are the " + num2words(len(admregdicts.admregion)) + " Special Adminstrative" \ " Regions and their abbreviations: \n") for admreg, abbrev in sorted(admregdicts.admregion.items()): print("%s --> %s" % (admreg, abbrev)) def capital_info(): print("\nHere is a list of each province's capital: \n") for province, capital in sorted(provdicts.prov_capitals.items()): if province == "Taiwan": print("* %s --> %s" % (province, capital)) else: print("%s --> %s" % (province, capital)) print("\nHere is each municipality's capital: \n") for mun, capital in sorted(mundicts.mun_capitals.items()): print("%s --> %s" % (mun, capital)) print("\nCapitals of Autonomous Regions: \n") for autregion, capital in sorted(autregdicts.autregion_capitals.items()): print("%s --> %s" % (autregion, capital)) print("\nCapitals of Special Administrative Regions: \n") for admregion, capital in sorted(admregdicts.admregion_capitals.items()): print("%s --> %s" % (admregion, capital)) def more_info(): provinces = [] province_abbrev = [] prov_capital = [] municipalities = [] mun_abbrev = [] mun_capital = [] autregions = [] aut_abbrev = [] autregion_cap = [] admregions = [] adm_abbrev = [] admregion_capital = [] for key, value in sorted(provdicts.province.items()): provinces.append(key) province_abbrev.append(value) for key, value in sorted(provdicts.prov_capitals.items()): prov_capital.append(value) for key, value in sorted(mundicts.municipality.items()): municipalities.append(key) mun_abbrev.append(value) for key, value in sorted(mundicts.mun_capitals.items()): mun_capital.append(value) for key, value in sorted(autregdicts.autregion.items()): autregions.append(key) aut_abbrev.append(value) for key, value in sorted(autregdicts.autregion_capitals.items()): autregion_cap.append(value) for key, value in admregdicts.admregion.items(): admregions.append(key) adm_abbrev.append(value) for key, value in admregdicts.admregion_capitals.items(): admregion_capital.append(value) while True: print("\nType a province's abbreviation for more information about each territory. ") print("For a list of province abbreviations, type 'province'.") print("Type 'q' to quit.") x = input("> ").lower() if x == 'q': print(u'\nHope you enjoyed learning about China, \u518d\u89c1!') exit(0) elif x == 'capital': capital_info() continue elif x == 'province': province_info() continue elif x == "ah": print_more_info_prov(provinces[0], province_abbrev[0], province_pop[0], prov_pop_rank[0], prov_area[0], prov_area_rank[0], prov_capital[0], prov_cap_pop[0]) continue elif x == "bj": print_more_info_muni(municipalities[0], mun_abbrev[0], muni_pop[0], muni_pop_rank[0], muni_area[0], muni_area_rank[0], mun_capital[0], muni_cap_pop[0]) continue elif x == "cq": print_more_info_muni(municipalities[1], mun_abbrev[1], muni_pop[1], muni_pop_rank[1], muni_area[1], muni_area_rank[1], mun_capital[1], muni_cap_pop[1]) continue elif x == "fj": print_more_info_prov(provinces[1], province_abbrev[1], province_pop[1], prov_pop_rank[1], prov_area[1], prov_area_rank[1], prov_capital[1], prov_cap_pop[1]) continue elif x == "gs": print_more_info_prov(provinces[2], province_abbrev[2], province_pop[2], prov_pop_rank[2], prov_area[2], prov_area_rank[2], prov_capital[2], prov_cap_pop[2]) continue elif x == "gd": print_more_info_prov(provinces[3], province_abbrev[3], province_pop[3], prov_pop_rank[3], prov_area[3], prov_area_rank[3], prov_capital[3], prov_cap_pop[3]) continue elif x == "gx": print_more_info_autreg(autregions[0], aut_abbrev[0], autregion_pop[0], autregion_pop_rank[0], autregion_area[0], autregion_area_rank[0], autregion_cap[0], autregion_cap_pop[0]) continue elif x == "gz": print_more_info_prov(provinces[4], province_abbrev[4], province_pop[4], prov_pop_rank[4], prov_area[4], prov_area_rank[4], prov_capital[4], prov_cap_pop[4]) continue elif x == "hi": print_more_info_prov(provinces[5], province_abbrev[5], province_pop[5], prov_pop_rank[5], prov_area[5], prov_area_rank[5], prov_capital[5], prov_cap_pop[5]) continue elif x == "he": print_more_info_prov(provinces[6], province_abbrev[6], province_pop[6], prov_pop_rank[6], prov_area[6], prov_area_rank[6], prov_capital[6], prov_cap_pop[6]) continue elif x == "hl": print_more_info_prov(provinces[7], province_abbrev[7], province_pop[7], prov_pop_rank[7], prov_area[7], prov_area_rank[7], prov_capital[7], prov_cap_pop[7]) continue elif x == "ha": print_more_info_prov(provinces[8], province_abbrev[8], province_pop[8], prov_pop_rank[8], prov_area[8], prov_area_rank[8], prov_capital[8], prov_cap_pop[8]) continue elif x == "hk": print_more_info_admreg(admregions[0], adm_abbrev[0], admregion_pop[0], admregion_pop_rank[0], admregion_area[0], admregion_area_rank[0], admregion_capital[0], admregion_pop[0]) continue elif x == "hb": print_more_info_prov(provinces[9], province_abbrev[9], province_pop[9], prov_pop_rank[9], prov_area[9], prov_area_rank[9], prov_capital[9], prov_cap_pop[9]) continue elif x == "hn": print_more_info_prov(provinces[10], province_abbrev[10], province_pop[10], prov_pop_rank[10], prov_area[10], prov_area_rank[10], prov_capital[10], prov_cap_pop[10]) continue elif x == "nm": print_more_info_autreg(autregions[1], aut_abbrev[1], autregion_pop[1], autregion_pop_rank[1], autregion_area[1], autregion_area_rank[1], autregion_cap[1], autregion_cap_pop[1]) continue elif x == "js": print_more_info_prov(provinces[11], province_abbrev[11], province_pop[11], prov_pop_rank[11], prov_area[11], prov_area_rank[11], prov_capital[11], prov_cap_pop[11]) continue elif x == "jx": print_more_info_prov(provinces[12], province_abbrev[12], province_pop[12], prov_pop_rank[12], prov_area[12], prov_area_rank[12], prov_capital[12], prov_cap_pop[12]) continue elif x == "jl": print_more_info_prov(provinces[13], province_abbrev[13], province_pop[13], prov_pop_rank[13], prov_area[13], prov_area_rank[13], prov_capital[13], prov_cap_pop[13]) continue elif x == "ln": print_more_info_prov(provinces[14], province_abbrev[14], province_pop[14], prov_pop_rank[14], prov_area[14], prov_area_rank[14], prov_capital[14], prov_cap_pop[14]) continue elif x == "mc": print_more_info_admreg(admregions[1], adm_abbrev[1], admregion_pop[1], admregion_pop_rank[1], admregion_area[1], admregion_area_rank[1], admregion_capital[1], admregion_pop[1]) continue elif x == "nx": print_more_info_autreg(autregions[2], aut_abbrev[2], autregion_pop[2], autregion_pop_rank[2], autregion_area[2], autregion_area_rank[2], autregion_cap[2], autregion_cap_pop[2]) continue elif x == "qh": print_more_info_prov(provinces[15], province_abbrev[15], province_pop[15], prov_pop_rank[15], prov_area[15], prov_area_rank[15], prov_capital[15], prov_cap_pop[15]) continue elif x == "sn": print_more_info_prov(provinces[16], province_abbrev[16], province_pop[16], prov_pop_rank[16], prov_area[16], prov_area_rank[16], prov_capital[16], prov_cap_pop[16]) continue elif x == "sd": print_more_info_prov(provinces[17], province_abbrev[17], province_pop[17], prov_pop_rank[17], prov_area[17], prov_area_rank[17], prov_capital[17], prov_cap_pop[17]) continue elif x == "sh": print_more_info_muni(municipalities[2], mun_abbrev[2], muni_pop[2], muni_pop_rank[2], muni_area[2], muni_area_rank[2], mun_capital[2], muni_cap_pop[2]) continue elif x == "sx": print_more_info_prov(provinces[18], province_abbrev[18], province_pop[18], prov_pop_rank[18], prov_area[18], prov_area_rank[18], prov_capital[18], prov_cap_pop[18]) continue elif x == "sc": print_more_info_prov(provinces[19], province_abbrev[19], province_pop[19], prov_pop_rank[19], prov_area[19], prov_area_rank[19], prov_capital[19], prov_cap_pop[19]) continue elif x == "tw": print_more_info_prov(provinces[20], province_abbrev[20], province_pop[20], prov_pop_rank[20], prov_area[20], prov_area_rank[20], prov_capital[20], prov_cap_pop[20]) continue elif x == "tj": print_more_info_muni(municipalities[3], mun_abbrev[3], muni_pop[3], muni_pop_rank[3], muni_area[3], muni_area_rank[3], mun_capital[3], muni_cap_pop[3]) continue elif x == "xz": print_more_info_autreg(autregions[3], aut_abbrev[3], autregion_pop[3], autregion_pop_rank[3], autregion_area[3], autregion_area_rank[3], autregion_cap[3], autregion_cap_pop[3]) continue elif x == "xj": print_more_info_autreg(autregions[4], aut_abbrev[4], autregion_pop[4], autregion_pop_rank[4], autregion_area[4], autregion_area_rank[4], autregion_cap[4], autregion_cap_pop[4]) continue elif x == "yn": print_more_info_prov(provinces[21], province_abbrev[21], province_pop[21], prov_pop_rank[21], prov_area[21], prov_area_rank[21], prov_capital[21], prov_cap_pop[21]) continue elif x == "zj": print_more_info_prov(provinces[22], province_abbrev[22], province_pop[22], prov_pop_rank[22], prov_area[22], prov_area_rank[22], prov_capital[22], prov_cap_pop[22]) continue else: print("Type a province abbreviation, or 'q' to quit: ") x = input("> ").lower() if x == 'q': print(u'\nHope you enjoyed learning about China, \u518d\u89c1!') exit(0) def print_more_info_prov(p, pab, pp, ppr, pa, par, pc, pcp): print("\nHere is some information about %s:\n" % p) print("Abbreviation: %s" % pab) print("Population: %s (%s)" % (pp, ppr)) print("Area: %s square km (%s)" % (pa, par)) print("Capital: %s" % pc) print("Population of %s: %s" % (pc, pcp)) print("\nType 'wiki' to read even more about %s! " % p) wiki = input().lower() if wiki == 'wiki': webbrowser.open("https://en.wikipedia.org/wiki/%s" % p) webbrowser.open("https://en.wikipedia.org/wiki/%s" % pc) def print_more_info_muni(m, mab, mp, mpr, ma, mar, mc, mcp): print("\nHere is some information about %s:\n" % m) print("Abbreviation: %s" % mab) print("Population: %s (%s)" % (mp, mpr)) print("Area: %s square km (%s)" % (ma, mar)) print("Capital: %s" % mc) print("Population of %s: %s" % (mc, mcp)) print("\nType 'wiki' to read even more about %s! " % m) wiki = input().lower() if wiki == 'wiki': webbrowser.open("https://en.wikipedia.org/wiki/%s" % m) def print_more_info_autreg(aur, aurab, aurp, aurpr, aura, aurar, aurc, aurcp): print("\nHere is some information about %s Autonomous Region:\n" % aur) print("Abbreviation: %s" % aurab) print("Population: %s (%s)" % (aurp, aurpr)) print("Area: %s square km (%s)" % (aura, aurar)) print("Capital: %s" % aurc) print("Population of %s: %s" % (aurc, aurcp)) print("\nType 'wiki' to read even more about %s! " % aur) wiki = input().lower() if wiki == 'wiki': webbrowser.open("https://en.wikipedia.org/wiki/%s" % aur) webbrowser.open("https://en.wikipedia.org/wiki/%s" % aurc) def print_more_info_admreg(admr, admrab, admrp, admrpr, admra, admrar, admrc, admrcpr): print("\nHere is some information about %s:\n" % admr) print("Abbreviation: %s" % admrab) print("Population: %s (%s)" % (admrp, admrpr)) print("Area: %s square km (%s)" % (admra, admrar)) print("Capital: %s" % admrc) print("Population of %s: %s" % (admr, admrcpr)) print("\nType 'wiki' to read even more about %s! " % admr) wiki = input().lower() if wiki == 'wiki': webbrowser.open("https://en.wikipedia.org/wiki/%s" % admr) start()
d4afee956c3992976c71bbe839a9410c5145bdab
Brooks-Willis/softdes
/chap04/polygon.py
1,483
4.3125
4
"""Created as a solution to an excersize in thinkpython by Allen Downey Written by Brooks Willis Creates a polygon with any number of sides of any length or an arc of set set radius and sweep angle """ from swampy.TurtleWorld import * from math import pi world = TurtleWorld() bob = Turtle() bob.delay = 0.01 def lines(bob,length,n,angle): """Draws n lines of given length bob: Turtle length: length of each side n: number of sides angle: angle between segments in degrees """ for i in range(n): fd(bob,length) lt(bob,angle) def polygon(t,length,n): """Creates a polygon with n sides t: Turtle length: length of each sides n: number of sides """ angle = 360.0/n lines(t,length,n,angle) def square(t,length): """Creates a square of variable side length t: Turtle length: Length of each side """ for i in range(4): fd(t,length) lt(t) def arc(t,angle,r): """Creates a arc of radius r overa given angle t: Turtle angle: angle covered by the arc r: radius of the arc """ arclength = (2*pi*r*abs(angle))/360 n = int(arclength/4) +1#number of line segments linelength = arclength/n lineangle = float(angle)/n lines(t,linelength,n,lineangle) def circle(t,r): """Creates a circle of radius r t: Turtle r: radius of the circle """ arc(t,360,r) circle(bob,75) polygon(bob,100,6) arc(bob,90,50) wait_for_user()
f1e71a78120bdddcd2d9510ea42b6b5c554484d7
haodonghui/python
/learning/py3/基本数据类型/Number(数字)/isinstance 和 type 的区别.py
781
4.21875
4
""" 查询变量所指的对象类型 内置的 type() 函数可以用来查询变量所指的对象类型。 此外还可以用 isinstance 来判断 isinstance 和 type 的区别在于: type()不会认为子类是一种父类类型。 isinstance()会认为子类是一种父类类型。 """ print('======type') # type() a, b, c, d = 20, 5.5, True, 4 + 3j print(type(a), type(b), type(c), type(d)) # <class 'int'> <class 'float'> <class 'bool'> <class 'complex'> print('======isinstance') # isinstance a = 1 print(isinstance(a, int)) # True print('======区别') # 区别 class A: pass class B(A): pass print(isinstance(A(), A)) # True print(type(A()) == A) # True print(isinstance(B(), A)) # True print(type(B) == A) # False
0e7f4ab012d7043608dbe98b4ffcb0e2cd9a806d
nykh2010/python_note
/02pythonBase/day03/res/if3.py
395
3.765625
4
#1、输入一个整数,用程序判断数据是奇数还是偶数,并打印输出? #2、输入一个整数,用程序判断数据是正数还是负数,并打印输出? # a = input("输入整数") # b = int(a) b = int(input("输入整数")) # if b%2 == 0: # print("偶数") # else: # print("奇数") if b%2 != 0: print("奇数") else: print("偶数") print("end")
e51236325c41793ca0eacf5a0dee0065da12d915
yeboahd24/python202
/python_etc_4/filtering.py
732
4.125
4
#!usr/bin/env/python3 # Sometimes, the filtering criteria cannot be easily expressed in a list comprehension or # generator expression. For example, suppose that the filtering process involves exception # handling or some other complicated detail. For this, put the filtering code into its own # function and use the built-in filter() function. For example: values = ['1', '2', '-3', '-', '4', 'N/A', '5'] def is_int(val): try: x = int(val) return True except ValueError: return False ivals = list(filter(is_int, values)) print(ivals) # Outputs ['1', '2', '-3', '4', '5'] # filter() creates an iterator, so if you want to create a list of results, make sure you also # use list() as shown. #
7e97fcd60de55b89a1725cfaa5b4cdf4b7d20c9c
maw3193/aoc-2016
/12/12-1.py
2,574
3.640625
4
#!/usr/bin/python import argparse, sys, re parser = argparse.ArgumentParser(description="Program to solve Advent of Code for 2016-12-12") parser.add_argument("--input", default="input.txt") args = parser.parse_args() # 4 registers, a, b, c, d # instruction cpy x y (copies value of x into y) # instruction inc x (increases x by 1) # instruction dec x (decreases x by 1) # instruction jnz x y (jumps y (positive or negative) steps if x isn't zero) state = {"registers": {"a": 0, "b": 0, "c": 0, "d": 0}, "pos": 0} instructions = [] def do_copy(state, src, dest): if type(src) == int: state["registers"][dest] = src elif type(src) == str: state["registers"][dest] = state["registers"][src] else: sys.exit("Unexpected type in do_copy: %s" % str(type(src))) def do_inc(state, reg): state["registers"][reg] += 1 def do_dec(state, reg): state["registers"][reg] -= 1 def do_jnz(state, reg, steps): if type(reg) == int: if reg == 0: return elif type(reg) == str: if state["registers"][reg] == 0: return else: sys.exit("Unexpected type in do_jnz: %s" % str(type(reg))) # Subtracting as horrible bodge state["pos"] += steps - 1 def parse_instruction(line): # Copy constant m = re.match("cpy (\d+) (\w)", line) if m: return [do_copy, {"src": int(m.group(1)), "dest": m.group(2), "state": state}] # Copy register m = re.match("cpy (\w) (\w)", line) if m: return [do_copy, {"src": m.group(1), "dest": m.group(2), "state": state}] # Increase register m = re.match("inc (\w)", line) if m: return [do_inc, {"reg": m.group(1), "state": state}] # Decrease register m = re.match("dec (\w)", line) if m: return [do_dec, {"reg": m.group(1), "state": state}] # Jump if non-zero (constant) m = re.match("jnz (\d+) (-?\d+)", line) if m: return [do_jnz, {"reg": int(m.group(1)), "steps": int(m.group(2)), "state": state}] # Jump if non-zero (register) m = re.match("jnz (\w) (-?\d+)", line) if m: return [do_jnz, {"reg": m.group(1), "steps": int(m.group(2)), "state": state}] sys.exit("Unhandled instruction '%s'" % line) with open(args.input, "r") as f: for line in f: instructions.append(parse_instruction(line)) while(state["pos"] < len(instructions)): instruction = instructions[state["pos"]] instruction[0](**instruction[1]) state["pos"] += 1 for register in state["registers"].iteritems(): print(register)
5312d89ce46b6bd7b7c0e481e3c2836638bb050e
MarlonMa/recreation
/drinker.py
1,516
3.90625
4
#!/usr/bin/env python """Program to calculate how many bottles of wine the drinkers with specified amount of money can drink. ========== Conditions: 1 bottle of wine is worth 2 yuan 2 bottles can exchange for 1 bottle of wine 4 caps can exchange for 1 bottle of wine ========== """ class Drinker: def __init__(self, money): self.property = money self.money = money self.drunk = 0 self.bottle = 0 self.cap = 0 def exchange_wine(self): exchangeable = 0 if self.money >= 2: e1, self.money = divmod(self.money, 2) exchangeable += e1 if self.bottle >= 2: e2, self.bottle = divmod(self.bottle, 2) exchangeable += e2 elif self.cap >= 4: e3, self.cap = divmod(self.cap, 4) exchangeable += e3 self.drunk += exchangeable self.bottle += exchangeable self.cap += exchangeable def drink_wine(drinker): while True: if drinker.money >= 2 or drinker.bottle >= 2 or drinker.cap >= 4: drinker.exchange_wine() else: print("%s yuan can drink %s %s of wine" % (drinker.property, drinker.drunk, 'bottles' if drinker.drunk > 1 else 'bottle')) break if __name__ == '__main__': drinker1 = Drinker(10) drinker2 = Drinker(10 ** 5) drinker3 = Drinker(10 ** 8) for drinker in [drinker1, drinker2, drinker3]: drink_wine(drinker)
f2bb53923db08fb7ee8919ada7dde17d9ade7415
ctlewitt/PracticeProblems
/guessing_game.py
756
4.21875
4
# have the computer think of an integer between 1 and 100 # have a human guess the number responding "higher" or "lower" for incorrect guesses # bonus points: keep a high-score table with names that persists between runs import random MIN_NUM = 1 MAX_NUM = 100 def guessing_game(): number = random.randint(MIN_NUM, MAX_NUM) num_guesses = 0 guessed = False while not guessed: guess = int(input("Guess a number between {} and {}: ".format(MIN_NUM, MAX_NUM))) num_guesses += 1 if number == guess: guessed = True print("Yay! You got it in {} tries!!".format(num_guesses)) elif guess < number: print("Higher...") else: print("Lower...") guessing_game()
0d0c0f8ae10d85b9fb08eeddb9dda074c0c74a8b
Zahidsqldba07/coding-problems-2
/dynamic-programming/Andrey-Grehov/0015_top_down_bottom_up.py
2,140
3.953125
4
import unittest from collections import Counter # recursive def fib(n): if n == 0: return 0 if n <= 2: return 1 return fib(n-1) + fib(n-2) # top down -> recursion + memoization def fib_top_down(n): memo = Counter() return fib_top_down_helper(n, memo) def fib_top_down_helper(n, memo): if n == 0: return 0 if n <= 2: return 1 if memo[n] > 0: return memo[n] memo[n] = fib_top_down_helper(n-1, memo) + fib_top_down_helper(n-2, memo) return memo[n] # bottom-up dynamic programming (forward dynamic programming) # # f(i-1) # \ # >-------> f(i) # / # f(i-2) def fib_bottom_up_dp_forward(n): if n == 0: return 0 if n <= 2: return 1 dp = [None] * (n+1) dp[0] = 0 dp[1] = 1 for i in range(2, n+1): dp[i] = dp[i-1] + dp[i-2] return dp[n] # this is a bottom-up dynamic programming (backward dynamic programming) # # -----> f(i+2) # | # f(i) # | # -----> f(i+1) def fib_bottom_up_dp_backward(n): if n == 0: return 0 if n <= 2: return 1 dp = [0] * (n+2) dp[0] = 0 dp[1] = 1 for i in range(1, n): dp[i+1] += dp[i] # dp[i] is already solved; use it to solve other subproblems dp[i+2] += dp[i] return dp[n] class Test(unittest.TestCase): '''Test Cases: (n, expected)''' data = [ (0, 0), (1, 1), (2, 1), (10, 55), ] def test_fib(self): for (n, expected) in self.data: actual = fib(n) self.assertEqual(actual, expected) def test_fib_top_down(self): for (n, expected) in self.data: actual = fib_top_down(n) self.assertEqual(actual, expected) def test_fib_bottom_up_dp_forward(self): for (n, expected) in self.data: actual = fib_bottom_up_dp_forward(n) self.assertEqual(actual, expected) def test_fib_bottom_up_dp_backward(self): for (n, expected) in self.data: actual = fib_bottom_up_dp_forward(n) self.assertEqual(actual, expected) if __name__ == "__main__": unittest.main()
e91e78cdabc9de8377bbb42bc830e0f299041659
hofertg/web-caesar
/caesar.py
619
3.71875
4
# Copied functions from previous Caesar project #from Caesar def encrypt(text, rot): encrypted = "" for letter in text: encrypted += rotate_character(letter, rot) return encrypted #from helpers def alphabet_position(letter): letter = letter.upper() return "ABCDEFGHIJKLMNOPQRSTUVWXYZ".index(letter) def rotate_character(char, rot): if not char.isalpha(): return char pos = alphabet_position(char) rotpos = (pos + rot) % 26 rotchar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[rotpos] if char == char.upper(): return rotchar else: return rotchar.lower()
37216445dab351f20c4557a1c33a2fbad9d27806
Allen-ITD-2313/hello-world
/math.py
223
3.890625
4
def main(): iteration = int(input("Please enter a value for iterations:")) total=0 for i in range(1,iteration): total += (-1)**(i+1)*((1.0/(i+i+1))) pi = 4*(1-total) print(pi) main()
357a704ac00196e34622b5ec2496177a794f7d8c
jeagle1286/Hort503
/Assignment04/ex18.py
638
4.09375
4
# this one is like your scripts with argv def print_two(*args): arg1, arg2, = args print(f"arg1: {arg1}, arg2: {arg2}") # DO not start a function name with a number #ok, that *args is actually pointless, we can just do this def print_two_again(arg1, arg2): print(f"arg1: {arg1}, arg2: {arg2}") # Args is like Argv which allows you to add arguments in a function # this just takes one argument def print_one(arg1): print(f"arg1: {arg1}") #Checklists are helpful #this one takes no argument def print_none(): print("I got nothing") print_two("Zed","Shaw") print_two_again("Zed","Shaw") print_one("First!") print_none()
81c932fefd0c379496e677fe298118c30f54e159
zx-joe/Computational-Motor-Control-for-Salamandar-Robot
/Lab0/Python/10_Classes.py
3,250
4.78125
5
#!/usr/bin/env python3 """This script introduces you to the usage of classes in Python. """ import farms_pylog as pylog #: Creating a new class class Animal: """New class for animal class. """ def __init__(self, name): """Initialization function with one input to set the name of the animal during initialization. """ super(Animal, self).__init__() self._name = None # : Internal class attribute # _ before variable indicates that this variable should not # be used by the user directly. # - self is special keyword in classes that points to itself. # The name self is a convention and not a Python keyword. self.name = name # Use of properties to set and get class attributes @property def name(self): """Get the name of the animal """ return self._name @name.setter def name(self, animal_name): """ Parameters ---------- animal_name : <str> Name of the animal. If it is not a string then a warning is thrown Returns ------- out : None """ # Check if animal is a string or not if not isinstance(animal_name, str): pylog.warning( 'You don\'t really know how to name your animals! ') # This also works and is useful for dealing with inheritance: if not isinstance(animal_name, str): pylog.warning( 'You don\'t really know how to name your animals! (isinstance)') self._name = animal_name # Use of this class pylog.info('Create a new animal using the Animal class') # Instantiate Animal object with a name animal = Animal('scooby') # Get the Class name and name of the animal created pylog.info('I am {} and my name is {}'.format(type(animal), animal.name)) # Use of @properties allows you to have more control over the # attributes of a class. # In this example we throw a funny warning to the user if they # create an animal with a name that is not a string. new_animal = Animal(1) # Class inheritance # You can make use of existing classes and then extend them with more # features. # Since animal is very generic we can use it and extend it to create # a cat class class Cat(Animal): """Class Inheritance. Create Cat as a child of Animal class. You now get access to all the attributes and methods of animal class for free! """ def __init__(self, cat_name): """You can use the name attribute from the Animal class. """ super(Cat, self).__init__(cat_name) def say_meow(self): """ Make the cat say its name and then meow. """ pylog.info('My master calls me {} and meow!'.format(self.name)) # Create a new cat chat = Cat('French') # Make the cat say meow # See how the Cat class inherits from Animal class to set and retrieve # its name # Methods of a class are accessed using the .dot operator chat.say_meow() # Check if the cat is an animal print("Is the cat of type animal (type): {}".format(isinstance(chat, Animal))) print("Is the cat an animal (isinstance): {}".format(isinstance(chat, Animal)))
606de12ff3f057c9005bb4f90520bf43708d325c
dennisnderitu254/HackerRank-3
/Python/numpy/dot-and-cross.py
215
3.609375
4
#!/usr/local/bin/python3 import numpy n = int(input()) array1 = numpy.array([input().split() for _ in range(n)], int) array2 = numpy.array([input().split() for _ in range(n)], int) print(numpy.dot(array1, array2))
bd9906a85365d75bb5d58693320ee23978610ae4
hehuanshu96/PythonWork
/dailycoding/TextStatistics/StatisticsTLBB.py
2,433
3.71875
4
# coding=utf-8 """ 统计天龙八部.txt里的一些文本信息 """ import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt mpl.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体 mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像的负号'-'显示为方块的问题 def read_characters(characters_path, txt_format='utf-8'): """ 将角色.txt中的所有人物名字提取出来并保存在一个list中。 """ names = [] with open(characters_path, 'r', encoding=txt_format) as f: # 对于Python3最好指定文件的编码方式,否则为系统默认(windows为gbk) for line in f: # line的数据类型为str if len(line) == 0: # 该行为空 pass line = line.strip() names += line.split('、') return names def statistics(stt_dir, line): for k in stt_dir.keys(): stt_dir[k] += line.count(k) return stt_dir def plot_bar(outpath, stt_dir, nums=10): """ Draw a histogram of TianLongBaBu's characters showup times. :param outpath: :param stt_dir: :param nums: The number of characters. E.g, if nums=10, there will be 10 bars in the histogram for 10 characters. :return: """ characters_stt = sorted(stt_dir.items(), key=lambda x: x[1], reverse=True)[:nums] characters = [x[0] for x in characters_stt] stts = [x[1] for x in characters_stt] fig = plt.figure() plt.bar(range(len(stts)), stts, width=0.5, color='yellow', alpha=0.6) plt.xticks(np.arange(len(stts)) + 0.5 / 2, characters) plt.title('天龙八部任务名字的出现次数排名') fig.savefig(outpath, pad_inches='tight') plt.close() class TextStatistics(object): def __init__(self, book_path, book_format): self.path = book_path self.format = book_format pass def read_book(self, names): stt_dir = dict.fromkeys(names, 0) with open(self.path, encoding=self.format) as f: count = 0 for line in f: if len(line) == 0: # 该行为空 pass if self.format == 'utf-8': stt_dir = statistics(stt_dir, line) else: stt_dir = statistics(stt_dir, line) if count % 100 == 0: print(count) count += 1 return stt_dir if __name__ == '__main__': names_main = read_characters('tlbb_characters.txt') ts = TextStatistics('tlbb_utf.txt', 'utf-8') # ts = TextStatistics('tlbb_gb2312.txt', 'gbk') # 另一个例子,编码方式为gb2312(gbk) stt_dir_main = ts.read_book(names_main) plot_bar('statistics.png', stt_dir_main)
4c36846aaeb90116acaf58d6be5b99f1c8b391dc
ncturoger/CodilityPractice
/Lesson3/task3_FrogJmp.py
166
3.578125
4
import math def solution(X, Y, D): step = 0 if X <= Y: dist = Y - X step = math.ceil(dist / D) return int(step) print(solution(1, 5, 2))
6b1d2e12c2968bea558cc354e14a4ed79917d664
HanKKK1515/PycharmProjects
/while.py
1,083
3.65625
4
''' count = 1 while count <=30: print("你是大傻子吗") print("嗯是啊撒") count = count + 1 while True: s = input("请开始喷:") if s == 'q': break if "马化腾" in s: print("输入非法") continue print("喷的内容是:" + s) count = 1 sum = 0 while count <= 100: print(count) sum = sum + count count = count + 1 print(sum) count = 1 while count <= 100: if count % 2 != 0: print(count) count = count + 1 ''' # name = input("请输入姓名") # age = input(' 年龄 ') # gender = input("输入年龄") #print(name + '今年' + age +'岁,是一个老头,性别:' + gender) # %s 字符串占位符 %d 数字的专用占位符 # print("%s 今年%s岁,是一个老头,性别:%s" % (name, age, gender)) # name = "all" # print("%s已经喜欢了班里%%40的女生" % (name))# 坑:注意,如果字符串有了占位符,那么后面的%都默认为占位,如果需要% 就要转义,用%% print("shazi喜欢了%30女生") 这句话里没有站位符,%还是%
e0c97cf96a0458dca21705648307a6a0f75a75ff
xzela/code-samples
/python/file_checks.py
4,598
3.640625
4
''' Attempts to test a file for specific attributes ''' import os import re from PIL import Image def detect_special_characters(file_name): ''' Attempts to detect whether a filename contains special characters. Special characters are bad We only accept the following characters: a-z a-Z _ (underscores) 0-9 Anything else should not be allowed. return: None || dict ''' pattern = "^[a-zA-Z0-9_]*\.(mov|dv|mp4)" if re.match(pattern, file_name): return None else: return {'special_chars': 'The file contains bad characters, only A-Z, 0-9, and underscores.'} def detect_whitespace(file_name): ''' Attempts to detect whether whitespaces exist in a give file name. file_name: name of file return: None || dict ''' if ' ' in file_name: return {"whitespace": 'File name contains whitespaces.'} return None def detect_thumbnails(thumbnail_path): ''' Attempts to detect whether a thumbnail exists for a given asset. All video assets should also have a thumbnail. thumbnail_path: path of the thumbnail return: None || dict ''' if os.path.exists(thumbnail_path): return None return {"thumbs": "Thumbnail is missing"} def detect_thumbnail_size(thumbnail_path, quality): ''' Attempts check the thumbnail sizes. Each thumbnail should less than 500px x 500px thumbnail_path: path of the thumbnail return: None || dict ''' img = Image.open(thumbnail_path) width, height = img.size if width > 500 or height > 500: return {'thumb_size': "Thumbnail sizes are incorrect, found: %s x %s " % (width, height)} return None def detect_video_type(file_name): ''' Attempts to check a file and determines the video type. Possible video types: Scene, Clip, Unknown Unknown is bad! file_name: name of file to check return: Unknown || Scene || Clip ''' # If neither regex catches, send back 'Unknown' media = "Unknown" # Test to see if the file is a scene if re.match('^([0-9]+)_s([0-9]+|[wWxXyYzZ][wWxXyYzZ])_.*.(dv|hdv|mov|mp4|mxf|mpeg)$', file_name): media = "Scene" # Test to see if file is a clip/promo if re.match('^([0-9]+)_([0-9]|pos|pre_promo|pre_scene)*.(dv|hdv|mov|mp4|mxf|mpeg)$', file_name): media = "Clip" return media def detect_file_name_matches(id, file_name): ''' Attempts to make sure that the name of the video file also contains the id in this format: <ID>_.<EXT> id: id file_name: file name of video return: None || dict ''' # cast id to string to avoid truthyness failures id = str(id) if file_name.split('_')[0] != id: return {'id': 'Either the Id does not match or the file is misnamed.'} return None def tests(id, file_path, quality): ''' Attempts to runs through a series of test for a given file id: id file_path: path of asset return: a list with error message ''' error_list = [] # export_path will be /media/fauxarchive/incoming/31726/exports export_path, video_file = os.path.split(file_path) # This should be /media/fauxarchive/incoming/31726 # Attempt to get the basename of the video file (same as thumbnail) # thumbnail_name = 12345_7 thumbnail_name, ext = os.path.splitext(video_file) thumbnail_file_path = os.path.join(os.path.join(os.path.split(export_path)[0], "thumbs"), thumbnail_name + ".jpg") # Test for special characters error_list.append(detect_special_characters(video_file)) # Test for whitespace in the file name error_list.append(detect_whitespace(video_file)) # Check that filename begins with id error_list.append(detect_file_name_matches(id, video_file)) # Test video type # we only want 'Clip' or 'Scene' if detect_video_type(video_file) is 'Unknown': error_list.append({"file_name": "File name is miss-named"}) # Test of existance of thumbnails thumbnail_exist_results = detect_thumbnails(thumbnail_file_path) if thumbnail_exist_results: error_list.append(thumbnail_exist_results) else: # If thumbnails exist, test their sizes error_list.append(detect_thumbnail_size(thumbnail_file_path, quality)) # Remove the None entries because we're only interested in failures error_list = filter(None, error_list) return error_list
568816f69911834abc77af5a84e9ac53a7ee4c25
koking0/Algorithm
/LeetCode/Problems/990. Satisfiability of Equality Equations/990. Satisfiability of Equality Equations.py
1,221
3.703125
4
#!/usr/bin/env python # -*- coding: utf-H -*- # @Time : 2020/6/H 7:34 # @File : 990. Satisfiability of Equality Equations.py # ---------------------------------------------- # ☆ ☆ ☆ ☆ ☆ ☆ ☆ # >>> Author : Alex 007 # >>> QQ : 2426671397 # >>> Mail : [email protected] # >>> Github : https://github.com/koking0 # >>> Blog : https://alex007.blog.csdn.net/ # ☆ ☆ ☆ ☆ ☆ ☆ ☆ from typing import List class Solution: class UnionFind: def __init__(self): self.parent = list(range(26)) def find(self, index): if index == self.parent[index]: return index self.parent[index] = self.find(self.parent[index]) return self.parent[index] def union(self, index1, index2): self.parent[self.find(index1)] = self.find(index2) def equationsPossible(self, equations: List[str]) -> bool: uf = Solution.UnionFind() for item in equations: if item[1] == '=': index1 = ord(item[0]) - ord("a") index2 = ord(item[3]) - ord("a") uf.union(index1, index2) for item in equations: if item[1] == '!': index1 = ord(item[0]) - ord("a") index2 = ord(item[3]) - ord("a") if uf.find(index1) == uf.find(index2): return False return True
e03dcbc33be5ae6d3dfbc0eb482c7b83f3b0bafe
Raquelcuartero/phyton
/texto_aleatorio.py
251
3.625
4
def texto_aleatorio(): texto=raw_input("Dime cualquier cosa") todo="a"or"e"or"i"or"o"or"u" for cont in range(0,len(texto),1): if texto[cont]==todo: print texto texto_aleatorio()
b3bd5dc39596b904cda049d055bd8b3770f01fcf
syurskyi/Algorithms_and_Data_Structure
/_algorithms_challenges/codeabbey/codeabbeyPrograms-master/division_of_two_numbers_with_round_off.py
715
3.828125
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 26 21:40:05 2016 @author: rajan Problem 6 This problem rounds off the number when divided by another number. """ print('Enter the numbers you want to divide. Dividend and divisor separated by space.') num = input() num_array = num.split() l = len(num_array) final_array = [] if l > 2: i = 0 while i < l: splitted_array = [] splitted_array = num_array[i:i+2] i += 2 final_array.append(splitted_array) else: final_array.append(num_array) result_array = [] for x in final_array: result = 0 result = round(float(x[0])/float(x[1])) result_array.append(result) print('The resulting array is ',result_array )
c9530acac16566b004f47a3317b385fcee257737
antoniolj07/IPC2-Practica1
/components/ReadCSVFiles.py
3,062
3.671875
4
class Read: candidates = [] def __init__(self): self.read_file() def read_file(self): path = input('Please enter the path of the CSV file \n') rows = [] try: with open(path, 'r') as f: lines = f.readlines() for line in lines: row = '' for x in range(len(line)): if not line[x] in '\n': row = row + line[x] rows.append(row) self.read_attributes(rows) except: print('Something went wrong :(') def read_attributes(self, rows): candidates = [] for row in rows: candidate = { 'id': '', 'nombre': '', 'apellido': '', 'edad': '', 'puesto': '', 'salario': '' } e = 0 for x in range(len(row)): if e == 0: if not row[x] in ',': candidate['id'] = candidate['id'] + row[x] else: e = 1 elif e == 1: if not row[x] in ',': candidate['nombre'] = candidate['nombre'] + row[x] else: e = 2 elif e == 2: if not row[x] in ',': candidate['apellido'] = candidate['apellido'] + row[x] else: e = 3 elif e == 3: if not row[x] in ',': candidate['edad'] = candidate['edad'] + row[x] else: e = 4 elif e == 4: if not row[x] in ',': candidate['puesto'] = candidate['puesto'] + row[x] else: e = 5 elif e == 5: if not row[x] in ',': candidate['salario'] = candidate['salario'] + row[x] else: e = 0 candidates.append(candidate) valid_candidates = [] i = 0 for candidate in candidates: if i == 0: valid_candidates.append(candidate) repeated = False for candi in valid_candidates: if candidate == candi: repeated = True if not repeated: valid_candidates.append(candidate) i = i + 1 self.print_candidates(valid_candidates) def print_candidates(self, candidates): for candidate in candidates: print(''' id: {} nombre: {} apellido: {} edad: {} puesto: {} salario: {} '''.format(candidate['id'], candidate['nombre'], candidate['apellido'], candidate['edad'], candidate['puesto'], candidate['salario'])) self.candidates = candidates
9ca627f50673cf748bfd3c897ca19fe6afd47baf
faithmyself92129/hellow100day
/D13/asyncio1.py
564
3.75
4
"""异步I/O 操作-asyncio模块""" import asyncio import threading async def hello(): print('%s:hello,world!' % threading.current_thread()) #休眠不会堵塞主线程因为使用异步I/o操作 #注意有yield from才会等待休眠操作执行完成 await asyncio.sleep(2) print('%s: goodbye, world!' % threading.current_thread()) loop = asyncio.get_event_loop() tasks = [hello(), hello()] #等待两个异步I/o操作执行结束 loop.run_until_complete(asyncio.wait(tasks)) print('game over') loop.close()
f3a0a1c9d79b91ac4871a504e3a58549ffeda59a
L200170180/Prak_ASD_E
/Modul-8/4_queue.py
611
3.8125
4
class Queue(object): def __init__(self): self.qlist = [] def isEmpty(self): return len(self)==0 def __len__(self): return len(self.qlist) def enqueue(self,data): self.qlist.append(data) def dequeue(self): assert not self.isEmpty() return self.qlist.pop(0) def getFront(self): return self.qlist[-1] def getRear(self): return self.qlist[0] a = Queue() a.enqueue('qqqqq') a.enqueue('wwwww') a.enqueue('eeeee') print(a.qlist) a.dequeue() print(a.qlist) print(a.getFront()) print(a.getRear())
ac885fef4d28db790ab4ed5c6dec9f932b91db71
renjieliu/leetcode
/1001_1499/1315.py
1,239
3.671875
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def sumEvenGrandparent(self, root: TreeNode) -> int: def dfs(node, output): curr = 0 if node.left != None: if node.left.left != None and node.val % 2 == 0: curr += node.left.left.val if node.left.right != None and node.val % 2 == 0: curr += node.left.right.val if node.left.left != None or node.left.right != None: dfs(node.left, output) if node.right != None: if node.right.left != None and node.val % 2 == 0: curr += node.right.left.val if node.right.right != None and node.val % 2 == 0: curr += node.right.right.val if node.right.left != None or node.right.right != None: dfs(node.right, output) if curr != 0: output.append(curr) output = [] if root == None: return 0 else: dfs(root, output) return sum(output)
43eb7c6e5dc6cfda2631c7db80fd1eba6f39bfa7
mariomanalu/shidoku_groebner
/test_shidoku.py
2,994
3.71875
4
import shidoku as S # This program solves a 4x4 version of the famous Sudoku puzzle called Shidoku using the Gröbner bases # How to use: # 1. Store any "solvable" Shidoku board as a 1D array of length 16 with 0 representing the empty cells # 2. Call solve_shidoku() # 3. Print the answer in the form of 2D array # We include eight tests for demonstration # Tests: # Test 1 shidoku_board_1 = [4, 0, 0, 0, 2, 1, 0, 0, 0, 4, 0, 2, 0, 0, 3, 0] # The above shidoku looks like following #[[4, 0, 0, 0] # [2, 1, 0, 0] # [0, 4, 0, 2] # [0, 0, 3, 4]] answer_1 = S.solve_shidoku(shidoku_board_1) print("Solution 1") print(answer_1) # The solution to the above shidoku, as returned by the solve_shidoku() function, is #[[4 3 2 1] # [2 1 4 3] # [3 4 1 2] # [1 2 3 4]] print("\n") # Test 2 shidoku_board_2 = [0, 0, 0, 3, 3, 2, 4, 0, 0, 4, 3, 2, 2, 0, 0, 0] # The above shidoku looks like following #[[0, 0, 0, 3] # [3, 2, 4, 0] # [0, 4, 3, 2] # [2, 0, 0, 0]] answer_2 = S.solve_shidoku(shidoku_board_2) print("Solution 2") print(answer_2) # The solution to the above shidoku, as returned by the solve_shidoku() function, is #[[4 1 2 3] # [3 2 4 1] # [1 4 3 2] # [2 3 1 4]] print("\n") # Test 3 shidoku_board_3 = [0, 0, 0, 4, 4, 0, 2, 0, 0, 3, 0, 1, 1, 0, 0, 0] # The above shidoku looks like following #[[0, 0, 0, 4] # [4, 0, 2, 0] # [0, 3, 0, 1] # [1, 0, 0, 0]] answer_3 = S.solve_shidoku(shidoku_board_3) print("Solution 3") print(answer_3) # The solution to the above shidoku, as returned by the solve_shidoku() function, is # [[3 2 1 4] # [4 1 2 3] # [2 3 4 1] # [1 4 3 2]] print("\n") # Test 4: A shidoku board with the minimum number of clues possible shidoku_board_4 = [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 2, 3, 0, 0, 0] # The above shidoku looks like following #[[0, 0, 0, 0] # [0, 0, 0, 1] # [0, 1, 0, 2] # [3, 0, 0, 0]] answer_4 = S.solve_shidoku(shidoku_board_4) print("Solution 4") print(answer_4) # The solution to the above shidoku, as returned by the solve_shidoku() function, is # [[1 4 2 3] # [2 3 4 1] # [4 1 3 2] # [3 2 1 4]] print("\n") # Test 5: A shidoku board with the minimum number of clues possible shidoku_board_5 = [0, 0, 0, 0, 0, 1, 0, 2, 0, 0, 0, 0, 1, 0, 3, 0] # The above shidoku looks like following #[[0, 0, 0, 0] # [0, 1, 0, 2] # [0, 0, 0, 0] # [1, 0, 3, 0]] answer_5 = S.solve_shidoku(shidoku_board_5) print("Solution 5") print(answer_5) # The solution to the above shidoku, as returned by the solve_shidoku() function, is # [[2 4 1 3] # [3 1 4 2] # [4 3 2 1] # [1 2 3 4]] print("\n") # Test 6: A shidoku board with the minimum number of clues possible shidoku_board_6 = [0, 0, 0, 1, 4, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 0] # The above shidoku looks like following #[[0, 0, 0, 1] # [4, 0, 0, 0] # [0, 0, 0, 0] # [0, 3, 2, 0]] answer_6 = S.solve_shidoku(shidoku_board_6) print("Solution 6") print(answer_6) # The solution to the above shidoku, as returned by the solve_shidoku() function, is # [[3 2 4 1] # [4 1 3 2] # [2 4 1 3] # [1 3 2 4]]
d93f75ca496622e5ce8d827faec674876770f448
eliasingea/interview-prep
/buildTree.py
930
3.71875
4
from collections import deque class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def buildTree(preorder, inorder): preorder = deque(preorder) inorder_map = {} for i, order in enumerate(inorder): inorder_map[order] = i def build_tree(start, end): if start > end: return None #popleft removes the first element of the deque root_index = inorder_map[preorder.popleft()] root = TreeNode(inorder[root_index]) root.left = build_tree(start, root_index-1) root.right = build_tree(root_index+1, end) return root return build_tree(0, len(inorder) - 1) def preOrder(node): if not node: return print(node.val) preOrder(node.left) preOrder(node.right) node = buildTree([3,9,20,15,7], [9,3,15,20,7]) preOrder(node)
2a5a39774a964880a2ecf5b145f6a84aee2d541c
kristinadziuba-zz/python
/lesson_1_task_1.py
708
4.15625
4
time = int(input('Duration: ')) second = time % 60 print('duration in seconds = ', second, "sec") time = int(input('Duration: ')) second = time % 60 minutes = (time % 3600) // 60 print("duration in minutes and seconds = ", minutes, "min", second, "sec") time = int(input('Duration: ')) second = time % 60 hour = (time // 3600) % 24 minutes = (time % 3600) // 60 print('duration in hours, minutes and seconds = ', hour, "h", minutes, "min", second, "sec") time = int(input('Duration: ')) second = time % 60 hour = (time // 3600) % 24 minutes = (time % 3600) // 60 day = (time // 3600) // 24 print('duration in days, hours, minutes and seconds = ', day, "days", hour, "h", minutes, "min", second, "sec")
320e9639a3cbe75cfc4836697f550f654e156fcd
Lansefanggezi/Reptile
/python/program1.py
186
3.515625
4
# zongshushi"+count count = 0 for a in range(1,5): for b in range(1,5): for c in range(1,5): for d in range(1,5): print d + c *10 +b *100 + a*1000 count +=1 print (count)
ee883ba6f2d13676566a78482dd844d81d706375
dailycodemode/dailyprogrammer
/Python/066_comparingRomanNumerals.py
1,797
4.09375
4
# DAILY CODE MODE # def is_X_bigger_than_Y(x,y): # l = len(max([x,y], key=len)) # for ind in range(l): # if ord(x[ind]) == ord(y[ind]): # pass # elif ord(x[ind]) >= ord(y[ind]): # return True # elif ord(x[ind]) <= ord(y[ind]): # return False # # # # Answer by loonybean # import re # # def compareRoman(x,y): # countCharsX, countCharsY = [len(re.findall(c,x)) for c in 'MDCLXVI'], [len(re.findall(c,y)) for c in 'MDCLXVI'] # for i in range(0, 7): # if countCharsX[i] != countCharsY[i]: # return True if countCharsX[i] < countCharsY[i] else False # return False # # BREAKDOWN # countCharsX = [len(re.findall(c,'XIII')) for c in 'MDCLXVI'] # >>> [0, 0, 0, 0, 1, 0, 3] # This is a very nice piece of code which breaks the string into a list where each count of that in the list appears. # As usual, lets split this apart to see what is happening # # for c in 'MDCLXVI' # this is creating a generator where each character will be sent into our regular expression. For simplicity, let's make it much smaller so that we can focus on everything else # # countCharsX = [len(re.findall(c,'XIII')) for c in 'I'] # # So what we can see now is that we are trying to find how often "I" is appearing in the string # # #Let's see what will happen when we remove the len part which will just give us lists with a list, showing the number of appearances of each character # countCharsX = [re.findall(c,'XIII') for c in 'I'] # >>> [['I', 'I', 'I']] # # Finally, the answer iterates over the answer and then checks the count of each number against each other. When one is finally bigger than the other, it will pick which one is bigger # # SUMMARY # Great challenge, and a lovely one to think about. Lovely answer.
d373f925e23e7fa8493152ccd12fca876baaa6c6
GreenVengeance/Matplotlib
/test_matplotlib_Ue6A3.py
847
3.671875
4
import unittest import Matplotlib_Ue6A3 as mat """Created by Bilal""" class TestMatplotlibUe6A3(unittest.TestCase): def test_create_plotF(self): """ F=x """ plt = mat.create_plot('x+2', min_range=0, max_range=4) self.assertEqual(plt[0], 2) # x=0 --> y=2 self.assertEqual(plt[1], 3) # x=1 --> y=3 self.assertEqual(plt[2], 4) # x=2 --> y=4 def test_create_plotF2(self): """ F2=x^2 """ plt = mat.create_plot('x**2', min_range=-2, max_range=2) self.assertEqual(plt[0], 4) # x=-2 --> y=4 self.assertEqual(plt[1], 1) # x=-1 --> y=1 self.assertEqual(plt[2], 0) # x=-0 --> y=0 self.assertEqual(plt[3], 1) # x=-3 --> y=1 def test_create_plot(self): plt = mat.create_plot('security_gap', min_range=0, max_range=4) self.assertEqual(plt, 'ERROR') if __name__ == '__main__': unittest.main()
08f062bd6d8484c42c402b9484bdfe90be5711bd
RyanHiltyAllegheny/blockchain-19
/src/print_content.py
2,540
3.5625
4
"""Prints tables and other program content.""" from prettytable import PrettyTable class color: """Defines different colors and text formatting settings to be used for CML output printing.""" PURPLE = "\033[95m" CYAN = "\033[96m" DARKCYAN = "\033[36m" BLUE = "\033[94m" GREEN = "\033[92m" YELLOW = "\033[93m" RED = "\033[91m" BOLD = "\033[1m" UNDERLINE = "\033[4m" END = "\033[0m" def program_info(): """Program relevant program information.""" print( color.GREEN + color.UNDERLINE + color.BOLD + "Program Info Center:\n" + color.END ) print( color.UNDERLINE + color.BOLD + "About The Program:" + color.END + " This program works with the Blockchain-19 protocols defined within it's respective project. Blockchain-19 is an adaptation of the cryptocurrency blockchain or the Blockchain game used for education purposes, instead relating the content on the Blockchain to COVID-19. Given patient information the program can calculate the hashes within the Blockchain, creating a solved ledger. The program offers users the option of creating a new ledger or importing a previously exported ledger.\n" ) print( color.UNDERLINE + color.BOLD + "Necessary Patient Info:" + color.END + "\n* Hospital \n* Patient ID \n* Current Status\n" ) print( color.UNDERLINE + color.BOLD + "Current Patient Status Key:" + color.END + "\n* A = Admitted \n* B = Stable \n* C = Moderate \n* D = Severe \n* E = Discharged \n* F = ICU\n\n" ) def print_table(ledger): """Prints a table of the ledger.""" table = PrettyTable() # defines a PrettyTable object table.field_names = [ "hospital", "patient", "status", "nonce", "prev_hash", "a", "b", "c", "current_hash", ] # define field names for table for block in ledger: table.add_row( [ block["hospital"], block["patient"], block["status"], block["nonce"], block["prev_hash"], block["a"], block["b"], block["c"], block["current_hash"], ] ) # add data to table print("\n\n" + color.BOLD + "Printing Your Ledger:" + color.END) print(table) # print prettytable of patient info
5cfd68769569e0cf54f5aebc03dee2d45629249d
younheeJang/pythonPractice
/algorithm/fromPythonTutorials/Linear_Search.py
286
3.65625
4
def linear_search(list, value): index = 0 for index in range(len(list)): if list[index] == value: return index else: index += 1 return None l = [64, 34, 25, 12, 22, 11, 90] print(linear_search(l, 12)) print(linear_search(l, 90))
25d2f53f6c83ffe70f515338b78c12dd5d096f09
gohar67/IntroToPython
/Practice/lecture4/practice7.py
166
3.765625
4
for num in range(1,21): print(num) if num % 5 == 0 and num % 3 ==0: break x = 0 while x <21: x +=1 print(x) if x % 15 ==0: break