blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
0b48be2de52b543d189741a5c5300f995adf84f2
EssamQabel/Problem-Solving
/Codeforces/A/41A.py
200
3.71875
4
s = input() t = input() result_list = [] for i in range(len(s)): result_list.append(s[i]) result_list.reverse() s = ''.join(result_list) if s == t: print('YES') else: print('NO')
6d3af464bbf9f8e9cf52f751bb66d9fde3cfbace
manankhaneja/hep-da
/programs/main.py
2,607
3.609375
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 23 18:50:07 2018 - constantly improving ever since @author: Manan Khaneja """ # Master program for data extraction without damaging file format # takes in input the directory in which all the files have to be analysed ( eg. a directory from which neutron data is extracted) #analyses all the files and names the txt file generated with those conditions. # asks for the path of the directory where you want to save that file (eg. I want to save my neutron.txt file in a directory named 'Particles', hence give path of 'Particles') #'variables.conditions' is accessing a list conditions in variable.py containing all the strings ( eg. neutron, DET0, protonInelastic etc.) # hence while entering variables.conditions take care of the format(case sensitive)/ spelling) import os import math import newoutfile import plot import variables def isSubset(words,conditions): for cond_index in range(0,len(conditions),1): word_index = 0 while word_index < len(words): if conditions[cond_index] == words[word_index]: break else: word_index = word_index + 1 if word_index == len(words): return 0 return 1 def dir_file_ext(): user_input = input("Enter the path of your directory where all the files are present: \n") assert os.path.isdir(user_input), "I did not find the directory" print("\n") all_files = os.listdir(user_input) print(all_files) count = 0 conditions = variables.conditions complete_name = variables.complete_name for file in all_files: f = open(user_input + "/" + file,"r+") k = open(complete_name, "a+") line = f.readline() while line: words = line.split() if isSubset(words,conditions): k.write(line) count += 1 line = f.readline() else: line=f.readline() f.close() k.close() print("The number of such particles is ", count) flag = int(input("Do you want to create the condensed file? \n0. NO \n1. YES\n")) if flag: newoutfile.newoutfile() old_del = int(input("Do you want to delete the originally created file ? \n0. NO \n1. YES\n")) if old_del: os.remove(complete_name) task = int(input("What do you want to do -\n0. Make a txt file with given conditions from a directory \n1. Call the plotting function\n")) if task: plot.plot() else: dir_file_ext()
b36872d55259a67b9b0ad8ef8ce8e26e30b75cc0
benkerns09/digital-crafts-lessons
/files/March8/phonebook.py
2,012
4.0625
4
class PhoneBook(object): def __init__(self, name, phone):#in it we have the name and phone number self.name = name self.phone = phone self.peopleList = []#I'm not sure what this is def phoneBookEmpty(self): if len(self.peopleList) == 0:#if the length of people list is zero...its finna print phonebook empty print "Phonebook empty" return False def lookUpEntry(self): name = raw_input("name to lookup: ")#user will input the name to lookup self.phoneBookEmpty()#i'm not sure why this is here for person in self.peopleList: if person.name == name: print (person.name, person.phone) def createContact(self): name = raw_input("input name: ") phone = raw_input("input phone: ") newContact = PhoneBook(name, phone) allContacts.peopleList.append(newContact) def delEntry(self): name = raw_input("name to delete: ") self.phoneBookEmpty() for i in range(len(self.peopleList)): person = self.peopleList[i] if person.name == name: del self.peopleList[i] def listAllEntries(self): self.phoneBookEmpty() for person in self.peopleList: print (person.name, person.phone) allContacts = PhoneBook("allContacts","null") def menu(): print """ Electronic Phone Book ===================== 1. Look up an entry 2. Set an entry 3. Delete an entry 4. List all entries 5. Quit""" def main(): while True: menu() answer = int(raw_input("What do you want to do (1-5)? ")) if answer == 1: allContacts.lookUpEntry() elif answer == 2: allContacts.createContact() elif answer == 3: allContacts.delEntry() elif answer == 4: allContacts.listAllEntries() elif answer == 5: print "Have a Good Day" return False main()
c6a3dc37f5d97438c3a9a3894cc82f65ec9ff35b
benkerns09/digital-crafts-lessons
/files/March6/mar307.py
666
3.828125
4
def drawtriangle(height, base): for row in range(1, height + 1): spaces = height - row print " " * spaces + "*" * (row * 2 - 1) drawtriangle(6, 4) def box(height, width): for row in range(height): if row in[0] or row in[(height-1)]: print("* " * (width)) else: print("*"+" "*(width-2)+" *") box(2, 7) def drawsquare(width, height): for row in range(height): if row == 0: print "*" * width elif row == height - 1: print "*" * width else: spaces = width - 2 print "*" + " " * spaces + "*" drawsquare(10, 5) drawsquare(50, 5)
6c51492aa5005099401d48ce50e6d84e41b59657
KhalidOmer/Exercises
/Work_Directory/Python/lottery.py
617
3.890625
4
import numpy as np """This is a simple common game that asks you to guess a number if you are lucky your number will match the computer's number""" def luck_game(): print("Hello, let's check if you're lucky!'") print("You are asked to guess a number between 0 and 10'") luck_number = int(np.random.uniform(0,11)) user_input = input("Enter your guess: ") if int(user_input) <= 10: if int(user_input) == luck_number: print("Wow! You're one of the luckiest people on the planet") else: print("Try again my friend the corret number is", luck_number,".") else: print("Invalid input") luck_game()
86773d8aa5d642f444192ecc1336560c86d718ca
siddu1998/sem6_labs
/Cloud Computing/Assignment 1/question9.py
218
4.40625
4
# Write a Python program to find whether a given number (accept from the user) # is even or odd, print out an appropriate message to the user. n=int(input("please enter the number")) print("even" if n%2==0 else "odd")
180256985bff15f54e150f1ff7a6cc4d86a1b365
siddu1998/sem6_labs
/Cloud Computing/Assignment 1/question10.py
250
3.984375
4
# Write a Python program to count the number 4 in a given list. length=int(input("Please enter the length")) list_with_fours=[] for i in range(0,length): list_with_fours.append(int(input())) print("number of 4's") print(list_with_fours.count(4))
f0501f677535546d870b4e28283048c78fb87771
zhh007/LearnPython
/2.List.py
619
4.0625
4
x = list('Hello') print(x) y = "".join(x) print(y) x = [1, 1, 1] x[1] = 2 print(x) names = ['Void', 'Alice', 'Jack'] del names[1] print(names) name = list('Perl') name[2:] = list('ar') print(name) list1 = [1, 2, 3] list1.append(4) print(list1) x = [1, 2, 1, 3] print(x.count(1)) a = [1, 2, 3] b = [4, 5] a.extend(b) print(a) a = ['love', 'for', 'good'] print(a.index('for')) a = [1, 2, 3] a.insert(1, 'b') print(a) x = [1, 2, 3] y = x.pop() print(y) x = ['to', 'be', 'or', 'not', 'to', 'be'] x.remove('be') print(x) x = [1, 2, 3] x.reverse() print(x) x = [4, 5, 8, 9, 2, 1, 7] x.sort() print(x)
891d590fe33896826dd3c5ce6c6e1bea06e5b980
pink-floyd-in-venice/pink-floyd-in-venice.github.io
/resources/functions/CsvTripleCreator/main.py
722
3.890625
4
import csv if __name__== "__main__": csv_name=input("Inserire nome file csv: ") if csv_name[-4:] !=".csv": csv_name += ".csv" with open(csv_name, "w", newline="") as csv_file: writer=csv.writer(csv_file, delimiter=' ', quotechar='|') writer.writerow(["Subject", "Predicate", "Object"]) while True: triple_string=input("Inserire tripla separata da un punto e virgola(;) o stop: ") if triple_string in"stopSTOP": break triple_list=list(triple_string.split(";")) if len(triple_list)!= 3: print("Errore nella definizione della tripla") continue writer.writerow(triple_list)
c03b3059a659730e6db51364c5dd5144bc5f64a6
SandeeraDS/FYP-Codes
/After 2019-08-25/python_string/stringTest.py
563
3.734375
4
import re name = " sande er " \ "dddsds sds sds sdd dsdsd ddsd dsds " name2 = " sande er " \ "dddsds sds sds sdd dsdsd ddsd dsdsa" name3 = " BCVFE | sande er " \ "dddsds sds sds sdd 2 .. 3 dsdsd ddsd ? dsdsA1" newString1 = "".join(name.split()) newString2 = "".join(name2.split()) newAlphabet = "".join(re.findall("[a-zA-Z]+", name3.lower())) # # print(newString1) # print(newString2) print(newAlphabet) # print(name.strip()) print(newAlphabet != newString2)
f0d2eef82b83a98f36f2a759f585c8cf03ad0327
SandeeraDS/FYP-Codes
/After 2019-08-25/encoding_test/test.py
1,093
3.53125
4
import re import nltk # to install contractions - pip install contractions from contractions import contractions_dict def expand_contractions(text, contractions_dict): contractions_pattern = re.compile('({})'.format('|'.join(contractions_dict.keys()))) def expand_match(contraction): # print(contraction) match = contraction.group(0) first_char = match[0] expanded_contraction = contractions_dict.get(match) \ if contractions_dict.get(match) \ else contractions_dict.get(match.lower()) expanded_contraction = expanded_contraction print(expanded_contraction) return expanded_contraction expanded_text = contractions_pattern.sub(expand_match, text) print(expanded_text) return expanded_text # for the transcript with open('2.txt', 'r', encoding="utf-8") as file: data = file.read() data = expand_contractions(data, contractions_dict) sentence = nltk.sent_tokenize(data) tokenized_sentences = [nltk.word_tokenize(sentences) for sentences in sentence] print(tokenized_sentences)
d3a2e416b3bd15607d71317808f17751667c9e0b
Jeremyreiner/DI_Bootcamp
/week5/Day4/exercise/exerciseXP.py
3,256
4.46875
4
# Exercise 1 – Random Sentence Generator # Instructions # Description: In this exercise we will create a random sentence generator. We will do this by asking the user how long the sentence should be and then printing the generated sentence. # Hint : The generated sentences do not have to make sense. # Download this word list # Save it in your development directory. # Ask the user how long they want the sentence to be. Acceptable values are: an integer between 2 and 20. Validate your data and test your validation! # If the user inputs incorrect data, print an error message and end the program. # If the user inputs correct data, run your code. # ----------------------------------------------------------------------------------------------- # import random # # Create a function called get_words_from_file. This function should read the file’s content and # # return the words as a collection. What is the correct data type to store the words? # def get_words_from_file(): # words = [] # with open('words.txt','r') as f: # for line in f: # words.append(line.rstrip('\n')) # f.close() # return words # # Create another function called get_random_sentence which takes a single parameter called length. # # The length parameter will be used to determine how many words the sentence should have. The function should: # # use the words list to get your random words. # # the amount of words should be the value of the length parameter. # def get_random_sentence(length): # sentence = '' # return_words = get_words_from_file() # random_words = random.choices(return_words, k = length) # for word in random_words: # sentence += word + ' ' # # Take the random words and create a sentence (using a python method), the sentence should be lower case. # print(sentence.lower) # def sent_length(): # num = int(input("Enter a number value for how long your sentence should be: ")) # if 2 <= num <= 20: # get_random_sentence(num) # else: # raise Exception("Incorrect value enterred") # # Create a function called main which will: # # Print a message explaining what the program does. # def main(): # print('this exercise we will create a random sentence generator') # print("Would you like to make a random sentence? (yes / no) ") # user_input = input() # if user_input == 'yes': # sent_length() # else: # print("Have a good day.") # main() # -------------------------------------------------------------------------- # Exercise 2: Working With JSON # Instructions import json # Access the nested “salary” key from the JSON-string above. # Add a key called “birth_date” to the JSON-string at the same level as the “name” key. # Save the dictionary as JSON to a file. # ---------------------------------------------------------------------------------------- with open('samplejson.json', 'r') as f: company = json.load(f) # print(company['company']['employee']['payable']['7000']) for key, values in company.items(): print(key, values['employee']['payable']['salary']) company['company']['empployee']['birthday'] = 24 with open('samplejson.json', 'w') as f: company = json.load(f)
316aa2bdc7e255944d154ce075592a157274c9bc
Jeremyreiner/DI_Bootcamp
/week5/Day3/daily_challenges/daily_challenge.py
2,874
4.28125
4
# Instructions : # The goal is to create a class that represents a simple circle. # A Circle can be defined by either specifying the radius or the diameter. # The user can query the circle for either its radius or diameter. # Other abilities of a Circle instance: # Compute the circle’s area # Print the circle and get something nice # Be able to add two circles together # Be able to compare two circles to see which is bigger # Be able to compare two circles and see if there are equal # Be able to put them in a list and sort them # ---------------------------------------------------------------- import math class Circle: def __init__(self, radius, ): self.radius = radius self.list = [] def area(self): return self.radius ** 2 * math.pi def perimeter(self): return 2*self.radius*math.pi def __le__(self, other): if self.radius <= other.radius: return True else: return False def __add__(self, other): if self.radius + other.radius: return self.radius + other.radius def add_circle(self): for item in self.list: if item not in self.list: self.list.append(item) def print_circle(self): return print(self.list) circle = Circle(50) circle_2 = Circle(7) print(circle.area()) Circle.add_circle(circle) Circle.add_circle(circle_2) print(Circle.print_circle(circle)) print(circle.perimeter()) print(circle.__le__(circle_2)) print(circle.__add__(circle_2)) # bigger_circle = n_circle.area + n_circle_2.area # print(bigger_circle.area()) # !class Racecar(): # def __init__(self, model, reg_no, top_speed=0, nitros=False): # self.model = model # self.reg_no = reg_no # self.top_speed = top_speed # self.nitros = nitros # if self.nitros: # self.top_speed += 50 # def __str__(self): # return self.model.capitalize() # def __repr__(self): # return f"This is a Racecar with registration: {self.reg_no}" # def __call__(self): # print(f"Vroom Vroom. The {self.model} Engines Started") # def __gt__(self, other): # if self.top_speed > other.top_speed: # return True # else: # return False # def drive(self, km): # print(f"You drove the {self.model} {km} km in {km / self.top_speed} hours.") # def race(self, other_car): # if self > other_car: # print(f"I am the winner") # else: # print(f"The {other_car.model} is the winner") # class PrintList(): # def __init__(self, my_list): # self.mylist = my_list # def __repr__(self): # return str(self.mylist) # car1 = Racecar("honda", "hello", 75, True) # car2 = Racecar("civic", "bingo", 55, True) # print(car1.__gt__(car2))
0cdc78355fca028bb19c771c343ae845b702f555
Jeremyreiner/DI_Bootcamp
/week5/Day1/Daily_challenge/daily_challenge.py
2,265
4.40625
4
# Instructions : Old MacDonald’s Farm # Take a look at the following code and output! # File: market.py # Create the code that is needed to recreate the code provided above. Below are a few questions to assist you with your code: # 1. Create a class called Farm. How should this be implemented? # 2. Does the Farm class need an __init__ method? If so, what parameters should it take? # 3. How many methods does the Farm class need? # 4. Do you notice anything interesting about the way we are calling the add_animal method? What parameters should this function have? How many…? # 5. Test your code and make sure you get the same results as the example above. # 6. Bonus: nicely line the text in columns as seen in the example above. Use string formatting. class Farm(): def __init__(self, name): self.name = name self.animals = [] self.sorted_animals = [] def add_animal(self, animal, amount = ""): if animal not in self.animals: added_animal = f"{animal} : {str(amount)}" self.animals.append(added_animal) def show_animals(self): # for animal in self.animals: print(f"These animals are currently in {self.name}'s farm: {self.animals}") # Expand The Farm # Add a method called get_animal_types to the Farm class. # This method should return a sorted list of all the animal types (names) in the farm. # With the example above, the list should be: ['cow', 'goat', 'sheep']. def get_animal_types(self): if __name__ == '__main__': sorted_by_name = sorted(self.animals, key=lambda x: x.animals) print(sorted_by_name) # Add another method to the Farm class called get_short_info. # This method should return the following string: “McDonald’s farm has cows, goats and sheep.”. # The method should call the get_animal_types function to get a list of the animals. macdonald = Farm("McDonald") macdonald.add_animal('cow', 5) macdonald.add_animal('sheep') macdonald.add_animal('sheep') macdonald.add_animal('goat', 12) macdonald.show_animals() all_animals = macdonald.animals macdonald.get_animal_types() # print(macdonald.get_info()) # McDonald's farm # cow : 5 # sheep : 2 # goat : 12 # E-I-E-I-0!
7a7c944b90acd5e775968c985c9f2b58789ed4a7
christopher-henderson/thesis
/writing.py
1,896
3.53125
4
''' Wikipedia sucks...unless it doesn't. This is the N-Queens problem implemented using the following general-form pseudocode. https://en.wikipedia.org/wiki/Backtracking#Pseudocode It is getting correct answers, although I am doing something wrong and also getting duplicates. ''' N = 8 def backtrack(P, root, accept, reject, first, next, output): if reject(P, root): return P.append(root) if accept(P): output(P) P.pop() return s = first(root) while s is not None: backtrack(P, s, accept, reject, first, next, output) s = next(s) P.pop() s = next(root) if s is not None: backtrack(P, s, accept, reject, first, next, output) def root(): # Return the partial candidate at the root of the search tree. # First spot on the board. return 1, 1 def reject(P, candidate): C, R = candidate for column, row in P: if (R == row or C == column or R + C == row + column or R - C == row - column): return True return False def accept(P): # Return true if c is a solution of P, and false otherwise. # The latest queen has been verified safe, so if we've placed N queens, we win. return len(P) == N def first(root): # Generate the first extension of candidate c. # That is, if we have a placed queen at 1, 1 (C, R) then this should return 2, 1. return None if root[0] >= N else (root[0] + 1, 1) def next(child): # generate the next alternative extension of a candidate, after the extension s. # So if first generated 2, 1 then this should produce 2, 2. return None if child[1] >= N else (child[0], child[1] + 1) def output(P): print(P) def more(R): return R < N if __name__ == "__main__": backtrack([], root(), accept, reject, first, next, output) print(derp)
69005c262433db7d85e18bf3b770ca093533c99f
christopher-henderson/thesis
/backtrack/01knapsack.py
1,681
3.8125
4
from backtrack import backtrack class KnapSack(object): WEIGHT = 50 ITEMS = ((10, 60), (20, 100), (30, 120)) MEMO = {} def __init__(self, item_number): self.item_number = item_number def first(self): return KnapSack(0) def next(self): if self.item_number >= len(self.ITEMS) - 1: return None return KnapSack(self.item_number + 1) @classmethod def reject(cls, P, candidate): weight = cls.total_weight(P) if weight + candidate.weight > cls.WEIGHT or weight in cls.MEMO: # It doesn't fill up the whole bag, but it IS a solution. cls.output(P) return True return False @classmethod def accept(cls, P): return cls.total_weight(P) == cls.WEIGHT @staticmethod def add(P, candidate): P.append(tuple([candidate.weight, candidate.value])) @staticmethod def remove(P): P.pop() @classmethod def output(cls, P): weight = cls.total_weight(P) if weight in cls.MEMO: if cls.total_value(P) > cls.total_value(cls.MEMO[weight]): cls.MEMO[weight] = tuple(P) else: cls.MEMO[weight] = tuple(P) # Three helpers @staticmethod def total_weight(P): return sum(item[0] for item in P) @staticmethod def total_value(P): return sum(item[1] for item in P) @property def weight(self): return self.ITEMS[self.item_number][0] @property def value(self): return self.ITEMS[self.item_number][1] if __name__ == '__main__': backtrack(KnapSack(0), KnapSack.first, KnapSack.next, KnapSack.reject, KnapSack.accept, KnapSack.add, KnapSack.remove, KnapSack.output) print("Max total is: {}\nUsing the solution: {}".format(KnapSack.total_value(KnapSack.MEMO[KnapSack.WEIGHT]), KnapSack.MEMO[KnapSack.WEIGHT]))
9c03b56ac31edf5d0163ec4cf3a9cab915a789a4
christopher-henderson/thesis
/nQueen0.py
2,178
3.75
4
import copy N = 8 NUM_FOUND = 0 derp = list() def backtrack(P, C, R): if reject(P, C, R): return # Not a part of the general form. Should it be in 'reject'? # That would be kinda odd, but it must appended before a call to output. P.append([C, R]) if accept(P): output(P) s = first(C) while s is not None: # Explicitly passing by value (deepcopy a list) is another addition of # mine. Is this mandatory? backtrack(copy.deepcopy(P), *s) s = next(*s) # The general form admits this case, although there can be a way around it. if R < N: P.pop() backtrack(copy.deepcopy(P), C, R + 1) def root(): # Return the partial candidate at the root of the search tree. # First spot on the board. return 1, 1 def reject(P, C, R): # Return true only if the partial candidate c is not worth completing. # c, in this case, is Column and Row together. for column, row in P: if (R == row or C == column or R + C == row + column or R - C == row - column): return True return False def accept(P): # Return true if c is a solution of P, and false otherwise. # The latest queen has been verified safe, so if we've placed N queens, we win. return len(P) == N def first(C): # Generate the first extension of candidate c. # That is, if we have a placed queen at 1, 1 (C, R) then this should return 2, 1. return None if C >= N else (C + 1, 1) def next(C, R): # generate the next alternative extension of a candidate, after the extension s. # So if first generated 2, 1 then this should produce 2, 2. return None if R >= N else (C, R + 1) def output(P): # use the solution c of P, as appropriate to the application. global NUM_FOUND NUM_FOUND += 1 derp.append(P) print(P) if __name__ == "__main__": backtrack([], *root()) dupes = 0 for index, i in enumerate(derp): for j in derp[index + 1::]: if i == j: dupes += 1 print(dupes) print("Found solutions: {NUM}".format(NUM=NUM_FOUND))
7ce103ab49574b9dcb251574c06934c9fb2b00e1
SvenLC/CESI-Algorithmique
/listes/triParSelection.py
439
3.828125
4
# Ecrire la procédure qui reçoit un tableau de taille N en entrée et qui réalise un tri par sélection exemple = [1, 3, 5, 6, 3, 2, 4, 5, 6] def triParSelection(tableau, n): for i in range(0, n): for j in range(i, n): if(tableau[i] > tableau[j]): min = tableau[j] tableau[j] = tableau[i] tableau[i] = min return tableau print(triParSelection(exemple, 9))
9693d52cc708aca038148b57c23f45976ef7ef01
SvenLC/CESI-Algorithmique
/boucles/exercice6.py
331
3.5625
4
# Écrire un algorithme qui demande un nombre de départ, et qui calcule la somme des entiers jusqu’à ce nombre, # par exemple, si on entre 5, on devrait afficher 1 + 2 + 3 + 4 + 5. def somme(nombre): total = 0 for i in range(0, nombre): total = total + i print(i) return total print(somme(10))
6438fc05212750bb32b2ca3aecbfb970f7568071
cran/excerptr
/inst/excerpts/excerpts/main.py
5,131
3.5625
4
#!/usr/bin/env python3 """ @file module functions """ from __future__ import print_function import re import os def extract(lines, comment_character, magic_character, allow_pep8=True): """ Extract Matching Lines Extract all itmes starting with a combination of comment_character and magic_character from a list. Kwargs: lines: A list containing the code lines. comment_character: The comment character of the language. magic_character: The magic character marking lines as excerpts. allow_pep8: Allow for a leading comment character and space to confrom to PEP 8 block comments. Returns: A list of strings containing the lines extracted. """ matching_lines = [] if allow_pep8: # allow for pep8 conforming block comments. markdown_regex = re.compile(r"\s*" + comment_character + "? ?" + comment_character + "+" + magic_character) else: markdown_regex = re.compile(r"\s*" + comment_character + "+" + magic_character) for line in lines: if markdown_regex.match(line): matching_lines.append(line) return matching_lines def convert(lines, comment_character, magic_character, allow_pep8=True): """ Convert Lines to Markdown Remove whitespace and magic characters from lines and output valid markdown. Kwargs: lines: The lines to be converted. comment_character: The comment character of the language. magic_character: The magic character marking lines as excerpts. allow_pep8: Allow for a leading comment character and space to confrom to PEP 8 block comments. Returns: A list of strings containing the lines converted. """ converted_lines = [] for line in lines: line = line.lstrip() if allow_pep8: # allow for pep8 conforming block comments. line = re.sub(comment_character + " ", "", line) # remove 7 or more heading levels. line = re.sub(comment_character + "{7,}", "", line) line = line.replace(comment_character, "#") if magic_character != "": # remove the first occurence of the magic_character only # (the header definition of pandoc's markdown uses the # percent sign, if that was the magic pattern, all pandoc # standard headers would end up to be simple text). line = re.sub(magic_character, "", line, count=1) # get rid of leading blanks line = re.sub(r"^\s*", "", line) # empty lines (ending markdown paragraphs) are not written by # file.write(), so we replace them by newlines. if line == " " or line == "": line = "\n" converted_lines.append(line) return converted_lines def excerpt(lines, comment_character, magic_character, allow_pep8=True): """ Extract and Convert Matching Lines Just a wrapper to extract() and convert(). Kwargs: lines: A list containing the code lines. comment_character: The comment character of the language. magic_character: The magic character marking lines as excerpts. allow_pep8: Allow for a leading comment character and space to confrom to PEP 8 block comments. Returns: A list of strings containing the lines extracted and converted. """ lines_matched = extract(lines=lines, comment_character=comment_character, magic_character=magic_character) converted_lines = convert(lines=lines_matched, comment_character=comment_character, magic_character=magic_character, allow_pep8=allow_pep8) return converted_lines def modify_path(file_name, postfix="", prefix="", output_path="", extension=None): """ Modify a Path Add a postfix and a prefix to the basename of a path and change it's extension. Kwargs: file_name: The file path to be modified. postfix: Set the output file postfix. prefix: Set the output file prefix. extension: Set a new file extension. output_path: Set a new file name or an output directory. If the path given is not an existing directory, it is assumed to be a file path and all other arguments are discarded. Returns: A string containing the modified path. """ if output_path != "" and not os.path.isdir(output_path): name = output_path else: base_name = os.path.basename(os.path.splitext(file_name)[0]) ext_base_name = prefix + base_name + postfix if extension is None: extension = os.path.splitext(file_name)[1] ext = extension.lstrip(".") if output_path == "": directory = os.path.dirname(file_name) else: directory = output_path name = os.path.join(directory, ext_base_name) + "." + ext return name
3bd68486e51753134cef0461c41bc1f01fa9d68c
NicholasTancredi/python_examples
/examples/simple.py
6,812
3.703125
4
""" File with simple examples of most common use cases for: - unittest - pytypes - pydantic - typing - enum """ from unittest import TextTestRunner, TestLoader, TestCase from argparse import ArgumentParser from typing import NamedTuple, Tuple, Union from enum import Enum from math import hypot from pytypes import typechecked from pydantic import validator, BaseModel, PydanticValueError @typechecked class Point(NamedTuple): y: int x: int @typechecked class Line(NamedTuple): start: Point end: Point @typechecked def get_line_distance(line: Line) -> float: """ # NOTE: a NamedTuple can still be accessed by index like a regular tuple, for example: return hypot( line[1][1] - line[0][1], line[1][0] - line[0][0] ) """ return hypot( line.end.x - line.start.x, line.end.y - line.start.y ) @typechecked def WARNING_DONT_WRITE_LIKE_THIS_get_line_distance(line: Tuple[Tuple[int, int], Tuple[int, int]]) -> float: """ NOTE: using the raw type 'get_line_distance' would be written like this. Looking at the type for line: "Tuple[Tuple[int, int], Tuple[int, int]]" you can see how opaque the input becomes. """ return hypot( line[1][1] - line[0][1], line[1][0] - line[0][0] ) # NOTE: In edge cases you may want to accept all types of input @typechecked def get_line_distance_polytype(line: Union[Line, Tuple[Point, Point], Tuple[Tuple[int, int], Tuple[int, int]]]) -> float: return hypot( line[1][1] - line[0][1], line[1][0] - line[0][0] ) # NOTE Reference material for enums - https://docs.python.org/3/library/enum.html#creating-an-enum # It is important to note that enums are functional constants. The importance of that is we should endure to use the functional constant whenever possible, and reserve the `value` # for the rare moment where we actually want to use the value (primarily for storage). This will have consequences for how we store and use data inside of data classes. # Note Nomenclature # The class TextAlign is an enumeration (or enum) # The attributes TextAlign.left, TextAlign.center, etc., are enumeration members (or enum members) and are functionally constants. # The enum members have names and values (the name of TextAlign.left is left, the value of TextAlign.hidden is 0, etc.) class TextAlign(str, Enum): LEFT = 'LEFT' RIGHT = 'RIGHT' CENTER = 'CENTER' # NOTE: Here to highlight the difference between name and value in enums HIDDEN = 'ANYTHING' @typechecked def pad_text(text: str, text_align: TextAlign = TextAlign.LEFT, width: int = 20, fillchar: str = '-') -> str: """ This also has an example of a "python" switch statement equivalent using a dict """ psuedo_switch_statement = { TextAlign.LEFT: text.ljust(width, fillchar), TextAlign.RIGHT: text.rjust(width, fillchar), TextAlign.CENTER: text.center(width, fillchar), } return psuedo_switch_statement[text_align] class AuthorizationError(PydanticValueError): code = 'AuthorizationError' msg_template = 'AuthorizationError: the Bearer token provided was invalid. value={value}' # NOTE: Doesn't need @typechecked for type checking class Header(BaseModel): Authorization: str @validator('Authorization') def validate_auth(cls, value: str) -> str: if value != 'Bearer {}'.format('SECRET_KEY'): raise AuthorizationError(value=value) return value class AssessmentType(str, Enum): GAIT = 'GAIT' class PoseJob(BaseModel): assessment_type: AssessmentType if __name__ == '__main__': parse = ArgumentParser() parse.add_argument( '--unittest', action='store_true' ) args = parse.parse_args() if args.unittest: class Test(TestCase): def test_get_line_distance(self): distance_a = get_line_distance( line=Line( start=Point( y=1, x=2 ), end=Point( y=3, x=4 ) ) ) # Less verbose example of calling get_line_distance distance_b = get_line_distance(Line(Point(1, 2), Point(3, 4))) print('distance_b: ', distance_b) # NOTE: WARNING! This is not an example how I'd recommend writing this! distance_c = get_line_distance_polytype(((1, 2), (3, 4))) distance_d = WARNING_DONT_WRITE_LIKE_THIS_get_line_distance(((1, 2), (3, 4))) self.assertEqual( distance_a, distance_b ) self.assertEqual( distance_a, distance_c ) self.assertEqual( distance_a, distance_d ) def test_pad_text(self): # NOTE: Simple validating enum has str in it. self.assertTrue('CENTER' in TextAlign.__members__) padded_text = pad_text('yolo', text_align = TextAlign.CENTER) print('padded_text: ', padded_text) self.assertEqual( padded_text, '--------yolo--------' ) def test_header(self): json_input = { 'Authorization': 'Bearer {}'.format('SECRET_KEY') } header = Header(**json_input) print('header.json(): ', header.json()) self.assertDictEqual( json_input, header.dict() ) # NOTE: Input does not have to be json, (i.e. is equivalent) header = Header( Authorization='Bearer {}'.format('SECRET_KEY') ) self.assertDictEqual( json_input, header.dict() ) def test_pose_job(self): # NOTE incoming data from some external source incoming_data = { 'assessment_type': 'GAIT' } job = PoseJob(**incoming_data) self.assertEqual( incoming_data['assessment_type'], job.assessment_type.value ) print('job.assessment_type: ', job.assessment_type) TextTestRunner().run(TestLoader().loadTestsFromTestCase(Test))
d8eea6878b92a31589a7b58cc6a3cdbc5a7299db
Bawya1098/python-Beginner
/day_2_assignment/list_sum.py
263
4.09375
4
number = input("enter elements") my_array = list() sum = 0 print("Enter numbers in array: ") for i in range(int(number)): n = input("num :") my_array.append(int(n)) print("ARRAY: ", my_array) for num in my_array: sum = sum + num print("sum is:", sum)
44971d0672295eea12f2d5f3ad8dad4faea2c47f
Bawya1098/python-Beginner
/Day3/Day3_Assignments/hypen_separated_sequence.py
273
4.15625
4
word = str(input("words to be separated by hypen:")) separated_word = word.split('-') sorted_separated_word = ('-'.join(sorted(separated_word))) print("word is: ", word) print("separated_word is:", separated_word) print("sorted_separated_word is: ", sorted_separated_word)
67a947661af531ea618cb15951041076cfaab19b
Bawya1098/python-Beginner
/Week2_day1/Multi_level_inheritance.py
873
3.734375
4
class Micro_Computers(): def __init__(self, size): self.size = size def display(self): print("size is:", self.size) class Desktop(Micro_Computers): def __init__(self, size, cost): Micro_Computers.__init__(self, size) self.cost = cost def display_desktop(self): print("cost is: Rs.", self.cost) class Laptop(Desktop): def __init__(self, size, cost, battery): Desktop.__init__(self, size, cost) self.battery = battery print('laptop are') def display_laptop(self): print("battery is:", self.battery) l = Laptop('small', 20000, 'battery_supported') l.display() l.display_desktop() l.display_laptop() print('---------------------------------------------') d = Desktop('large', 30000) d.display_desktop() d.display() print('---------------------------------------------')
af0200ae519c67895fbb02c24de47233935b9b0b
Bawya1098/python-Beginner
/Day_1_Assignments/mystery_n.py
762
3.8125
4
def mystery(numbers): sum = 1 for i in range(0, numbers): if i < 6: for k in range(1, numbers): #num1 to 5: sum=2^(numbers**2) sum *= 2 print(sum) else: #number6: sum=2^(5*number)*5 if i < 10: #number7: sum=2^(5*number)*5^2 sum *= 5 #number8: sum=2^(5*number)*5^3 print(sum) #number9: sum=2^(5*number)*5^4 else: #number10: sum=2^(5*number)*(5^4)*(3^1) sum *= 3 #number11: sum=2^(5*number)*(5^4)*(3^2) print(sum) return sum myserty(3)
abde32d028db53073878822c4ab038eda0b5a507
ranellegomez/Object-oriented-Python-calculator
/test/CalculatorTest.py
3,317
3.5
4
import unittest import ModularCalculator import RecursiveExponentCalculator class MyTestCase(unittest.TestCase): def test_add(self): for a in range(-100, 100): for b in range(-100, 100): for c in range(-100, 100): print( 'add_test', a, b, c, 'result: ', ModularCalculator.ModularCalculator.add( self, [a, b, c])) self.assertAlmostEqual( a + b + c, ModularCalculator.ModularCalculator.add( self, [a, b, c])) def test_subtract(self): for a in range(-100, 100): for b in range(-100, 100): for c in range(-100, 100): print( 'subtract_test', a, b, c, 'result: ', ModularCalculator.ModularCalculator.subtract( self, [a, b, c])) self.assertAlmostEqual( a - b - c, ModularCalculator.ModularCalculator.subtract( self, [a, b, c])) def test_multiply(self): for x in range(-100, 100): for y in range(-100, 100): for z in range(-100, 100): print( 'multiply_test', x, y, z, 'result: ', ModularCalculator.ModularCalculator.multiply( self, [x, y, z])) self.assertAlmostEqual( x * y * z, ModularCalculator.ModularCalculator.multiply( self, [x, y, z])) def test_exponentiate(self): for b in range(-10, 100): for p in range(-10, 100): self.assertEqual( b**p, RecursiveExponentCalculator.RecursiveExponentiation. tail_recursive_exponentiate(self, b, p)) self.assertEqual( b**p, RecursiveExponentCalculator.RecursiveExponentiation. recursive_exponentiate(self, b, p)) self.assertEqual( b**p, ModularCalculator.ModularCalculator. two_integer_exponentiate(self, b, p)) def test_divide(self): for a in range(-100, 100): for b in range(-100, 100): for c in range(-100, 100): if b == 0 or c == 0: self.assertEqual( 'Whoops. Cannot divide by zero. 😭', ModularCalculator.ModularCalculator.divide( self, [a, b, c])) else: print( 'divide_test', a, b, c, 'result: ', ModularCalculator.ModularCalculator.divide( self, [a, b, c])) self.assertAlmostEqual( a / b / c, ModularCalculator.ModularCalculator.divide( self, [a, b, c])) if __name__ == '__main__': unittest.main()
fcd96d8a74d9a565277a2ee8b44e9056943a3f30
tonyfg/project_euler
/python/p04.py
473
3.875
4
#Q: Find the largest palindrome made from the product of two 3-digit numbers. #A: 906609 def is_palindrome(t): a = list(str(t)) b = list(a) a.reverse() if b == a: return True return False a = 0 last_j = 0 for i in xrange(999, 99, -1): if i == last_j: break for j in xrange(999, 99, -1): temp = i*j if is_palindrome(temp) and temp > a: a = temp last_j = j break print(str(a))
35d047c6d9377e87680dcc98b62182b49bf89a3e
tonyfg/project_euler
/python/p21.py
424
3.546875
4
#Q: Evaluate the sum of all the amicable numbers under 10000. #A: 31626 def divisor_sum(n): return sum([i for i in xrange (1, n//2+1) if not n%i]) def sum_amicable(start, end): sum = 0 for i in xrange(start, end): tmp = divisor_sum(i) if i == divisor_sum(tmp) and i != tmp: sum += i+tmp return sum/2 #each pair is found twice, so divide by 2 ;) print sum_amicable(1,10000)
8ea1a9399f7b7325159494391e648245e0e76179
Danielkaas94/Any-Colour-You-Like
/code/python/PythonApplication1.py
2,115
4.1875
4
def NameFunction(): name = input("What is your name? ") print("Aloha mahalo " + name) return name def Sum_func(): print("Just Testing") x = input("First: ") y = input("Second: ") sum = float(x) + float(y) print("Sum: " + str(sum)) def Weight_func(): weight = int(input("Weight: ")) unit_option = input("(K)g or (L)bs:") if unit_option.upper() == "K": converted_value = weight / 0.45 print("Weight in Lbs:" + str(converted_value)) else: converted_value = weight * 0.45 print("Weight in Kg:" + str(converted_value)) NameFunction(); print("") Sum_func(); print("") birth_year = input("Enter your birth year: ") age = 2020 - int(birth_year) print(age) course = 'Python for Beginners' print(course.upper()) print(course.find('for')) print(course.replace('for', '4')) print('Python' in course) #True print(10 / 3) # 3.3333333333333335 print(10 // 3) # 3 print(10 % 3) # 1 print(10 ** 3) # 1000 print(10 * 3) # 30 x = 10 x = x + 3 x += 3 x = 10 + 3 * 2 temperature = 35 if temperature > 30: print("Hot night, in a cold town") print("Drink infinite water") elif temperature > 20: print("It's a fine day") elif temperature > 10: print("It's a bit cold") else: print("It's cold") print("LORT! ~ Snehaderen") Weight_func(); print("") i = 1 while i <= 1_1: #print(i) print(i * '*') i += 1 names = ["Doktor Derp", "Jens Jensen", "John Smith", "Toni Bonde", "James Bond", "Isaac Clark", "DOOMGUY"] print(names) print(names[0]) print(names[-1]) # Last Element - DOOMGUY print(names[0:3]) # ['Doktor Derp', 'Jens Jensen', 'John Smith'] numbers = [1,2,3,4,5] numbers.append(6) numbers.insert(0,-1) numbers.remove(3) #numbers.clear() print(numbers) print(1 in numbers) print(len(numbers)) for item in numbers: print(item) i = 0 while i < len(numbers): print(numbers[i]) i += 1 #range_numbers = range(5) #range_numbers = range(5, 10) range_numbers = range(5, 10, 2) print(range_numbers) for number in range_numbers: print(number) for number in range(7,45,5): print(number) numbers2 = (1,2,3) #Tuple
7b1c346f4ef2097de68fbd0b2a4430765ee1d13e
TeknikhogskolanGothenburg/Docker_MySQL_Alembic_SQLAlchemy
/app/UI/customers_menu.py
2,117
3.578125
4
from Controllers.customers_controller import get_all_customers, get_customer_by_id, get_customer_by_name, store_changes, \ store_new_first_name def customers_menu(): while True: print("Customers Menu") print("==============") print("1. View All Customers") print("2. View Customer by Id") print("3. Find Customers by Name") print("5. Quit Customers Menu") selection = input("> ") if selection == "1": customers = get_all_customers() for customer in customers: print(customer) elif selection == "2": id = input("Enter Customer Id: ") customer = get_customer_by_id(id) if customer: print(customer) else: print("Could not find customer with id ", id) elif selection == "3": pattern = input("Enter full or partial customer name: ") customers = get_customer_by_name(pattern) for key, customer in customers.items(): print(f'{key}. {customer}') edit_selection = input("Enter number for customer to edit: ") edit_selection = int(edit_selection) customer = customers[edit_selection] print(f'1. Customer Name: {customer.customerName}') print(f'2. Contact First Name: {customer.contactFirstName}') print(f'3. Contact Last Name: {customer.contactLastName}') print(f'4. Phone: {customer.phone}') print(f'5. Address Line 1: {customer.addressLine1}') print(f'6. Address Line 2: {customer.addressLine2}') print(f'7. City: {customer.city}') print(f'8. State: {customer.state}') print(f'9. Postal Code: {customer.postalCode}') print(f'10. Country: {customer.country}') line = input("Enter number for what line to edit: ") if line == "2": new_value = input("Enter new First Name: ") store_new_first_name(customer, new_value) else: break
b8d583b681f9579475e30829ac3a596c41406e94
lsiddd/ml
/NeuralNets/ELM.py
1,882
3.578125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np verbose = False erro = lambda y, d: 1/2 * sum([np.sum (i **2) for i in np.nditer(y - d)]) def output(x, d, w1, w2=[]): sh = list(x.shape) sh[1] = sh[1] + 1 Xa = np.ones(sh) Xa[:,:-1] = x #ativação sigmoidal S = np.tanh(np.matmul(Xa, w1.transpose())) sh = list(S.shape) sh[1] = sh[1] + 1 Ha = np.ones(sh) Ha[:,:-1] = S #se os pesos de saída não forem fornecidos #calculamos eles aqui if(w2 == []): w2 = np.matmul(np.linalg.pinv(Ha), d).transpose() #caso contrário, se faz propagação direta Y = np.matmul(Ha, w2.transpose()) if (verbose): print (f'pesos da camada oculta: \n{w1}') print (f'pesos da camada de saída: \n{w2}') print (f'resposta da camada oculta:\n {S}') print (f'resposta da camada de saída:\n {Y}') print (f' O erro RMS da rede é {erro(Y, d)}\n\n') plt.style.use("ggplot") plt.figure() plt.title(f"Sen(x), erro RMS = {erro(Y, d)}") plt.plot(x, Y, "+", color="green", label="resposta da Rede") plt.plot(x, d, "-.", color="red", label="Função Original") plt.ylabel("Saída") plt.xlabel("Entrada") plt.legend() plt.show() return w2, Y def main(): x = [] d = [] linspace = np.arange(0, 10, 0.01) for i in linspace: x.append([i]) d.append([np.sin(i)]) #O conjunto de testes testx = np.array(x[1::20]) testd = np.array(d[1::20]) #conjunto de treinamento x = np.array(x[::30]) d = np.array(d[::30]) #número de neurônioa na camada oculta P = 12000 M = 1 C = 1 #inicialiazação dos pesos w1 = (np.random.rand(P,M+1) - 0.5) / 2 #obtenção dos pesos de saída w2, response = output(x, d, w1) #testes para valores não presentes no conjunto de treinamento global verbose verbose = True output(testx, testd, w1, w2) if __name__ == "__main__": main()
f2540cf61a8935116b8ed9153e693541e3c91706
fear-the-lord/Structural-Balance-Identificator
/manual_network.py
4,432
3.625
4
# Import all the necessary dependencies import networkx as nx import matplotlib.pyplot as plt import random import itertools def checkStability(tris_list, G): stable = [] unstable = [] for i in range(len(tris_list)): temp = [] temp.append(G[tris_list[i][0]][tris_list[i][1]]['sign']) temp.append(G[tris_list[i][1]][tris_list[i][2]]['sign']) temp.append(G[tris_list[i][0]][tris_list[i][2]]['sign']) if(temp.count('+') % 2 == 0): unstable.append(tris_list[i]) else: stable.append(tris_list[i]) stableNum = len(stable) unstableNum = len(unstable) balance_score = stableNum / (stableNum + unstableNum) if balance_score == 1.0: print('The network is STRUCTURALLY BALANCED') elif balance_score >= 0.9: print('The network is APPROXIMATELY STRUCTURALLY BALANCED') else: print('The network is Not STRUCTURALLY BALANCED') print("Stable triangles: ", stableNum) print("Unstable triangles: ", unstableNum) print("Number of Triangles: ", stableNum + unstableNum) return stable, unstable if __name__ == "__main__": G = nx.Graph() # Number of nodes n = 6 # G.add_nodes_from([i for i in range(1, n+1)]) # mapping = {1:'Alexandra',2:'Anterim', 3:'Bercy',4:'Bearland',5:'Eplex', 6:'Ron'} # Hard Coding positions for better presentation G.add_node(1,pos=(2,3)) G.add_node(2,pos=(1,2)) G.add_node(3,pos=(2,1)) G.add_node(4,pos=(4,3)) G.add_node(5,pos=(5,2)) G.add_node(6,pos=(4,1)) mapping = {} for i in range(1,n+1): mapping[i] = "Node" + str(i) G = nx.relabel_nodes(G, mapping) # Hard coding the signs G.add_edge( 'Node1', 'Node2', sign ='+') G.add_edge( 'Node1', 'Node3', sign ='+') G.add_edge( 'Node1', 'Node4', sign ='-') G.add_edge( 'Node1', 'Node5', sign ='-') G.add_edge( 'Node1', 'Node6', sign ='-') G.add_edge( 'Node2', 'Node3', sign ='+') G.add_edge( 'Node2', 'Node4', sign ='-') G.add_edge( 'Node2', 'Node5', sign ='-') G.add_edge( 'Node2', 'Node6', sign ='-') G.add_edge( 'Node3', 'Node4', sign ='-') G.add_edge( 'Node3', 'Node5', sign ='-') G.add_edge( 'Node3', 'Node6', sign ='-') G.add_edge( 'Node4', 'Node5', sign ='+') G.add_edge( 'Node4', 'Node6', sign ='+') G.add_edge( 'Node5', 'Node6', sign ='+') # # Random signs # G = nx.relabel_nodes(G, mapping) # signs = ['+', '-'] # for i in G.nodes(): # for j in G.nodes(): # if i != j: # G.add_edge(i, j, sign = random.choice(signs)) edges = G.edges() nodes = G.nodes() tris_list = [list(x) for x in itertools.combinations(nodes, 3)] stable, unstable = checkStability(tris_list, G) edge_labels = nx.get_edge_attributes(G, 'sign') # pos = nx.circular_layout(G) pos = nx.spring_layout(G) # Getting positions from the nodes pos=nx.get_node_attributes(G,'pos') nx.draw(G, pos, node_size = 2000, with_labels = True, font_size = 10) nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, font_size = 15) Friends = [k for k, v in edge_labels.items() if v == '+'] Enemies = [k for k, v in edge_labels.items() if v == '-'] nx.draw_networkx_edges(G, pos, edgelist = Friends, edge_color="g") nx.draw_networkx_edges(G, pos, edgelist = Enemies, edge_color="r") # plt.savefig("network.png", format="PNG") plt.show() # # Uncomment this to see individual triangle states # plt.pause(10) # for i in range(len(stable)): # temp = [tuple(x) for x in itertools.combinations(stable[i], 2)] # plt.cla() # nx.draw(G, pos, node_size = 2000, with_labels = True, font_size = 10) # nx.draw_networkx_edges(G, pos, edgelist = temp, edge_color="g", width = 6 ) # # plt.savefig("stable{}.png".format(i), format="PNG") # plt.pause(2) # plt.show() # for i in range(len(unstable)): # temp = [tuple(x) for x in itertools.combinations(unstable[i], 2)] # plt.cla() # nx.draw(G, pos, node_size = 2000, with_labels = True, font_size = 10) # nx.draw_networkx_edges(G, pos, edgelist = temp, edge_color="r", width = 6) # plt.pause(2)
18f50b38f9ef8dfc927c8850927d6739bba3dac7
Philthy-Phil/practice-python
/ex3-ListLessThanTen.py
541
3.765625
4
__author__ = 'phil.ezb' a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] x = [] ui = "\n*************************" print("Given list of numbers: ", a) print(ui) for num in a: if (num < 5): print(num, end=", ") print(ui) for num in a: if (num < 5): x.append(num) print("here are all the numbers < 5: ", x) print(ui) usrnum = int(input("what's your number? ")) ulist = [] for num in a: if(num < usrnum): ulist.append(num) print("here are all the numbers from a, which are smaller than your input: ", ulist)
b698727d6dfa278ead4845b0b150dde2e8439b6e
stawary/LeetCode
/LeetCode/Median_of_Two_Sorted_Arrays.py
796
3.96875
4
#There are two sorted arrays nums1 and nums2 of size m and n respectively. #两个排好序的数组,求这两个数组的中位数。 #Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). #Example 1: #nums1 = [1, 3] #nums2 = [2] #The median is 2.0 #Example 2: #nums1 = [1, 2] #nums2 = [3, 4] #The median is (2 + 3)/2 = 2.5 class Solution: def findMedianSortedArrays(self, nums1, nums2): for i in range(len(nums2)): nums1.append(nums2[i]) #合并nums1和nums2 nums = sorted(nums1) #排序 length = len(nums) if length%2==1: #长度为奇数 median = nums[length//2] else: #长度为偶数 median = (nums[length//2-1]+nums[length//2])/2 return float(median)
692a0421d4258a93f1a16759976a4a98c5f1af41
Ejas12/pythoncursobasicoEstebanArtavia
/dia7/tarea6.py
936
3.5
4
import csv input_file = csv.DictReader(open("C:\\Users\\Esteban Artavia\\Documents\\scripts\\\Pythoncourse\\dia7\\serverdatabase.csv")) outputfile = open('C:\\Users\\Esteban Artavia\\Documents\\scripts\\\Pythoncourse\\dia7\\output.txt', 'w+') outputfile.write('NEW RUN\n') outputfile.close outputfile = open('C:\\Users\\Esteban Artavia\\Documents\\scripts\\\Pythoncourse\\dia7\\output.txt', 'a+') for lineausuario in input_file: nombre = lineausuario['first_name'] apellido = lineausuario['last_name'] numero = lineausuario['phone1'] mail = lineausuario['email'].split('@') login = mail[0] proveedorurl = mail[1].split('.')[0] pass mensaje_print = "Hola me llamo {nombre} {apellido}. Mi teléfono es {numero} .Mi usuario de correo es: {login} usando una cuenta de {proveedorurl}\n".format(nombre = nombre, apellido = apellido, numero = numero, login = login, proveedorurl = proveedorurl) outputfile.writelines(mensaje_print)
26b5cff2b5c9a9eca56befae9956bc895690c60e
sundusaijaz/pythonpractise
/calculator.py
681
4.125
4
num1 = int(input("Enter 1st number: ")) num2 = int(input("Enter 2nd number: ")) op = input("Enter operator to perform operation: ") if op == '+': print("The sum of " + str(num1) + " and " + str(num2) + " = " +str(num1+num2)) elif op == '-': print("The subtraction of " + str(num1) + " and " + str(num2) + " = " +str(num1-num2)) elif op == '*': print("The multiplication of " + str(num1) + " and " + str(num2) + " = " +str(num1*num2)) elif op == '/': print("The division of " + str(num1) + " and " + str(num2) + " = " +str(num1/num2)) elif op == '%': print("The mod of " + str(num1) + " and " + str(num2) + " = " +str(num1%num2)) else: print("Invalid Input")
1a301b5f2b834fb833f81fcb8060853474736c87
pjjefferies/python_practice
/huffman_encoding.py
6,229
3.5625
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 13 21:10:34 2019 @author: PaulJ """ # import unittest # takes: str; returns: [ (str, int) ] (Strings in return value are single # characters) def frequencies(s): return [(char, s.count(char)) for char in set(s)] # takes: [ (str, int) ], str; returns: String (with "0" and "1") def encode(freqs, s): if len(freqs) <= 1: return None if not s: return '' nodes_in_tree, root_node_key = create_node_tree(freqs) result = '' for a_char in s: curr_node = nodes_in_tree[root_node_key] while True: new_char = True for a_child_no in ['0', '1']: a_child_node = 'child_' + a_child_no if curr_node[a_child_node] is not None: if a_char in curr_node[a_child_node]: result += a_child_no curr_node = nodes_in_tree[curr_node[a_child_node]] new_char = False continue if not new_char: continue break return result def create_node_tree(freqs): nodes_to_add = {} for a_char, a_freq in freqs: # adding parent, lh_child, rh_child nodes nodes_to_add[a_char] = { 'freq': a_freq, 'parent': None, 'child_0': None, 'child_1': None } # adding l/r_child nodes_in_tree = {} while nodes_to_add: node_freq = zip(nodes_to_add.keys(), [nodes_to_add[x]['freq'] for x in nodes_to_add]) min_key1 = min(node_freq, key=lambda x: x[1])[0] node1_to_add = nodes_to_add.pop(min_key1) node_freq = zip(nodes_to_add.keys(), [nodes_to_add[x]['freq'] for x in nodes_to_add]) min_key2 = min(node_freq, key=lambda x: x[1])[0] node2_to_add = nodes_to_add.pop(min_key2) new_node = { # node1_to_add[0] + node2_to_add[0], 'freq': node1_to_add['freq'] + node2_to_add['freq'], 'parent': None, 'child_0': min_key2, 'child_1': min_key1} node1_to_add['parent'] = min_key1 + min_key2 node2_to_add['parent'] = min_key1 + min_key2 nodes_in_tree[min_key1] = node1_to_add nodes_in_tree[min_key2] = node2_to_add nodes_to_add[min_key1 + min_key2] = new_node if len(nodes_to_add) == 1: root_node_key = min_key1 + min_key2 root_node = nodes_to_add.pop(root_node_key) nodes_in_tree[root_node_key] = root_node return nodes_in_tree, root_node_key # takes [ [str, int] ], str (with "0" and "1"); returns: str # e.g. freqs = [['b', 1], ['c', 2], ['a', 4]] # bits = '0000111010' def decode(freqs, bits): if len(freqs) <= 1: return None if len(bits) == 0: return '' nodes_in_tree, root_node_key = create_node_tree(freqs) bits_list = bits[:] result = '' curr_node_key = root_node_key while bits_list: curr_node = nodes_in_tree[curr_node_key] curr_bit = bits_list[0] bits_list = bits_list[1:] child_str = 'child_' + curr_bit if nodes_in_tree[curr_node[child_str]][child_str] is None: result += curr_node[child_str] # take letter curr_node_key = root_node_key else: curr_node_key = curr_node[child_str] # no letter found yet, g-down return result s = 'aaaabcc' fs = frequencies(s) encoded = encode(fs, s) decoded = decode(fs, encoded) print('s:', s, ', fs:', fs, ', encoded:', encoded, ', decoded:', decoded) fs1 = [('a', 1), ('b', 1)] test1 = ["a", "b"] for a_test in test1: encoded = encode(fs1, a_test) decoded = decode(fs1, encoded) print('a_test:', a_test, ', fs1:', fs1, ', encoded:', encoded, ', decoded:', decoded) """ class InterpreterTestMethods(unittest.TestCase): len_tests = [["aaaabcc", 10]] #, """ """ ['2 - 1', 1], ['2 * 3', 6], ['8 / 4', 2], ['7 % 4', 3], ['x = 1', 1], ['x', 1], ['x + 3', 4], ['y', ValueError], ['4 + 2 * 3', 10], ['4 / 2 * 3', 6], ['7 % 2 * 8', 8], ['(7 + 3) / (2 * 2 + 1)', 2]] def test_basic(self): interpreter = Interpreter() for expression, answer in self.tests: print('\n') try: result = interpreter.input(expression) except ValueError: result = ValueError print('expression:', expression, ', answer:', answer, ', result:', result) self.assertEqual(result, answer) """ """ if __name__ == '__main__': unittest.main() test.describe("basic tests") fs = frequencies("aaaabcc") test.it("aaaabcc encoded should have length 10") def test_len(res): test.assert_not_equals(res, None) test.assert_equals(len(res), 10) test_len(encode(fs, "aaaabcc")) test.it("empty list encode") test.assert_equals(encode(fs, []), '') test.it("empty list decode") test.assert_equals(decode(fs, []), '') def test_enc_len(fs, strs, lens): def enc_len(s): return len(encode(fs, s)) test.assert_equals(list(map(enc_len, strs)), lens) test.describe("length") test.it("equal lengths with same frequencies if alphabet size is a power of two") test_enc_len([('a', 1), ('b', 1)], ["a", "b"], [1, 1]) test.it("smaller length for higher frequency, if size of alphabet is not power of two") test_enc_len([('a', 1), ('b', 1), ('c', 2)], ["a", "b", "c"], [2, 2, 1]) test.describe("error handling") s = "aaaabcc" fs = frequencies(s) test.assert_equals( sorted(fs), [ ("a",4), ("b",1), ("c",2) ] ) test_enc_len(fs, [s], [10]) test.assert_equals( encode( fs, "" ), "" ) test.assert_equals( decode( fs, "" ), "" ) test.assert_equals( encode( [], "" ), None ); test.assert_equals( decode( [], "" ), None ); test.assert_equals( encode( [('a', 1)], "" ), None ); test.assert_equals( decode( [('a', 1)], "" ), None ); """
10c1c00ec710a8a6e32c4e0f6f73df375f5a72d5
pjjefferies/python_practice
/find_anagrams.py
824
3.875
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 28 21:59:44 2019 @author: PaulJ """ def anagrams(word, words): anagrams_found = [] for a_word in words: a_word_remain = a_word poss_anagram = True for a_letter in word: print('1: a_word_remain:', a_word_remain) first_let_pos = a_word_remain.find(a_letter) if first_let_pos == -1: poss_anagram = False continue a_word_remain = (a_word_remain[:first_let_pos] + a_word_remain[first_let_pos + 1:]) print('2: a_word_remain:', a_word_remain) if not a_word_remain and poss_anagram: anagrams_found.append(a_word) return anagrams_found print('result: ', anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']))
e7eb877dfa1edc9e2f3e0c59c71338453ff9b964
pjjefferies/python_practice
/censor_test.py
545
3.75
4
def censor(text, word): word_replace = "*" * len(word) for i in range(len(text)): print (i, text[i], word[0]) if text[i] == word[0]: for j in range(len(word)): print (i, j, text[i+j], word[j]) if text[i+j] != word[j]: break else: print (text, word, word_replace) text = text.replace(word, word_replace) return text print (censor("Now is the time for all good men to come to the aid of their country", "to"))
07a627b0e4ab6bb12ec51db84fb72f56032649c4
Skyorca/deeplearning_practice_code
/FC_tf.py
3,607
4.03125
4
import tensorflow as tf import numpy as np from numpy.random import RandomState #Here is a built-in 3-layer FC with tf as practice """ how tf works? 1. create constant tensor(e.g.: use for hparam) tensor looks like this: [[]](1D) [[],[]](2D)... tf.constant(self-defined fixed tensor, and type(eg. tf.int16, should be defined following tensor)) tf.zeros/ones([shape]) tf.random... just like numpy 2. create variable tensor(e.g.: use for weight&bias) tf.Variable(init_tensor, type), value could change but shape can not, initial could be any value 3. create placeholder(e.g.: use for feeding batch data, repeatedly use) tf.placeholder(type, shape=()) before training(session begins), everything you do within functions are done by placeholders&constants, no variables 4. define operations(from basic operations to complicated functions) tf.func_name(params) [some are like numpy] sess.run(defined_operation, feed_dict) 5. everything starts with a graph tf.Graph(), used in session. if there is only one graph, without defining a graph is allowed if you like, use graph like this: with graph.as_default(): define nodes&vects for Net 6. training starts with a session after having defined NetStructure&operations, start a session to start training. with tf.Session() as session: #if multiple graphs, tf.Session(graph=graph_x) training... sess.run(operation, feed_dict) 7. practical notes: a. use None in shape=(), could alternatively change b. use tf functions to build loss_function, and define train_step with optimizer(optimizing this loss) c. how to use Class to make a Net??? d. tf.reduce_mean: calculate average along whole tensor/appointed axis a=[[1,1], [2,2]] tf.reduce_mean(a) = 1.5 ,type=float32 tf.reduce_mean(a, 0) = [1.5, 1.5], do along each column (1+2)/2 tf.reduce_mean(a, 1) = [1, 2], do along each row 1+1/2, 2+2/2 """ graph = tf.Graph() #define Net Structure with graph.as_default(): x = tf.placeholder(tf.float32, shape=(2, None)) #x=(a,b) y = tf.placeholder(tf.float32, shape=(1, None)) W1 = tf.Variable(tf.random_normal([3,2], stddev=1, seed=1)) # auto. float32 W2 = tf.Variable(tf.random_normal([1,3], stddev=1, seed=1)) b1 = tf.Variable(tf.random_normal([1,1])) b2 = tf.Variable(tf.random_normal([1,1])) #1st layer is input a_0=x #2nd layer a_1 = tf.nn.relu(tf.matmul(W1, x)+b1) # a_1 is (3, none) # output layer y_pred = tf.nn.sigmoid(tf.matmul(W2, a_1)+b1) # a_2 is(1, none) #define loss cross_entropy_loss = -tf.reduce_mean(y*tf.log(tf.clip_by_value(y_pred, 1e-10,1.0))) train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy_loss) #define a simulated sample rdm=RandomState(1) data_size=512 X = [] for i in range(data_size): X.append(rdm.rand(2,1)) X = np.array(X) Y = [] for i in range(data_size): Y.append([int((X[i][0]+X[i][1])<1)]) Y = np.array(Y) #begin training epoch = 100 batch_size = 10 with tf.Session(graph=graph) as sess: sess.run(tf.initialize_all_variables()) for time in range(epoch): for i in range(data_size/batch_size+1): start = i*batch_size % data_size end = min(start+batch_size, batch_size) # build batch Y_u = Y.T sess.run(train_step, feed_dict={x:X[start:end], y:Y_u[start:end]}) """ here is a trick: in 1st batch, start=0, end=10, there are 11 samples; However, in slice[start:end], get idx 0~9 actually """ loss = sess.run(cross_entropy_loss, feed_dict={x:X, y:Y}) print("at %d epoch, loss->%f" % (time, float(loss)))
26d288b468e8cf62b3d27a5ab20513e6889373bf
Wigrovski/Python3
/SandwichApp/sandwich.py
399
3.625
4
import sys if sys.version_info < (3, 0): # Python 2 import Tkinter as tk else: # Python 3 import tkinter as tk def eat(event): print("Вкуснятина") def make(event): print ("Бутер с колбасой готов") root = tk.Tk() root.title("Sandwich") tk.Button(root, text="Make me a Sandwich").pack() tk.Button(root, text="Eat my Sandwich").pack() tk.mainloop()
9c013a6131b469a6d40a294243ec6b6f1c0da02d
JenniferHhj/UcBerkeley-IndustryEng135
/Neural_Network/NN.py
4,743
3.671875
4
import tensorflow as tf import tensorflow_datasets as tfds tfds.disable_progress_bar() import math import numpy as np import matplotlib.pyplot as plt import logging logger = tf.get_logger() logger.setLevel(logging.ERROR) from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.regularizers import l2 import os from tensorflow.keras.layers import Conv2D #print(tf.version.VERSION) dataset, metadata = tfds.load('fashion_mnist', as_supervised=True, with_info=True) train_dataset, test_dataset = dataset['train'], dataset['test'] num_train_examples = metadata.splits['train'].num_examples num_test_examples = metadata.splits['test'].num_examples print("Number of training examples: {}".format(num_train_examples)) print("Number of test examples: {}".format(num_test_examples)) def normalize(images, labels): images = tf.cast(images, tf.float32) images /= 255 return images, labels # The map function applies the normalize function to each element in the train # and test datasets train_dataset = train_dataset.map(normalize) test_dataset = test_dataset.map(normalize) # The first time you use the dataset, the images will be loaded from disk # Caching will keep them in memory, making training faster train_dataset = train_dataset.cache() test_dataset = test_dataset.cache() ''' Build the model Building the neural network requires configuring the layers of the model, then compiling the model. Setup the layers The basic building block of a neural network is the layer. A layer extracts a representation from the data fed into it. Hopefully, a series of connected layers results in a representation that is meaningful for the problem at hand. Much of deep learning consists of chaining together simple layers. Most layers, like tf.keras.layers.Dense, have internal parameters which are adjusted ("learned") during training. ''' # Initialize model constructor model = Sequential() ''' TO DO # Add layers sequentially Keras tutorial is helpful: https://www.tensorflow.org/guide/keras/sequential_model The score you get depends on your testing data accuracy. 0.00 <= test_accuracy < 0.85: 0/18 0.85 <= test_accuracy < 0.86: 3/18 0.86 <= test_accuracy < 0.87: 6/18 0.87 <= test_accuracy < 0.88: 9/18 0.88 <= test_accuracy < 0.89: 12/18 0.89 <= test_accuracy < 0.90: 15/18 0.90 <= test_accuracy < 1.00: 18/18 ''' ################# TO DO ################### ##reference: https://www.kaggle.com/saraei1pyr/classifying-images-of-clothing ##reference: https://www.programcreek.com/python/example/89658/keras.layers.Conv2D ##Using reference help from kaggle for the layer adding and analyzation of the moddel model.add(Conv2D(28, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1))) model.add(Flatten()) model.add(Dense(256, activation='relu')) model.add(Dense(units=20, activation='softmax')) ########################################### ''' Compile the model Before the model is ready for training, it needs a few more settings. These are added during the model's compile step: Loss function — An algorithm for measuring how far the model's outputs are from the desired output. The goal of training is this measures loss. Optimizer —An algorithm for adjusting the inner parameters of the model in order to minimize loss. Metrics —Used to monitor the training and testing steps. The following example uses accuracy, the fraction of the images that are correctly classified. ''' model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=['accuracy']) ''' ### Training is performed by calling the `model.fit` method: 1. Feed the training data to the model using `train_dataset`. 2. The model learns to associate images and labels. 3. The `epochs=5` parameter limits training to 5 full iterations of the training dataset, so a total of 5 * 60000 = 300000 examples. (Don't worry about `steps_per_epoch`, the requirement to have this flag will soon be removed.) ''' BATCH_SIZE = 32 train_dataset = train_dataset.cache().repeat().shuffle(num_train_examples).batch(BATCH_SIZE) test_dataset = test_dataset.cache().batch(BATCH_SIZE) ''' TO DO # Decide how mnay epochs you want ''' model.fit(train_dataset, epochs=20, steps_per_epoch=math.ceil(num_train_examples/BATCH_SIZE)) ''' As the model trains, the loss and accuracy metrics are displayed. This model reaches an accuracy of about 0.88 (or 88%) on the training data. ''' model.save('my_model') test_loss, test_accuracy = model.evaluate(test_dataset, steps=math.ceil(num_test_examples/32)) print('Accuracy on test dataset:', test_accuracy)
ac62e611bd36e4117f7705720bf39692148835f5
elvirich04/myOOP
/OOP/OOP2.PY
724
3.796875
4
class Person: def __init__(self, Name, Sex, Age): self.Name=Name self.Sex=Sex self.Age=Age def Show(self): if self.Sex=="Male": pronoun="Mr." else: pronoun="Ms." print("%s %s is %i years old."%(pronoun, self.Name, self.Age)) Person1=Person("John", "Male", 19) Person2=Person("Sony", "Male", 27) Person3=Person("Elvira","Female",22) Person4=Person("Ondoy","Female",20) Person5=Person("Jhane","Female",17) Person6=Person("Joy","Female",19) Person7=Person("Ferdinand","Male",17) Person8=Person("Gabriel","Male",19) Person1.Show() Person2.Show() Person3.Show() Person4.Show() Person5.Show() Person6.Show() Person7.Show() Person8.Show()
ac79e5ed6bfa7b1d928aa2d6eb07f9fcab72d39f
elvirich04/myOOP
/OOP/OOP.PY
473
3.8125
4
class Person: def __init__(self): self.Name="" self.Sex="" self.Age=0 def Show(self): if self.Sex=="Male": pronoun="Mr." else: pronoun="Ms." print("%s %s is %i years old."%(pronoun, self.Name, self.Age)) Person1=Person() Person1.Name="John" Person1.Sex="Male" Person1.Age=19 Person2=Person() Person2.Name="Elvira" Person2.Sex="Female" Person2.Age=22 Person1.Show() Person2.Show()
4f2f5eb803fee7c8ba6e73a1a142864f6ae91660
dmnjzl/jupyter
/class-and-object/maxHeap.py
2,471
3.921875
4
#MaxHeap class from Lab 3 class MaxHeap(object): def __init__(self,data=[]): # constructor - empty array self.data = data def isEmpty(self): # return true if maxheaph has zero elements return(len(self.data)==0) def getSize(self): # return number of elements in maxheap return(len(self.data)) def clear(self): # remove all elements of maxheap self.data=[] def printout(self): # print elements of maxheap print (self.data) def getMax(self): # return max element of maxHeap # check that maxHeaph is non-empty if (not self.isEmpty()): return(max(self.data)) else: return None #helper method for add(newEntry) and removeMax() #swap elements so parent node is greater than both its children #if swap made, call heapify on swapped child def heapify(self, parentIndex): #given parentIndex, find left and right child indices child1Index = parentIndex*2+1 child2Index = parentIndex*2+2 largest=parentIndex # check if left child is larger than parent if (child1Index < len(self.data)) and (self.data[child1Index] > self.data[parentIndex]): largest = child1Index # check if right child is larger than the max of left child # and parent if (child2Index < len(self.data)) and (self.data[child2Index] > self.data[largest]): largest = child2Index # if either child is greater than parent: # swap child with parent if (largest != parentIndex): self.data[largest], self.data[parentIndex] = self.data[parentIndex], self.data[largest] self.heapify(largest) # call heapify() on subtree def buildHeap(self, A): # build maxheap, calling heapify() on each non-leaf node self.data = A for i in range((len(A)-1)//2, -1, -1): self.heapify(i) def removeMax(self): # remove root node, call heapify() to recreate maxheap if (not self.isEmpty()): maxVal = self.data[0] if (len(self.data)>1): self.data[0] = self.data[len(self.data)-1] # remove last element self.data.pop() self.heapify(0) else: self.data.pop() return maxVal else: return None
8d048eb12a10e55edafe9d0e56ac4c4313eb0137
srawlani22/LSystems-Genetic-Algorithms-with-Python3
/Intro-to-L-Systems/recursionexamples/tutorial.py
1,104
3.984375
4
import turtle import time import math #from turtleLS import randint draw = turtle.Turtle() # # drawing a square # draw.forward(100) # draw.right(90) # draw.forward(100) # draw.right(90) # draw.forward(100) # draw.right(90) # draw.forward(100) # # time.sleep(3) # # draw.reset() # draw.penup() # draw.forward(100) # draw.pendown() # Another design- draws a fancy star graph using recursion in Python. pickachu = turtle.Turtle() screen = turtle.Screen() pickachu.pencolor("white") pickachu.getscreen().bgcolor("black") # r = randint(0,255) # g = randint(0,255) # b = randint(0,255) # screen.colormode(255) # draw.pencolor(r,g,b) # for i in range(5): # pickachu.forward(200) # pickachu.left(216) pickachu.speed(0) pickachu.penup() pickachu.goto((-200,100)) pickachu.pendown() def starGraph(turtle, size): if size <= 10: return else: turtle.begin_fill() for i in range(5): pickachu.forward(size) starGraph(turtle, size/3) pickachu.left(216) turtle.end_fill() starGraph(pickachu,360) turtle.done()
20821b277bb38285010d11b0bace9a4da4d539b5
shreo-adh/Python
/PDF_rotator.py
485
3.890625
4
import PyPDF2 file_path = input("Input file path: ") rotate = 0 with open(file_path, mode='rb') as my_file: reader = PyPDF2.PdfFileReader(my_file) page = reader.getPage(0) rotate = int(input("Enter the degree of rotation(Clockwise): ")) page.rotateClockwise(rotate) writer = PyPDF2.PdfFileWriter() writer.addPage(page) new_file_path = input("Enter path of new file: ") with open(new_file_path, mode='wb') as new_file: writer.write(new_file)
c03f949e619ad6bdec690bd942043a3bfca7d816
acstibi02/4.ora
/hf4_4.py
403
3.625
4
bekert_szöveg = input("Írjon be egy szöveget: ") i = 0 j = 1 lista=[] a = 'False' while i < (len(bekert_szöveg)//2): if bekert_szöveg[i] == bekert_szöveg[len(bekert_szöveg)-j]: lista.append('True') i+=1 j+=1 else: lista.append('False') i+=1 j+=1 if a in lista: print("Ez nem palindrom. ") if a not in lista: print("Ez palindrom. ")
c0a4b3de94544033bfa95b7a208f58f2b5c0eedc
NBALAJI95/Python-programming
/inClass/Class - 2/inClass-charac-freq.py
471
3.984375
4
def findCharFreq(s, c): if c not in s: return 'Letter not in string' else: count = s.count(c) return count def main(): inp_str = input('Enter the string:') distinct_letters = [] for i in inp_str: if i not in distinct_letters: distinct_letters.append(i) for e in distinct_letters: print('Character Frequency of %s is %s' % (e, findCharFreq(inp_str, e))) if __name__ == '__main__': main()
8a869f9cc02943a51c4d0ce03dafe50c15740dc3
NBALAJI95/Python-programming
/inClass/Class - 4/inClass.py
729
3.703125
4
import requests from bs4 import BeautifulSoup import os def main(): url = "https://en.wikipedia.org/wiki/Android_(operating_system)" source_code = requests.get(url) plain_text = source_code.text # Parsing the html file soup = BeautifulSoup(plain_text, "html.parser") # Finding all div tags result_list = soup.findAll('div') # In the list of div tags, we are extracing h1 for div in result_list: h1 = div.find('h1') if h1 != None: # Printing only text associated with h1 print(h1.text) # Doing the same procedure for body result_list1 = soup.findAll('body') for b in result_list1: print(b.text) if __name__=='__main__': main()
10becb5b4a704625c66e56c5a66b975ab3c1628e
NBALAJI95/Python-programming
/inClass/Class - 3/inClass-1.py
905
3.859375
4
def print_horiz_line(): return '---' def print_vert_line(): return '|' def main(): inp = input('Enter dimensions of the board separated by "x":') inp = inp.split('x') inp = list(map(lambda a: int(a), inp)) print(inp) op ='' t = 0 case = '' it = 0 if (inp[0] + inp[1]) % 2 == 0: it = inp[0] + inp[1] + 1 else: it = inp[0] + inp[1] for i in range(it): if i % 2 == 0: t = inp[1] case = 'even' else: t = inp[1] + 1 case = 'odd' for j in range(t): if j == 0 and case == 'even': op += ' ' if case == 'even': op += print_horiz_line() + ' ' elif case == 'odd': op += print_vert_line() op += ' ' op += '\n' print(op) if __name__ == '__main__': main()
fb213cb12399aa1b08a15d4040ef3ce15457e9e9
NBALAJI95/Python-programming
/Assignments/Week - 3/Task-3.py
1,624
3.953125
4
# Getting input co-ordinates from the user def getCoordinates(turn, tt): player = '' while True: if turn % 2 == 0: inp = input("Player 1, enter your move in r,c format:") player = 'X' else: inp = input("Player 2, enter your move in r,c format:") player = 'O' inp = inp.split(',') inp = list(map(lambda a: int(a), inp)) r = inp[0]-1 c = inp[1]-1 if tt[r][c] != -1: print('INVALID MOVE, TRY AGAIN!') else: break inp.append(player) return inp # Setting values def setCoordinates(t, m): m[0] -= 1 m[1] -= 1 t[m[0]][m[1]] = m[2] return t def print_horiz_line(): return '--- ' * 3 def print_vert_line(): return '|' #function for printing the board def gameBoard(tt): ret = '' for i in range(3): for j in range(3): if j == 0: ret += print_horiz_line() ret += '\n' ret += print_vert_line() if tt[i][j] != -1: ret += tt[i][j] else: ret += ' ' ret += print_vert_line() ret += ' ' ret += '\n' ret += print_horiz_line() return ret print_horiz_line() def main(): tic_tac = list() for i in range(3): t = [] for j in range(3): t.append(-1) tic_tac.append(t) for i in range(9): g = getCoordinates(i, tic_tac) tic_tac = setCoordinates(tic_tac, g) print(gameBoard(tic_tac)) if __name__ == "__main__": main()
9154ab03fa537db195606670fe318a1240ca20ba
djd1283/UndiagnosedDiseaseClassifier
/get_random_submissions.py
2,058
3.5
4
"""Get random submissions from Reddit as negative examples for classifier.""" import os import csv import praw from filter_reddit_data import load_credentials from tqdm import tqdm data_dir = 'data/' negative_submissions_file = 'negative_submissions.tsv' accepted_submissions_file = 'accepted_submissions.tsv' def generate_negative_posts(reddit, n_posts): # TODO find regular posts from popular subreddits as negative examples for training a classifier negative_posts = [] bar = tqdm(total=n_posts) while True: random_submissions = reddit.subreddit('all').random_rising(limit=n_posts) random_submissions = [submission for submission in random_submissions] for submission in random_submissions: title = submission.title text = ' '.join(submission.selftext.split()) subreddit = submission.subreddit if len(text) > 0: negative_posts.append([title, text, subreddit]) bar.update() if len(negative_posts) >= n_posts: return negative_posts def main(): n_posts = 2000 creds = load_credentials() reddit = praw.Reddit(client_id=creds['client'], client_secret=creds['secret'], user_agent=creds['agent']) # we generate the same number of negative examples as positive examples if n_posts is not specified if n_posts is None: n_posts = sum([1 for line in open(os.path.join(data_dir, accepted_submissions_file), 'r')]) print(f'Number of negative submissions: {n_posts}') negative_submissions = generate_negative_posts(reddit, n_posts) # random posts from common subreddit we use as negative examples and save to negative file with open(os.path.join(data_dir, negative_submissions_file), 'w', newline='\n') as f_negative: writer = csv.writer(f_negative, delimiter='\t') for submission in negative_submissions: writer.writerow(submission) if __name__ == '__main__': main()
775bc457736c4a7dd6c98a389e63432c814cd1a4
custu2000/curs_python
/lab1/lab1.py
843
3.8125
4
#ex 1 for i in range(100): print ("hello world") # ex 2 s="hello world"*100 print (s) #ex 3 #fizz %3, buzz %5, fizz buzz cu 3 si 5 #rest numarul for i in range(100): if i % 3 ==0 and i % 5 ==0: print "fizz buzz for: ",i if i % 3 ==0 : print "fizz for: ",i if i % 5 ==0 : print "buzz for: ",i #ex 4 n=input('introduceti numarul: ') n1=(n%100)//10 print "cifra zecilor este :",n1 #ex 5 print "ex 5" n=input('introduceti numarul de minute: ') n1=n//60 n2=n-n1*60 print ("Minute : %d Secunde:%d "%(n1,n2)) print ("Minute : {} Secunde: {}".format(n1,n2)) #ex 6 #bisect %4 dar nu si cu 100 #bisect daca este diviz cu 400 an=input('introduceti anul: ') if an % 400 ==0 or (an % 4==0 or an %100==0): print("anul {} este bisect".format(an)) else: print("anul nu este bisect"); #ex7
3da597b2bcdcdaf16bfa50bc86a060fa56173667
ND13/zelle_python
/chapter_2/futval.py
792
4.15625
4
#!/usr/bin/python3.6 # File: futval.py # A program that computes an investment carried 10 years into future # 2.8 Exercises: 5, 9 def main(): print("This program calculates the future value of a 10-year investment.") principal = float(input("Enter the principal amount: ")) apr = float(input("Enter the annualized interest rate: ")) length = int(input("Enter the length in years of investment: ")) inflation = float(input("Enter yearly rate of inflation: ")) apr = apr * .01 inflation = inflation * .01 for i in range(length): principal = principal * (1 + apr) principal = principal / (1 + inflation) year = i + 1 print(f"Year {year}: {principal:.2f}") print(f"The amount in {length} years is: {principal:.2f}") main()
7482b65b788259f74c8719944618f9d856417780
ND13/zelle_python
/chapter_3/pizza.py
450
4.3125
4
# sphere_2.py # calculates the price per square inch of circular pizza using price and diameter def main(): price = float(input("Enter the price for your pizza: $")) diameter = float(input("Enter the diameter of the pizza: ")) radius = diameter / 2 area = 3.14159 * radius ** 2 price_per_sq_inch = price / area print(f"The price per square inch of pizza is ${price_per_sq_inch:.2f}") if __name__ == '__main__': main()
bd85de544ae4984bddacf4f091f186fec0b8e3f4
AmarJ/ieeeCodingChallenge
/2018-Fall/solutions/Q1.py
484
3.671875
4
def rot_1(A, d): output_list = [] # Will add values from n to the new list for item in range(len(A) - d, len(A)): output_list.append(A[item]) # Will add the values before # n to the end of new list for item in range(0, len(A) - d): output_list.append(A[item]) return output_list def rot_2(A, d): return (A[-d:] + A[:-d]) A = [1, 2, 3, 4, 5, 6, 7] d = 2 print rot_1(A, d) print rot_2(A, d)
4e58aa912b1e41bf3fb42cfc8917909137174ea6
jsy2906/Portfolio
/프로그래머스/실력 테스트/Q2.py
198
3.53125
4
# Q2) 입력된 숫자만큼 문자 밀기 def solution(s, n): string = '' for i in s: result = ord(i) + n string += chr(result) return string solution('eFg', 10)
f1a0cde50de74b36ff22705364f41fb62a26f56a
jsy2906/Portfolio
/파이썬/동명이인 찾기.py
193
3.53125
4
def find_same_name(a): n = len(a) result = set() for i in range(n-1): for j in range(i+1,n): if a[i] == a[j]: result.add(a[i]) return result
1e284588df9d0a43fde6af4e7358c1d1691c82c7
nikdavis/poker_hand
/poker_hand/parsers/card_parser.py
559
3.6875
4
class CardParser(object): RANK = { "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "T": 10, "J": 11, "Q": 12, "K": 13, "A": 14 } SUIT = { "H": "heart", "D": "diamond", "C": "club", "S": "spade" } def __init__(self, card_str): """Takes one hands string, returns dict""" self.cards = card_str.split(" ") def ranks(self): return [self.RANK[card[0]] for card in self.cards] def suits(self): return [self.SUIT[card[-1]] for card in self.cards]
6cf792b36892e4c8372d95eb9857034bf939e378
leogao/examples
/hackerrank/isFib.py
763
3.734375
4
#!/usr/bin/env python # https://www.hackerrank.com/challenges/is-fibo import sys T = int(raw_input()) assert 1<=T<=10**5 def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) X = 10 fibs = [] for i in xrange(X): fibs.append(fib(i)) for i in xrange(T): a = int(raw_input()) assert 1<=a<=10**10 if a in fibs: print 'isFibo' elif a > fibs[-1]: for i in xrange(1000): fibsv = fibs[X-2+i] + fibs[X-1+i] fibs.append(fibsv) if fibsv == a: print 'isFibo' break elif fibsv > a: print 'isNotFibo' break elif a < fibs[-1]: print 'isNotFibo'
415ceea1e04a46bbab094f7abe18de80e487e0b5
heartthrob227/kenstoolbox
/convfilecheckerV0.1.py
2,049
3.5625
4
import csv, re, pandas from collections import defualtdict print('=================================') print('Welcome to the Conversion File Checker') #Ask for file to parse rawfile = input('What file do you want to test (without extension; must be csv)? ') firstfile = rawfile + '.csv' #Open file fout=open(outputname,"w+", newline='') def dateformat(): datecolumn = input('What is the name of the date column? ') #Draw value for one key from one row dateformat = #drawn value from key def idcheckandcount(): # Determine profile/affcode or KClickID idtype = input('Is this a Click ID (C) or Profile|Affcode (P) based file (case sensitive)? ') if idtype == 'C': #insert regex Check #valid rows validrows = #count of rows that meet criteria #not valid rows (return an error file with row that had error) invalidrows = #count of rows that do not meet criteria elif idtype == 'P': #insert regex Check #valid rows #not valid rows (return an error file with row that had error) else: print ('Not a valid Type') def singleormulti(): # Determine if single column for conv type or multiple columns singleormulti = input('Is this file based on single (S) or multiple (M) columns for conversions (case sensitive)? ') if singleormulti == 'S' # If single run this ## of conversions by Type # $ by Type elif singleormulti == 'M' #if multiple run this ## of conversions by Type # $ by Type else: print ('That is not a valid response') dateformat() idcheckandcount() singleormulti() def createreport(): print ('======================================') print ('Date format is ' + dateformat) print ('The number of valid rows is ' + validrows) print ('The number of valid rows is ' + invalidrows) print ('') #figure out a way to get the consolidated list of conv types and their aggregation print ('') #same as above but with Rev
d95ad94be6d99173fbab10e23b772a94d8ed0cd8
mclearning2/Algorithm_Practice
/math/204_Count_Primes.py
508
3.953125
4
''' Count the number of prime numbers less than a non-negative number, n. Example: Input: 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. ''' class Solution: def countPrimes(self, n: int) -> int: answer = 0 memory = list(range(n)) memory[:2] = None, None for i in range(2, n): if memory[i]: answer += 1 for j in range(i, n, i): memory[j] = None return answer
61b71063cf7828bbb2806a7992b43da37d41a9a2
Cathelion/Numerical-Approximation-Course
/Assignment4_Remez_algo.py
3,736
3.75
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 3 20:16:53 2021 @author: florian A short demonstration of the Remez algorithm to obtain the best approximation of a function in the supremum norm on a compact interval. The test function used is f(x) = x*sin(x) and we use 7 points We also plot the sign-changing error a characteristic of the approximation in the supremum norm, and its convergence. Furthermore we keep track of the set of extremal points. """ import numpy as np import matplotlib.pyplot as plt from matplotlib import style plt.style.use('seaborn') plt.figure(1,figsize=(10,7)) plt.figure(2,figsize=(10,7)) plt.figure(1) def coeff(xDat,func): n = len(xDat)-2 powerM = np.tile( np.arange(n+1) ,(n+2,1)) dataM = np.tile(np.reshape(xDat, (-1, 1)) , n+1) Mat= np.power(dataM,powerM) eta_vec = np.array([-(-1)**i for i in range(n+2)]) Mat = np.hstack((Mat,np.reshape(eta_vec, (-1, 1)))) b = func(xDat) a = np.linalg.solve(Mat, b) return a def evalPoly(coeff,x): n = len(coeff) powerV = np.array([x**i for i in range(n)]) return np.dot(powerV,coeff) def findxhat(coeff,func,a,b): xD = np.linspace(a,b,1000) yD = np.array([evalPoly(coeff, x) for x in xD]) error = np.abs(yD-func(xD)) return xD[error.argmax()] def exchange(xDat, xNew, coeff, func): sgn_hat = np.sign(evalPoly(coeff, xNew)-func(xNew)) if xNew<xDat[0]: sgn_x0 = np.sign(evalPoly(coeff, xDat[0])-func(xDat[0])) if sgn_x0==sgn_hat: xDat[0] = xNew else: xDat[-1] = xNew return elif xNew>xDat[-1]: sgn_x0 = np.sign(evalPoly(coeff, xDat[-1])-func(xDat[-1])) if sgn_x0==sgn_hat: xDat[-1] = xNew else: xDat[0] = xNew return for k in range(len(xDat)-1): if xDat[k]<=xNew<=xDat[k+1]: sgn_xk = np.sign(evalPoly(coeff, xDat[k])-func(xDat[k])) if sgn_xk==sgn_hat: xDat[k] = xNew else: xDat[k+1] = xNew return xDat.sort() # sort data in case new value in start/end def remez(xDat,f,a,b): errors = [] maxErrorOld = 0 E_k_sets = [["%.4f" % x for x in xDat]] for i in range(20): coeff1 = coeff(xDat,f) maxErrorNew = coeff1[-1] coeff1=coeff1[:-1] if i%2==0: plt.figure(1) xD = np.linspace(a,b,5000) yD = [evalPoly(coeff1, x) for x in xD] plt.plot(xD,yD,label="i = "+str(i),linewidth=0.8) plt.xlabel("x") plt.ylabel("f(x)") plt.figure(2) yD2 = [evalPoly(coeff1, x)-f(x) for x in xD] plt.plot(xD,yD2, label="i = "+str(i),linewidth =1) plt.xlabel("x") plt.ylabel("error") xHat = findxhat(coeff1, f,a,b) exchange(xDat, xHat, coeff1, f) E_k_sets.append(["%.4f" % x for x in xDat]) errors.append(np.abs(maxErrorNew-maxErrorOld)) if np.abs(maxErrorOld-maxErrorNew)<10**(-12): plt.figure(3) plt.scatter(list(range(len(errors))), errors) plt.xlabel("number of iterations") plt.ylabel("absolute change in error") print("DONE! max error is ", np.abs(maxErrorNew)) print("Polynomial coeffs are ", coeff1 ) print("E_k: \n", E_k_sets) break else: maxErrorOld = maxErrorNew a,b=0,2*np.pi test = np.linspace(a,b,7) f = lambda x: x*np.sin(x) xD = np.linspace(a,b,1000) plt.plot(xD,f(xD)) remez(test,f,a,b) plt.figure(2) plt.legend() plt.figure(1) plt.legend()
5a8aef01cc4e4dd1ec33a423b4b7fe01134371be
kcarson097/Beginner-Projects
/Text-editor.py
560
4.03125
4
def read_text_file(file): #file name is entered as 'file.txt' with open(file) as f: contents = f.read() return contents def edit_text_file(file, new_text): #this function will overwrite the current txt file with open(file, mode = 'w') as f: #opens file as read and write option - any edits overwrites past files edited_file = f.write(new_text) def add_to_file(file,add_text): #this function adds to text file with open(file, mode = 'a') as f: new_file = f.write(add_text)
c41a32b3bc188f45b33e89d1d4f9f8ada85abe84
RikaIljina/PythonLearning
/word_count_script/count_words.py
4,264
4.0625
4
import os import sys from pathlib import Path # Add your file name here file_path = r"counttext.txt" result_path = r"result.csv" # Remember names of source and target files f_name = Path(file_path) r_name = Path(result_path) print("#" * 86) print(f"This script will read the file {f_name} that must be placed in the same folder\n" f"and analyse the amount and distribution of words used in it. The result is saved\n" f"in a csv file in the same directory and can be opened in Excel or a text editor.\n" f"The file encoding is iso-8859-1, suitable for German language.") print("#" * 86) try: my_file = open(file_path, "r", encoding="iso-8859-1") except: print("\nCouldn't open source file counttext.txt. Place it in the same directory as this script.\n") input() sys.exit("Aborting script...") # Deleting old result file if it exists if os.path.isfile(result_path): print(f"\nThe existing file {r_name} will be deleted and recreated. Proceed? y/n ") user_input = input() if user_input == "y" or user_input == "Y": os.remove(result_path) else: sys.exit("Aborting script...") result_file = open(r"result.csv", "a+", encoding="iso-8859-1") # This function reads the file, removes all unwanted characters, replaces line breaks with whitespace, # converts all characters to lowercase and splits the string into a list containing all words. def make_word_list(file): file_contents = file.read() file_contents_upd = "".join( c for c in file_contents if c not in "\"\t\\/'_;{}“”‘’“”«»[]()?:!.,—-–=<>*123y4567890§$%&#+|") file_contents_upd = file_contents_upd.replace("\n", " ") # print(file_contents_upd) file_contents_upd = file_contents_upd.lower() file_contents_list = file_contents_upd.split() # print(file_contents_list) return file_contents_list, len(file_contents_list) # This function creates a dictionary and reads the list word by word. # Each word will be used as a unique key in the dict, and its value is a counter # indicating how many times it was used throughout the text. def count_words(w_list): w_dict = {} for el in w_list: if el in w_dict: w_dict[el] += 1 else: w_dict[el] = 1 return w_dict # This function sorts the dict by most used word and alphabetically, calculates the percentage for each word # and appends an f-string formatted line to a comma separated csv file. def show_result(w_dict, w_count): sorted_list_by_usage = [(k, w_dict[k]) for k in sorted(w_dict, key=w_dict.get, reverse=True)] sorted_list_alphab = [(k, w_dict[k]) for k in sorted(w_dict.keys())] result_file.write(f"sep=,\n") result_file.write(f"Analysed file: {f_name}\n") result_file.write(f"Unique words: {len(sorted_list_alphab)}, Total words: {w_count}\n\n") result_file.write(f"Words by usage,Percentage,Amount,Words alphabetically,Percentage,Amount\n") plural_s = "s" for el in range(0, len(sorted_list_by_usage)): prc_1 = format(100 * int(sorted_list_by_usage[el][1]) / w_count, '.3f') \ if 100 * int(sorted_list_by_usage[el][1]) / w_count < 1 \ else format(100 * int(sorted_list_by_usage[el][1]) / w_count, '.2f') prc_2 = format(100 * int(sorted_list_alphab[el][1]) / w_count, '.3f') \ if 100 * int(sorted_list_alphab[el][1]) / w_count < 1 \ else format(100 * int(sorted_list_alphab[el][1]) / w_count, '.2f') # print(f"{sorted_list_by_usage[el][0]} : {prc_1:.2f}%") result_file.write(f"{sorted_list_by_usage[el][0]},{prc_1}%,{sorted_list_by_usage[el][1]} " f"usage{plural_s if sorted_list_by_usage[el][1] > 1 else ''}," f"{sorted_list_alphab[el][0]},{prc_2}%,{sorted_list_alphab[el][1]} " f"usage{plural_s if sorted_list_alphab[el][1] > 1 else ''}\n") word_list, words_total = make_word_list(my_file) # word_dict = count_words(make_word_list(my_file)) print(f"...Creating the result file {r_name} from {f_name}") show_result(count_words(word_list), words_total) print("...File created. Press enter to finish.") input() print("...Closing files...") result_file.close() my_file.close()
99add258003c36dcd2023264fd4af8c2e7045333
RikaIljina/PythonLearning
/cypher_1/cypher_template.py
6,030
4.5
4
############################################## # This code is a template for encoding and # decoding a string using a custom key that is # layered on top of the string with ord() and # chr(). The key can be any sequence of symbols, # e.g. "This is my $uper-$ecret k3y!!" # Optimally, this code would ask users to # choose between encoding and decoding a # string, read in a file with the secret # content, take the key as input and overwrite # the secret file with the encoded string. # When decoding, it would take a key, apply # it to the encoded file and show the result. ############################################## # this import is just needed for a test import random # This function takes the string secret_content and # the key. It turns every letter into its Unicode # code point, adds the Unicode value of the key on top # and returns the encoded string containing int values # separated with '.' def encode_string(secret_content, incr_key): # this will count how many symbols from the key have been used counter = 0 # this will be added to each letter to encode it incr = 0 # this will be the Unicode code point of the letter int_letter = 0 # this is the resulting string safe_string = '' # It is possible that the key is longer than the secret text. # In that case, I want to encode the encoded string again with # the remainder of the key by running additional encryption loops. # If the key is shorter than the text, encryption_loops is 1. encryption_loops = int(0 if incr_key == "" else (len(incr_key) / len(secret_content))) + 1 # Now let's go through each letter of our secret content # and convert it: for letter in secret_content: int_letter = ord(letter) # Let's find the value from the key that # will be added to our secret letter: incr = get_next_increment(incr_key, counter) # If we have more than 1 encryption loop, this loop # checks if there are characters in the key left that # have not been used yet and adds them to the increment. for loop in range(1, encryption_loops): if counter + len(secret_content) * loop < len(incr_key): incr += get_next_increment(incr_key, (counter + len(secret_content) * loop)) # Let's check if we used up the entire key and reset # or set the counter to the next symbol in the key: if (incr_key is not None or incr_key != "") and len(incr_key) - counter != 1: counter += 1 else: counter = 0 # Here, the letter is finally encoded and added to the safe string: safe_string = safe_string + "." + str(int_letter + incr) return safe_string # This function is the same as encode_string, # only backwards. It takes the safe string and # a key and returns the decoded string. def decode_string(safe_string, incr_key): counter = 0 incr = 0 chr_letter = '' int_letter = 0 decr_string = '' # Let's parse the encoded string, create a list # with all Unicode values and remove the first # empty value: encoded_list = safe_string.split('.') del (encoded_list[0]) decryption_loops = int(0 if incr_key == "" else (len(incr_key) / len(encoded_list))) + 1 for el in encoded_list: incr = get_next_increment(incr_key, counter) for loop in range(1, decryption_loops): if counter + len(encoded_list) * loop < len(incr_key): incr = incr + get_next_increment(incr_key, (counter + len(encoded_list) * loop)) if (incr_key is not None or incr_key != "") and len(incr_key) - counter != 1: counter += 1 else: counter = 0 # Here, we decode the letter by subtracting the # calculated increment value and turning it back # into a character. int_letter = int(el) - incr chr_letter = chr(int_letter if 0 <= int_letter <= 1114111 else 0) decr_string += chr_letter return decr_string # This function takes the increment key # and the current counter as arguments and returns # the Unicode value of the key at position [counter]. def get_next_increment(incr_key, counter): return 0 if incr_key is None or incr_key == "" else int(ord(incr_key[counter])) def main(): # This is your secret text. It should be replaced with # a string read from a file. secret_content = "This is the text I will encode. It is highly classified, of course.\nNo one is allowed to see it. Ever." print(secret_content + "\n") print("##########\nEnter your secret key (any characters, the longer, the better)\n##########:") incr_key = input() safe_string = encode_string(secret_content, incr_key) print("\n##########\nThis is the encoded string. It should be stored in a file for future decoding:\n##########\n", safe_string) decoded_string = decode_string(safe_string, "") print("\n##########\nThis is what you get if you decode the string without a key:\n##########\n", decoded_string) # The following logic constructs a random key with 1-35 characters # and tries to decode the string with it: random.seed() rnd_key = '' for i in range(random.randrange(1, 35)): random.seed() rnd_key = rnd_key + chr(random.randint(33, 127)) decoded_string = decode_string(safe_string, str(rnd_key)) print("\n##########\nThis is what you get if you decode the string with the random key ", rnd_key, ":\n##########\n", decoded_string) # Obviously, incr_key shouldn't be saved anywhere. Rather, the user # should be prompted to enter the correct key now. decoded_string = decode_string(safe_string, incr_key) print("\n##########\nThis is what you get if you decode the string with the correct key:\n##########\n") print(decoded_string) print("\n##########\nI hope you enjoyed my first attempt at encryption! :)\n##########\n") if __name__ == "__main__": main()
f75081ff4aa02c2d226247c160a69e941149c980
zhaokaiju/fluent_python
/c07_closure_deco/p05_closure.py
728
4.34375
4
""" 闭包: 闭包指延伸了作用域的函数,其中包含函数定义体中引用、但是不在定义体中定义的非全局变量。 函数是不是匿名的没关系,关键是它能访问定义体之外定义的非全局变量。 """ def make_averager(): """ 闭包 """ # 局部变量(非全局变量)(自由变量) series = [] def averager(new_value): series.append(new_value) total = sum(series) return total / len(series) return averager def use_make_averager(): avg = make_averager() print(avg(10)) print(avg(12)) # 输出结果: """ 10.0 11.0 """ if __name__ == '__main__': use_make_averager()
77d5735d02e893939063d955f7e32ca4b64a1f48
kescott027/PythonHacker
/ransomnote.py
1,365
3.578125
4
#!/bin/python3 import math import os import random import re import sys def checkMagazine(magazine, note): d = {} result = 'Yes' for word in magazine: d.setdefault(word, 0) d[word] +=1 for word in note: if word in d and d[word] -1 >= 0: d[word] -=1 else: result = 'No' print(result) stillnotefficient = """ def checkMagazine(magazine, note): d = {} result = 'Yes' for word in magazine: d.setdefault(word, 0) d[word] +=1 for word in note: if word in d and d[word] -1 >= 0: note[word] -=1 else: result = 'No' def checkMagazine(magazine, note): result = 'Yes' for i in range(len(note)): try: magazine.pop(magazine.index(i)) except ValueError: result = 'No' print(result) """ # Valid but too expensive at higher # list counts # def checkMagazine(magazine, note): # # # result = 'Yes' # for word in note: # if word not in magazine: # result = 'No' # else: # magazine.pop(magazine.index(word)) # print(result) if __name__ == '__main__': mn = input().split() m = int(mn[0]) n = int(mn[1]) magazine = input().rstrip().split() note = input().rstrip().split() checkMagazine(magazine, note)
feb5d900ebb46fd80cfa86d8346b12c17e94ce0b
kescott027/PythonHacker
/maxmin.py
2,527
4
4
#!/bin/python3 import math import os import random import re import sys # Complete the maxMin function below. def maxMin(k, arr): """ given a list of integers arr, and a single integer k, create an array of length k from elements arr such as its unfairness is minimized. Call that array subarr. unfairness of an array is calculated as: max(subarr) - min(subarr) :param k: an integer - the number of elements in the array to create :param arr: a list of integers :return: """ debug = False newarr = [] c = {} arr = sorted(arr) if debug: print("array size: {0}".format(k)) print("starting array {0}".format(arr)) i=0 while i + k <= len(arr): c[arr[i+(k - 1)] - arr[i]] = i i+=1 print("ranges: {0}".format(c)) start_index = c[min(c.keys())] if debug: print("min key: {0}".format(min(c.keys()))) print("starting index: {0}".format(start_index)) newarr = arr[start_index:start_index+k] final = max(newarr) - min(newarr) if debug: print("sorted array {0}".format(arr)) print("final array {0}".format(newarr)) print("min {0}".format(min(newarr))) print("max {0}".format(max(newarr))) print("result = {0} ".format(final)) return final if __name__ == '__main__': k = [3, 4, 2, 5, 3] inputs = [[10, 100, 300, 200, 1000, 20, 30], [1, 2, 3, 4, 10, 20, 30, 40, 100, 200], [1, 2, 1, 2, 1], [4504, 1520, 5857, 4094, 4157, 3902, 822, 6643, 2422, 7288, 8245, 9948, 2822, 1784, 7802, 3142, 9739, 5629, 5413, 7232], [100, 200, 300, 350, 400, 401, 402]] expected = [20, 3, 0, 1335, 2] case = range(0, len(inputs)) failures = 0 i = 0 while i < len(inputs): print("Test Case {0} ({1})".format(case[i], i)) expect = expected[i] print("inputs: {0}\nk: {1}".format(inputs[i], k[i])) result = maxMin(k[i], inputs[i]) if result != expect: print("Test Case {0}: FAIL\n\tinput:{1}\n\touput: {2}\n\texpected: {3}".format(case[i], inputs[i], result, expect)) failures += 1 else: print("Test Case {0}: PASS\n\tinput: {1}\n\toutput: {2}".format(i, inputs[i], result)) # pass print(" ") i += 1 if failures > 0: print("Test cases failed.") else: print("All cases Pass successfully")
162e451ee6116712ba11c38246234fd1ea324138
suhyeok24/Programmers-For-Coding-Test
/Programmers Lv.1/lv1. 최소직사각형.py
1,037
3.5
4
# 내 풀이 import numpy as np def solution(sizes): sizes=np.array(sizes).T.tolist() print(sizes) #[[가로],[세로]] width=sizes[0] height=sizes[1] big=max(max(width),max(height)) #가장 big을 찾는다. > 나머지 가로(세로)를 최소화시켜야 함. # index끼리 대소비교해서 smaller를 나머지 선분으로 몰빵 if big in width: for i in range(len(width)): if width[i] < height[i]: width[i],height[i] = height[i],width[i] return big*max(height) else: for i in range(len(height)): if width[i] > height[i]: width[i],height[i] = height[i],width[i] return big*max(width) #좋은 풀이 > 아 ㅋㅋ def solution(sizes): return max(max(x) for x in sizes) * max(min(x) for x in sizes) #max(max(x) for x in sizes) : 내가 말한 가장 큰놈. big #max(min(x) for x in sizes) : smaller ones 들중 가장 큰 놈..(나머지 선분의 최소화)
ce89c9d119563e15bdf426ae3d6d18800802ffe0
suhyeok24/Programmers-For-Coding-Test
/Programmers Lv.1/프로그래머스 lv1. 나누어 떨어지는 숫자 배열.py
858
3.53125
4
# 가장 흔한 for문 def solution(arr, divisor): answer = [] for n in arr: if n % divisor == 0: answer.append(n) if not answer: return [-1] else: return sorted(answer) # lIST COMPRHENSION 이용 def solution(arr, divisor): return sorted([ num for num in arr if num % divisor == 0]) or [-1] # sorted([]) = [] 은 boolean으로 FaLSE 이므로 [-1]이 대신 리턴된다. # return에 관하여 한말씀 올리면 # return A or B 일때 A,B가 둘다 참이면, A가 return됨(가장 첫번쨰 값) # but A 와 B 중에 none, empty 값(boolean이 False)이 있으면 그 값을 제외한 True 값이 리턴됨 # 즉, 하나만 참이면 그 참인 값이 리턴. #파이썬에서는 괄호 없이 값을 콤마로 구분하면 튜플이 된다. # ex) 1,2 = (1,2)
3895cae859876b54b659f2b8a8b4edec12fddee3
corneliag08/Rezolvarea-problemelor-IF-WHILE-FOR
/problema 9.py
250
3.6875
4
n=int(input("Dati un numar: ")) suma=0 if(n!=0) and (n!=1): for i in range (1,n): if n%i==0: suma+=i if suma==n: print("Numarul", n,"este perfect.") else: print("Numarul", n,"nu este perfect.")
eb8542490893d3b99e9a8cfd416e0f363182de13
codeking-hub/Coding-Problems
/AlgoExpert/balanceBrackets.py
585
3.90625
4
def balancedBrackets(string): # Write your code here. stack = [] opening_brackets = "([{" closing_brackets = "}])" matching_brackets = { ")": "(", "}": "{", "]": "[" } for char in string: peek = len(stack)-1 if char in opening_brackets: stack.append(char) if char in closing_brackets: if stack == []: return False if matching_brackets[char] == stack[peek]: stack.pop() else: return False return stack == []
8401b89e555a10d530a528355193b0207ac6be6c
codeking-hub/Coding-Problems
/AlgoExpert/moveElementToEnd/spacealsoopt.py
321
3.578125
4
def moveElementToEnd(array, toMove): # Write your code here. left = 0 right = len(array)-1 while left < right: while left < right and array[right] == toMove: right -= 1 if array[left] == toMove: array[left], array[right] = array[right], array[left] left += 1 return array # time O(n) # space O(n)
171042e8da302efa359e350feaf92915e9d33b8b
codeking-hub/Coding-Problems
/AlgoExpert/find3LargestNums.py
711
4.125
4
def findThreeLargestNumbers(array): # Write your code here. three_largest = [None, None, None] for num in array: updateThreeLargest(num, three_largest) return three_largest def updateThreeLargest(num, three_largest): if three_largest[2] == None or num > three_largest[2]: shiftValue(three_largest, num, 2) elif three_largest[1] == None or num > three_largest[1]: shiftValue(three_largest, num, 1) elif three_largest[0] == None or num > three_largest[0]: shiftValue(three_largest, num, 0) def shiftValue(array, num, idx): for i in range(idx + 1): if i == idx: array[i] = num else: array[i] = array[i+1]
e328b1b43b04ea504d88dc37e936a0c3925cea60
codeking-hub/Coding-Problems
/AlgoExpert/2Sum/s2.py
257
3.875
4
def twoNumberSum(array, targetSum): # Write your code here. nums = {} for num in array: complement = targetSum-num if complement in nums: return [complement, num] else: nums[num] = True return [] # time complexity O(n)
e2519f0ca1c42f5cb04287a8d63bd563e136a2de
codeking-hub/Coding-Problems
/AlgoExpert/branchSums.py
601
3.703125
4
# This is the class of the input root. Do not edit it. class BinaryTree: def __init__(self, value): self.value = value self.left = None self.right = None def branchSums(root): # Write your code here. sums = [] findbranchSums(root, 0, sums) return sums def findbranchSums(node, currentSum, sums): if node is None: return newCurrentNode = currentSum + node.value if node.left is None and node.right is None: sums.append(newCurrentNode) return findbranchSums(node.left, newCurrentNode, sums) findbranchSums(node.right, newCurrentNode, sums)
49e336496e2452c7c33621dbd888c78ba43405b0
codeking-hub/Coding-Problems
/AlgoExpert/binarySearch/recersive.py
476
3.875
4
def binarySearch(array, target): # Write your code here. return binarySearchHelper(array, target, 0, len(array)-1) def binarySearchHelper(array, target, low, high): if low > high: return -1 mid = (low+high)//2 match = array[mid] if match == target: return mid elif target < match: return binarySearchHelper(array, target, low, mid-1) elif target > match: return binarySearchHelper(array, target, mid+1, high)
3ddab9cd05622d64529fb633064ee8cfa0db0492
luciano588/d30-family-api
/src/datastructures.py
2,768
4.0625
4
""" update this file to implement the following already declared methods: - add_member: Should add a member to the self._members list - delete_member: Should delete a member from the self._members list - update_member: Should update a member from the self._members list - get_member: Should return a member from the self._members list """ from random import randint class FamilyStructure: def __init__(self, last_name): self.last_name = last_name # example list of members self._members = [ { "id": self._generateId(), "first_name": "John", "last_name": last_name, "lucky_number": [1] }, { "id": self._generateId(), "first_name": "John", "last_name": last_name, }, { "id": self._generateId(), "first_name": "John", "last_name": last_name, } ] # John Jackson # 33 Years old # Lucky Numbers: 7, 13, 22 # read-only: Use this method to generate random members ID's when adding members into the list def _generateId(self): return randint(0, 99999999) def add_member(self, member): # fill this method and update the return # Add a new object to an array # if member["id"] is None: # member["id"] = self._generateId() if "id" not in member: member.update(id=self._generateId()) member["last_name"]= self.last_name self._member.append(member) return member def delete_member(self, id): # fill this method and update the return` status = "" try: for i,x in enumerate(self._members): if x["id"] == id: self._members.pop(i) status = { "status": "Successfully deleted member" } break else: status = False except: status = False return status def get_member(self, id): # fill this method and update the return member = {} # try: # for x in self._members: # if x["id"] == id: # member = x # except: # member = { # "Status": "Not Found" # } for i,x in enumerate(self._members): if x["id"]== id: member= x break else: member= False return member # this method is done, it returns a list with all the family members def get_all_members(self): return self._members
77d7c4b29aad0ad0d7d7ab04b1f7d3231bf2d0b7
Symas1/metaprogramming_lab1
/meta_method.py
1,468
3.703125
4
import utils class MetaMethod: def __init__(self): self.name = utils.input_identifier('Enter method\'s name: ') self.arguments = [] self.add_arguments() def add_arguments(self): if utils.is_continue('arguments'): while True: name = utils.input_agrument('Enter argument\'s name: ') if name in self.arguments: print(f'An argument with name: {name} already exists, ' f'please, try again') elif utils.starts_with_symbol(name, 1, '*') and any( utils.starts_with_symbol(arg_name, 1, '*') for arg_name in self.arguments): print(f'Can\'t have more than one argument with * at the beginning: {name}, ' f'please, try again') elif utils.starts_with_symbol(name, 2, '*') and any( utils.starts_with_symbol(arg_name, 2, '*') for arg_name in self.arguments): print(f'Can\'t have more than one argument with ** at the beginning: {name}, ' f'please, try again') else: self.arguments.append(name) if utils.is_continue('another argument'): continue break def get_arguments(self): return self.arguments def set_arguments(self, arguments): self.arguments = arguments
48458c3ba2011e0c23112d26a5b65d7d0822c5bf
RECKLESS6321/Libaries
/BFS(queue).py
483
4
4
def bfs(graph, start_vertex, target_value): path = [start_vertex] vertex_and_path = [start_vertex, path] bfs_queue = [vertex_and_path] visited = set() while bfs_queue: current_vertex, path = bfs_queue.pop(0) visited.add(current_vertex) for neighbor in graph[current_vertex]: if neighbor not in visited: if neighbor is target_value: return path + [neighbor] else: bfs_queue.append([neighbor, path + [neighbor]])
8e7e80d3e42f32e4cb414d8e90e3c4ae079d8038
RahulNewbie/Job_REST_API
/job_insertion.py
984
3.84375
4
import csv import sqlite3 import os import constants def job_insertion(): """ Read the CSV file and insert records in Database """ con = sqlite3.connect(constants.DB_FILE) cur = con.cursor() cur.execute("CREATE TABLE IF NOT EXISTS job_data_table (Id,Title,Description,Company," "Location,Job_Category);") with open('job_listing.csv', 'rt') as fin: # csv.DictReader read line by line dr = csv.DictReader(fin) to_db = [(i['Id'], i['Title'], i['Description'], i['Company'], i['Location'], i['Job_Category']) for i in dr] cur.executemany("INSERT INTO job_data_table " "(Id,Title,Description,Company,Location," "Job_Category) " "VALUES (?, ?, ?, ?,?, ?);", to_db) print("database insertion finished") con.commit() con.close() if __name__ == "__main__": job_insertion()
6c0dc7a54d1e00bd5cb02b06bf6fa804cd665de9
kadhirash/leetcode
/problems/happy_number/solution.py
593
3.546875
4
class Solution: def isHappy(self, n: int) -> bool: #happy = # positive integer --- (n > 0) # replace num by sum of square of its digits --- replace n by sum(square of digits) # repeat until == 1 # if 1 then happy, else false hash_set = set() total_sum = 0 while n > 0 and n != 1: for i in str(n): n= sum(int(i) ** 2 for i in str(n)) if n in hash_set: return False else: hash_set.add(n) else: return True
4d138ec4e0f4349b3eeb9842acc10f2a0c1ca748
kadhirash/leetcode
/problems/minesweeper/solution.py
1,131
3.6875
4
class Solution: def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]: x, y = click surround = [(-1, 0), (1, 0), (0, 1), (0, -1), (1, -1), (1, 1), (-1, 1), (-1, -1)] def available(x, y): return 0 <= x < len(board) and 0 <= y < len(board[0]) def reveal(board, x, y): # reveal blank cell with dfs if not available(x, y) or board[x][y] != "E": return # count adjacent mines mine_count = 0 for dx, dy in surround: if available(dx+x, dy+y) and board[dx+x][dy+y] == "M": mine_count += 1 if mine_count: # have mines in adjacent cells board[x][y] = str(mine_count) else: # not adjacent mines board[x][y] = "B" for dx, dy in surround: reveal(board, dx+x, dy+y) if board[x][y] == "M": board[x][y] = "X" elif board[x][y] == "E": reveal(board, x, y) return board
374eb12b1ec6126e692a94315444e4a7bcf0621b
kadhirash/leetcode
/problems/search_suggestions_system/solution.py
1,011
3.671875
4
class Solution: def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]: products.sort() # time O(nlogn) array_len = len(products) ans = [] input_char = "" for chr in searchWord: tmp = [] input_char += chr insertion_index = self.binary_search(products, input_char) # find where input_char can be inserted in-order in the products array for word_ind in range(insertion_index, min(array_len, insertion_index+3)): # check the following 3 words, if valid if products[word_ind].startswith(input_char): tmp.append(products[word_ind]) ans.append(tmp) return ans def binary_search(self, array, target): # bisect.bisect_left implementation lo = 0 hi = len(array) while lo < hi: mid = (lo + hi) //2 if array[mid] < target: lo = mid + 1 else: hi = mid return lo
5b27c86e6e8a8286719120abc005c3766632d7f0
ElenaPontecchiani/Python_Projects
/0-hello/16-for.py
306
4.09375
4
for letter in "lol": print(letter) friends = ["Kim", "Tom", "Kris"] for friend in friends: print(friend) #altro modo per fare la stessa cosa con range for index in range(len(friends)): print(friends[index]) for index in range(10): print(index) for index in range(3,10): print(index)
8467f46df1d0750c60bdd4c67ece16ef34707c48
ElenaPontecchiani/Python_Projects
/0-hello/35-sortedAdvanced.py
531
3.53125
4
#format=(nome, raggio, denisità, distanza dal sole) planets =[ ("Mercury", 2440, 5.43, 0.395), ("Venus", 6052, 5.24, 0.723), ("Earth", 6378, 5.52, 1.000), ("Mars", 3396, 3.93, 1.530), ("Jupiter", 71492, 1.33, 5.210), ("Saturn", 60268, 0.69, 9.551), ("Uranus", 25559, 1.27, 19.213), ("Neptune", 24764, 1.64, 30.070), ] #se voglio riordinare per vari parametri, faccio una f che torna il risultato dell'op di sort size = lambda planet: planet[1] planets.sort(key = size, reverse=True) print(planets)
a9bbd74af9b343cf940c2a7eeb6de12dbcc4bdd9
ElenaPontecchiani/Python_Projects
/0-hello/12-calculatorV2.py
466
4.1875
4
n1 = float(input("First number: ")) n2 = float(input("Second number: ")) operator = input("Digit the operator: ") def calculatorV2 (n1, n2, operator): if operator == '+': return n1+n2 elif operator == '-': return n1-n2 elif operator == '*': return n1*n2 elif operator == '/': return n1/n2 else: print("Error, operator not valid") return 0 result = calculatorV2(n1, n2, operator) print(result)
e5d0c701272a91bb56882ffb433ead594311d5b5
ElenaPontecchiani/Python_Projects
/0-hello/2-variable.py
555
3.953125
4
character_name= "Jhon" character_age= 50.333 is_male= False #cincionamenti con le variabili print("His name is " +character_name) print (character_name) print (character_name.upper().islower()) print(len(character_name)) print(character_name[0]) print(character_name.index("J")) print(character_name.index("ho")) phrase= "giraffe academy" print(phrase.replace("giraffe", "lol")) #this is a comment #cincionamenti con i numeri my_num= -2.097 print(my_num) print((-2.097 + 8)*7) print(str(my_num) + "my favorite number") print(abs(my_num)) print(max(1,4))
0eeeef457fd8543b7ba80d2645b0bac3624dffc3
fanjiamin1/cryptocurrencies
/scratchpad/exponentiation.py
564
3.703125
4
def modularpoweroftwo(number,poweroftwo,module): #returns number**(2**poweroftwo) % module value=number%module currexponent=0 while currexponent<poweroftwo: value=(value*value)%module currexponent+=1 return value def fastmodularexponentiation(number,exponent,module): value=1 for i in range(len(bin(exponent)[2:][::-1])): if bin(exponent)[2:][::-1][i]=='1': value*=modularpoweroftwo(number,i,module) return value print(fastmodularexponentiation(5,3,200))
c9a49ce478ccbe1df25e3b5c0ee18932ae222f86
mateuszkanabrocki/LMPTHW
/ex11/project/tail.py
804
3.734375
4
#! /usr/bin/env python3 from sys import argv, exit, stdin # history | ./tail -25 def arguments(argv): try: lines_num = int(argv[1].strip('-')) return lines_num except IndexError: print('Number of lines not gien.') exit(1) def main(): count = arguments(argv) if len(argv) > 2: try: lines = [] for file in argv[2:]: with open(file, 'r') as f: for line in f.readlines(): lines.append(line) except FileNotFoundError: print('File not found.') exit(1) else: lines = stdin.readlines() result_lines = lines[-count:] for line in result_lines: print(line.strip('\n')) if __name__ == '__main__': main()
def2e855860ded62733aa2ddcfe4b51029a8edd2
PSReyat/Python-Practice
/car_game.py
784
4.125
4
print("Available commands:\n1) help\n2) start\n3) stop\n4) quit\n") command = input(">").lower() started = False while command != "quit": if command == "help": print("start - to start the car\nstop - to stop the car\nquit - to exit the program\n") elif command == "start": if started: print("Car has already started.\n") else: started = True print("Car has started.\n") elif command == "stop": if started: started = False print("Car has stopped.\n") else: print("Car has already stopped.\n") else: print("Input not recognised. Please enter 'help' for list of valid inputs.\n") command = input(">").lower() print("You have quit the program.")
f6b50fb2c608e9990ed1e3870fd73e2039e17b3d
ananyo141/Python3
/uptoHundred.py
301
4.3125
4
#WAP to print any given no(less than 100) to 100 def uptoHundred(num): '''(num)-->NoneType Print from the given number upto 100. The given num should be less than equal to 100. >>>uptoHundred(99) >>>uptoHundred(1) ''' while(num<=100): print(num) num+=1
004253ee0f2505f145d011e35d28ed4e9f96f36b
ananyo141/Python3
/Automate The Boring Stuff/sandwichMaker.py
1,484
4.09375
4
# Make a sandwich maker and display the cost. from ModuleImporter import module_importer pyip = module_importer('pyinputplus', 'pyinputplus') orderPrice = 0 print("Welcome to Python Sandwich!".center(100,'*')) print("We'll take your order soon.\n") breadType = pyip.inputMenu(['wheat','white','sourdough'],prompt="How do you like your bread?\n",blank=True) if breadType: orderPrice += 20 proteinType = pyip.inputMenu(['chicken','turkey','ham','tofu'],prompt="\nWhat is your protein preference?\n",blank=True) if proteinType: orderPrice += 35 cheese = pyip.inputYesNo(prompt = '\nDo you prefer cheese?: ') if cheese == 'yes': cheeseType = pyip.inputMenu(['cheddar','Swiss','mozarella'],prompt="Enter cheese type: ") orderPrice += 10 mayo = pyip.inputYesNo(prompt='\nDo you want mayo?: ') if mayo == 'yes': orderPrice += 5 mustard = pyip.inputYesNo(prompt='\nDo you want to add mustard?: ') if mustard == 'yes': orderPrice += 2 lettuce = pyip.inputYesNo(prompt='\nDo you want lettuce?: ') tomato = pyip.inputYesNo(prompt='\nDo you want tomato in your sandwich?: ') orderQuantity = pyip.inputInt('\nHow many sandwiches do you want to order?: ',min=1) confirmation = pyip.inputYesNo(prompt='\nConfirm your order?: ') if confirmation == 'yes': totalOrderPrice = orderPrice * orderQuantity print(f"\nYour order has been confirmed! Total order price is Rs.{totalOrderPrice} for {orderQuantity} sandwiches.") else: print('\nYou cancelled your order')
437c321c8a52c3ae13db3bfa5e48c7a5dac2c1eb
ananyo141/Python3
/gradeDistribution/functions.py
2,519
4.15625
4
# This function reads an opened file and returns a list of grades(float). def findGrades(grades_file): '''(file opened for reading)-->list of float Return a list of grades from the grades_file according to the format. ''' # Skip over the header. lines=grades_file.readline() grades_list=[] while lines!='\n': lines=grades_file.readline() lines=grades_file.readline() while lines!='': # No need to .rstrip('\n') newline as float conversion removes it automatically. grade=float(lines[lines.rfind(' ')+1:]) grades_list.append(grade) lines=grades_file.readline() return grades_list # This function takes the list of grades and returns the distribution of students in that range. def gradesDistribution(grades_list): '''(list of float)-->list of int Return a list of ints where each index indicates how many grades are in these ranges: 0-9: 0 10-19: 1 20-29: 2 : 90-99: 9 100 : 10 ''' ranges=[0]*11 for grade in grades_list: which_index=int(grade//10) ranges[which_index]+=1 return ranges # This function writes the histogram of grades returned by distribution. def writeHistogram(histogram,write_file): '''(list of int,file opened for writing)-->NoneType Write a histogram of '*'s based on the number of grades in the histogram list. The output format: 0-9: * 10-19: ** 20-29: ****** : 90-99: ** 100: * ''' write_file.write("0-9: ") write_file.write('*' * histogram[0]+str(histogram[0])) write_file.write('\n') # Write the 2-digit ranges. for i in range(1,10): low = i*10 high = low+9 write_file.write(str(low)+'-'+str(high)+': ') write_file.write('*'*histogram[i]+str(histogram[i])) write_file.write('\n') write_file.write("100: ") write_file.write('*' * histogram[-1]+str(histogram[-1])) write_file.write('\n') write_file.close # Self-derived algorithm, have bugs.(Not deleting for further analysis and possible debugging.) # for i in range(0,100,9): # write_file.write(str(i)) # write_file.write('-') # write_file.write(str(i+9)) # write_file.write(':') # write_file.write('*'*histogram[(i//10)]) # write_file.write(str(histogram[(i//10)])) # write_file.write('\n') # write_file.close()
65c9becebedca46aed5c13c04aa0bff47460d23b
ananyo141/Python3
/Automate The Boring Stuff/clipboardNumbering.py
1,238
4
4
#!python3 # WAP that takes the text in the clipboard and adds a '*' and space before each line and copies to the # clipboard for further usage. import sys from ModuleImporter import module_importer pyperclip = module_importer('pyperclip', 'pyperclip') def textNumbering(text, mode): '''(str,str)-->str Returns a ordered or unordered string according to newlines of the given text argument and mode. ''' textList = text.split('\n') if mode.lower()=='unordered': for i in range(len(textList)): textList[i] = "* "+textList[i] elif mode.lower()=='ordered': numbering = 1 for i in range(len(textList)): textList[i] = str(numbering)+') '+textList[i] numbering += 1 else: sys.exit("Invalid Choice") processedText = ('\n').join(textList) return processedText def main(): # Uses terminal argument as mode-choice for easier operation # if len(sys.argv)<2: sys.exit("Usage: python [filename.py] [mode]") choice=sys.argv[1] clipboard=pyperclip.paste() numberedText=textNumbering(clipboard,choice) pyperclip.copy(numberedText) print("Successfully completed.") if __name__ == '__main__': main()
0cc53ef8c755669e55176ebad4cd5b0c0d758eef
ananyo141/Python3
/Automate The Boring Stuff/passwordStrengthNOREGEX.py
3,765
4.03125
4
# Give the user option to find the passwords in the given text, or enter one manually. # Check the password and give rating as weak, medium, strong, unbreakable and include tips to improve it. import re, time, sys from ModuleImporter import module_importer pyperclip = module_importer('pyperclip', 'pyperclip') def passwordFinder(text): '''(str)--->list Find and return matching password strings in the given text. ''' passwordRegex = re.compile(r'''( (password | pass) # Starts with 'password' (?: : | -)? # optional separator (?: \s*)? # Optional whitespaces (\S{3,}) # Atleast 3 non-space characters )''', re.VERBOSE | re.IGNORECASE) passwordsFound = [] for tupleGroup in passwordRegex.findall(text): passwordsFound.append(tupleGroup[2]) return passwordsFound def passwordStrength(passw): '''(str)--->NoneType Print the strength of the given password between weak, medium, strong and unbreakable along with tips to strengthen the password. ''' specialCharRegex = re.compile(r'[!@#$%^&*-+]') characterCheck = uppercaseCheck = lowercaseCheck = digitCheck = specialCharCheck = False strengthScore = 0 if len(passw) >= 8: characterCheck = True strengthScore += 1 # Find uppercase for char in passw: if char.isupper(): uppercaseCheck = True strengthScore += 1 break # Find lowercase for char in passw: if char.islower(): lowercaseCheck = True strengthScore += 1 break # Find digit for char in passw: if char.isdecimal(): digitCheck = True strengthScore += 1 break # Find special Character specialChar = specialCharRegex.search(passw) if specialChar: specialCharCheck = True strengthScore += 1 # Score strength if strengthScore == 5: print("Unbreakable\nYou can challenge a hacker!") elif strengthScore == 4: print("Strong") elif strengthScore == 3: print("Medium") elif strengthScore < 3: print("Weak") # Add tips to strengthen the password if not characterCheck: print("Password length is too short") if not uppercaseCheck: print("Tip: Add an uppercase letter.") if not lowercaseCheck: print("Tip: Add a lowercase letter.") if not digitCheck: print("Tip: Add a digit.") if not specialCharCheck: print("Tip: Add a special character.") def main(): if len(sys.argv)>1: if sys.argv[1].lower().startswith('clip'): clipboard = pyperclip.paste() passwords = passwordFinder(clipboard) if len(passwords) == 0: sys.exit("No passwords found") print("Analyzing".ljust(20,'.')) time.sleep(1) for i in range(len(passwords)): print("\nPassword found:", passwords[i]) passwordStrength(passwords[i]) time.sleep(0.25) sys.exit("\nThanks for trying this out!") else: sys.exit("Enter 'clip' during script execution {python <filename>.py clip}\nto find and analyze passwords from your clipboard.") password = input("Enter the password: ") if ' ' in password: sys.exit("Passwords can't contain spaces. Invalid.") print("Analyzing......") time.sleep(0.5) passwordStrength(password) # Usage Reminder print('''\nYou can also enter 'clip' during script execution {python <filename>.py clip} to find and analyze passwords from your clipboard.''') if __name__ == '__main__': main()
67613b888eaa088a69a0fec26f1ace376f95cbbb
ananyo141/Python3
/calListAvg.py
624
4.15625
4
# WAP to return a list of averages of values in each of inner list of grades. # Subproblem: Find the average of a list of values def calListAvg(grades): '''(list of list of num)--list of num Return the list of average of numbers from the list of lists of numbers in grades. >>> calListAvg([[5,2,4,3],[4,6,7,8],[4,3,5,3,4,4],[4,35,3,45],[56,34,3,2,4],[5,3,56,6,7,6]]) [3.5, 6.25, 3.833, 21.75, 19.8, 13.833] ''' avg_list=[] for sublist in grades: total=0 for grade in sublist: total+=grade avg_list.append(total/len(sublist)) return avg_list
aba312740d42e2f175d79984bc2d3ec8042b891b
ananyo141/Python3
/area_of_triangle.py
184
4.1875
4
def area(base, height): ''' (num,num)--> float Return the area of a triangle of given base and height. >>>area(8,12) 48.0 >>>area(9,6) 27.0 ''' return (base*height)/2